Skip to main content

blit_gui/
text.rs

1use alloc::borrow::Cow;
2use core::{
3    hash::{Hash, Hasher},
4    ops::Range,
5};
6
7use blit::{
8    Fit, FrameSlice, LogicalPoint, LogicalRect, LogicalSize, Paint, PhysicalPoint, Scratch, ScratchBuffer, StrSource,
9    Widget, state,
10};
11
12use crate::{
13    Context,
14    color::Color,
15    display_list::{Compare, DisplayList},
16};
17
18//
19// text system
20//
21
22pub trait TextSystem: 'static {
23    /// registers geometry using the font attributes in style
24    /// returned text runs remain valid until finish_frame
25    fn text_run(&mut self, text: &str, style: TextStyle) -> TextRun {
26        self.rich_text(text, &[], style)
27    }
28
29    /// registers geometry using span ranges and font attributes
30    /// returned text runs remain valid until finish_frame
31    fn rich_text(&mut self, text: &str, spans: &[Span<'_>], style: TextStyle) -> TextRun;
32
33    fn measure(&mut self, text: TextRun, max_width: Option<f32>, options: TextOptions) -> Fit<LogicalSize>;
34
35    fn offset_at_position(&mut self, area: LogicalRect, request: &TextRequest, position: LogicalPoint) -> usize;
36
37    /// returns the zero-width caret rectangle at `offset`
38    /// `upstream` keeps an offset at a soft wrap on the line it ends
39    fn caret_rect(&mut self, area: LogicalRect, request: &TextRequest, offset: usize, upstream: bool) -> LogicalRect;
40
41    /// returns visual rectangles for `range` in `scratch`
42    fn range_rects<'a>(
43        &mut self,
44        area: LogicalRect,
45        request: &TextRequest,
46        range: Range<usize>,
47        scratch: &'a ScratchBuffer,
48    ) -> Scratch<'a, LogicalRect>;
49
50    /// returns positioned glyphs for painting in `scratch`
51    /// returned glyph keys remain valid for rasterize until finish_frame
52    fn resolve<'a>(
53        &mut self,
54        area: LogicalRect,
55        request: &TextRequest,
56        scale: f32,
57        scratch: &'a ScratchBuffer,
58    ) -> Scratch<'a, PositionedGlyph>;
59
60    /// equal keys must produce identical pixels and bearings
61    fn rasterize(&mut self, key: GlyphKey) -> GlyphImage;
62
63    fn finish_frame(&mut self);
64}
65
66#[derive(Clone, Copy, Debug)]
67pub struct PositionedGlyph {
68    pub key: GlyphKey,
69    pub origin: PhysicalPoint,
70    pub span: u32,
71}
72
73/// glyph identity for renderer pixel caches
74#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
75pub struct GlyphKey {
76    pub font: u64,
77    pub size: u32,
78    pub glyph: u32,
79    pub phase: u8,
80}
81
82impl Hash for GlyphKey {
83    #[inline]
84    fn hash<H: Hasher>(&self, state: &mut H) {
85        state.write_u64(self.font);
86        state.write_u64((u64::from(self.size) << 32) | u64::from(self.glyph));
87        state.write_u8(self.phase);
88    }
89}
90
91#[derive(Debug, Default)]
92pub struct GlyphImage {
93    pub metrics: GlyphMetrics,
94    pub format: GlyphFormat,
95    pub pixels: Cow<'static, [u8]>,
96}
97
98#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
99pub enum GlyphFormat {
100    /// tightly packed coverage tinted by the text color
101    #[default]
102    Alpha8,
103    /// tightly packed rgba with encoded srgb channels multiplied by alpha
104    /// keeps intrinsic colors and receives text alpha once
105    Rgba8,
106}
107
108impl GlyphFormat {
109    pub const fn bytes_per_pixel(self) -> usize {
110        match self {
111            Self::Alpha8 => 1,
112            Self::Rgba8 => 4,
113        }
114    }
115}
116
117#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
118pub struct GlyphMetrics {
119    pub width: u16,
120    pub height: u16,
121    /// pixel offset from the glyph origin including any horizontal subpixel phase
122    pub left: i16,
123    /// pixel offset from the baseline with positive values pointing down
124    pub top: i16,
125}
126
127//
128// widgets
129//
130
131blit::builder! {
132    #[derive(Clone, Copy, Debug)]
133    pub struct Text<'a> {
134        new(#[into] text: StrSource<'a>),
135        style: TextStyle<'a> = TextStyle::new(),
136        offset: LogicalPoint = LogicalPoint::new(0.0, 0.0),
137        options: TextOptions = TextOptions::new(),
138    }
139}
140
141impl<C> Widget<C, state::Insert> for Text<'_>
142where
143    C: Context + Paint<FrameText>,
144{
145    type Response = ();
146
147    fn build(self, mut ui: blit::Ui<'_, C, state::Insert>) {
148        let text = ui.scratch().str(self.text);
149        let run = ui.context_mut().text().text_run(&text, self.style);
150        let colors = ui.context_mut().store_mut().slice_from(&[self.style.color]);
151        ui.insert(FrameText::new(run, colors).offset(self.offset).options(self.options));
152    }
153}
154
155blit::builder! {
156    /// text partitioned by ordered, contiguous spans
157    #[derive(Clone, Copy, Debug, PartialEq)]
158    pub struct RichText<'a> {
159        new(text: &'a str, spans: &'a [Span<'a>]),
160        style: TextStyle<'a> = TextStyle::new(),
161        offset: LogicalPoint = LogicalPoint::new(0.0, 0.0),
162        options: TextOptions = TextOptions::new(),
163    }
164}
165
166impl<C> Widget<C, state::Insert> for RichText<'_>
167where
168    C: Context + Paint<FrameText>,
169{
170    type Response = ();
171
172    fn build(self, mut ui: blit::Ui<'_, C, state::Insert>) {
173        let run = ui.context_mut().text().rich_text(self.text, self.spans, self.style);
174        // empty spans lay out as one span in the base color
175        let mut colors = ui.context_mut().store_mut().slice(self.spans.len().max(1));
176        if self.spans.is_empty() {
177            colors.push(self.style.color);
178        } else {
179            colors.extend(
180                self.spans
181                    .iter()
182                    .map(|span| span.style.color.unwrap_or(self.style.color)),
183            )
184        }
185        let colors = colors.finish();
186        ui.insert(FrameText::new(run, colors).offset(self.offset).options(self.options));
187    }
188}
189
190//
191// painting
192//
193
194blit::builder! {
195    /// resolved text with span colors stored in the frame
196    #[derive(Clone, Copy, Debug, PartialEq)]
197    pub struct FrameText {
198        // one color per span
199        new(text: TextRun, colors: FrameSlice<Color>),
200        offset: LogicalPoint = LogicalPoint::new(0.0, 0.0),
201        options: TextOptions = TextOptions::new(),
202    }
203}
204
205impl<C> Widget<C, state::Insert> for FrameText
206where
207    C: Context + Paint<Self>,
208{
209    type Response = ();
210
211    fn build(self, mut ui: blit::Ui<'_, C, state::Insert>) {
212        let text = self.text;
213        let options = self.options;
214        ui.measure(move |cx, constraints| {
215            let max_width =
216                (options.wrap != TextWrap::None && constraints.max.width.is_finite()).then_some(constraints.max.width);
217            cx.text().measure(text, max_width, options)
218        });
219        ui.paint(move |cx, area| cx.context_mut().paint(area, &self));
220    }
221}
222
223impl FrameText {
224    /// placement used for text system queries
225    #[inline]
226    pub fn request(&self) -> TextRequest {
227        TextRequest::new(self.text).offset(self.offset).options(self.options)
228    }
229
230    /// missing spans repeat the last color
231    pub fn span_color(&self, list: &DisplayList, span: usize) -> Color {
232        let colors = list.store().view(self.colors);
233        colors
234            .get(span)
235            .or(colors.last())
236            .copied()
237            .unwrap_or(Color::TRANSPARENT)
238    }
239}
240
241impl Compare for FrameText {
242    #[inline]
243    fn equal(a: &Self, left: &DisplayList, b: &Self, right: &DisplayList) -> bool {
244        a.request() == b.request() && left.store().view(a.colors) == right.store().view(b.colors)
245    }
246
247    fn hash(value: &Self, list: &DisplayList, state: &mut impl Hasher) {
248        value.request().hash(state);
249        list.store().view(value.colors).hash(state);
250    }
251}
252
253//
254// requests and runs
255//
256
257/// cached text geometry
258#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
259pub struct TextRun(pub u64);
260
261blit::builder! {
262    /// placed text for text system queries such as cursor and hit testing
263    #[derive(Clone, Copy, Debug, PartialEq)]
264    pub struct TextRequest {
265        new(text: TextRun),
266        offset: LogicalPoint = LogicalPoint::new(0.0, 0.0),
267        options: TextOptions = TextOptions::new(),
268    }
269}
270
271impl Hash for TextRequest {
272    fn hash<H: Hasher>(&self, state: &mut H) {
273        let float_bits = |value: f32| if value == 0.0 { 0 } else { value.to_bits() };
274        self.text.hash(state);
275        float_bits(self.offset.x).hash(state);
276        float_bits(self.offset.y).hash(state);
277        self.options.wrap.hash(state);
278        self.options.overflow.hash(state);
279        self.options.horizontal_align.hash(state);
280        self.options.vertical_align.hash(state);
281        self.options.max_lines.hash(state);
282    }
283}
284
285//
286// style and fonts
287//
288
289blit::builder! {
290    #[derive(Clone, Copy, Debug, PartialEq)]
291    pub struct TextStyle<'a> {
292        new(),
293        font: FontId = FontId(0),
294        size: f32 = 16.0,
295        line_height: LineHeight = LineHeight::Metrics(1.0),
296        weight: u16 = 400,
297        stretch: u16 = 100,
298        style: FontStyle = FontStyle::Normal,
299        color: Color = Color::BLACK,
300        settings: FontSettings<'a> = FontSettings::new(),
301    }
302}
303
304blit::builder! {
305    /// style overrides for a rich text span
306    #[derive(Clone, Copy, Debug, PartialEq)]
307    pub struct SpanStyle<'a> {
308        new(),
309        #[into]
310        font: Option<FontId> = None,
311        #[into]
312        size: Option<f32> = None,
313        /// backends without per-span line height use the base style's
314        #[into]
315        line_height: Option<LineHeight> = None,
316        #[into]
317        weight: Option<u16> = None,
318        #[into]
319        stretch: Option<u16> = None,
320        #[into]
321        style: Option<FontStyle> = None,
322        #[into]
323        color: Option<Color> = None,
324        #[into]
325        settings: Option<FontSettings<'a>> = None,
326    }
327}
328
329#[derive(Clone, Copy, Debug, PartialEq)]
330pub enum LineHeight {
331    /// multiple of the font's natural line height
332    Metrics(f32),
333    /// fixed line height in logical pixels
334    Absolute(f32),
335}
336
337blit::builder! {
338    /// a styled byte range within a rich text string
339    #[derive(Clone, Debug, PartialEq)]
340    pub struct Span<'a> {
341        new(range: Range<usize>),
342        style: SpanStyle<'a> = SpanStyle::new(),
343    }
344}
345
346#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
347pub struct FontId(pub u16);
348
349#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
350pub enum FontStyle {
351    #[default]
352    Normal,
353    Italic,
354    Oblique,
355}
356
357blit::builder! {
358    #[derive(Clone, Copy, Debug, PartialEq)]
359    pub struct FontSettings<'a> {
360        new(),
361        features: &'a [([u8; 4], u32)] = &[],
362        variations: &'a [([u8; 4], f32)] = &[],
363        #[into]
364        language: Option<&'a str> = None,
365        optical_size: OpticalSize = OpticalSize::Auto,
366    }
367}
368
369#[derive(Clone, Copy, Debug, Default, PartialEq)]
370pub enum OpticalSize {
371    #[default]
372    Auto,
373    FontDefault,
374    Fixed(f32),
375}
376
377//
378// options
379//
380
381blit::builder! {
382    #[derive(Clone, Copy, Debug, PartialEq)]
383    pub struct TextOptions {
384        new(),
385        wrap: TextWrap = TextWrap::None,
386        overflow: TextOverflow = TextOverflow::Clip,
387        horizontal_align: HorizontalAlign = HorizontalAlign::Left,
388        vertical_align: VerticalAlign = VerticalAlign::Top,
389        #[into]
390        max_lines: Option<u16> = None,
391    }
392}
393
394#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
395pub enum TextOverflow {
396    #[default]
397    Clip,
398    Ellipsis,
399}
400
401#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
402pub enum TextWrap {
403    #[default]
404    None,
405    Word,
406    Character,
407}
408
409#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
410pub enum HorizontalAlign {
411    #[default]
412    Left,
413    Center,
414    Right,
415}
416
417#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
418pub enum VerticalAlign {
419    #[default]
420    Top,
421    Center,
422    Bottom,
423}