Skip to main content

devpage_design/render/
mod.rs

1//! Scene → drawing. The engine lays a scene out ([`layout`]: taffy, parley),
2//! paints each node's own commands ([`painter`]) into a [`Drawing`]
3//! ([`drawing`]): its display list in chunks under property trees, kept and
4//! brought up to date by what changes ([`update`]). No pixels are made here:
5//! a backend paints any area of it through [`crate::display::paint`].
6//! This module holds the renderer — its fonts and text shaping.
7
8use parley::{
9    Alignment, AlignmentOptions, FontContext, FontFamily, FontWeight, Layout as Text,
10    LayoutContext, LineHeight, StyleProperty,
11};
12use std::collections::{BTreeSet, HashMap};
13use taffy::prelude::*;
14
15use kurbo::Rect as KRect;
16use peniko::ImageData;
17
18use crate::display::{Draw, Frame, Glyph, Paint};
19use crate::fonts::{self, FontFiles, FontId};
20use crate::scene::{self, ImageId, Origin, TextAlign};
21
22mod drawing;
23#[cfg(test)]
24mod examples;
25mod layout;
26mod painter;
27#[cfg(test)]
28pub(crate) mod testing;
29mod update;
30
31use drawing::*;
32pub use drawing::{Damage, Drawing};
33use layout::*;
34use painter::*;
35
36/// The embedded Inter faces: regular, medium, semibold and bold.
37const FONTS: [&[u8]; 4] = [
38    include_bytes!("../../fonts/Inter-Regular.ttf"),
39    include_bytes!("../../fonts/Inter-Medium.ttf"),
40    include_bytes!("../../fonts/Inter-SemiBold.ttf"),
41    include_bytes!("../../fonts/Inter-Bold.ttf"),
42];
43
44/// The fonts and text layout state a renderer keeps between paints.
45pub struct Renderer {
46    /// The font collection layout finds fonts in: Inter, and the scene's own font
47    /// files.
48    fonts: FontContext,
49    /// The embedded Inter faces, each under one blob for the renderer's life.
50    inter: Vec<parley::fontique::Blob<u8>>,
51    /// The font files registered besides Inter — those of a scene laid out —
52    /// or `None` before anything is.
53    registered: Option<BTreeSet<FontId>>,
54    /// Parley's scratch state for laying text out, kept between layouts.
55    layouts: LayoutContext<()>,
56    /// While a display list is made: the image each image file is painted
57    /// from in it, and every image it paints, in the order it first does,
58    /// with the attribute that asked for it.
59    blobs: HashMap<ImageId, ImageData>,
60    /// Every image the display list being made paints, in the order it first
61    /// does, with the attribute that asked for it.
62    painted: Vec<(Painted, Origin)>,
63}
64
65impl Default for Renderer {
66    fn default() -> Self {
67        Self::new()
68    }
69}
70
71/// Why a scene can't be drawn: images and shadows that don't fit the GPU's
72/// atlas — `at` the attribute that broke it, when one did.
73#[derive(Debug, Clone, PartialEq)]
74pub struct Undrawable {
75    /// What went wrong, in words.
76    pub message: String,
77    /// The attribute that broke it; `None` when none did.
78    pub at: Option<Origin>,
79}
80
81impl std::fmt::Display for Undrawable {
82    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83        f.write_str(&self.message)
84    }
85}
86
87impl Renderer {
88    /// A renderer with only the embedded Inter faces registered; no system fonts.
89    pub fn new() -> Renderer {
90        let fonts = FontContext {
91            collection: parley::fontique::Collection::new(parley::fontique::CollectionOptions {
92                shared: false,
93                system_fonts: false,
94            }),
95            source_cache: parley::fontique::SourceCache::default(),
96        };
97        let mut renderer = Renderer {
98            fonts,
99            inter: FONTS
100                .iter()
101                .map(|font| parley::fontique::Blob::new(std::sync::Arc::new(*font)))
102                .collect(),
103            registered: None,
104            layouts: LayoutContext::new(),
105            blobs: HashMap::new(),
106            painted: Vec::new(),
107        };
108        renderer.register(&FontFiles::new());
109        renderer
110    }
111
112    /// Makes the scene's font files available to layout, each under a
113    /// family name of its own. The collection keeps what it has while a
114    /// scene uses no other font file; otherwise it starts again from Inter
115    /// and this scene's, so it never holds more than one scene's fonts.
116    fn register(&mut self, files: &FontFiles) {
117        if let Some(registered) = &self.registered
118            && files.keys().all(|id| registered.contains(id))
119        {
120            return;
121        }
122        let collection = &mut self.fonts.collection;
123        collection.clear();
124        for blob in &self.inter {
125            collection.register_fonts(blob.clone(), None);
126        }
127        for (id, file) in files {
128            let family = id.family();
129            collection.register_fonts(
130                file.blob.clone(),
131                Some(parley::fontique::FontInfoOverride {
132                    family_name: Some(&family),
133                    ..Default::default()
134                }),
135            );
136        }
137        self.registered = Some(files.keys().copied().collect());
138    }
139
140    /// `text` laid out: shaped in its font, size, weight and line height, broken
141    /// into lines at `width` — none when `None` — and aligned.
142    fn text_layout(&mut self, text: &scene::TextStyle, width: Option<f32>) -> Text<()> {
143        let mut builder = self
144            .layouts
145            .ranged_builder(&mut self.fonts, &text.content, 1.0, true);
146        let family = match text.font {
147            Some(id) => id.family(),
148            None => fonts::INTER.to_string(),
149        };
150        builder.push_default(StyleProperty::FontFamily(FontFamily::named(&family)));
151        builder.push_default(StyleProperty::FontSize(text.size));
152        builder.push_default(StyleProperty::FontWeight(FontWeight::new(
153            text.weight as f32,
154        )));
155        builder.push_default(StyleProperty::LineHeight(LineHeight::FontSizeRelative(
156            text.line_height,
157        )));
158        let mut layout = builder.build(&text.content);
159        layout.break_all_lines(width);
160        let align = match text.align {
161            TextAlign::Left => Alignment::Left,
162            TextAlign::Center => Alignment::Center,
163            TextAlign::Right => Alignment::Right,
164        };
165        layout.align(align, AlignmentOptions::default());
166        layout
167    }
168}
169
170/// `f`'s box as a kurbo rectangle.
171fn frame_rect(f: Frame) -> KRect {
172    KRect::new(
173        f.x as f64,
174        f.y as f64,
175        (f.x + f.width) as f64,
176        (f.y + f.height) as f64,
177    )
178}