Skip to main content

matrix_gui/widgets/
label.rs

1//! Text label widget for displaying static text.
2//!
3//! This module provides a simple text label widget that displays
4//! a text string within a specified region with customizable
5//! font, alignment, and color.
6
7use crate::prelude::*;
8
9/// Text label widget for displaying static text.
10///
11/// This widget displays a text string within a specified region with
12/// customizable font, horizontal alignment, and color. The text is
13/// automatically positioned based on the alignment setting.
14///
15/// # Type Parameters
16///
17/// * `'a` - The lifetime of the text string reference
18/// * `ID` - The widget ID type implementing [`WidgetId`]
19/// * `COL` - The pixel color type implementing [`PixelColor`]
20pub struct Label<'a, ID, COL: PixelColor> {
21    /// The region defining the label's position and size.
22    region: &'a Region<ID>,
23    /// The text string to display.
24    text: &'a str,
25    /// Optional font for rendering the text.
26    font: OptionFont<'a>,
27    /// Horizontal alignment for the text.
28    align: HorizontalAlign,
29    /// Optional color for the text.
30    color: OptionColor<COL>,
31}
32
33impl<'a, ID: WidgetId, COL: PixelColor> Label<'a, ID, COL> {
34    pub const fn new(region: &'a Region<ID>, text: &'a str) -> Label<'a, ID, COL> {
35        Label {
36            region,
37            text,
38            font: OptionFont::none(),
39            align: HorizontalAlign::Left,
40            color: OptionColor::none(),
41        }
42    }
43
44    pub const fn with_font(mut self, font: UiFont<'a>) -> Self {
45        self.font.set_font(font);
46        self
47    }
48
49    pub const fn with_align(mut self, align: HorizontalAlign) -> Self {
50        self.align = align;
51        self
52    }
53
54    pub const fn with_color(mut self, color: COL) -> Self {
55        self.color.set_color(color);
56        self
57    }
58}
59
60impl<DRAW: DrawTarget<Color = COL>, ID: WidgetId, COL: PixelColor> Widget<DRAW, COL>
61    for Label<'_, ID, COL>
62{
63    fn draw(&mut self, ui: &mut Ui<DRAW, COL>) -> GuiResult<Response> {
64        let widget_state = ui.get_widget_state(self.region.id())?;
65        if widget_state.compare_set(RenderStatus::Rendered) {
66            return Ok(Response::Idle);
67        }
68
69        let area = self.region.rectangle();
70        let font = self.font.font(ui.style());
71        let color = self.color.text_color(ui.style());
72        let mut text = matrix_utils::make_text(self.text, font, color);
73
74        matrix_utils::text_align_translate(&mut text, &area, self.align);
75
76        ui.clear_area(&area)?;
77        ui.draw(&text)?;
78
79        Ok(Response::Idle)
80    }
81}