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, a `Frame` for a
19//! filled region, and the decision of what to do when an intent has no colour
20//! yet. It owns no colours and no sizes. [`Palette`] is supplied by the caller,
21//! already resolved, and every radius, margin and stroke width arrives in
22//! [`FrameStyle`].
23//!
24//! That split is why the crate has no dependency on `makeover` itself: the app
25//! already resolves a theme, and coupling a renderer to a colour crate's
26//! version would buy nothing.
27//!
28//! # The cascade is the real difference
29//!
30//! A stylesheet can say "a pressed button inverts its bevel" once and let the
31//! cascade carry it. An immediate-mode renderer has nowhere to put that, so
32//! every call site decides. [`makeover_layout::Depth::pressed`] is what keeps
33//! the decision from being re-derived per widget.
34
35#![forbid(unsafe_code)]
36
37use egui::{Color32, CornerRadius, Margin, Painter, Rect, Shape, Stroke, Ui};
38use makeover_layout::{Bevel, Depth, Edge, Fill};
39
40/// The resolved colours this renderer needs, as flat values.
41///
42/// Built by the app from whatever it already uses to resolve a theme, then
43/// held and reused. Deliberately not a trait and not string-keyed: a bevel is
44/// painted per widget per frame, and a map lookup per edge is a cost with
45/// nothing to show for it.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct Palette {
48 /// `surface-page`.
49 pub page: Color32,
50 /// `surface-raised`.
51 pub raised: Color32,
52 /// `surface-overlay`.
53 pub overlay: Color32,
54 /// `surface-well`, absent on makeover before 2.3.0.
55 pub well: Option<Color32>,
56 /// `bevel-light`.
57 pub bevel_light: Color32,
58 /// `bevel-dark`.
59 pub bevel_dark: Color32,
60}
61
62impl Palette {
63 /// Resolve a surface intent.
64 ///
65 /// `Fill::Well` substitutes the page when the theme has no `surface-well`,
66 /// which is every theme on makeover before 2.3.0. That substitution lives
67 /// here rather than in the description because it is only right for a
68 /// renderer that can always paint an exact colour: makeover-tui had to
69 /// reject it, since on a terminal the page is often the very surface the
70 /// well is cut into and the two quantise together.
71 ///
72 /// Delete it once 2.3.0 is published and the consumers adopt it.
73 #[must_use]
74 pub fn fill(&self, fill: Fill) -> Color32 {
75 match fill {
76 Fill::Page => self.page,
77 Fill::Raised => self.raised,
78 Fill::Overlay => self.overlay,
79 Fill::Well => self.well.unwrap_or(self.page),
80 }
81 }
82
83 /// Resolve a bevel edge intent.
84 #[must_use]
85 pub const fn edge(&self, edge: Edge) -> Color32 {
86 match edge {
87 Edge::Light => self.bevel_light,
88 Edge::Dark => self.bevel_dark,
89 }
90 }
91}
92
93/// The geometry a framed region is drawn with.
94///
95/// Every field is a value, which is why they all arrive from the caller:
96/// radius and border width belong to `makeover-geometry`, and margins come
97/// from its relational gaps.
98#[derive(Debug, Clone, Copy, PartialEq)]
99pub struct FrameStyle {
100 /// Corner radius. Square under the Platinum default.
101 pub radius: CornerRadius,
102 /// Inner margin between the frame and its contents.
103 pub margin: Margin,
104 /// Bevel stroke width, in points.
105 pub stroke: f32,
106}
107
108impl Default for FrameStyle {
109 /// A one-point square frame with no inner margin.
110 fn default() -> Self {
111 Self {
112 radius: CornerRadius::ZERO,
113 margin: Margin::ZERO,
114 stroke: 1.0,
115 }
116 }
117}
118
119/// Paint a two-tone edge just inside `rect`.
120///
121/// Fill first, bevel after: this adds two polylines and nothing else, so it
122/// composes over whatever is already there. That is what lets it go over an
123/// [`egui::TextEdit`] after `ui.add`, where the widget's own fill has landed.
124///
125/// Two three-point polylines meeting at opposite corners, rather than four
126/// segments, so egui mitres the corner joins instead of leaving a notch.
127pub fn paint_bevel(painter: &Painter, rect: Rect, bevel: Bevel, palette: &Palette, stroke: f32) {
128 let (top_left, bottom_right) = bevel.edges();
129
130 // Inset by half a stroke so the line lands inside `rect` rather than
131 // straddling its edge, which on a fractional-scale display is the
132 // difference between one crisp pixel and two dim ones.
133 let r = rect.shrink(stroke / 2.0);
134
135 painter.add(Shape::line(
136 vec![r.left_bottom(), r.left_top(), r.right_top()],
137 Stroke::new(stroke, palette.edge(top_left)),
138 ));
139 painter.add(Shape::line(
140 vec![r.right_top(), r.right_bottom(), r.left_bottom()],
141 Stroke::new(stroke, palette.edge(bottom_right)),
142 ));
143}
144
145/// Draw a region at a given [`Depth`]: its fill and its edge, together.
146///
147/// [`Depth::Flat`] gets neither, and inherits whatever it sits on. That is the
148/// difference between level-with and painted-the-same-colour, and it is the
149/// reason `Depth::fill` returns an [`Option`] rather than defaulting to the
150/// page.
151pub fn frame<R>(
152 ui: &mut Ui,
153 depth: Depth,
154 palette: &Palette,
155 style: FrameStyle,
156 add_contents: impl FnOnce(&mut Ui) -> R,
157) -> R {
158 let mut f = egui::Frame::new()
159 .corner_radius(style.radius)
160 .inner_margin(style.margin);
161 if let Some(fill) = depth.fill() {
162 f = f.fill(palette.fill(fill));
163 }
164 let framed = f.show(ui, add_contents);
165 if let Some(bevel) = depth.bevel() {
166 paint_bevel(
167 ui.painter(),
168 framed.response.rect,
169 bevel,
170 palette,
171 style.stroke,
172 );
173 }
174 framed.inner
175}
176
177#[cfg(test)]
178mod tests {
179 use super::*;
180
181 fn palette(well: Option<Color32>) -> Palette {
182 Palette {
183 page: Color32::from_rgb(1, 1, 1),
184 raised: Color32::from_rgb(2, 2, 2),
185 overlay: Color32::from_rgb(3, 3, 3),
186 well,
187 bevel_light: Color32::WHITE,
188 bevel_dark: Color32::BLACK,
189 }
190 }
191
192 #[test]
193 fn a_well_falls_back_to_the_page_before_makeover_2_3() {
194 // This renderer's policy, not the description's. See makeover-tui,
195 // which reaches the opposite conclusion for the same intent.
196 let p = palette(None);
197 assert_eq!(p.fill(Fill::Well), p.page);
198 // and uses the real token once the theme carries one
199 let w = Color32::from_rgb(9, 9, 9);
200 assert_eq!(palette(Some(w)).fill(Fill::Well), w);
201 }
202
203 #[test]
204 fn every_other_intent_resolves_without_a_fallback() {
205 let p = palette(None);
206 assert_eq!(p.fill(Fill::Page), p.page);
207 assert_eq!(p.fill(Fill::Raised), p.raised);
208 assert_eq!(p.fill(Fill::Overlay), p.overlay);
209 }
210
211 #[test]
212 fn a_raised_region_never_resolves_to_the_well_fill() {
213 // The cross-app bug, asserted at the renderer boundary this time.
214 let p = palette(Some(Color32::from_rgb(9, 9, 9)));
215 let raised = Depth::Raised.fill().map(|f| p.fill(f));
216 let well = Depth::Well.fill().map(|f| p.fill(f));
217 assert_eq!(raised, Some(p.raised));
218 assert_ne!(raised, well);
219 }
220
221 #[test]
222 fn the_lit_edge_swaps_when_a_card_is_pressed() {
223 let p = palette(None);
224 let (tl, _) = Depth::Raised.bevel().unwrap().edges();
225 let (ptl, _) = Depth::Raised.pressed().bevel().unwrap().edges();
226 assert_eq!(p.edge(tl), p.bevel_light);
227 assert_eq!(p.edge(ptl), p.bevel_dark);
228 }
229
230 #[test]
231 fn flat_asks_for_neither_fill_nor_edge() {
232 assert!(Depth::Flat.fill().is_none());
233 assert!(Depth::Flat.bevel().is_none());
234 }
235
236 #[test]
237 fn the_default_frame_is_square_and_one_point() {
238 let d = FrameStyle::default();
239 assert_eq!(d.radius, CornerRadius::ZERO);
240 assert_eq!(d.margin, Margin::ZERO);
241 assert!((d.stroke - 1.0).abs() < f32::EPSILON);
242 }
243}