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 draws
17//!
18//! The parts of the description that carry no vocabulary member: depth
19//! ([`frame`], [`paint_bevel`]), the resolved colours ([`Palette`]), a table's
20//! per-frame facts and cell tones ([`table`]), the token and the waiting
21//! marks ([`piece`]), and the egui visuals and metrics a host starts from
22//! ([`host`]).
23//!
24//! The vocabulary members (fields, columns, meters, controls, facts, figures
25//! and charts) are drawn by `quasi-immediate`, which owns those types through
26//! `quasi-router` and calls into this crate for everything above. The style
27//! types it draws them with stay here: [`FieldStyle`], [`Editing`],
28//! [`piece::PieceStyle`] and [`table::TableStyle`].
29//!
30//! # What this crate does and does not own
31//!
32//! It owns the *expression*: two mitred polylines for a bevel and a `Frame`
33//! for a filled region. It owns no colours and no substitutions: makeover
34//! derives `surface-well` and every consumer reads the real token. [`Palette`]
35//! is supplied by the caller already resolved.
36//!
37//! It picks no sizes either. Every radius, margin, stroke width and floor
38//! arrives in a style type ([`FrameStyle`], [`FieldStyle`], [`piece::PieceStyle`],
39//! [`table::TableStyle`], [`host::Metrics`]), and where one has a default it is
40//! the suite's number rather than this crate's: the focus ring and the target
41//! floor in [`host::Metrics`] default to what `makeover-webview` emits.
42//!
43//! `makeover` itself is linked only by the `theme` feature, for
44//! `Palette::from_theme`: it embeds every shipped theme file, and an app that
45//! resolves its own colours should not carry them.
46//!
47//! # The cascade is the real difference
48//!
49//! A stylesheet can say "a pressed button inverts its bevel" once and let the
50//! cascade carry it. An immediate-mode renderer has nowhere to put that, so
51//! every call site decides. [`makeover_layout::Depth::pressed`] is what keeps
52//! the decision from being re-derived per widget.
53//!
54//! # Overlays
55//!
56//! [`Palette::cast`] is what overlaying means in immediate mode. [`frame`] hands
57//! the cast shadow to the `egui::Frame` for any depth whose fill is
58//! [`Fill::Overlay`], keyed off the fill rather than the variant.
59//!
60//! # Tones
61//!
62//! [`Palette`] carries the three status intents together rather than one per
63//! widget, for the reason [`Palette::fill`] is an `Option`: `Tone` is five
64//! members wide, and a resolver missing one has to invent a colour, which is a
65//! substitution this crate does not make.
66//!
67//! # Focus and chrome
68//!
69//! **Focus is not describable, and egui owns all of it here.** Reach, focus
70//! and the focus ring are this renderer's three answers and egui already has
71//! all three: its own id stack decides what is reachable, its own state decides
72//! what holds the keyboard, and it paints exactly one ring. Drawing a second
73//! ring on top of egui's would break the one-ring rule. The terms are defined
74//! once in `makeover_layout`'s crate header, "Reach, focus and the focus ring".
75//!
76//! **App-level chrome is not drawn here.** `quasi-router` names the affordances
77//! that outlive one screen, and `quasi-immediate` answers them: this crate
78//! depends on `makeover-layout` and not on `quasi-router`, one layer below the
79//! renderers that consume a `Screen`.
80
81#![forbid(unsafe_code)]
82
83use egui::{Color32, CornerRadius, Margin, Painter, Rect, Shape, Stroke, Ui};
84use makeover_layout::{Bevel, Depth, Edge, Fill, HEAT_BANDS, Heat, Tone};
85
86pub mod host;
87pub mod piece;
88pub mod table;
89
90/// The resolved colours this renderer needs, as flat values.
91///
92/// Built by the app from whatever it already uses to resolve a theme, then
93/// held and reused. Deliberately not a trait and not string-keyed: a bevel is
94/// painted per widget per frame, and a map lookup per edge is a cost with
95/// nothing to show for it.
96///
97/// `#[non_exhaustive]`, so a colour added here is not a breaking change: build
98/// one with `Palette::from_theme` (the `theme` feature), or start from
99/// [`Palette::two_tone`] and set every colour the app resolves.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101#[non_exhaustive]
102pub struct Palette {
103 /// `surface-page`.
104 pub page: Color32,
105 /// `surface-raised`.
106 pub raised: Color32,
107 /// `surface-overlay`.
108 pub overlay: Color32,
109 /// `surface-well`.
110 ///
111 /// Required, not optional. makeover derives it for every theme, so a
112 /// resolved palette without a well is not a thing that exists here.
113 /// `makeover-tui` keeps its own `Option` for a different reason, since a
114 /// terminal can have the colour and still be unable to show it.
115 pub well: Color32,
116 /// `surface-sunken`.
117 ///
118 /// A surface set back from the one it sits on, by colour and nothing else.
119 /// Not a well: a well is a hole with an edge, and this has no edge. An
120 /// immediate-mode renderer paints an arbitrary rect, so unlike
121 /// `makeover-tui` it has no excuse for declining this one.
122 ///
123 /// Required rather than optional, on the same footing as `well`: all 31
124 /// themes makeover embeds author it.
125 pub sunken: Color32,
126 /// `bevel-light`.
127 pub bevel_light: Color32,
128 /// `bevel-dark`.
129 pub bevel_dark: Color32,
130 /// `elevation`.
131 ///
132 /// What a surface that floats OVER the page is cast onto it with. The one
133 /// intent here that is about a surface's relationship to the page rather
134 /// than about the surface, which is why it is a translucent near-black on
135 /// every theme rather than something read off the palette's own ramp.
136 ///
137 /// **Only for a surface that overlays.** A menu, a tooltip, a modal. A
138 /// surface *in* the layout takes a bevel, and reaching for this on a panel
139 /// or a card is how a pre-Platinum look survives a conversion under a new
140 /// name.
141 ///
142 /// egui has a real answer for this where a terminal does not: see
143 /// [`Palette::cast`], which is the shadow to hand an
144 /// [`egui::Frame`].
145 pub elevation: Color32,
146 /// `content`.
147 ///
148 /// Ordinary text.
149 pub content: Color32,
150 /// `content-secondary`.
151 ///
152 /// Inactive but usable: it still answers a press. The middle tone of the
153 /// three (wiki `three-tone-convention`), and the one an unchosen option in
154 /// a choice field takes.
155 ///
156 /// Not [`content_disabled`](Self::content_disabled), which carries a
157 /// claim: `State::Disabled` resolves to it, so a live control wearing it
158 /// tells the user it will not answer. `makeover-tui` draws the same widget the same
159 /// way from `makeover-tui@230bf63`.
160 ///
161 /// A step of `content` toward the page, derived at load by `makeover`
162 /// rather than authored, so it is read off the resolved theme here like
163 /// any other token and never re-derived.
164 pub content_secondary: Color32,
165 /// `content-muted`.
166 ///
167 /// A field's hint, a caption, a reading: text that was never a control.
168 /// Held to body text's floor.
169 pub content_muted: Color32,
170 /// `content-disabled`.
171 ///
172 /// What [`makeover_layout::State::Disabled`] resolves to: the label of a
173 /// control that will not answer, fainter than any hint. The reading comes
174 /// from the description rather than from here: `State::Disabled` names
175 /// this intent by token.
176 pub content_disabled: Color32,
177 /// `action-primary`.
178 ///
179 /// What a control is drawn in.
180 ///
181 /// This is the intent [`CellPart`](makeover_layout::CellPart) exists to
182 /// separate. A cell holding a control that takes the cell's text colour is
183 /// the drift `CellPart` names.
184 pub action: Color32,
185 /// `content-on-action`: ink that stays readable on [`action`](Self::action).
186 ///
187 /// Resolved by makeover (the theme's page or content at 4.5:1, black or
188 /// white otherwise) rather than picked here, so a theme whose action hue is
189 /// pale gets dark ink without this renderer knowing which themes those are.
190 ///
191 /// The one thing that fills with `action` is the act a screen is for, the
192 /// leading control, which is why this colour exists.
193 /// A renderer that fills with the accent and leaves the label on the
194 /// ordinary content colour is one theme change away from unreadable.
195 pub content_on_action: Color32,
196 /// `danger`.
197 ///
198 /// A field's error message, a destructive control, a bar that has run over.
199 pub danger: Color32,
200 /// `success`.
201 ///
202 /// The three status intents arrive together and not one at a time:
203 /// [`Tone`] is five members wide and a resolver missing one has to invent
204 /// a colour for it, which is the substitution [`Palette::fill`] refuses.
205 pub success: Color32,
206 /// `warning`.
207 pub warning: Color32,
208 /// `info`.
209 pub info: Color32,
210 /// `border`, the authored line colour.
211 ///
212 /// A neutral badge's edge: a badge on the raised ground is raised too, so
213 /// the edge is what draws it.
214 pub border: Color32,
215 /// `info-surface`: raised with 12 percent of `info`. A badge's fill.
216 ///
217 /// The four tone surfaces arrive together for the status intents' reason.
218 pub info_surface: Color32,
219 /// `success-surface`.
220 pub success_surface: Color32,
221 /// `warning-surface`.
222 pub warning_surface: Color32,
223 /// `danger-surface`.
224 pub danger_surface: Color32,
225 /// `row-hover`: the row under the pointer, at 9 percent.
226 pub row_hover: Color32,
227 /// `row-rule`: the hairline between rows and around a table, at 26
228 /// percent.
229 pub row_rule: Color32,
230 /// `row-selected`: a selected row, raised with 18 percent of the accent.
231 ///
232 /// A fill and never a foreground, so a row that is red for a failure stays
233 /// red while it is selected.
234 pub row_selected: Color32,
235 /// `heat-0` to `heat-4`: the measure ramp, quietest first, from the
236 /// raised ground to the cursor row's mix. Read through
237 /// [`heat`](Self::heat).
238 pub heats: [Color32; HEAT_BANDS as usize],
239}
240
241impl Palette {
242 /// Every surface `page` and every ink `ink`, with no cast shadow.
243 ///
244 /// A starting point for the setters, legible on its own and wrong in every
245 /// detail a theme decides: an app that resolves its own colours starts here
246 /// and sets each one, and a colour added to this type later arrives at one
247 /// of these two rather than as a compile error in every consumer.
248 #[must_use]
249 pub const fn two_tone(page: Color32, ink: Color32) -> Self {
250 Self {
251 page,
252 raised: page,
253 overlay: page,
254 well: page,
255 sunken: page,
256 bevel_light: page,
257 bevel_dark: ink,
258 elevation: Color32::TRANSPARENT,
259 content: ink,
260 content_secondary: ink,
261 content_muted: ink,
262 content_disabled: ink,
263 action: ink,
264 content_on_action: page,
265 danger: ink,
266 success: ink,
267 warning: ink,
268 info: ink,
269 border: ink,
270 info_surface: page,
271 success_surface: page,
272 warning_surface: page,
273 danger_surface: page,
274 row_hover: page,
275 row_rule: ink,
276 row_selected: page,
277 heats: [page; HEAT_BANDS as usize],
278 }
279 }
280
281 /// Set [`page`](Self::page).
282 #[must_use]
283 pub const fn page(mut self, colour: Color32) -> Self {
284 self.page = colour;
285 self
286 }
287
288 /// Set [`raised`](Self::raised).
289 #[must_use]
290 pub const fn raised(mut self, colour: Color32) -> Self {
291 self.raised = colour;
292 self
293 }
294
295 /// Set [`overlay`](Self::overlay).
296 #[must_use]
297 pub const fn overlay(mut self, colour: Color32) -> Self {
298 self.overlay = colour;
299 self
300 }
301
302 /// Set [`well`](Self::well).
303 #[must_use]
304 pub const fn well(mut self, colour: Color32) -> Self {
305 self.well = colour;
306 self
307 }
308
309 /// Set [`sunken`](Self::sunken).
310 #[must_use]
311 pub const fn sunken(mut self, colour: Color32) -> Self {
312 self.sunken = colour;
313 self
314 }
315
316 /// Set [`bevel_light`](Self::bevel_light).
317 #[must_use]
318 pub const fn bevel_light(mut self, colour: Color32) -> Self {
319 self.bevel_light = colour;
320 self
321 }
322
323 /// Set [`bevel_dark`](Self::bevel_dark).
324 #[must_use]
325 pub const fn bevel_dark(mut self, colour: Color32) -> Self {
326 self.bevel_dark = colour;
327 self
328 }
329
330 /// Set [`elevation`](Self::elevation).
331 #[must_use]
332 pub const fn elevation(mut self, colour: Color32) -> Self {
333 self.elevation = colour;
334 self
335 }
336
337 /// Set [`content`](Self::content).
338 #[must_use]
339 pub const fn content(mut self, colour: Color32) -> Self {
340 self.content = colour;
341 self
342 }
343
344 /// Set [`content_secondary`](Self::content_secondary).
345 #[must_use]
346 pub const fn content_secondary(mut self, colour: Color32) -> Self {
347 self.content_secondary = colour;
348 self
349 }
350
351 /// Set [`content_muted`](Self::content_muted).
352 #[must_use]
353 pub const fn content_muted(mut self, colour: Color32) -> Self {
354 self.content_muted = colour;
355 self
356 }
357
358 /// Set [`content_disabled`](Self::content_disabled).
359 #[must_use]
360 pub const fn content_disabled(mut self, colour: Color32) -> Self {
361 self.content_disabled = colour;
362 self
363 }
364
365 /// Set [`action`](Self::action).
366 #[must_use]
367 pub const fn action(mut self, colour: Color32) -> Self {
368 self.action = colour;
369 self
370 }
371
372 /// Set [`content_on_action`](Self::content_on_action).
373 #[must_use]
374 pub const fn content_on_action(mut self, colour: Color32) -> Self {
375 self.content_on_action = colour;
376 self
377 }
378
379 /// Set [`danger`](Self::danger).
380 #[must_use]
381 pub const fn danger(mut self, colour: Color32) -> Self {
382 self.danger = colour;
383 self
384 }
385
386 /// Set [`success`](Self::success).
387 #[must_use]
388 pub const fn success(mut self, colour: Color32) -> Self {
389 self.success = colour;
390 self
391 }
392
393 /// Set [`warning`](Self::warning).
394 #[must_use]
395 pub const fn warning(mut self, colour: Color32) -> Self {
396 self.warning = colour;
397 self
398 }
399
400 /// Set [`info`](Self::info).
401 #[must_use]
402 pub const fn info(mut self, colour: Color32) -> Self {
403 self.info = colour;
404 self
405 }
406
407 /// Set [`border`](Self::border).
408 #[must_use]
409 pub const fn border(mut self, colour: Color32) -> Self {
410 self.border = colour;
411 self
412 }
413
414 /// Set [`info_surface`](Self::info_surface).
415 #[must_use]
416 pub const fn info_surface(mut self, colour: Color32) -> Self {
417 self.info_surface = colour;
418 self
419 }
420
421 /// Set [`success_surface`](Self::success_surface).
422 #[must_use]
423 pub const fn success_surface(mut self, colour: Color32) -> Self {
424 self.success_surface = colour;
425 self
426 }
427
428 /// Set [`warning_surface`](Self::warning_surface).
429 #[must_use]
430 pub const fn warning_surface(mut self, colour: Color32) -> Self {
431 self.warning_surface = colour;
432 self
433 }
434
435 /// Set [`danger_surface`](Self::danger_surface).
436 #[must_use]
437 pub const fn danger_surface(mut self, colour: Color32) -> Self {
438 self.danger_surface = colour;
439 self
440 }
441
442 /// Set [`row_hover`](Self::row_hover).
443 #[must_use]
444 pub const fn row_hover(mut self, colour: Color32) -> Self {
445 self.row_hover = colour;
446 self
447 }
448
449 /// Set [`row_rule`](Self::row_rule).
450 #[must_use]
451 pub const fn row_rule(mut self, colour: Color32) -> Self {
452 self.row_rule = colour;
453 self
454 }
455
456 /// Set [`row_selected`](Self::row_selected).
457 #[must_use]
458 pub const fn row_selected(mut self, colour: Color32) -> Self {
459 self.row_selected = colour;
460 self
461 }
462
463 /// Set [`heats`](Self::heats).
464 #[must_use]
465 pub const fn heats(mut self, ramp: [Color32; HEAT_BANDS as usize]) -> Self {
466 self.heats = ramp;
467 self
468 }
469
470 /// Every colour, read from a resolved makeover theme.
471 ///
472 /// # Errors
473 ///
474 /// [`MissingToken`] naming the first token the theme does not resolve.
475 /// makeover derives every one of these for every shipped theme, so this
476 /// fails only on a theme file missing a base intent.
477 #[cfg(feature = "theme")]
478 pub fn from_theme(tokens: &makeover::SemanticTokens) -> Result<Self, MissingToken> {
479 use makeover::Token;
480 let colour = |token: Token| {
481 tokens
482 .rgba(token)
483 .map(|(r, g, b, a)| Color32::from_rgba_unmultiplied(r, g, b, a))
484 .ok_or(MissingToken(token))
485 };
486 Ok(Self {
487 page: colour(Token::SurfacePage)?,
488 raised: colour(Token::SurfaceRaised)?,
489 overlay: colour(Token::SurfaceOverlay)?,
490 well: colour(Token::SurfaceWell)?,
491 sunken: colour(Token::SurfaceSunken)?,
492 bevel_light: colour(Token::BevelLight)?,
493 bevel_dark: colour(Token::BevelDark)?,
494 elevation: colour(Token::Elevation)?,
495 content: colour(Token::Content)?,
496 content_secondary: colour(Token::ContentSecondary)?,
497 content_muted: colour(Token::ContentMuted)?,
498 content_disabled: colour(Token::ContentDisabled)?,
499 action: colour(Token::Action)?,
500 content_on_action: colour(Token::ContentOnAction)?,
501 danger: colour(Token::Danger)?,
502 success: colour(Token::Success)?,
503 warning: colour(Token::Warning)?,
504 info: colour(Token::Info)?,
505 border: colour(Token::Border)?,
506 info_surface: colour(Token::InfoSurface)?,
507 success_surface: colour(Token::SuccessSurface)?,
508 warning_surface: colour(Token::WarningSurface)?,
509 danger_surface: colour(Token::DangerSurface)?,
510 row_hover: colour(Token::RowHover)?,
511 row_rule: colour(Token::RowRule)?,
512 row_selected: colour(Token::RowSelected)?,
513 heats: [
514 colour(Token::Heat0)?,
515 colour(Token::Heat1)?,
516 colour(Token::Heat2)?,
517 colour(Token::Heat3)?,
518 colour(Token::Heat4)?,
519 ],
520 })
521 }
522}
523
524/// A token `Palette::from_theme` needed and the theme did not resolve.
525#[cfg(feature = "theme")]
526#[derive(Debug, Clone, Copy, PartialEq, Eq)]
527pub struct MissingToken(pub makeover::Token);
528
529#[cfg(feature = "theme")]
530impl std::fmt::Display for MissingToken {
531 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
532 write!(f, "the theme resolves no `{}`", self.0.as_str())
533 }
534}
535
536#[cfg(feature = "theme")]
537impl std::error::Error for MissingToken {}
538
539impl Palette {
540 /// Resolve a surface intent, or `None` for one this renderer does not know.
541 ///
542 /// A plain lookup, and no substitution.
543 ///
544 /// `Option`, because [`Fill`] is `#[non_exhaustive]` and a total function
545 /// over an open enum can only stay total by inventing a colour for a member
546 /// it has never heard of. Every member the description has today is
547 /// answered with `Some`.
548 #[must_use]
549 pub const fn fill(&self, fill: Fill) -> Option<Color32> {
550 match fill {
551 Fill::Page => Some(self.page),
552 Fill::Raised => Some(self.raised),
553 Fill::Overlay => Some(self.overlay),
554 Fill::Well => Some(self.well),
555 Fill::Sunken => Some(self.sunken),
556 _ => None,
557 }
558 }
559
560 /// The colour a [`Tone`] reads as.
561 ///
562 /// Total, unlike [`fill`](Self::fill), and the difference is not an
563 /// inconsistency. `Fill` is `#[non_exhaustive]` and `Tone` is not: the
564 /// description layer settled tone at five members and grows surfaces, so a
565 /// total function here cannot be made to invent a colour by an upstream
566 /// release the way a total `fill` could.
567 ///
568 /// [`Tone::Neutral`] is [`content`](Self::content) rather than a colour of
569 /// its own, which is what "an ordinary fact" means: a neutral badge is text
570 /// in a box, not a fifth status.
571 #[must_use]
572 pub const fn tone(&self, tone: Tone) -> Color32 {
573 match tone {
574 Tone::Neutral => self.content,
575 Tone::Info => self.info,
576 Tone::Success => self.success,
577 Tone::Warning => self.warning,
578 Tone::Danger => self.danger,
579 // A tone this renderer has not learnt yet reads as an ordinary
580 // fact rather than as a status it might misstate.
581 _ => self.content,
582 }
583 }
584
585 /// The fill a measure band sits on, or `None` at band 0, which is the
586 /// ground and draws nothing. A band past the last reads as the last.
587 #[must_use]
588 pub const fn heat(&self, heat: Heat) -> Option<Color32> {
589 let last = HEAT_BANDS - 1;
590 match if heat.0 > last { last } else { heat.0 } {
591 0 => None,
592 band => Some(self.heats[band as usize]),
593 }
594 }
595
596 /// What a badge of this tone is filled with: its tone surface, or the
597 /// raised surface for [`Tone::Neutral`], as `makeover-webview` fills one.
598 #[must_use]
599 pub const fn tone_surface(&self, tone: Tone) -> Color32 {
600 match tone {
601 Tone::Neutral => self.raised,
602 Tone::Info => self.info_surface,
603 Tone::Success => self.success_surface,
604 Tone::Warning => self.warning_surface,
605 Tone::Danger => self.danger_surface,
606 _ => self.raised,
607 }
608 }
609
610 /// What a badge of this tone is edged with: its tone, or
611 /// [`border`](Self::border) for [`Tone::Neutral`], whose tone is the ink.
612 #[must_use]
613 pub const fn tone_edge(&self, tone: Tone) -> Color32 {
614 match tone {
615 Tone::Neutral => self.border,
616 other => self.tone(other),
617 }
618 }
619
620 /// The cast shadow for a surface that overlays the page.
621 ///
622 /// What "overlaying" means in immediate mode, answered rather than skipped.
623 /// egui already paints shadows for its menus and windows through
624 /// [`egui::Frame::shadow`], so the honest port is to hand that machinery the
625 /// theme's tone instead of egui's own default, not to invent a painter here
626 /// the way [`paint_bevel`] had to.
627 ///
628 /// The geometry matches what `makeover-webview` composes, in points rather
629 /// than pixels: a small downward offset and a wide soft blur. A Platinum-era
630 /// menu sits just off the page rather than hovering above it.
631 ///
632 /// ```no_run
633 /// # let palette: makeover_immediate::Palette = unimplemented!();
634 /// # let ui: &mut egui::Ui = unimplemented!();
635 /// egui::Frame::popup(ui.style())
636 /// .shadow(palette.cast())
637 /// .show(ui, |ui| { ui.label("over the page"); });
638 /// ```
639 #[must_use]
640 pub const fn cast(&self) -> egui::Shadow {
641 egui::Shadow {
642 offset: [0, 2],
643 blur: 24,
644 spread: 0,
645 color: self.elevation,
646 }
647 }
648
649 /// Resolve a bevel edge intent.
650 #[must_use]
651 pub const fn edge(&self, edge: Edge) -> Color32 {
652 match edge {
653 Edge::Light => self.bevel_light,
654 Edge::Dark => self.bevel_dark,
655 // An edge this renderer has not learnt is drawn as the border, the
656 // one line every surface already has.
657 _ => self.border,
658 }
659 }
660}
661
662/// The geometry a framed region is drawn with.
663///
664/// Every field is a value, which is why they all arrive from the caller:
665/// radius and border width belong to `makeover-geometry`, and margins come
666/// from its relational gaps.
667#[derive(Debug, Clone, Copy, PartialEq)]
668pub struct FrameStyle {
669 /// Corner radius. Square under the Platinum default.
670 pub radius: CornerRadius,
671 /// Inner margin between the frame and its contents.
672 pub margin: Margin,
673 /// Bevel stroke width, in points.
674 pub stroke: f32,
675}
676
677impl Default for FrameStyle {
678 /// A one-point square frame with no inner margin.
679 fn default() -> Self {
680 Self {
681 radius: CornerRadius::ZERO,
682 margin: Margin::ZERO,
683 stroke: f32::from(makeover_geometry::Stroke::Hairline.px()),
684 }
685 }
686}
687
688/// Paint a two-tone edge just inside `rect`.
689///
690/// Fill first, bevel after: this adds two polylines and nothing else, so it
691/// composes over whatever is already there. That is what lets it go over an
692/// [`egui::TextEdit`] after `ui.add`, where the widget's own fill has landed.
693///
694/// Two three-point polylines meeting at opposite corners, rather than four
695/// segments, so egui mitres the corner joins instead of leaving a notch.
696///
697/// The dark polyline is drawn second, so the two corners where the runs meet
698/// take its tone. That is the right answer here rather than a concession.
699/// [`makeover_layout::Bevel`] holds those corners to belong to both edges, and
700/// a renderer with room to divide one should; at the default one-point stroke
701/// the corner is a one-point square, so the division is sub-pixel and
702/// antialiasing resolves it to the same blend the mitre already gives. Splitting
703/// it would add a seam and no information. `makeover-tui` does split, because a
704/// terminal cell is large enough that not splitting costs a visible cell of edge
705/// weight. The same rule, at a resolution where it has something to say.
706pub fn paint_bevel(painter: &Painter, rect: Rect, bevel: Bevel, palette: &Palette, stroke: f32) {
707 let (top_left, bottom_right) = bevel.edges();
708
709 // Inset by half a stroke so the line lands inside `rect` rather than
710 // straddling its edge, which on a fractional-scale display is the
711 // difference between one crisp pixel and two dim ones.
712 let r = rect.shrink(stroke / 2.0);
713
714 painter.add(Shape::line(
715 vec![r.left_bottom(), r.left_top(), r.right_top()],
716 Stroke::new(stroke, palette.edge(top_left)),
717 ));
718 // Three points close the box, two leave the bottom open: the shaded run
719 // comes down the right side and stops. That is the folder tab, and it is
720 // the same edge the browser draws by dropping the shadow's vertical
721 // offset. The lit polyline is untouched either way, so the join is the
722 // only thing that changes.
723 let shaded = if bevel.draws_bottom() {
724 vec![r.right_top(), r.right_bottom(), r.left_bottom()]
725 } else {
726 vec![r.right_top(), r.right_bottom()]
727 };
728 painter.add(Shape::line(
729 shaded,
730 Stroke::new(stroke, palette.edge(bottom_right)),
731 ));
732}
733
734/// Draw a region at a given [`Depth`]: its fill and its edge, together.
735///
736/// [`Depth::Flat`] gets neither, and inherits whatever it sits on. That is the
737/// difference between level-with and painted-the-same-colour, and it is the
738/// reason `Depth::fill` returns an [`Option`] rather than defaulting to the
739/// page.
740pub fn frame<R>(
741 ui: &mut Ui,
742 depth: Depth,
743 palette: &Palette,
744 style: FrameStyle,
745 add_contents: impl FnOnce(&mut Ui) -> R,
746) -> R {
747 let mut f = egui::Frame::new()
748 .corner_radius(style.radius)
749 .inner_margin(style.margin);
750 // Two ways there is no fill to paint, and they collapse to the same
751 // outcome: the depth names none (Depth::Flat), or it names one this
752 // renderer cannot resolve. Either way the frame goes unfilled and the
753 // bevel below carries the depth on its own, which is the rule this
754 // module already documents for Flat.
755 if let Some(fill) = depth.fill().and_then(|f| palette.fill(f)) {
756 f = f.fill(fill);
757 }
758 // A surface that overlays the page is cast onto it, with
759 // [`Palette::cast`]. Keyed off the fill rather than the variant, so it stays right for whatever else the description calls an
760 // overlay later.
761 if depth.fill() == Some(Fill::Overlay) {
762 f = f.shadow(palette.cast());
763 }
764 let framed = f.show(ui, add_contents);
765 if let Some(bevel) = depth.bevel() {
766 paint_bevel(
767 ui.painter(),
768 framed.response.rect,
769 bevel,
770 palette,
771 style.stroke,
772 );
773 }
774 framed.inner
775}
776
777/// The geometry a field group is drawn with.
778///
779/// The fields themselves are drawn by `quasi-immediate`; the style lives here
780/// beside [`FrameStyle`], which it embeds, so an app sets both in one place.
781/// Values again, for the reason [`FrameStyle`] is: every number here belongs to
782/// `makeover-geometry` and arrives already resolved.
783#[derive(Debug, Clone, Copy, PartialEq)]
784pub struct FieldStyle {
785 /// The well a text control sits in.
786 pub frame: FrameStyle,
787 /// Between a field's own parts: its label, its control, its hint and its
788 /// error.
789 pub gap: f32,
790 /// Between one field and the next.
791 pub group_gap: f32,
792 /// What marks a required field, appended to its label.
793 ///
794 /// A knob rather than a constant, because it is the one piece of *copy* in
795 /// this crate and copy is not a renderer's call. A webview does not need it
796 /// at all (it emits the `required` attribute and the browser answers), so
797 /// this renderer is the first place where a compulsory field either shows
798 /// that it is or silently does not.
799 pub required_marker: &'static str,
800}
801
802impl Default for FieldStyle {
803 /// The default frame, no gaps, and an asterisk.
804 fn default() -> Self {
805 Self {
806 frame: FrameStyle::default(),
807 gap: 0.0,
808 group_gap: 0.0,
809 required_marker: "*",
810 }
811 }
812}
813
814/// What the field currently holds, borrowed from wherever the app keeps it.
815///
816/// Handed to `quasi-immediate`'s field, which writes through it as the user
817/// edits.
818///
819/// The editable counterpart of [`makeover_layout::Value`], which is what the
820/// other renderers read: there the value is read back after the fact, and here
821/// the widget writes through this borrow as it is edited. The description
822/// carries neither, for the same reason.
823///
824/// An enum rather than a bag of options, on the reasoning
825/// [`makeover_layout::Value`] records: a checkbox holding a string is
826/// unsayable here, where a struct would let it be said and then have to cope.
827///
828/// `#[non_exhaustive]`: a host builds these and never matches on them, so the
829/// next shape of held value costs nobody a match arm.
830#[derive(Debug, Default)]
831#[non_exhaustive]
832pub enum Editing<'a> {
833 /// Nothing to edit. The control is drawn and does not answer.
834 #[default]
835 Absent,
836 /// The buffer behind anything that takes typed text, a select included:
837 /// what a select holds is the `value` of one of its options.
838 Text(&'a mut String),
839 /// A checkbox, on or off.
840 On(&'a mut bool),
841 /// The values of a [`FieldKind::Checklist`](makeover_layout::FieldKind::Checklist)'s ticked options.
842 ///
843 /// The values rather than a bool per option, because the options are the
844 /// description's and the set is the app's: a host keeps what was ticked
845 /// under the option values it submits, and a parallel list of bools would
846 /// have to be re-aligned with the options every time the list changed.
847 /// Ticking pushes the option's value and unticking removes it, so the order
848 /// is the order things were ticked in, which is no order a handler should
849 /// read anything into.
850 Ticked(&'a mut Vec<String>),
851 /// The two buffers behind a [`FieldKind::Interval`](makeover_layout::FieldKind::Interval), lower first.
852 ///
853 /// Two buffers rather than one string with a separator: an
854 /// interval is submitted under two names, so it is edited as two values,
855 /// and a delimiter this crate owned could appear inside either of them.
856 ///
857 /// Either end may be empty while the other stands. An open end is an
858 /// answer ("over 120 BPM") rather than a half-filled box.
859 Between {
860 /// The lower end's buffer.
861 lower: &'a mut String,
862 /// The upper end's buffer.
863 upper: &'a mut String,
864 },
865}
866
867#[cfg(test)]
868mod tests;