//! The immediate-mode renderer for [`makeover_layout`]. //! //! //! //! Named for the mode, not the library, the way `makeover-tui` is named for //! the target and not for ratatui. Immediate mode is the constraint that //! actually separates this renderer from the other two, and egui is the //! backend it is written against. //! //! It is the harshest renderer the description has to survive: no //! `box-shadow`, no `inset`, no cascade, no retained tree to mutate, and //! `Visuals.widgets.*.bg_stroke` is a single stroke with no per-side control. //! A two-tone lit edge is not something egui can be configured into producing, //! so it gets painted by hand here, once, instead of in every consuming app. //! //! # What this crate does and does not own //! //! It owns the *expression*: two mitred polylines for a bevel and a `Frame` //! for a filled region. It owns no colours and no sizes, and no longer owns a //! substitution: it briefly supplied the page for a well, which was a stand-in //! for `surface-well` before makeover derived it, and every consumer reads the //! real token now. [`Palette`] is supplied by the caller, //! already resolved, and every radius, margin and stroke width arrives in //! [`FrameStyle`]. //! //! That split is why the crate has no dependency on `makeover` itself: the app //! already resolves a theme, and coupling a renderer to a colour crate's //! version would buy nothing. //! //! # The cascade is the real difference //! //! A stylesheet can say "a pressed button inverts its bevel" once and let the //! cascade carry it. An immediate-mode renderer has nowhere to put that, so //! every call site decides. [`makeover_layout::Depth::pressed`] is what keeps //! the decision from being re-derived per widget. //! //! # Forms //! //! 0.5.0 adds the field vocabulary on top of the depth vocabulary: //! [`makeover_layout::Field`] rendered to egui widgets, in [`field`], and a set //! of them laid down a column in [`group`]. Before it, a description saying //! "text field, labelled, required, with this hint" had no way to become a //! widget here, and audiofiles' forms stayed hand-rolled. //! //! `makeover-webview` got there first and its form emitter is the precedent //! followed rather than re-derived, including the parts that are bug fixes: a //! select handed a value none of its options carries keeps that value visible //! instead of silently reading as the first option, which is a save-the-wrong- //! thing bug goingson hit for real. //! //! What differs is forced by the mode and not chosen: //! //! - **The value arrives as a `&mut`.** [`Filling`] borrows the app's own field //! and the widget writes through it. There is no DOM to read back out of, //! which is also why the description deliberately does not carry the value. //! - **A text control is drawn as a well and a select is not.** The description //! holds that a well is for anything the user looks *into*, and a text field //! is its own example; a select and a checkbox are pressed rather than looked //! into, so they keep egui's own control painting. //! - **[`makeover_layout::State::Focus`] is not drawn here.** egui already //! paints exactly one focus stroke, and the description's rule is one ring //! rather than a ring per primitive, so adding a second would break the rule //! it came from. [`makeover_layout::State::Disabled`] *is* drawn, because egui //! has no opinion about it until told. #![forbid(unsafe_code)] use egui::{ Color32, ComboBox, CornerRadius, Margin, Painter, Rect, Response, RichText, Shape, Stroke, TextEdit, Ui, }; use makeover_layout::{Bevel, Choice, Depth, Edge, Field, FieldKind, Fill, State}; /// The resolved colours this renderer needs, as flat values. /// /// Built by the app from whatever it already uses to resolve a theme, then /// held and reused. Deliberately not a trait and not string-keyed: a bevel is /// painted per widget per frame, and a map lookup per edge is a cost with /// nothing to show for it. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Palette { /// `surface-page`. pub page: Color32, /// `surface-raised`. pub raised: Color32, /// `surface-overlay`. pub overlay: Color32, /// `surface-well`. /// /// Required, not optional. makeover derives it for every theme from 2.3.0, /// so a resolved palette without a well is not a thing that exists here. /// It was an `Option` while that was untrue, and this renderer substituted /// the page; `makeover-tui` keeps its own `Option` for a different reason, /// since a terminal can have the colour and still be unable to show it. pub well: Color32, /// `surface-sunken`. /// /// A surface set back from the one it sits on, by colour and nothing else. /// Not a well: a well is a hole with an edge, and this has no edge. An /// immediate-mode renderer paints an arbitrary rect, so unlike /// `makeover-tui` it has no excuse for declining this one. /// /// Required rather than optional, on the same footing as `well`: all 31 /// themes makeover embeds author it. pub sunken: Color32, /// `bevel-light`. pub bevel_light: Color32, /// `bevel-dark`. pub bevel_dark: Color32, /// `elevation`. /// /// What a surface that floats OVER the page is cast onto it with. The one /// intent here that is about a surface's relationship to the page rather /// than about the surface, which is why it is a translucent near-black on /// every theme rather than something read off the palette's own ramp. /// /// **Only for a surface that overlays.** A menu, a tooltip, a modal. A /// surface *in* the layout takes a bevel, and reaching for this on a panel /// or a card is how a pre-Platinum look survives a conversion under a new /// name. /// /// egui has a real answer for this where a terminal does not: see /// [`Palette::cast`], which is the shadow to hand an /// [`egui::Frame`](egui::Frame). pub elevation: Color32, /// `content`. /// /// Ordinary text. Added 0.5.0 with the field renderer, which is the first /// thing here that draws any: until then this crate painted surfaces and /// edges and let the caller's own egui visuals answer for text. pub content: Color32, /// `content-muted`. /// /// A field's hint, and what /// [`makeover_layout::State::Disabled`](makeover_layout::State::Disabled) /// resolves to. Both readings come from the description rather than from /// here: `State::Disabled` names this intent by token. pub content_muted: Color32, /// `danger`. /// /// A field's error message. The one [`makeover_layout::Tone`] this renderer /// needs so far, and it is here rather than as a whole resolved tone set /// because notices are not drawn here yet and a palette should carry what /// is used. pub danger: Color32, } impl Palette { /// Resolve a surface intent, or `None` for one this renderer does not know. /// /// A plain lookup. There is still no substitution: the old one existed only /// while `surface-well` was underived, and every consumer reads the real /// token now. /// /// `Option` since 0.3.0, because [`Fill`] became `#[non_exhaustive]` in /// `makeover-layout` 0.4.0 and a total function over an open enum can only /// stay total by inventing a colour for a member it has never heard of. /// That is the substitution this crate spent 0.2.0 removing, so the return /// type moved instead. Every member the description has today is answered /// with `Some`. #[must_use] pub const fn fill(&self, fill: Fill) -> Option { match fill { Fill::Page => Some(self.page), Fill::Raised => Some(self.raised), Fill::Overlay => Some(self.overlay), Fill::Well => Some(self.well), Fill::Sunken => Some(self.sunken), _ => None, } } /// The cast shadow for a surface that overlays the page. /// /// What "overlaying" means in immediate mode, answered rather than skipped. /// egui already paints shadows for its menus and windows through /// [`egui::Frame::shadow`], so the honest port is to hand that machinery the /// theme's tone instead of egui's own default, not to invent a painter here /// the way [`paint_bevel`] had to. /// /// The geometry matches what `makeover-webview` composes, in points rather /// than pixels: a small downward offset and a wide soft blur. A Platinum-era /// menu sits just off the page rather than hovering above it. /// /// ```no_run /// # let palette: makeover_immediate::Palette = unimplemented!(); /// # let ui: &mut egui::Ui = unimplemented!(); /// egui::Frame::popup(ui.style()) /// .shadow(palette.cast()) /// .show(ui, |ui| { ui.label("over the page"); }); /// ``` #[must_use] pub const fn cast(&self) -> egui::Shadow { egui::Shadow { offset: [0, 2], blur: 24, spread: 0, color: self.elevation, } } /// Resolve a bevel edge intent. #[must_use] pub const fn edge(&self, edge: Edge) -> Color32 { match edge { Edge::Light => self.bevel_light, Edge::Dark => self.bevel_dark, } } } /// The geometry a framed region is drawn with. /// /// Every field is a value, which is why they all arrive from the caller: /// radius and border width belong to `makeover-geometry`, and margins come /// from its relational gaps. #[derive(Debug, Clone, Copy, PartialEq)] pub struct FrameStyle { /// Corner radius. Square under the Platinum default. pub radius: CornerRadius, /// Inner margin between the frame and its contents. pub margin: Margin, /// Bevel stroke width, in points. pub stroke: f32, } impl Default for FrameStyle { /// A one-point square frame with no inner margin. fn default() -> Self { Self { radius: CornerRadius::ZERO, margin: Margin::ZERO, stroke: 1.0, } } } /// Paint a two-tone edge just inside `rect`. /// /// Fill first, bevel after: this adds two polylines and nothing else, so it /// composes over whatever is already there. That is what lets it go over an /// [`egui::TextEdit`] after `ui.add`, where the widget's own fill has landed. /// /// Two three-point polylines meeting at opposite corners, rather than four /// segments, so egui mitres the corner joins instead of leaving a notch. /// /// The dark polyline is drawn second, so the two corners where the runs meet /// take its tone. That is the right answer here rather than a concession. /// [`makeover_layout::Bevel`] holds those corners to belong to both edges, and /// a renderer with room to divide one should; at the default one-point stroke /// the corner is a one-point square, so the division is sub-pixel and /// antialiasing resolves it to the same blend the mitre already gives. Splitting /// it would add a seam and no information. `makeover-tui` does split, because a /// terminal cell is large enough that not splitting costs a visible cell of edge /// weight — the same rule, at a resolution where it has something to say. pub fn paint_bevel(painter: &Painter, rect: Rect, bevel: Bevel, palette: &Palette, stroke: f32) { let (top_left, bottom_right) = bevel.edges(); // Inset by half a stroke so the line lands inside `rect` rather than // straddling its edge, which on a fractional-scale display is the // difference between one crisp pixel and two dim ones. let r = rect.shrink(stroke / 2.0); painter.add(Shape::line( vec![r.left_bottom(), r.left_top(), r.right_top()], Stroke::new(stroke, palette.edge(top_left)), )); painter.add(Shape::line( vec![r.right_top(), r.right_bottom(), r.left_bottom()], Stroke::new(stroke, palette.edge(bottom_right)), )); } /// Draw a region at a given [`Depth`]: its fill and its edge, together. /// /// [`Depth::Flat`] gets neither, and inherits whatever it sits on. That is the /// difference between level-with and painted-the-same-colour, and it is the /// reason `Depth::fill` returns an [`Option`] rather than defaulting to the /// page. pub fn frame( ui: &mut Ui, depth: Depth, palette: &Palette, style: FrameStyle, add_contents: impl FnOnce(&mut Ui) -> R, ) -> R { let mut f = egui::Frame::new() .corner_radius(style.radius) .inner_margin(style.margin); // Two ways there is no fill to paint, and they collapse to the same // outcome: the depth names none (Depth::Flat), or it names one this // renderer cannot resolve. Either way the frame goes unfilled and the // bevel below carries the depth on its own, which is the rule this // module already documents for Flat. if let Some(fill) = depth.fill().and_then(|f| palette.fill(f)) { f = f.fill(fill); } let framed = f.show(ui, add_contents); if let Some(bevel) = depth.bevel() { paint_bevel( ui.painter(), framed.response.rect, bevel, palette, style.stroke, ); } framed.inner } /// The geometry a field group is drawn with. /// /// Values again, for the reason [`FrameStyle`] is: every number here belongs to /// `makeover-geometry` and arrives already resolved. #[derive(Debug, Clone, Copy, PartialEq)] pub struct FieldStyle { /// The well a text control sits in. pub frame: FrameStyle, /// Between a field's own parts: its label, its control, its hint and its /// error. pub gap: f32, /// Between one field and the next. pub group_gap: f32, /// What marks a required field, appended to its label. /// /// A knob rather than a constant, because it is the one piece of *copy* in /// this crate and copy is not a renderer's call. A webview does not need it /// at all — it emits the `required` attribute and the browser answers — so /// this renderer is the first place where a compulsory field either shows /// that it is or silently does not. pub required_marker: &'static str, } impl Default for FieldStyle { /// The default frame, no gaps, and an asterisk. fn default() -> Self { Self { frame: FrameStyle::default(), gap: 0.0, group_gap: 0.0, required_marker: "*", } } } /// What the field currently holds, borrowed from wherever the app keeps it. /// /// The immediate-mode counterpart of `makeover_webview::form::Value`, and the /// place the two renderers are forced apart: there the value is read back out /// of the DOM after the fact, and here the widget writes through this borrow as /// it is edited. Same reason the description carries neither. /// /// An enum rather than a bag of options, on the reasoning /// `makeover_webview::form::Value` records: a checkbox holding a string is /// unsayable here, where a struct would let it be said and then have to cope. #[derive(Debug, Default)] pub enum Filling<'a> { /// Nothing to edit. The control is drawn and does not answer. #[default] Absent, /// The buffer behind anything that takes typed text, a select included: /// what a select holds is the `value` of one of its [`Choice`]s. /// /// [`Choice`]: makeover_layout::Choice Text(&'a mut String), /// A checkbox, on or off. On(&'a mut bool), } /// The label, marked if the field is compulsory. fn label_text(field: &Field<'_>, style: &FieldStyle) -> String { if field.required { format!("{} {}", field.label, style.required_marker) } else { field.label.to_owned() } } /// The four shapes a control comes in here, which is fewer than there are /// kinds. /// /// [`FieldKind`] is `#[non_exhaustive]` and grows; this does not, because the /// ways egui has of asking for a value do not. Reducing the open set to this /// closed one in one total function is what keeps a new kind from needing a new /// arm at every match below. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Control { /// Typed into, so it is drawn as a well: the user looks into it. Typed, /// Picked from a control that shows one option at a time. Pressed rather /// than looked into, so egui's own control painting stands. Chosen, /// Picked from options that are all on screen at once. /// /// Apart from [`Chosen`](Self::Chosen) because the description holds them /// apart, and holding them apart is the whole content of /// [`FieldKind::Radio`]: same question, and an answer the user can read /// without opening anything. Listed, /// Held on or off. Toggled, } /// Which shape a kind takes. /// /// The wildcard falls to [`Control::Typed`] on purpose: a kind added to the /// description since this renderer was built degrades to a text box, which /// accepts any value the others would, rather than to nothing drawn at all. /// /// `FieldKind::File` lands there as of makeover-layout 0.11.0, and it is left /// there rather than grown a shape of its own. egui's honest answer is a button /// that opens a native picker, which is a fifth control and a file-dialog /// dependency; no consumer of this crate asks for a file field yet. Same /// position this crate took on `Meter` at 0.10.0: the membership test is that /// every renderer *could* answer honestly, not that each one does on the day. /// A path in a text box is not nothing, and it is what an app that needs this /// tomorrow gets today. const fn control_shape(kind: FieldKind) -> Control { match kind { FieldKind::Select => Control::Chosen, FieldKind::Radio => Control::Listed, FieldKind::Checkbox => Control::Toggled, _ => Control::Typed, } } /// What a select shows for the value it currently holds. /// /// A value no option carries stays on screen as itself rather than reading as /// whichever option happens to be first. goingson saved a backup retention of /// 10 against a 1/3/7/14/0 list and the browser silently showed it as 1, so the /// next save wrote a value nobody chose; `makeover-webview` grew the fix as a /// stray `