crcbl-ui 0.2.0

Crucible immediate-mode GUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
//! Text layout: advancing, kerning, greedy line breaking and alignment.
//!
//! # The line breaker's rules
//!
//! * **Explicit newlines** end a line, always; an empty string, and an empty
//!   line between two newlines, is still one line tall.
//! * **Soft breaks are at spaces** (U+0020) and nowhere else. Words are the
//!   runs between spaces; a line takes words greedily while the word's right
//!   edge stays within the wrap width.
//! * **The spaces a line breaks at belong to no line**: they are not drawn,
//!   not measured, and the next line starts at the word after them. Spaces a
//!   line ends with before a newline or the end of the text are not measured
//!   either. Spaces anywhere else — leading a paragraph, or several between two
//!   words — take their advance.
//! * **A word wider than the wrap width is not broken**: it takes a line of its
//!   own and overflows it, which is CSS's `overflow-wrap: normal`.
//! * **The wrap width is whole pixels**: [`wrap_width`] floors it, so a
//!   measurement and a later layout at widths that differ by a fraction of a
//!   pixel — Taffy's unrounded box and the rounded one — break at the same
//!   places, and a measured width, rounded up by [`TextLayout::measure`], always
//!   fits the lines it was measured from.
//!
//! Kerning applies between every two consecutive glyphs on a line in the same
//! face, spaces included, and never across a break.
//!
//! # Fallback faces
//!
//! Each char is drawn by the face [`fallback::map_char`] picks from the font
//! and the fallback faces it carries, advanced by that face's own advance at
//! its own scale; [`TextLayout::face_runs`] cuts the glyphs into the
//! stretches each face draws. A presentation selector or a zero-width joiner
//! draws nothing and takes no width. The lines' vertical metrics are the
//! font's own: a taller fallback glyph does not make its line taller.
//!
//! # Vertical metrics
//!
//! Lines are [`TextLayout::line_height`] apart. Within one, the baseline is
//! placed the way CSS places it: the font's ascent-to-descent box centred in
//! the line, so half the leading is above it and half below.

use core::ops::Range;

use glam::Vec2;

use super::fallback::{self, Mapped};
use super::{Font, GlyphId};

/// How close below a whole pixel a width may be and still count as that pixel.
///
/// Two computations of one box width — Taffy's measurement and a later layout
/// from its stored size — can land an ulp either side of an integer, and
/// flooring those two would disagree by a whole pixel.
pub const WRAP_EPSILON: f32 = 1.0 / 256.0;

/// The width lines are broken at for a box `width` pixels wide: whole pixels.
/// See the module docs.
#[must_use]
pub fn wrap_width(width: f32) -> f32 {
    (width + WRAP_EPSILON).floor()
}

/// `text-align`: where each line sits across its box.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TextAlign {
    /// Against the left edge — `left` and `start`.
    #[default]
    Left,
    /// Centred — `center`.
    Center,
    /// Against the right edge — `right` and `end`.
    Right,
}

/// One glyph as laid out.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PositionedGlyph {
    /// Which glyph.
    pub glyph: GlyphId,
    /// Its pen position relative to the text's top-left: x along the line, y
    /// the line's baseline.
    pub offset: Vec2,
}

/// One line as laid out.
#[derive(Clone, Debug, PartialEq)]
pub struct TextLine {
    /// Its glyphs in [`TextLayout::glyphs`]. Spaces draw nothing and are not
    /// among them.
    pub glyphs: Range<usize>,
    /// Its width in pixels, trailing spaces excluded.
    pub width: f32,
    /// Its baseline, from the text's top.
    pub baseline: f32,
    /// Its left edge's offset from the text's left, from alignment.
    pub offset: f32,
}

/// A string laid out in one font at one size. See the module docs.
#[derive(Clone, Debug, PartialEq)]
pub struct TextLayout {
    /// The font it was laid out in, fallback faces and all.
    font: Font,
    glyphs: Vec<PositionedGlyph>,
    /// Each glyph's face, as [`Font::face`] numbers it.
    faces: Vec<u8>,
    /// The byte offset in the text of each glyph's char.
    bytes: Vec<usize>,
    /// The text's length in bytes.
    text_len: usize,
    lines: Vec<TextLine>,
    line_height: f32,
}

