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