Skip to main content

rust_glass/
text.rs

1//! Text layout. Text uses the interface font of the platform, shaped by
2//! cosmic-text. Layouts are cached, so laying out the same text every frame
3//! is cheap.
4
5use std::collections::HashMap;
6use std::hash::{Hash, Hasher};
7use std::rc::Rc;
8
9use cosmic_text::{
10    Align as CtAlign, Attrs, Buffer, CacheKey, CacheKeyFlags, Family, FontSystem, Metrics, Shaping,
11    SwashCache, SwashContent, Weight as CtWeight, Wrap, fontdb,
12};
13
14use crate::geometry::{Vec2, vec2};
15use crate::icon::Icon;
16
17pub(crate) const ATLAS_SIZE: u32 = 2048;
18pub(crate) const SPRITE_ATLAS_SIZE: u32 = 1024;
19
20/// Font weight.
21#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
22pub enum Weight {
23    /// 400.
24    #[default]
25    Regular,
26    /// 500.
27    Medium,
28    /// 600.
29    Semibold,
30    /// 700.
31    Bold,
32}
33
34impl Weight {
35    fn value(self) -> u16 {
36        match self {
37            Weight::Regular => 400,
38            Weight::Medium => 500,
39            Weight::Semibold => 600,
40            Weight::Bold => 700,
41        }
42    }
43}
44
45/// Horizontal alignment of wrapped lines.
46#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
47pub enum TextAlign {
48    /// Lines start at the left edge.
49    #[default]
50    Left,
51    /// Lines are centered.
52    Center,
53    /// Lines end at the right edge.
54    Right,
55}
56
57/// How text is set: size, weight, font and wrapping.
58#[derive(Clone, Copy, Debug, PartialEq)]
59pub struct TextStyle {
60    /// Font size in points.
61    pub size: f32,
62    /// Font weight.
63    pub weight: Weight,
64    /// Use the monospace font.
65    pub mono: bool,
66    /// Wrap lines at this width in points. `None` keeps one line.
67    pub wrap: Option<f32>,
68    /// Alignment of wrapped lines.
69    pub align: TextAlign,
70}
71
72impl TextStyle {
73    /// Creates a regular, unwrapped style of `size` points.
74    pub fn new(size: f32) -> Self {
75        Self { size, weight: Weight::Regular, mono: false, wrap: None, align: TextAlign::Left }
76    }
77    /// Sets the weight.
78    pub fn weight(mut self, weight: Weight) -> Self {
79        self.weight = weight;
80        self
81    }
82    /// Uses the monospace font.
83    pub fn mono(mut self) -> Self {
84        self.mono = true;
85        self
86    }
87    /// Wraps lines at `width` points.
88    pub fn wrap(mut self, width: f32) -> Self {
89        self.wrap = Some(width);
90        self
91    }
92    /// Sets the alignment of wrapped lines.
93    pub fn align(mut self, align: TextAlign) -> Self {
94        self.align = align;
95        self
96    }
97}
98
99#[derive(Clone, Copy, Debug)]
100pub(crate) struct Glyph {
101    /// Pen position in points, relative to the layout origin. `y` is the baseline.
102    pub pos: Vec2,
103    font: fontdb::ID,
104    glyph: u16,
105    weight: CtWeight,
106    flags: CacheKeyFlags,
107}
108
109#[derive(Clone, Debug)]
110pub(crate) struct Line {
111    pub top: f32,
112    pub height: f32,
113    /// Byte range in the source text.
114    pub start: usize,
115    pub end: usize,
116    /// (byte offset, x) for every cursor stop on the line, in order.
117    pub stops: Vec<(usize, f32)>,
118}
119
120/// Text that has been shaped and laid out. Paint it with
121/// [`Painter::text`](crate::Painter::text).
122#[derive(Clone, Debug)]
123pub struct TextLayout {
124    /// Size of the laid out text in points.
125    pub size: Vec2,
126    /// Font size it was laid out at.
127    pub font_size: f32,
128    pub(crate) glyphs: Vec<Glyph>,
129    pub(crate) lines: Vec<Line>,
130}
131
132impl TextLayout {
133    /// Returns the caret before byte `index` as `(x, top, height)`.
134    pub fn caret(&self, index: usize) -> (f32, f32, f32) {
135        for (i, l) in self.lines.iter().enumerate() {
136            let last = i + 1 == self.lines.len();
137            if index <= l.end || last {
138                let next_starts_here = !last && self.lines[i + 1].start == index && index == l.end;
139                if next_starts_here {
140                    continue;
141                }
142                let x = l.stops.iter().rev().find(|s| s.0 <= index).map_or(0.0, |s| s.1);
143                return (x, l.top, l.height);
144            }
145        }
146        (0.0, 0.0, self.font_size * 1.3)
147    }
148
149    /// Returns the byte index closest to `point`.
150    pub fn hit(&self, point: Vec2) -> usize {
151        let p = point;
152        let Some(line) = self.lines.iter().find(|l| p.y < l.top + l.height).or(self.lines.last()) else {
153            return 0;
154        };
155        let mut best = (f32::MAX, line.start);
156        for &(i, x) in &line.stops {
157            let d = (x - p.x).abs();
158            if d < best.0 {
159                best = (d, i);
160            }
161        }
162        best.1
163    }
164}
165
166/// Where a rasterized glyph lives in its atlas.
167#[derive(Clone, Copy, Debug)]
168pub(crate) struct AtlasEntry {
169    pub uv: [f32; 4],
170    pub offset: Vec2,
171    pub size: Vec2,
172    pub color: bool,
173}
174
175pub(crate) struct AtlasUpload {
176    pub color: bool,
177    pub x: u32,
178    pub y: u32,
179    pub w: u32,
180    pub h: u32,
181    pub data: Vec<u8>,
182}
183
184struct Shelf {
185    size: u32,
186    x: u32,
187    y: u32,
188    row: u32,
189}
190
191impl Shelf {
192    fn new(size: u32) -> Self {
193        Self { size, x: 1, y: 1, row: 0 }
194    }
195    fn allocate(&mut self, w: u32, h: u32) -> Option<(u32, u32)> {
196        if self.x + w + 1 > self.size {
197            self.x = 1;
198            self.y += self.row + 1;
199            self.row = 0;
200        }
201        if self.y + h + 1 > self.size || w + 2 > self.size {
202            return None;
203        }
204        let at = (self.x, self.y);
205        self.x += w + 1;
206        self.row = self.row.max(h);
207        Some(at)
208    }
209}
210
211#[derive(Clone, Copy, PartialEq, Eq, Hash)]
212enum Key {
213    Glyph(CacheKey),
214    Icon(Icon, u32),
215}
216
217/// Lays out text and keeps the fonts. Reach it through
218/// [`Context::text`](crate::Context::text).
219pub struct TextEngine {
220    pub(crate) fonts: FontSystem,
221    swash: SwashCache,
222    buffer: Buffer,
223    layouts: HashMap<u64, (Rc<TextLayout>, u64)>,
224    atlas: HashMap<Key, Option<AtlasEntry>>,
225    shelf: Shelf,
226    sprite_shelf: Shelf,
227    pub(crate) uploads: Vec<AtlasUpload>,
228    /// Family name of the interface font. Change it after
229    /// [`TextEngine::add_font`] to use your own font.
230    pub sans: String,
231    /// Family name of the monospace font.
232    pub mono: String,
233    frame: u64,
234    full: bool,
235    ppp: f32,
236}
237
238impl Default for TextEngine {
239    fn default() -> Self {
240        Self::new()
241    }
242}
243
244impl TextEngine {
245    /// Loads the system fonts and picks the interface font of the platform.
246    pub fn new() -> Self {
247        let mut db = fontdb::Database::new();
248        db.load_system_fonts();
249        let has =
250            |db: &fontdb::Database, name: &str| db.faces().any(|f| f.families.iter().any(|x| x.0 == name));
251        let pick =
252            |db: &fontdb::Database, names: &[&str]| names.iter().find(|n| has(db, n)).map(|n| n.to_string());
253        // The platform's own interface font, so text matches other native apps.
254        let sans = pick(
255            &db,
256            &[
257                "SF Pro Text",
258                ".SF NS",
259                "Inter",
260                "Segoe UI Variable",
261                "Segoe UI",
262                "Cantarell",
263                "Noto Sans",
264                "DejaVu Sans",
265                "Arial",
266            ],
267        )
268        .unwrap_or_else(|| "sans-serif".into());
269        let mono = pick(
270            &db,
271            &["SF Mono", "Cascadia Mono", "Consolas", "JetBrains Mono", "Menlo", "DejaVu Sans Mono"],
272        )
273        .unwrap_or_else(|| "monospace".into());
274        let mut fonts = FontSystem::new_with_locale_and_db("en-US".into(), db);
275        let buffer = Buffer::new(&mut fonts, Metrics::new(16.0, 20.0));
276        Self {
277            fonts,
278            swash: SwashCache::new(),
279            buffer,
280            layouts: HashMap::new(),
281            atlas: HashMap::new(),
282            shelf: Shelf::new(ATLAS_SIZE),
283            sprite_shelf: Shelf::new(SPRITE_ATLAS_SIZE),
284            uploads: Vec::new(),
285            sans,
286            mono,
287            frame: 0,
288            full: false,
289            ppp: 1.0,
290        }
291    }
292
293    /// Adds a font file. Its family becomes available by name.
294    pub fn add_font(&mut self, bytes: Vec<u8>) {
295        self.fonts.db_mut().load_font_data(bytes);
296        self.layouts.clear();
297    }
298
299    pub(crate) fn begin_frame(&mut self, ppp: f32) {
300        self.frame += 1;
301        if ppp != self.ppp {
302            self.ppp = ppp;
303            self.layouts.clear();
304            self.full = true;
305        }
306        if self.full {
307            // Start over with an empty atlas; visible glyphs are rasterized again
308            // during this frame.
309            self.full = false;
310            self.atlas.clear();
311            self.shelf = Shelf::new(ATLAS_SIZE);
312            self.sprite_shelf = Shelf::new(SPRITE_ATLAS_SIZE);
313            self.uploads.clear();
314        }
315        if self.frame.is_multiple_of(240) {
316            let f = self.frame;
317            self.layouts.retain(|_, v| f - v.1 < 240);
318        }
319    }
320
321    /// Lays out `text` in `style`. Results are cached.
322    pub fn layout(&mut self, text: &str, style: &TextStyle) -> Rc<TextLayout> {
323        let st = style;
324        let mut h = std::hash::DefaultHasher::new();
325        text.hash(&mut h);
326        st.size.to_bits().hash(&mut h);
327        st.weight.hash(&mut h);
328        st.mono.hash(&mut h);
329        st.wrap.map(f32::to_bits).hash(&mut h);
330        st.align.hash(&mut h);
331        let key = h.finish();
332        if let Some((l, used)) = self.layouts.get_mut(&key) {
333            *used = self.frame;
334            return l.clone();
335        }
336        let l = Rc::new(self.shape(text, st));
337        self.layouts.insert(key, (l.clone(), self.frame));
338        l
339    }
340
341    fn shape(&mut self, text: &str, st: &TextStyle) -> TextLayout {
342        let ppp = self.ppp;
343        let px = st.size * ppp;
344        let line_h = (px * 1.28).round();
345        let family = if st.mono { self.mono.clone() } else { self.sans.clone() };
346        let attrs = Attrs::new().family(Family::Name(&family)).weight(CtWeight(st.weight.value()));
347        let align = match st.align {
348            TextAlign::Left => None,
349            TextAlign::Center => Some(CtAlign::Center),
350            TextAlign::Right => Some(CtAlign::Right),
351        };
352        let b = &mut self.buffer;
353        b.set_metrics(Metrics::new(px, line_h));
354        b.set_wrap(if st.wrap.is_some() { Wrap::WordOrGlyph } else { Wrap::None });
355        b.set_size(st.wrap.map(|w| w * ppp), None);
356        b.set_text(text, &attrs, Shaping::Advanced, align);
357        b.shape_until_scroll(&mut self.fonts, false);
358
359        // Byte offset of each source line in the full text.
360        let mut line_start = vec![0usize];
361        for (i, c) in text.char_indices() {
362            if c == '\n' {
363                line_start.push(i + 1);
364            }
365        }
366        let mut glyphs = Vec::new();
367        let mut lines: Vec<Line> = Vec::new();
368        let mut width = 0f32;
369        for run in b.layout_runs() {
370            let base = line_start.get(run.line_i).copied().unwrap_or(0);
371            let mut stops: Vec<(usize, f32)> = Vec::with_capacity(run.glyphs.len() + 1);
372            let (mut start, mut end) = (usize::MAX, 0);
373            for g in run.glyphs {
374                glyphs.push(Glyph {
375                    pos: vec2(
376                        (g.x + g.font_size * g.x_offset) / ppp,
377                        (run.line_y + g.y - g.font_size * g.y_offset) / ppp,
378                    ),
379                    font: g.font_id,
380                    glyph: g.glyph_id,
381                    weight: g.font_weight,
382                    flags: g.cache_key_flags,
383                });
384                stops.push((base + g.start, g.x / ppp));
385                start = start.min(base + g.start);
386                end = end.max(base + g.end);
387            }
388            let last_x = run.glyphs.last().map_or(0.0, |g| (g.x + g.w) / ppp);
389            if start == usize::MAX {
390                start = base;
391                end = base;
392            }
393            stops.push((end, last_x));
394            width = width.max(last_x - run.glyphs.first().map_or(0.0, |g| g.x / ppp).min(0.0));
395            lines.push(Line { top: run.line_top / ppp, height: run.line_height / ppp, start, end, stops });
396        }
397        if text.ends_with('\n') {
398            let top = lines.last().map_or(0.0, |l| l.top + l.height);
399            lines.push(Line {
400                top,
401                height: line_h / ppp,
402                start: text.len(),
403                end: text.len(),
404                stops: vec![(text.len(), 0.0)],
405            });
406        }
407        if lines.is_empty() {
408            lines.push(Line { top: 0.0, height: line_h / ppp, start: 0, end: 0, stops: vec![(0, 0.0)] });
409        }
410        if let (Some(w), true) = (st.wrap, st.align != TextAlign::Left) {
411            width = w;
412        }
413        let height = lines.last().map_or(line_h / ppp, |l| l.top + l.height);
414        TextLayout { size: vec2(width, height), font_size: st.size, glyphs, lines }
415    }
416
417    /// Rasterize (or fetch) a glyph drawn at pixel position `pos`. Returns the
418    /// entry plus the integer pixel origin.
419    pub(crate) fn glyph(&mut self, g: &Glyph, px: f32, pos: Vec2) -> Option<(AtlasEntry, Vec2)> {
420        let (key, x, y) = CacheKey::new(g.font, g.glyph, px, (pos.x, pos.y), g.weight, g.flags);
421        let k = Key::Glyph(key);
422        let origin = vec2(x as f32, y as f32);
423        if let Some(e) = self.atlas.get(&k) {
424            return e.map(|e| (e, origin));
425        }
426        let entry = self.swash.get_image_uncached(&mut self.fonts, key).and_then(|img| {
427            let p = img.placement;
428            if p.width == 0 || p.height == 0 {
429                return None;
430            }
431            let color = matches!(img.content, SwashContent::Color);
432            let data = match img.content {
433                SwashContent::SubpixelMask => img.data.as_chunks::<4>().0.iter().map(|c| c[1]).collect(),
434                _ => img.data,
435            };
436            self.insert(color, p.width, p.height, data, vec2(p.left as f32, -p.top as f32))
437        });
438        self.atlas.insert(k, entry);
439        entry.map(|e| (e, origin))
440    }
441
442    /// Icon rasterized at `px` by `px` pixels.
443    pub(crate) fn icon(&mut self, icon: Icon, px: u32) -> Option<AtlasEntry> {
444        let k = Key::Icon(icon, px);
445        if let Some(e) = self.atlas.get(&k) {
446            return *e;
447        }
448        let (data, w, h) = icon.rasterize(px);
449        let entry = self.insert(false, w, h, data, Vec2::ZERO);
450        self.atlas.insert(k, entry);
451        entry
452    }
453
454    fn insert(&mut self, color: bool, w: u32, h: u32, data: Vec<u8>, offset: Vec2) -> Option<AtlasEntry> {
455        let (shelf, size) = if color {
456            (&mut self.sprite_shelf, SPRITE_ATLAS_SIZE as f32)
457        } else {
458            (&mut self.shelf, ATLAS_SIZE as f32)
459        };
460        let Some((x, y)) = shelf.allocate(w, h) else {
461            self.full = true;
462            return None;
463        };
464        self.uploads.push(AtlasUpload { color, x, y, w, h, data });
465        Some(AtlasEntry {
466            uv: [x as f32 / size, y as f32 / size, (x + w) as f32 / size, (y + h) as f32 / size],
467            offset,
468            size: vec2(w as f32, h as f32),
469            color,
470        })
471    }
472
473    /// The atlas overflowed during this frame; it is rebuilt on the next one.
474    pub(crate) fn needs_rebuild(&self) -> bool {
475        self.full
476    }
477}
478
479#[cfg(test)]
480mod tests {
481    use super::*;
482
483    #[test]
484    fn caret_and_hit_agree() {
485        let mut t = TextEngine::new();
486        let l = t.layout("Hello glass", &TextStyle::new(16.0));
487        for i in 0..=11 {
488            let (x, top, h) = l.caret(i);
489            assert_eq!(l.hit(vec2(x, top + h * 0.5)), i);
490        }
491    }
492
493    #[test]
494    fn multi_line_offsets() {
495        let mut t = TextEngine::new();
496        let l = t.layout("ab\ncd", &TextStyle::new(16.0));
497        assert_eq!(l.lines.len(), 2);
498        assert_eq!(l.caret(3).1, l.lines[1].top);
499        assert_eq!(l.hit(vec2(0.0, l.lines[1].top + 1.0)), 3);
500    }
501
502    #[test]
503    fn layout_is_cached() {
504        let mut t = TextEngine::new();
505        let a = t.layout("same", &TextStyle::new(14.0));
506        let b = t.layout("same", &TextStyle::new(14.0));
507        assert!(Rc::ptr_eq(&a, &b));
508    }
509}