/// A stretch of a [`TextLayout`]'s glyphs that one face draws: what
/// [`TextLayout::face_runs`] cuts it into.
#[derive(Clone, Debug, PartialEq)]
pub struct FaceRun<'a> {
    /// The face: the layout's font or one of its fallback faces.
    pub font: &'a Font,
    /// Its glyphs.
    pub glyphs: &'a [PositionedGlyph],
    /// The bytes of the text it spells: from its first glyph's char, or the
    /// text's start for the first run, to the next run's start or the text's
    /// end.
    pub text: Range<usize>,
}

/// The line being filled.
struct Line {
    first: usize,
    pen: f32,
    previous: Option<Mapped>,
    /// The right edge of its last word.
    width: f32,
    has_word: bool,
}

impl Line {
    const fn new(first: usize) -> Self {
        Self {
            first,
            pen: 0.0,
            previous: None,
            width: 0.0,
            has_word: false,
        }
    }
}

/// Where `mapped`, drawn in `font` at `size` after `previous` on its line, is
/// placed from a pen at `pen`, and the pen after it: kerned against
/// `previous` when one face draws both, then advanced by its face's advance
/// at its face's scale.
pub(crate) fn advance_pen(
    font: &Font,
    size: f32,
    pen: f32,
    previous: Option<Mapped>,
    mapped: Mapped,
) -> (f32, f32) {
    let face = font.face(mapped.face);
    let scale = face.metrics().scale(size);
    let mut at = pen;
    if let Some(previous) = previous.filter(|previous| previous.face == mapped.face) {
        at += face.kerning(previous.glyph, mapped.glyph) * scale;
    }
    (at, at + face.advance(mapped.glyph) * scale)
}

impl TextLayout {
    /// Positions the glyphs `word` at `size` from `line`'s pen, writing each
    /// one's x, and returns the word's right edge.
    fn place(&mut self, word: Range<usize>, size: f32, line: &Line) -> f32 {
        let mut pen = line.pen;
        let mut previous = line.previous;
        let faces = &self.faces[word.clone()];
        for (positioned, &face) in self.glyphs[word].iter_mut().zip(faces) {
            let mapped = Mapped {
                face,
                glyph: positioned.glyph,
            };
            let (at, after) = advance_pen(&self.font, size, pen, previous, mapped);
            positioned.offset.x = at;
            pen = after;
            previous = Some(mapped);
        }
        pen
    }

    /// Lays `text` out in `font` — and the fallback faces it carries — at
    /// `size` pixels per em, lines `line_height` apart, broken to fit `wrap`
    /// pixels when given — see the module docs — and every line against the
    /// left.
    #[must_use]
    pub fn new(font: &Font, text: &str, size: f32, line_height: f32, wrap: Option<f32>) -> Self {
        let metrics = font.metrics();
        let scale = metrics.scale(size);
        let wrap = wrap.map(wrap_width);
        let mut layout = Self {
            font: font.clone(),
            glyphs: Vec::with_capacity(text.len()),
            faces: Vec::with_capacity(text.len()),
            bytes: Vec::with_capacity(text.len()),
            text_len: text.len(),
            lines: Vec::new(),
            line_height,
        };
        let mut paragraph_start = 0;
        for paragraph in text.split('\n') {
            let mut line = Line::new(layout.glyphs.len());
            let mut chars = fallback::map_text(font, paragraph).peekable();
            while let Some(&(_, c, mapped)) = chars.peek() {
                if c == ' ' {
                    chars.next();
                    if let Some(mapped) = mapped {
                        line.pen = advance_pen(font, size, line.pen, line.previous, mapped).1;
                        line.previous = Some(mapped);
                    }
                    continue;
                }
                let word_start = layout.glyphs.len();
                while let Some(&(byte, c, mapped)) = chars.peek() {
                    if c == ' ' {
                        break;
                    }
                    chars.next();
                    let Some(mapped) = mapped else { continue };
                    layout.glyphs.push(PositionedGlyph {
                        glyph: mapped.glyph,
                        offset: Vec2::ZERO,
                    });
                    layout.faces.push(mapped.face);
                    layout.bytes.push(paragraph_start + byte);
                }
                let word = word_start..layout.glyphs.len();
                let mut right = layout.place(word.clone(), size, &line);
                if line.has_word && wrap.is_some_and(|wrap| right > wrap) {
                    layout.finish_line(&line, word_start);
                    line = Line::new(word_start);
                    right = layout.place(word.clone(), size, &line);
                }
                if let Some(last) = word.clone().last() {
                    line.previous = Some(Mapped {
                        face: layout.faces[last],
                        glyph: layout.glyphs[last].glyph,
                    });
                }
                line.pen = right;
                line.width = right;
                line.has_word = true;
            }
            let end = layout.glyphs.len();
            layout.finish_line(&line, end);
            paragraph_start += paragraph.len() + 1;
        }

        let ascent = metrics.ascent * scale;
        let descent = metrics.descent * scale;
        let above = (line_height - (ascent - descent)) * 0.5 + ascent;
        for (index, line) in layout.lines.iter_mut().enumerate() {
            line.baseline = index as f32 * line_height + above;
            for glyph in &mut layout.glyphs[line.glyphs.clone()] {
                glyph.offset.y = line.baseline;
            }
        }
        layout
    }

