Skip to main content

wde_ui/
text.rs

1//! Text nodes: shaped with cosmic-text for layout, rasterized and drawn with glyphon.
2use std::sync::{Arc, Mutex};
3
4use bevy::prelude::*;
5use glyphon::{Attrs, Buffer, Family, FontSystem, Metrics, Shaping, Weight};
6use wde_renderer::prelude::WdeColor;
7
8use crate::node::UiNode;
9
10/// Line height, relative to the font size.
11const LINE_HEIGHT: f32 = 1.25;
12
13/// A text leaf node. Its size is measured from the text, wrapped to the width given by its parent.
14#[derive(Component, Clone, Debug, PartialEq)]
15#[require(UiNode)]
16pub struct UiText {
17    pub text: String,
18    /// In logical pixels.
19    pub font_size: f32,
20    pub color: WdeColor,
21    pub bold: bool
22}
23impl UiText {
24    pub fn new(text: impl Into<String>) -> Self {
25        Self {
26            text: text.into(),
27            font_size: 16.0,
28            color: WdeColor::WHITE,
29            bold: false
30        }
31    }
32    pub fn with_size(self, font_size: f32) -> Self {
33        Self { font_size, ..self }
34    }
35    pub fn with_color(self, color: WdeColor) -> Self {
36        Self { color, ..self }
37    }
38    pub fn bold(self) -> Self {
39        Self { bold: true, ..self }
40    }
41}
42
43/// Font database and shaping caches, shared by the main world (layout) and the render world (rasterization).
44#[derive(Resource, Clone)]
45pub(crate) struct UiFonts(pub Arc<Mutex<FontSystem>>);
46impl Default for UiFonts {
47    fn default() -> Self {
48        Self(Arc::new(Mutex::new(FontSystem::new())))
49    }
50}
51
52/// Shaped text of a [`UiText`] node, held as its taffy node context. Shared with the render
53/// world, so it is only cloned when reshaped while the render world still draws it.
54pub(crate) struct UiTextBuffer(pub Arc<Buffer>);
55
56pub(crate) fn shape(font_system: &mut FontSystem, text: &UiText) -> UiTextBuffer {
57    let mut buffer = Buffer::new(
58        font_system,
59        Metrics::new(text.font_size, text.font_size * LINE_HEIGHT)
60    );
61    let weight = if text.bold {
62        Weight::BOLD
63    } else {
64        Weight::NORMAL
65    };
66    buffer.set_text(
67        &text.text,
68        &Attrs::new().family(Family::SansSerif).weight(weight),
69        Shaping::Advanced,
70        None
71    );
72    buffer.shape_until_scroll(font_system, false);
73    UiTextBuffer(Arc::new(buffer))
74}
75
76/// Wraps the text to `width` (unbounded if `None`), and returns its size.
77pub(crate) fn measure(
78    font_system: &mut FontSystem,
79    buffer: &mut Arc<Buffer>,
80    width: Option<f32>
81) -> Vec2 {
82    // Reshapes on resize only
83    if buffer.size().0 != width {
84        let buffer = Arc::make_mut(buffer);
85        buffer.set_size(width, None);
86        buffer.shape_until_scroll(font_system, false);
87    }
88    let (width, lines) = buffer
89        .layout_runs()
90        .fold((0.0f32, 0), |(width, lines), run| {
91            (width.max(run.line_w), lines + 1)
92        });
93    Vec2::new(width, lines as f32 * buffer.metrics().line_height)
94}