1use 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
10const LINE_HEIGHT: f32 = 1.25;
12
13#[derive(Component, Clone, Debug, PartialEq)]
15#[require(UiNode)]
16pub struct UiText {
17 pub text: String,
18 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#[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
52pub(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
76pub(crate) fn measure(
78 font_system: &mut FontSystem,
79 buffer: &mut Arc<Buffer>,
80 width: Option<f32>
81) -> Vec2 {
82 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}