    fn finish_line(&mut self, line: &Line, end: usize) {
        self.lines.push(TextLine {
            glyphs: line.first..end,
            width: line.width,
            baseline: 0.0,
            offset: 0.0,
        });
    }

    /// Moves every line across a box `width` pixels wide as `align` says. A
    /// line wider than the box starts at its left edge, as CSS starts an
    /// overflowing line.
    pub fn align(&mut self, width: f32, align: TextAlign) {
        for line in &mut self.lines {
            let room = (width - line.width).max(0.0);
            let offset = match align {
                TextAlign::Left => 0.0,
                TextAlign::Center => room * 0.5,
                TextAlign::Right => room,
            };
            for glyph in &mut self.glyphs[line.glyphs.clone()] {
                glyph.offset.x += offset - line.offset;
            }
            line.offset = offset;
        }
    }

    /// Every drawn glyph, line by line.
    #[must_use]
    pub fn glyphs(&self) -> &[PositionedGlyph] {
        &self.glyphs
    }

    /// Each of [`TextLayout::glyphs`]' faces, as [`Font::face`] numbers them
    /// for the font it was laid out in.
    #[must_use]
    pub fn faces(&self) -> &[u8] {
        &self.faces
    }

    /// The glyphs cut where the face drawing them changes, in order: what a
    /// caller draws one
    /// [`DrawList::text_glyphs`](crate::draw_list::DrawList::text_glyphs)
    /// run per, since a run is in one font. Text with no glyphs at all is one
    /// empty run in the font itself.
    #[must_use]
    pub fn face_runs(&self) -> Vec<FaceRun<'_>> {
        let mut runs = Vec::new();
        let mut start = 0;
        while start < self.glyphs.len() {
            let face = self.faces[start];
            let end = (start..self.glyphs.len())
                .find(|&at| self.faces[at] != face)
                .unwrap_or(self.glyphs.len());
            let text_start = if start == 0 { 0 } else { self.bytes[start] };
            let text_end = self.bytes.get(end).copied().unwrap_or(self.text_len);
            runs.push(FaceRun {
                font: self.font.face(face),
                glyphs: &self.glyphs[start..end],
                text: text_start..text_end,
            });
            start = end;
        }
        if runs.is_empty() {
            runs.push(FaceRun {
                font: &self.font,
                glyphs: &[],
                text: 0..self.text_len,
            });
        }
        runs
    }

    /// Every line, top to bottom.
    #[must_use]
    pub fn lines(&self) -> &[TextLine] {
        &self.lines
    }

    /// The pitch between baselines.
    #[must_use]
    pub const fn line_height(&self) -> f32 {
        self.line_height
    }

    /// The widest line's width.
    #[must_use]
    pub fn width(&self) -> f32 {
        self.lines
            .iter()
            .fold(0.0, |widest, line| widest.max(line.width))
    }

    /// Every line's height together.
    #[must_use]
    pub fn height(&self) -> f32 {
        self.lines.len() as f32 * self.line_height
    }

    /// The box the text needs: its widest line rounded up to a whole pixel, and
    /// its lines' height.
    #[must_use]
    pub fn measure(&self) -> Vec2 {
        Vec2::new(self.width().ceil(), self.height())
    }
}
#[cfg(all(test, feature = "parsed-font"))]
mod tests {
    use super::*;

