Skip to main content

pushrod/text/
layout.rs

1// Text Layout
2// Pushrod
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! # Text layout
17//!
18//! A [`TextLayout`] turns a string, a [`TextStyle`] and a maximum width into a [`LaidOut`]: the
19//! size of the text, where each line sits, the glyph runs to draw, and the caret and selection
20//! geometry a text field needs.  A layout engine only *computes*; drawing stays with the painter,
21//! which rasterizes each glyph once into the atlas texture and copies rectangles from it.
22//!
23//! Engines that ship with Pushrod:
24//!
25//! * `TtfLayout` (in the `pushrod-sdl2` crate) measures with SDL2_ttf.  It reports sizes,
26//!   lines and caret geometry but no glyph runs; the SDL2 painter draws its text with SDL2_ttf.
27//! * `ParleyLayout` (the `parley` Cargo feature) uses Parley for shaping, bidirectional text,
28//!   line breaking and font fallback, and returns glyph runs.
29//!
30//! Applications can implement [`TextLayout`] for another engine (Cosmic Text, a bitmap font).
31//! Wrap an engine in a [`LayoutCache`] so a widget lays its text out again only when the text,
32//! font, or width changes.
33
34use crate::geometry::{Point, Rect, Size};
35use crate::paint::TextStyle;
36use std::ops::Range;
37use std::sync::Arc;
38
39/// A font file shared by the glyph runs that use it.
40#[derive(Clone)]
41pub struct FontData {
42    /// A process-unique identifier for the font file, usable as a cache key.
43    pub id: u64,
44
45    /// The index of the font in a font collection, or `0` for a single font.
46    pub index: u32,
47
48    /// The bytes of the font file, shared and never copied per run.
49    pub bytes: Arc<dyn AsRef<[u8]> + Send + Sync>,
50}
51
52impl std::fmt::Debug for FontData {
53    /// Formats the identifier and index, not the font bytes.
54    ///
55    /// # Arguments
56    ///
57    /// * `f` - The formatter to write to.
58    ///
59    /// # Returns
60    ///
61    /// The formatter's result.
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        f.debug_struct("FontData")
64            .field("id", &self.id)
65            .field("index", &self.index)
66            .finish()
67    }
68}
69
70/// One glyph, positioned relative to the top-left corner of the laid-out text.
71#[derive(Debug, Clone, Copy, PartialEq)]
72pub struct PositionedGlyph {
73    /// The glyph's identifier within its font.
74    pub id: u32,
75
76    /// Horizontal position of the glyph origin, in pixels.
77    pub x: f32,
78
79    /// Vertical position of the glyph origin (on the baseline), in pixels.
80    pub y: f32,
81}
82
83/// A run of glyphs sharing one font and size.
84#[derive(Debug, Clone)]
85pub struct GlyphRun {
86    /// The font the glyphs come from (the fallback font when the requested one lacks a glyph).
87    pub font: FontData,
88
89    /// The font size in pixels.
90    pub font_size: f32,
91
92    /// The glyphs, in visual order.
93    pub glyphs: Vec<PositionedGlyph>,
94}
95
96/// One laid-out line of text.
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub struct Line {
99    /// The bytes of the source text on this line.
100    pub text_range: Range<usize>,
101
102    /// The line's bounds, relative to the top-left corner of the laid-out text.
103    pub bounds: Rect,
104}
105
106/// Caret, selection and hit-test geometry for one laid-out text.
107pub trait TextGeometry {
108    /// The caret rectangle for a byte index into the text.
109    ///
110    /// # Arguments
111    ///
112    /// * `index` - A byte index; values past the end of the text give the caret at the end.
113    ///
114    /// # Returns
115    ///
116    /// A one-pixel-wide rectangle as tall as the line.
117    fn caret_rect(&self, index: usize) -> Rect;
118
119    /// The rectangles covering a selection, one or more per line.
120    ///
121    /// # Arguments
122    ///
123    /// * `range` - The selected bytes of the text.
124    ///
125    /// # Returns
126    ///
127    /// The rectangles to fill (several per line for mixed-direction text); empty for an empty range.
128    fn selection_rects(&self, range: Range<usize>) -> Vec<Rect>;
129
130    /// The byte index of the caret position nearest a point.
131    ///
132    /// # Arguments
133    ///
134    /// * `point` - A point relative to the top-left corner of the laid-out text.
135    ///
136    /// # Returns
137    ///
138    /// A byte index on a character boundary of the text.
139    fn hit_test(&self, point: Point) -> usize;
140}
141
142/// The result of laying out a text.
143pub struct LaidOut {
144    /// The size of the text in pixels.
145    pub size: Size,
146
147    /// The width of the longest unbreakable word: the narrowest width the text can wrap to.
148    pub min_width: u32,
149
150    /// The lines, top to bottom.
151    pub lines: Vec<Line>,
152
153    /// The glyph runs to draw; empty for engines whose painter draws the text itself.
154    pub runs: Vec<GlyphRun>,
155
156    /// Caret, selection and hit-test geometry.
157    pub geometry: Box<dyn TextGeometry>,
158}
159
160impl LaidOut {
161    /// The size hint for layout managers.
162    ///
163    /// # Returns
164    ///
165    /// `(min, preferred)`: the narrowest width the text wraps to and the size it was laid out at.
166    pub fn size_hint(&self) -> (u32, Size) {
167        (self.min_width, self.size)
168    }
169}
170
171/// A text layout engine.
172pub trait TextLayout {
173    /// Lays out a text.
174    ///
175    /// # Arguments
176    ///
177    /// * `text` - The text to lay out.
178    /// * `style` - The font, size and style.
179    /// * `max_width` - The width in pixels at which to wrap, or `None` for no wrapping.
180    ///
181    /// # Returns
182    ///
183    /// The size, lines, glyph runs and geometry of the text.
184    fn layout(&mut self, text: &str, style: &TextStyle, max_width: Option<u32>) -> LaidOut;
185}
186
187/// The inputs a cached layout was computed from.
188#[derive(Clone, PartialEq)]
189struct LayoutKey {
190    text: String,
191    font_name: String,
192    font_size: u16,
193    font_style: crate::color::FontStyle,
194    max_width: Option<u32>,
195}
196
197/// Keeps the last layout of one widget's text and recomputes it only when an input changes.
198#[derive(Default)]
199pub struct LayoutCache {
200    entry: Option<(LayoutKey, LaidOut)>,
201    layouts: usize,
202}
203
204impl LayoutCache {
205    /// Creates an empty cache.
206    ///
207    /// # Returns
208    ///
209    /// The new `LayoutCache`.
210    pub fn new() -> Self {
211        Self::default()
212    }
213
214    /// Returns the layout for the inputs, computing it with `engine` only if the text, font,
215    /// font size, font style or width differ from the previous call.  Changing only the color
216    /// or the justification does not lay out again.
217    ///
218    /// # Arguments
219    ///
220    /// * `engine` - The layout engine to use on a miss.
221    /// * `text` - The text to lay out.
222    /// * `style` - The font, size and style.
223    /// * `max_width` - The width in pixels at which to wrap, or `None` for no wrapping.
224    ///
225    /// # Returns
226    ///
227    /// The cached or freshly computed layout.
228    pub fn get(
229        &mut self,
230        engine: &mut dyn TextLayout,
231        text: &str,
232        style: &TextStyle,
233        max_width: Option<u32>,
234    ) -> &LaidOut {
235        let key = LayoutKey {
236            text: text.to_string(),
237            font_name: style.font_name.clone(),
238            font_size: style.font_size,
239            font_style: style.font_style,
240            max_width,
241        };
242
243        if !matches!(&self.entry, Some((k, _)) if *k == key) {
244            self.entry = None;
245        }
246
247        let layouts = &mut self.layouts;
248        let (_, laid) = self.entry.get_or_insert_with(|| {
249            *layouts += 1;
250            let laid = engine.layout(text, style, max_width);
251
252            (key, laid)
253        });
254
255        laid
256    }
257
258    /// Forgets the cached layout so the next [`get`](Self::get) lays out again.
259    pub fn invalidate(&mut self) {
260        self.entry = None;
261    }
262
263    /// How many times the engine has been asked to lay out (cache misses).
264    ///
265    /// # Returns
266    ///
267    /// The number of layouts computed so far.
268    pub fn layouts(&self) -> usize {
269        self.layouts
270    }
271}
272
273#[cfg(test)]
274mod tests {
275    use super::*;
276    use crate::color::{Color, FontStyle};
277    use crate::paint::TextJustify;
278
279    struct NullGeometry;
280
281    impl TextGeometry for NullGeometry {
282        /// A fixed caret.
283        ///
284        /// # Arguments
285        ///
286        /// * `_index` - Ignored.
287        ///
288        /// # Returns
289        ///
290        /// An empty rectangle.
291        fn caret_rect(&self, _index: usize) -> Rect {
292            Rect::default()
293        }
294        /// No selection.
295        ///
296        /// # Arguments
297        ///
298        /// * `_range` - Ignored.
299        ///
300        /// # Returns
301        ///
302        /// No rectangles.
303        fn selection_rects(&self, _range: Range<usize>) -> Vec<Rect> {
304            Vec::new()
305        }
306        /// Always the start.
307        ///
308        /// # Arguments
309        ///
310        /// * `_point` - Ignored.
311        ///
312        /// # Returns
313        ///
314        /// Zero.
315        fn hit_test(&self, _point: Point) -> usize {
316            0
317        }
318    }
319
320    /// A fake engine: 10 pixels per character, one line.
321    struct Fake;
322
323    impl TextLayout for Fake {
324        /// Ten pixels per character.
325        ///
326        /// # Arguments
327        ///
328        /// * `text` - The text to measure.
329        /// * `_style` - Ignored.
330        /// * `_max` - Ignored.
331        ///
332        /// # Returns
333        ///
334        /// A one-line layout.
335        fn layout(&mut self, text: &str, _style: &TextStyle, _max: Option<u32>) -> LaidOut {
336            let size = Size {
337                w: text.chars().count() as u32 * 10,
338                h: 20,
339            };
340            LaidOut {
341                size,
342                min_width: 10,
343                lines: vec![Line {
344                    text_range: 0..text.len(),
345                    bounds: Rect {
346                        x: 0,
347                        y: 0,
348                        w: size.w,
349                        h: size.h,
350                    },
351                }],
352                runs: Vec::new(),
353                geometry: Box::new(NullGeometry),
354            }
355        }
356    }
357
358    fn style() -> TextStyle {
359        TextStyle {
360            font_name: "a.ttf".into(),
361            font_style: FontStyle::NORMAL,
362            font_size: 12,
363            font_color: Color {
364                r: 0,
365                g: 0,
366                b: 0,
367                a: 255,
368            },
369            justification: TextJustify::Left,
370        }
371    }
372
373    #[test]
374    fn same_inputs_lay_out_once() {
375        let (mut cache, mut engine) = (LayoutCache::new(), Fake);
376        cache.get(&mut engine, "hello", &style(), Some(100));
377        let laid = cache.get(&mut engine, "hello", &style(), Some(100));
378        assert_eq!(laid.size.w, 50);
379        assert_eq!(cache.layouts(), 1);
380    }
381
382    #[test]
383    fn text_font_size_style_and_width_changes_recompute() {
384        let (mut cache, mut engine) = (LayoutCache::new(), Fake);
385        cache.get(&mut engine, "a", &style(), None);
386        cache.get(&mut engine, "ab", &style(), None);
387        let mut s = style();
388        s.font_name = "b.ttf".into();
389        cache.get(&mut engine, "ab", &s, None);
390        s.font_size = 14;
391        cache.get(&mut engine, "ab", &s, None);
392        s.font_style = FontStyle::BOLD;
393        cache.get(&mut engine, "ab", &s, None);
394        cache.get(&mut engine, "ab", &s, Some(50));
395        assert_eq!(cache.layouts(), 6);
396    }
397
398    #[test]
399    fn color_and_justification_do_not_recompute() {
400        let (mut cache, mut engine) = (LayoutCache::new(), Fake);
401        cache.get(&mut engine, "a", &style(), None);
402        let mut s = style();
403        s.font_color = Color {
404            r: 255,
405            g: 0,
406            b: 0,
407            a: 255,
408        };
409        s.justification = TextJustify::Center;
410        cache.get(&mut engine, "a", &s, None);
411        assert_eq!(cache.layouts(), 1);
412    }
413
414    #[test]
415    fn invalidate_forces_a_new_layout() {
416        let (mut cache, mut engine) = (LayoutCache::new(), Fake);
417        cache.get(&mut engine, "a", &style(), None);
418        cache.invalidate();
419        cache.get(&mut engine, "a", &style(), None);
420        assert_eq!(cache.layouts(), 2);
421    }
422
423    #[test]
424    fn size_hint_reports_min_and_preferred() {
425        let mut engine = Fake;
426        let laid = engine.layout("abc", &style(), None);
427        assert_eq!(laid.size_hint(), (10, Size { w: 30, h: 20 }));
428    }
429}