makeover-immediate 0.1.0

The immediate-mode renderer for makeover-layout. Immediate mode is the constraint that matters, not the library: no cascade, no retained tree, one stroke per widget. Backed by egui.
Documentation
//! The immediate-mode renderer for [`makeover_layout`].
//!
//! <!-- wiki: makeover-immediate -->
//!
//! 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, a `Frame` for a
//! filled region, and the decision of what to do when an intent has no colour
//! yet. It owns no colours and no sizes. [`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.

#![forbid(unsafe_code)]

use egui::{Color32, CornerRadius, Margin, Painter, Rect, Shape, Stroke, Ui};
use makeover_layout::{Bevel, Depth, Edge, Fill};

/// 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`, absent on makeover before 2.3.0.
    pub well: Option<Color32>,
    /// `bevel-light`.
    pub bevel_light: Color32,
    /// `bevel-dark`.
    pub bevel_dark: Color32,
}

impl Palette {
    /// Resolve a surface intent.
    ///
    /// `Fill::Well` substitutes the page when the theme has no `surface-well`,
    /// which is every theme on makeover before 2.3.0. That substitution lives
    /// here rather than in the description because it is only right for a
    /// renderer that can always paint an exact colour: makeover-tui had to
    /// reject it, since on a terminal the page is often the very surface the
    /// well is cut into and the two quantise together.
    ///
    /// Delete it once 2.3.0 is published and the consumers adopt it.
    #[must_use]
    pub fn fill(&self, fill: Fill) -> Color32 {
        match fill {
            Fill::Page => self.page,
            Fill::Raised => self.raised,
            Fill::Overlay => self.overlay,
            Fill::Well => self.well.unwrap_or(self.page),
        }
    }

    /// 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.
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<R>(
    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);
    if let Some(fill) = depth.fill() {
        f = f.fill(palette.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
}

#[cfg(test)]
mod tests {
    use super::*;

    fn palette(well: Option<Color32>) -> Palette {
        Palette {
            page: Color32::from_rgb(1, 1, 1),
            raised: Color32::from_rgb(2, 2, 2),
            overlay: Color32::from_rgb(3, 3, 3),
            well,
            bevel_light: Color32::WHITE,
            bevel_dark: Color32::BLACK,
        }
    }

    #[test]
    fn a_well_falls_back_to_the_page_before_makeover_2_3() {
        // This renderer's policy, not the description's. See makeover-tui,
        // which reaches the opposite conclusion for the same intent.
        let p = palette(None);
        assert_eq!(p.fill(Fill::Well), p.page);
        // and uses the real token once the theme carries one
        let w = Color32::from_rgb(9, 9, 9);
        assert_eq!(palette(Some(w)).fill(Fill::Well), w);
    }

    #[test]
    fn every_other_intent_resolves_without_a_fallback() {
        let p = palette(None);
        assert_eq!(p.fill(Fill::Page), p.page);
        assert_eq!(p.fill(Fill::Raised), p.raised);
        assert_eq!(p.fill(Fill::Overlay), p.overlay);
    }

    #[test]
    fn a_raised_region_never_resolves_to_the_well_fill() {
        // The cross-app bug, asserted at the renderer boundary this time.
        let p = palette(Some(Color32::from_rgb(9, 9, 9)));
        let raised = Depth::Raised.fill().map(|f| p.fill(f));
        let well = Depth::Well.fill().map(|f| p.fill(f));
        assert_eq!(raised, Some(p.raised));
        assert_ne!(raised, well);
    }

    #[test]
    fn the_lit_edge_swaps_when_a_card_is_pressed() {
        let p = palette(None);
        let (tl, _) = Depth::Raised.bevel().unwrap().edges();
        let (ptl, _) = Depth::Raised.pressed().bevel().unwrap().edges();
        assert_eq!(p.edge(tl), p.bevel_light);
        assert_eq!(p.edge(ptl), p.bevel_dark);
    }

    #[test]
    fn flat_asks_for_neither_fill_nor_edge() {
        assert!(Depth::Flat.fill().is_none());
        assert!(Depth::Flat.bevel().is_none());
    }

    #[test]
    fn the_default_frame_is_square_and_one_point() {
        let d = FrameStyle::default();
        assert_eq!(d.radius, CornerRadius::ZERO);
        assert_eq!(d.margin, Margin::ZERO);
        assert!((d.stroke - 1.0).abs() < f32::EPSILON);
    }
}