    const SIZE: f32 = 16.0;
    const LINE: f32 = 20.0;
    const TEXT: &str = "The quick brown fox jumps";

    /// `text`'s width at [`SIZE`], summed here glyph by glyph: every advance,
    /// and the kerning between every two neighbours.
    fn width(text: &str) -> f32 {
        let font = Font::sans();
        let scale = font.metrics().scale(SIZE);
        let mut pen = 0.0;
        let mut previous = None;
        for c in text.chars() {
            let glyph = font.glyph_id(c);
            if let Some(previous) = previous {
                pen += font.kerning(previous, glyph) * scale;
            }
            pen += font.advance(glyph) * scale;
            previous = Some(glyph);
        }
        pen
    }

    /// Each line's glyphs, as the non-space glyphs of the string it should be.
    fn assert_lines(layout: &TextLayout, want: &[&str], what: &str) {
        let font = Font::sans();
        let got: Vec<Vec<GlyphId>> = layout
            .lines()
            .iter()
            .map(|line| {
                layout.glyphs()[line.glyphs.clone()]
                    .iter()
                    .map(|g| g.glyph)
                    .collect()
            })
            .collect();
        let expected: Vec<Vec<GlyphId>> = want
            .iter()
            .map(|line| {
                line.chars()
                    .filter(|&c| c != ' ')
                    .map(|c| font.glyph_id(c))
                    .collect()
            })
            .collect();
        assert_eq!(got, expected, "{what}: lines are not {want:?}");
        for (line, text) in layout.lines().iter().zip(want) {
            assert!(
                (line.width - width(text.trim_end())).abs() < 1e-4,
                "{what}: {text:?} measured {} rather than {}",
                line.width,
                width(text.trim_end())
            );
        }
    }

    /// **Greedy breaks at exact places for fixed widths**, the widths chosen
    /// either side of where each line's last word ends.
    #[test]
    fn lines_break_at_the_exact_places_for_fixed_widths() {
        let font = Font::sans();
        // The table's premise, from the independent sum.
        assert!(width("The quick brown fox jumps") > 188.0 && width(TEXT) < 189.0);
        assert!(width("The quick brown fox") > 141.0 && width("The quick brown fox") < 142.0);
        assert!(width("brown fox") < 68.0 && width("fox jumps") > 68.0);

        let cases: [(Option<f32>, &[&str]); 11] = [
            (None, &["The quick brown fox jumps"]),
            (Some(189.0), &["The quick brown fox jumps"]),
            (Some(188.0), &["The quick brown fox", "jumps"]),
            (Some(142.0), &["The quick brown fox", "jumps"]),
            (Some(141.9), &["The quick brown", "fox jumps"]),
            (Some(116.0), &["The quick brown", "fox jumps"]),
            (Some(69.0), &["The quick", "brown fox", "jumps"]),
            (Some(68.0), &["The", "quick", "brown fox", "jumps"]),
            (Some(67.0), &["The", "quick", "brown", "fox", "jumps"]),
            (Some(0.0), &["The", "quick", "brown", "fox", "jumps"]),
            // A word wider than the width overflows its own line unbroken.
            (Some(20.0), &["The", "quick", "brown", "fox", "jumps"]),
        ];
        for (wrap, want) in cases {
            let layout = TextLayout::new(font, TEXT, SIZE, LINE, wrap);
            assert_lines(&layout, want, &format!("wrap {wrap:?}"));
        }
    }

    /// **Newlines always break, spaces are measured only inside a line, and an
    /// empty line is still a line.**
    #[test]
    fn newlines_and_spaces_follow_the_rules() {
        let font = Font::sans();
        let layout = TextLayout::new(font, "ab\n\ncd", SIZE, LINE, None);
        assert_lines(&layout, &["ab", "", "cd"], "blank line");
        assert_eq!(layout.height(), 3.0 * LINE);

        let empty = TextLayout::new(font, "", SIZE, LINE, None);
        assert_eq!(empty.lines().len(), 1);
        assert_eq!(empty.measure(), Vec2::new(0.0, LINE));

        let spaced = TextLayout::new(font, "  The  quick   \nfox ", SIZE, LINE, None);
        assert_lines(&spaced, &["  The  quick", "fox"], "spaces");
        assert!(spaced.lines()[0].width > width("The quick"));

        // The spaces at a soft break vanish: the next line starts at zero.
        let broken = TextLayout::new(font, "The     quick", SIZE, LINE, Some(40.0));
        assert_lines(&broken, &["The", "quick"], "break in a run of spaces");
        assert_eq!(
            broken.glyphs()[broken.lines()[1].glyphs.start].offset.x,
            0.0
        );
    }

