Skip to main content

eternal_ui/
render.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! What a rendering backend has to provide.
6//!
7//! The toolkit never draws anything itself. It measures text through
8//! [`Fonts`] and paints through [`Renderer`], and a backend crate implements
9//! both for a particular graphics library. `eternal-ui-skia` does so for
10//! Skia; the same two traits are all a Vello or tiny-skia backend would need.
11
12use eternal_styler::{Color, ComputedStyle, Corners, FontFamily, FontStyle, FontWeight, Sides};
13
14use crate::geometry::{Point, Rect};
15
16/// The font a piece of text is set in, taken from a computed style.
17#[derive(Clone, Debug, PartialEq)]
18pub struct FontSpec {
19    pub family: FontFamily,
20    /// In pixels.
21    pub size: f32,
22    pub weight: FontWeight,
23    pub style: FontStyle,
24    /// The line box height in pixels, or `None` for the font's own.
25    pub line_height: Option<f32>,
26}
27
28impl FontSpec {
29    pub fn from_style(style: &ComputedStyle) -> Self {
30        Self {
31            family: style.font_family.clone(),
32            size: style.font_size,
33            weight: style.font_weight,
34            style: style.font_style,
35            line_height: style.line_height.resolve(style.font_size),
36        }
37    }
38}
39
40/// How much room a run of text takes.
41#[derive(Clone, Copy, Debug, PartialEq, Default)]
42pub struct TextMetrics {
43    /// The advance width of the whole run.
44    pub width: f32,
45    /// Distance from the baseline up to the top of the line box.
46    pub ascent: f32,
47    /// Distance from the baseline down to the bottom of the line box.
48    pub descent: f32,
49    /// The height of the line box. At least `ascent + descent`, more if the
50    /// style asked for a taller line.
51    pub line_height: f32,
52}
53
54/// Measures text. Implemented by a backend, since only it knows the fonts.
55pub trait Fonts {
56    fn measure(&self, text: &str, font: &FontSpec) -> TextMetrics;
57}
58
59/// Draws. Implemented by a backend for one frame's drawing target.
60///
61/// Coordinates are window pixels with the origin at the top left. Colours
62/// are straight-alpha sRGB. Rectangles are filled and stroked without
63/// anti-aliasing where the backend can manage it, so that 1px borders stay
64/// crisp.
65pub trait Renderer {
66    fn fill_rect(&mut self, rect: Rect, radius: Corners<f32>, color: Color);
67
68    /// A border drawn inside `rect`, one width and colour per side.
69    fn border(
70        &mut self,
71        rect: Rect,
72        widths: Sides<f32>,
73        colors: Sides<Color>,
74        radius: Corners<f32>,
75    );
76
77    /// A single line of text, its line box starting at `top_left`. The
78    /// backend places the baseline inside the line box the same way
79    /// [`Fonts::measure`] measured it.
80    fn text(&mut self, text: &str, font: &FontSpec, top_left: Point, color: Color);
81
82    /// Restricts drawing to `rect` until the matching [`pop_clip`](Self::pop_clip).
83    fn push_clip(&mut self, rect: Rect);
84
85    fn pop_clip(&mut self);
86
87    /// Draws everything until the matching [`pop_opacity`](Self::pop_opacity)
88    /// through a layer with the given opacity.
89    fn push_opacity(&mut self, opacity: f32);
90
91    fn pop_opacity(&mut self);
92}
93
94/// A font source that pretends every glyph is the same width.
95///
96/// For tests, and for laying out without a real backend. Each character is
97/// `advance` times the font size wide; the line box is 1.25 times the font
98/// size high unless the style says otherwise.
99#[derive(Clone, Debug)]
100pub struct MonospaceFonts {
101    pub advance: f32,
102}
103
104impl Default for MonospaceFonts {
105    fn default() -> Self {
106        Self { advance: 0.6 }
107    }
108}
109
110impl Fonts for MonospaceFonts {
111    fn measure(&self, text: &str, font: &FontSpec) -> TextMetrics {
112        let ascent = font.size * 1.0;
113        let descent = font.size * 0.25;
114        TextMetrics {
115            width: text.chars().count() as f32 * self.advance * font.size,
116            ascent,
117            descent,
118            line_height: font.line_height.unwrap_or(ascent + descent),
119        }
120    }
121}
122
123/// One drawing call, as recorded by [`RecordingRenderer`].
124#[derive(Clone, Debug, PartialEq)]
125pub enum DrawOp {
126    FillRect {
127        rect: Rect,
128        radius: Corners<f32>,
129        color: Color,
130    },
131    Border {
132        rect: Rect,
133        widths: Sides<f32>,
134        colors: Sides<Color>,
135        radius: Corners<f32>,
136    },
137    Text {
138        text: String,
139        font: FontSpec,
140        top_left: Point,
141        color: Color,
142    },
143    PushClip(Rect),
144    PopClip,
145    PushOpacity(f32),
146    PopOpacity,
147}
148
149/// A renderer that records what it was asked to draw, for tests and for
150/// inspecting what a frame would contain.
151#[derive(Clone, Debug, Default)]
152pub struct RecordingRenderer {
153    pub ops: Vec<DrawOp>,
154}
155
156impl Renderer for RecordingRenderer {
157    fn fill_rect(&mut self, rect: Rect, radius: Corners<f32>, color: Color) {
158        self.ops.push(DrawOp::FillRect {
159            rect,
160            radius,
161            color,
162        });
163    }
164
165    fn border(
166        &mut self,
167        rect: Rect,
168        widths: Sides<f32>,
169        colors: Sides<Color>,
170        radius: Corners<f32>,
171    ) {
172        self.ops.push(DrawOp::Border {
173            rect,
174            widths,
175            colors,
176            radius,
177        });
178    }
179
180    fn text(&mut self, text: &str, font: &FontSpec, top_left: Point, color: Color) {
181        self.ops.push(DrawOp::Text {
182            text: text.to_owned(),
183            font: font.clone(),
184            top_left,
185            color,
186        });
187    }
188
189    fn push_clip(&mut self, rect: Rect) {
190        self.ops.push(DrawOp::PushClip(rect));
191    }
192
193    fn pop_clip(&mut self) {
194        self.ops.push(DrawOp::PopClip);
195    }
196
197    fn push_opacity(&mut self, opacity: f32) {
198        self.ops.push(DrawOp::PushOpacity(opacity));
199    }
200
201    fn pop_opacity(&mut self) {
202        self.ops.push(DrawOp::PopOpacity);
203    }
204}