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.
149pub fn paint_bevel(painter: &Painter, rect: Rect, bevel: Bevel, palette: &Palette, stroke: f32) {
150 let (top_left, bottom_right) = bevel.edges();
151
152 // Inset by half a stroke so the line lands inside `rect` rather than
153 // straddling its edge, which on a fractional-scale display is the
154 // difference between one crisp pixel and two dim ones.
155 let r = rect.shrink(stroke / 2.0);
156
157 painter.add(Shape::line(
158 vec![r.left_bottom(), r.left_top(), r.right_top()],
159 Stroke::new(stroke, palette.edge(top_left)),
160 ));
161 painter.add(Shape::line(
162 vec![r.right_top(), r.right_bottom(), r.left_bottom()],
163 Stroke::new(stroke, palette.edge(bottom_right)),
164 ));
165}
166
167/// Draw a region at a given [`Depth`]: its fill and its edge, together.
168///
169/// [`Depth::Flat`] gets neither, and inherits whatever it sits on. That is the
170/// difference between level-with and painted-the-same-colour, and it is the
171/// reason `Depth::fill` returns an [`Option`] rather than defaulting to the
172/// page.
173pub fn frame<R>(
174 ui: &mut Ui,
175 depth: Depth,
176 palette: &Palette,
177 style: FrameStyle,
178 add_contents: impl FnOnce(&mut Ui) -> R,
179) -> R {
180 let mut f = egui::Frame::new()
181 .corner_radius(style.radius)
182 .inner_margin(style.margin);
183 // Two ways there is no fill to paint, and they collapse to the same
184 // outcome: the depth names none (Depth::Flat), or it names one this
185 // renderer cannot resolve. Either way the frame goes unfilled and the
186 // bevel below carries the depth on its own, which is the rule this
187 // module already documents for Flat.
188 if let Some(fill) = depth.fill().and_then(|f| palette.fill(f)) {
189 f = f.fill(fill);
190 }
191 let framed = f.show(ui, add_contents);
192 if let Some(bevel) = depth.bevel() {
193 paint_bevel(
194 ui.painter(),
195 framed.response.rect,
196 bevel,
197 palette,
198 style.stroke,
199 );
200 }
201 framed.inner
202}
203
204#[cfg(test)]
205mod tests {
206 use super::*;
207
208 fn palette(well: Color32) -> Palette {
209 Palette {
210 page: Color32::from_rgb(1, 1, 1),
211 raised: Color32::from_rgb(2, 2, 2),
212 overlay: Color32::from_rgb(3, 3, 3),
213 well,
214 sunken: Color32::from_rgb(4, 4, 4),
215 bevel_light: Color32::WHITE,
216 bevel_dark: Color32::BLACK,
217 }
218 }
219
220 #[test]
221 fn a_well_resolves_to_its_own_token() {
222 // No substitution left. The page-filled well was a stand-in for a
223 // token that did not exist yet; it exists now.
224 let w = Color32::from_rgb(9, 9, 9);
225 let p = palette(w);
226 assert_eq!(p.fill(Fill::Well), Some(w));
227 assert_ne!(p.fill(Fill::Well), Some(p.page));
228 }
229
230 #[test]
231 fn every_intent_is_a_plain_lookup() {
232 let p = palette(Color32::from_rgb(9, 9, 9));
233 assert_eq!(p.fill(Fill::Page), Some(p.page));
234 assert_eq!(p.fill(Fill::Raised), Some(p.raised));
235 assert_eq!(p.fill(Fill::Overlay), Some(p.overlay));
236 }
237
238 /// Sunken is its own colour, not the well's and not the page's. The two
239 /// are authored in opposite directions and an earlier cut of the
240 /// description conflated them.
241 #[test]
242 fn sunken_is_neither_the_well_nor_the_page() {
243 let p = palette(Color32::from_rgb(9, 9, 9));
244 assert_eq!(p.fill(Fill::Sunken), Some(p.sunken));
245 assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Well));
246 assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Page));
247 }
248
249 #[test]
250 fn a_raised_region_never_resolves_to_the_well_fill() {
251 // The cross-app bug, asserted at the renderer boundary this time.
252 let p = palette(Color32::from_rgb(9, 9, 9));
253 let raised = Depth::Raised.fill().and_then(|f| p.fill(f));
254 let well = Depth::Well.fill().and_then(|f| p.fill(f));
255 assert_eq!(raised, Some(p.raised));
256 assert_ne!(raised, well);
257 }
258
259 #[test]
260 fn the_lit_edge_swaps_when_a_card_is_pressed() {
261 let p = palette(Color32::from_rgb(9, 9, 9));
262 let (tl, _) = Depth::Raised.bevel().unwrap().edges();
263 let (ptl, _) = Depth::Raised.pressed().bevel().unwrap().edges();
264 assert_eq!(p.edge(tl), p.bevel_light);
265 assert_eq!(p.edge(ptl), p.bevel_dark);
266 }
267
268 #[test]
269 fn flat_asks_for_neither_fill_nor_edge() {
270 assert!(Depth::Flat.fill().is_none());
271 assert!(Depth::Flat.bevel().is_none());
272 }
273
274 #[test]
275 fn the_default_frame_is_square_and_one_point() {
276 let d = FrameStyle::default();
277 assert_eq!(d.radius, CornerRadius::ZERO);
278 assert_eq!(d.margin, Margin::ZERO);
279 assert!((d.stroke - 1.0).abs() < f32::EPSILON);
280 }
281}