    /// **A kerned pair is advanced by the font's pair adjustment**: `AV`'s
    /// second glyph sits at `A`'s advance plus the kerning the font gives.
    #[test]
    fn a_kerned_pair_is_advanced_by_the_fonts_adjustment() {
        let font = Font::sans();
        let (a, v) = (font.glyph_id('A'), font.glyph_id('V'));
        let adjustment = font.kerning(a, v);
        assert!(adjustment < 0.0, "the committed font does not kern AV");
        let scale = font.metrics().scale(SIZE);
        let layout = TextLayout::new(font, "AV", SIZE, LINE, None);
        let step = layout.glyphs()[1].offset.x - layout.glyphs()[0].offset.x;
        assert_eq!(step, font.advance(a) * scale + adjustment * scale);
        assert!(step < font.advance(a) * scale);
    }

    /// **Baselines are one line height apart**, with the font's box centred in
    /// each line.
    #[test]
    fn baselines_are_a_line_height_apart_with_the_box_centred() {
        let font = Font::sans();
        let metrics = font.metrics();
        let scale = metrics.scale(SIZE);
        let layout = TextLayout::new(font, TEXT, SIZE, LINE, Some(0.0));
        let first =
            (LINE - (metrics.ascent - metrics.descent) * scale) * 0.5 + metrics.ascent * scale;
        for (index, line) in layout.lines().iter().enumerate() {
            assert_eq!(line.baseline, index as f32 * LINE + first);
            for glyph in &layout.glyphs()[line.glyphs.clone()] {
                assert_eq!(glyph.offset.y, line.baseline);
            }
        }
    }

    /// **Alignment moves each line across its box**: left at zero, centred at
    /// half the room, right at all of it, and an overflowing line at zero.
    #[test]
    fn alignment_places_each_line_in_its_box() {
        let font = Font::sans();
        let base = TextLayout::new(font, "The quick\nfox", SIZE, LINE, None);
        for (align, share) in [
            (TextAlign::Left, 0.0),
            (TextAlign::Center, 0.5),
            (TextAlign::Right, 1.0),
        ] {
            let mut layout = base.clone();
            layout.align(100.0, align);
            // Aligning twice is aligning once.
            layout.align(100.0, align);
            for (line, before) in layout.lines().iter().zip(base.lines()) {
                let want = (100.0 - line.width) * share;
                assert_eq!(line.offset, want, "{align:?}");
                let first = line.glyphs.start;
                assert_eq!(
                    layout.glyphs()[first].offset.x,
                    base.glyphs()[first].offset.x + want,
                    "{align:?}"
                );
                assert_eq!(line.width, before.width);
            }
        }
        let mut wide = TextLayout::new(font, TEXT, SIZE, LINE, None);
        wide.align(50.0, TextAlign::Center);
        assert_eq!(wide.lines()[0].offset, 0.0);
    }

    /// **The wrap width snaps to whole pixels with a sliver of slack**, so two
    /// computations of one width an ulp apart agree.
    #[test]
    fn the_wrap_width_is_whole_pixels() {
        assert_eq!(wrap_width(100.0), 100.0);
        assert_eq!(wrap_width(99.999_99), 100.0);
        assert_eq!(wrap_width(100.000_01), 100.0);
        assert_eq!(wrap_width(100.9), 100.0);
        let measured = TextLayout::new(Font::sans(), TEXT, SIZE, LINE, None).measure();
        let again = TextLayout::new(Font::sans(), TEXT, SIZE, LINE, Some(measured.x));
        assert_eq!(
            again.lines().len(),
            1,
            "a measured width does not fit its own line"
        );
    }
}