Skip to main content

nadir_render/
text.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Laying text out in a [`Font`]: lines, wrapping, alignment, kerning and
16//! the color markup (`docs/subsystems/render.md`, "Text").
17//!
18//! Every position is a whole number of the font's pixels, from the top-left
19//! corner of the text's block. A line is scanned once to find where it
20//! ends, and again to place its glyphs, so that measuring and laying out
21//! agree and neither needs a list of its own.
22
23use std::fmt;
24
25use nadir_core::{Color, IVec2, UVec2};
26
27use crate::{Font, Glyph};
28
29/// How a text is laid out.
30#[non_exhaustive]
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
32pub struct TextLayout {
33    /// The widest a line may be, in the font's pixels, before it wraps;
34    /// `None` wraps only at `\n`.
35    ///
36    /// A line breaks at its last run of spaces before a character that
37    /// would pass it, and the spaces of that run are dropped. A word wider
38    /// than the width alone breaks between its characters, with one at
39    /// least on each line, so a line may still be wider.
40    pub max_width: Option<u32>,
41    /// Where each line goes across the block.
42    pub align: Align,
43    /// Whether the color markup is read: `{c:#ff0}` starts a run of a
44    /// color, `{/c}` ends it, and `{{` is a `{`. Off, every character is
45    /// drawn as it is.
46    pub markup: bool,
47}
48
49impl TextLayout {
50    /// No wrapping, left aligned, with markup.
51    pub const fn new() -> Self {
52        Self {
53            max_width: None,
54            align: Align::Left,
55            markup: true,
56        }
57    }
58}
59
60impl Default for TextLayout {
61    fn default() -> Self {
62        Self::new()
63    }
64}
65
66/// Where the lines of a text go across its block.
67#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
68pub enum Align {
69    /// Each line starts at the block's left edge.
70    #[default]
71    Left,
72    /// Each line is in the middle, the odd pixel to its right.
73    Center,
74    /// Each line ends at the block's right edge.
75    Right,
76}
77
78/// A character of a text, laid out: which glyph it draws, and where.
79#[non_exhaustive]
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81pub struct PlacedGlyph {
82    /// The character, as the text has it.
83    pub character: char,
84    /// Where it starts in the text, in bytes.
85    pub byte: usize,
86    /// The glyph it draws: its font's, its font's space for a no-break
87    /// space (U+00A0) the font lacks, or the fallback.
88    pub glyph: Glyph,
89    /// Where the glyph's rectangle's top-left corner is, in the font's
90    /// pixels from the block's top-left corner.
91    pub position: IVec2,
92    /// The color of the markup run it is in, if any.
93    pub run: Option<Color>,
94    /// Whether the font lacks the character, so that it draws the fallback.
95    pub missing: bool,
96    /// Its line, from 0 at the top.
97    pub line: u32,
98}
99
100/// `text` with each `{` doubled, so that markup draws it as it is: for a
101/// name a player typed, say, in a text that has markup of its own.
102///
103/// ```
104/// use nadir_render::Escaped;
105///
106/// assert_eq!(Escaped("{c:#f00}").to_string(), "{{c:#f00}");
107/// ```
108#[derive(Clone, Copy, Debug, PartialEq, Eq)]
109pub struct Escaped<'a>(pub &'a str);
110
111impl fmt::Display for Escaped<'_> {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        for piece in self.0.split_inclusive('{') {
114            f.write_str(piece)?;
115            if piece.ends_with('{') {
116                f.write_str("{")?;
117            }
118        }
119        Ok(())
120    }
121}
122
123impl Font {
124    /// The size of `text`'s block as `layout` lays it out, in the font's
125    /// pixels: as wide as its widest line, or `layout.max_width` if that is
126    /// wider, and a line height for each line. A text has one line, and one
127    /// more for each `\n` and each wrap: `""` is one line of width 0.
128    ///
129    /// The block is the pen's: a glyph may reach past it by its offsets.
130    pub fn measure(&self, text: &str, layout: &TextLayout) -> UVec2 {
131        let (widest, lines) = self.lines(text, layout);
132        self.block(layout, widest, lines)
133    }
134
135    /// Lays `text` out as `layout` says, appending a [`PlacedGlyph`] to
136    /// `out` for each character drawn, spaces too, in the text's order, and
137    /// returns the block's size, as [`Font::measure`] does.
138    ///
139    /// - `\n` breaks a line, and a `\r` takes no room. A control character
140    ///   the font has no glyph for takes no room either, and places
141    ///   nothing.
142    /// - The pen starts each line at 0. Each glyph's rectangle is placed at
143    ///   the pen plus its [`Glyph::offset`], and the pen then moves by its
144    ///   advance. Before a glyph, the pen moves by the kerning of the
145    ///   glyph before it on the line and this one ([`Font::kerning`]).
146    /// - A character the font lacks draws its fallback, with no kerning on
147    ///   either side, and is `missing`.
148    /// - A line's width is the pen after its last character that is not a
149    ///   space, at least 0: spaces at a line's end take no room.
150    /// - With markup, a tag places nothing, takes no room, and kerns
151    ///   through: `A{c:#f00}V` kerns as `AV`. A run lasts across lines.
152    pub fn layout(&self, text: &str, layout: &TextLayout, out: &mut Vec<PlacedGlyph>) -> UVec2 {
153        let widest = if layout.align == Align::Left {
154            0
155        } else {
156            self.lines(text, layout).0
157        };
158        let width = i64::from(layout.max_width.unwrap_or(0)).max(widest);
159        let mut start = 0;
160        let mut lines: u32 = 0;
161        let mut widest_seen = 0;
162        let mut run = None;
163        loop {
164            let line = self.line(text, start, layout);
165            widest_seen = widest_seen.max(line.width);
166            let offset = match layout.align {
167                Align::Left => 0,
168                Align::Center => (width - line.width) / 2,
169                Align::Right => width - line.width,
170            };
171            let at = Placement {
172                start,
173                line,
174                left: offset,
175                top: i64::from(lines) * i64::from(self.line_height()),
176                index: lines,
177            };
178            self.place(text, layout, &at, &mut run, out);
179            lines = lines.saturating_add(1);
180            if line.last {
181                break;
182            }
183            start = line.next;
184        }
185        self.block(layout, widest_seen, lines)
186    }
187
188    /// The widest line of `text`, and how many lines it has.
189    fn lines(&self, text: &str, layout: &TextLayout) -> (i64, u32) {
190        let mut start = 0;
191        let mut widest = 0;
192        let mut lines: u32 = 0;
193        loop {
194            let line = self.line(text, start, layout);
195            widest = widest.max(line.width);
196            lines = lines.saturating_add(1);
197            if line.last {
198                return (widest, lines);
199            }
200            start = line.next;
201        }
202    }
203
204    /// The block of `lines` lines whose widest is `widest`.
205    fn block(&self, layout: &TextLayout, widest: i64, lines: u32) -> UVec2 {
206        let width = i64::from(layout.max_width.unwrap_or(0)).max(widest);
207        let height = i64::from(lines) * i64::from(self.line_height());
208        UVec2::new(saturate_u32(width), saturate_u32(height))
209    }
210
211    /// Finds where the line that starts at byte `start` of `text` ends.
212    fn line(&self, text: &str, start: usize, layout: &TextLayout) -> Line {
213        let max = layout.max_width.map(i64::from);
214        let mut pen: i64 = 0;
215        let mut width: i64 = 0;
216        let mut previous: Option<char> = None;
217        let mut placed_word = false;
218        // The run of spaces being read, after a word: its first byte, and
219        // the line's width before it.
220        let mut spaces: Option<(usize, i64)> = None;
221        // The last run of spaces after a word that a word followed: where
222        // the line ends if it breaks there, its width then, and where the
223        // next line starts.
224        let mut opening: Option<(usize, i64, usize)> = None;
225        let mut tokens = Tokens::new(text, start, layout.markup);
226        while let Some((byte, token)) = tokens.next() {
227            let Token::Char(character) = token else {
228                continue;
229            };
230            let (glyph, kerns, drawn) = match self.classify(character) {
231                Kind::Break => {
232                    return Line {
233                        end: byte,
234                        next: tokens.at,
235                        width: width.max(0),
236                        last: false,
237                    };
238                }
239                Kind::Nothing => continue,
240                Kind::Glyph {
241                    glyph,
242                    missing,
243                    character: drawn,
244                } => (glyph, !missing, drawn),
245            };
246            let kerning = match previous {
247                Some(before) if kerns => i64::from(self.kerning(before, drawn)),
248                _ => 0,
249            };
250            let right = pen + kerning + i64::from(glyph.advance());
251            if character == ' ' {
252                if placed_word && spaces.is_none() {
253                    spaces = Some((byte, width));
254                }
255            } else {
256                if let Some((first, before)) = spaces.take() {
257                    opening = Some((first, before, byte));
258                }
259                if let Some(max) = max
260                    && right > max
261                    && placed_word
262                {
263                    return match opening {
264                        Some((end, before, next)) => Line {
265                            end,
266                            next,
267                            width: before.max(0),
268                            last: false,
269                        },
270                        None => Line {
271                            end: byte,
272                            next: byte,
273                            width: width.max(0),
274                            last: false,
275                        },
276                    };
277                }
278                width = right;
279                placed_word = true;
280            }
281            pen = right;
282            previous = kerns.then_some(drawn);
283        }
284        Line {
285            end: text.len(),
286            next: text.len(),
287            width: width.max(0),
288            last: true,
289        }
290    }
291
292    /// Places the glyphs of a line, as `at` says, reading the markup through
293    /// to the next line's start, so that `run` is the run there.
294    fn place(
295        &self,
296        text: &str,
297        layout: &TextLayout,
298        at: &Placement,
299        run: &mut Option<Color>,
300        out: &mut Vec<PlacedGlyph>,
301    ) {
302        let Placement {
303            start,
304            line,
305            left,
306            top,
307            index,
308        } = *at;
309        let mut pen: i64 = 0;
310        let mut previous: Option<char> = None;
311        for (byte, token) in Tokens::new(text, start, layout.markup) {
312            if byte >= line.next {
313                break;
314            }
315            let character = match token {
316                Token::Color(color) => {
317                    *run = Some(color);
318                    continue;
319                }
320                Token::End => {
321                    *run = None;
322                    continue;
323                }
324                Token::Char(character) => character,
325            };
326            if byte >= line.end {
327                continue;
328            }
329            let Kind::Glyph {
330                glyph,
331                missing,
332                character: drawn,
333            } = self.classify(character)
334            else {
335                continue;
336            };
337            let kerns = !missing;
338            if let Some(before) = previous
339                && kerns
340            {
341                pen += i64::from(self.kerning(before, drawn));
342            }
343            let position = IVec2::new(
344                saturate_i32(left + pen + i64::from(glyph.offset().x)),
345                saturate_i32(top + i64::from(glyph.offset().y)),
346            );
347            out.push(PlacedGlyph {
348                character,
349                byte,
350                glyph,
351                position,
352                run: *run,
353                missing,
354                line: index,
355            });
356            pen += i64::from(glyph.advance());
357            previous = kerns.then_some(drawn);
358        }
359    }
360
361    /// What `character` is to the layout.
362    fn classify(&self, character: char) -> Kind {
363        match character {
364            '\n' => return Kind::Break,
365            '\r' => return Kind::Nothing,
366            _ => {}
367        }
368        if let Some(glyph) = self.glyph(character) {
369            return Kind::Glyph {
370                glyph,
371                missing: false,
372                character,
373            };
374        }
375        if character.is_control() {
376            return Kind::Nothing;
377        }
378        if character == '\u{a0}'
379            && let Some(glyph) = self.glyph(' ')
380        {
381            return Kind::Glyph {
382                glyph,
383                missing: false,
384                character: ' ',
385            };
386        }
387        Kind::Glyph {
388            glyph: self.fallback(),
389            missing: true,
390            character,
391        }
392    }
393}
394
395/// The color a glyph of a markup run is drawn in, in a text of `color`:
396/// the run's red, green and blue, and its alpha times the text's.
397pub(crate) fn run_color(color: Color, run: Option<Color>) -> Color {
398    match run {
399        None => color,
400        Some(run) => {
401            let alpha = (u16::from(run.a) * u16::from(color.a) + 127) / 255;
402            Color::rgba(run.r, run.g, run.b, alpha as u8)
403        }
404    }
405}
406
407/// Where a line ends.
408#[derive(Clone, Copy, Debug, PartialEq, Eq)]
409struct Line {
410    /// The byte its characters end at: the `\n`, the run of spaces it broke
411    /// at, the character it broke before, or the text's end.
412    end: usize,
413    /// The byte the next line starts at.
414    next: usize,
415    /// Its width in pixels, at least 0.
416    width: i64,
417    /// Whether it ends the text.
418    last: bool,
419}
420
421/// Where a line's glyphs go.
422#[derive(Clone, Copy, Debug)]
423struct Placement {
424    /// The byte the line starts at.
425    start: usize,
426    line: Line,
427    /// The pen's origin, from the block's top-left corner.
428    left: i64,
429    top: i64,
430    /// The line's index, from 0 at the top.
431    index: u32,
432}
433
434/// What a character is to the layout.
435enum Kind {
436    /// A `\n`.
437    Break,
438    /// Nothing: no glyph, no room.
439    Nothing,
440    /// A glyph: the font's, or the fallback when the font lacks the
441    /// character (`missing`). `character` is the one it kerns as.
442    Glyph {
443        glyph: Glyph,
444        missing: bool,
445        character: char,
446    },
447}
448
449/// A piece of a text: a character, or a tag of its markup.
450#[derive(Clone, Copy, Debug, PartialEq, Eq)]
451enum Token {
452    Char(char),
453    /// `{c:#…}`: a run of this color starts.
454    Color(Color),
455    /// `{/c}`: the run ends.
456    End,
457}
458
459/// The tokens of a text from a byte on, each with the byte it starts at.
460struct Tokens<'a> {
461    text: &'a str,
462    /// The byte the next token starts at.
463    at: usize,
464    markup: bool,
465}
466
467impl<'a> Tokens<'a> {
468    fn new(text: &'a str, at: usize, markup: bool) -> Self {
469        Self { text, at, markup }
470    }
471}
472
473impl Iterator for Tokens<'_> {
474    type Item = (usize, Token);
475
476    fn next(&mut self) -> Option<(usize, Token)> {
477        let start = self.at;
478        let rest = self.text.get(start..)?;
479        let character = rest.chars().next()?;
480        if self.markup && character == '{' {
481            let tag = if rest.starts_with("{{") {
482                Some((Token::Char('{'), 2))
483            } else if rest.starts_with("{/c}") {
484                Some((Token::End, 4))
485            } else {
486                color_tag(rest).map(|(color, length)| (Token::Color(color), length))
487            };
488            if let Some((token, length)) = tag {
489                self.at += length;
490                return Some((start, token));
491            }
492        }
493        self.at += character.len_utf8();
494        Some((start, Token::Char(character)))
495    }
496}
497
498/// The color of the tag `rest` starts with, `{c:#` then 3, 4, 6 or 8 hex
499/// digits then `}`, and the tag's length in bytes. Three or four digits are
500/// each one channel's twice (`#f80` is `#ff8800`); with no alpha, alpha is
501/// 255.
502fn color_tag(rest: &str) -> Option<(Color, usize)> {
503    let body = rest.strip_prefix("{c:#")?;
504    let digits = body.bytes().take_while(u8::is_ascii_hexdigit).count();
505    if !matches!(digits, 3 | 4 | 6 | 8) || body.as_bytes().get(digits) != Some(&b'}') {
506        return None;
507    }
508    let hex = body.as_bytes();
509    let nibble = |i: usize| (hex[i] as char).to_digit(16).unwrap_or(0) as u8;
510    let channel = |i: usize| {
511        if digits <= 4 {
512            nibble(i) * 17
513        } else {
514            nibble(2 * i) * 16 + nibble(2 * i + 1)
515        }
516    };
517    let alpha = if digits == 4 || digits == 8 {
518        channel(3)
519    } else {
520        255
521    };
522    let color = Color::rgba(channel(0), channel(1), channel(2), alpha);
523    Some((color, "{c:#".len() + digits + 1))
524}
525
526/// `value` as a `u32`, at most `u32::MAX` and at least 0.
527fn saturate_u32(value: i64) -> u32 {
528    value.clamp(0, i64::from(u32::MAX)) as u32
529}
530
531/// `value` as an `i32`, within the `i32` range.
532fn saturate_i32(value: i64) -> i32 {
533    value.clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32
534}
535
536#[cfg(test)]
537mod tests {
538    use nadir_core::testing::check;
539
540    use super::*;
541    use crate::font::tests::{FONT, decoded};
542
543    /// The tiny test font: A and V 4 wide, kerned -1 together; i 3 wide,
544    /// placed 1 in; a space 2 wide; the fallback 4 wide; lines 6 high. It
545    /// kerns A and B, and B and V, though it lacks B.
546    fn font() -> Font {
547        decoded(FONT).expect("a font")
548    }
549
550    /// The characters placed, with their x and line, and the block.
551    fn placed(text: &str, layout: TextLayout) -> (Vec<(char, i32, u32)>, UVec2) {
552        let font = font();
553        let mut out = Vec::new();
554        let size = font.layout(text, &layout, &mut out);
555        assert_eq!(size, font.measure(text, &layout), "{text:?}");
556        let placed = out
557            .iter()
558            .map(|glyph| (glyph.character, glyph.position.x, glyph.line))
559            .collect();
560        (placed, size)
561    }
562
563    fn wrapped(width: u32) -> TextLayout {
564        TextLayout {
565            max_width: Some(width),
566            ..TextLayout::new()
567        }
568    }
569
570    fn aligned(align: Align, max_width: Option<u32>) -> TextLayout {
571        TextLayout {
572            max_width,
573            align,
574            ..TextLayout::new()
575        }
576    }
577
578    #[test]
579    fn by_default_it_reads_markup_and_neither_wraps_nor_aligns() {
580        let layout = TextLayout::default();
581        assert_eq!(layout, TextLayout::new());
582        assert!(layout.markup);
583        assert_eq!((layout.max_width, layout.align), (None, Align::Left));
584    }
585
586    #[test]
587    fn kerning_moves_the_second_glyph_and_never_crosses_a_line() {
588        // A at 0, then V at 4 - 1: the pair's kerning adds to A's advance.
589        let (glyphs, size) = placed("AV", TextLayout::new());
590        assert_eq!(glyphs, [('A', 0, 0), ('V', 3, 0)]);
591        assert_eq!(size, UVec2::new(7, 6));
592        let (glyphs, size) = placed("AVA", TextLayout::new());
593        assert_eq!(glyphs, [('A', 0, 0), ('V', 3, 0), ('A', 6, 0)]);
594        assert_eq!(size.x, 10);
595        // Not across a `\n`, or a space.
596        let (glyphs, size) = placed("A\nV", TextLayout::new());
597        assert_eq!(glyphs, [('A', 0, 0), ('V', 0, 1)]);
598        assert_eq!(size, UVec2::new(4, 12));
599        assert_eq!(placed("A V", TextLayout::new()).0[2], ('V', 6, 0));
600        // Each glyph's rectangle at the pen plus its offset: i is 1 in.
601        assert_eq!(
602            placed("Ai", TextLayout::new()).0,
603            [('A', 0, 0), ('i', 5, 0)]
604        );
605    }
606
607    #[test]
608    fn a_pair_is_kerned_in_its_own_order() {
609        // V then A kerned -2, A then V -1.
610        let font = decoded(&FONT.replacen("[86, 65, -1]", "[86, 65, -2]", 1)).expect("a font");
611        let mut out = Vec::new();
612        assert_eq!(font.layout("AV", &TextLayout::new(), &mut out).x, 7);
613        assert_eq!(out[1].position.x, 3);
614        out.clear();
615        assert_eq!(font.layout("VA", &TextLayout::new(), &mut out).x, 6);
616        assert_eq!(out[1].position.x, 2);
617    }
618
619    #[test]
620    fn a_glyph_s_rectangle_is_placed_by_its_offsets_on_its_line() {
621        let font = font();
622        let mut out = Vec::new();
623        font.layout("A\ni", &TextLayout::new(), &mut out);
624        assert_eq!(out[0].position, IVec2::new(0, 1));
625        assert_eq!(out[1].position, IVec2::new(1, 6 + 1));
626        assert_eq!(out[1].byte, 2);
627        assert_eq!(out[1].glyph, font.glyph('i').expect("i"));
628    }
629
630    #[test]
631    fn lines_count_every_break_and_the_empty_ones() {
632        assert_eq!(placed("", TextLayout::new()), (vec![], UVec2::new(0, 6)));
633        assert_eq!(placed("\n", TextLayout::new()).1, UVec2::new(0, 12));
634        let (glyphs, size) = placed("Ai\n", TextLayout::new());
635        assert_eq!(glyphs.len(), 2);
636        assert_eq!(size, UVec2::new(7, 12));
637        // `\r` takes no room, so `\r\n` is one break.
638        assert_eq!(
639            placed("A\r\nV", TextLayout::new()),
640            placed("A\nV", TextLayout::new())
641        );
642        assert_eq!(
643            placed("A\rV", TextLayout::new()).0,
644            [('A', 0, 0), ('V', 3, 0)]
645        );
646        // An empty text in a box is as wide as the box.
647        assert_eq!(placed("", wrapped(10)).1, UVec2::new(10, 6));
648    }
649
650    #[test]
651    fn each_line_is_aligned_in_the_widest_or_the_box() {
652        // Lines of 7 (AV, kerned) and 3 (i): the block is 7 wide.
653        let text = "AV\ni";
654        let (left, size) = placed(text, aligned(Align::Left, None));
655        assert_eq!(size, UVec2::new(7, 12));
656        assert_eq!(left[2], ('i', 1, 1));
657        let (right, _) = placed(text, aligned(Align::Right, None));
658        assert_eq!(right, [('A', 0, 0), ('V', 3, 0), ('i', 4 + 1, 1)]);
659        // 7 - 3 = 4, halved.
660        let (center, _) = placed(text, aligned(Align::Center, None));
661        assert_eq!(center[2], ('i', 2 + 1, 1));
662        // In a box of 12: the odd pixel to the right.
663        let (center, size) = placed(text, aligned(Align::Center, Some(12)));
664        assert_eq!(size, UVec2::new(12, 12));
665        assert_eq!(center[..2], [('A', 2, 0), ('V', 5, 0)]);
666        assert_eq!(center[2], ('i', 4 + 1, 1));
667        let (right, _) = placed(text, aligned(Align::Right, Some(12)));
668        assert_eq!(right[0], ('A', 5, 0));
669        // Spaces at a line's end take no room, and are still placed.
670        let (right, size) = placed("A  ", aligned(Align::Right, Some(10)));
671        assert_eq!(size.x, 10);
672        assert_eq!(right, [('A', 6, 0), (' ', 10, 0), (' ', 12, 0)]);
673    }
674
675    #[test]
676    fn a_line_wraps_at_its_last_spaces_and_drops_them() {
677        // "A A A": each A 4, each space 2. At 10, "A A" (10) fits, and the
678        // third A goes down; the space between is dropped.
679        let (glyphs, size) = placed("A A A", wrapped(10));
680        assert_eq!(glyphs, [('A', 0, 0), (' ', 4, 0), ('A', 6, 0), ('A', 0, 1)]);
681        assert_eq!(size, UVec2::new(10, 12));
682        // A run of spaces is dropped whole.
683        let (glyphs, _) = placed("A   A", wrapped(8));
684        assert_eq!(glyphs, [('A', 0, 0), ('A', 0, 1)]);
685        // Spaces before a break, or at the end, never wrap.
686        let (glyphs, size) = placed("A      ", wrapped(4));
687        assert_eq!(glyphs.len(), 7);
688        assert_eq!(size, UVec2::new(4, 6));
689        // The width counts kerning: "AV" is 7.
690        assert_eq!(placed("AV AV", wrapped(7)).1, UVec2::new(7, 12));
691        assert_eq!(placed("AV AV", wrapped(16)).1, UVec2::new(16, 6));
692    }
693
694    #[test]
695    fn spaces_that_start_a_paragraph_are_kept_and_never_a_break() {
696        let (glyphs, size) = placed("  A", wrapped(4));
697        assert_eq!(glyphs, [(' ', 0, 0), (' ', 2, 0), ('A', 4, 0)]);
698        assert_eq!(size, UVec2::new(8, 6), "wider than its box: one word");
699        let (glyphs, _) = placed("A\n  A", wrapped(4));
700        assert_eq!(glyphs[1..], [(' ', 0, 1), (' ', 2, 1), ('A', 4, 1)]);
701        // Nor are they a place to break a word that goes on past the box.
702        let (glyphs, size) = placed("  AAAA", wrapped(9));
703        assert_eq!(
704            glyphs,
705            [
706                (' ', 0, 0),
707                (' ', 2, 0),
708                ('A', 4, 0),
709                ('A', 0, 1),
710                ('A', 4, 1),
711                ('A', 0, 2)
712            ]
713        );
714        assert_eq!(size, UVec2::new(9, 18));
715    }
716
717    #[test]
718    fn a_word_wider_than_the_box_breaks_between_its_characters() {
719        // "AAAA" at 9: two of 4 a line.
720        let (glyphs, size) = placed("AAAA", wrapped(9));
721        assert_eq!(glyphs, [('A', 0, 0), ('A', 4, 0), ('A', 0, 1), ('A', 4, 1)]);
722        assert_eq!(size, UVec2::new(9, 12));
723        // A box narrower than a glyph still takes one a line.
724        let (glyphs, size) = placed("AiA", wrapped(0));
725        assert_eq!(glyphs, [('A', 0, 0), ('i', 1, 1), ('A', 0, 2)]);
726        assert_eq!(size, UVec2::new(4, 18));
727        // A word that does not fit after another goes down whole first.
728        let (glyphs, _) = placed("i AAAA", wrapped(9));
729        assert_eq!(
730            glyphs,
731            [
732                ('i', 1, 0),
733                ('A', 0, 1),
734                ('A', 4, 1),
735                ('A', 0, 2),
736                ('A', 4, 2)
737            ]
738        );
739    }
740
741    #[test]
742    fn a_wrapped_line_is_aligned_by_what_stays_on_it() {
743        // "i AAAA" at 9: "i" (3), "AA" (8), "AA" (8), in a box of 9.
744        let (right, _) = placed("i AAAA", aligned(Align::Right, Some(9)));
745        assert_eq!(right[0], ('i', 6 + 1, 0));
746        assert_eq!(right[1..3], [('A', 1, 1), ('A', 5, 1)]);
747        let (center, _) = placed("i AAAA", aligned(Align::Center, Some(9)));
748        assert_eq!(center[0], ('i', 3 + 1, 0));
749        assert_eq!(center[1], ('A', 0, 1));
750    }
751
752    #[test]
753    fn a_missing_character_draws_the_fallback_and_kerns_with_nothing() {
754        let font = font();
755        let mut out = Vec::new();
756        // B is missing: no kerning on either side, though the font kerns
757        // A and B, and B and V.
758        font.layout("ABV", &TextLayout::new(), &mut out);
759        let b = out[1];
760        assert_eq!(
761            (b.character, b.missing, b.glyph),
762            ('B', true, font.fallback())
763        );
764        assert_eq!(out[2].position.x, 8);
765        assert!(!out[0].missing && !out[2].missing);
766        // A no-break space the font lacks is its space, and never a break:
767        // "i A A" at 12 would break after the second space, and with a
768        // no-break space for it breaks after the first.
769        out.clear();
770        font.layout("i A\u{a0}A", &wrapped(12), &mut out);
771        let space = out[2];
772        assert_eq!((space.character, space.missing), ('\u{a0}', false));
773        assert_eq!(space.glyph, font.glyph(' ').expect("a space"));
774        let lines: Vec<(char, u32)> = out
775            .iter()
776            .map(|glyph| (glyph.character, glyph.line))
777            .collect();
778        assert_eq!(lines, [('i', 0), ('A', 1), ('\u{a0}', 1), ('A', 1)]);
779        assert_eq!(placed("i A A", wrapped(12)).0.last(), Some(&('A', 0, 1)));
780        // A control character the font lacks takes no room, and kerns
781        // through.
782        assert_eq!(
783            placed("A\tV", TextLayout::new()).0,
784            [('A', 0, 0), ('V', 3, 0)]
785        );
786        assert_eq!(placed("A\u{7f}", TextLayout::new()).1.x, 4);
787        // C1 too.
788        assert_eq!(
789            placed("A\u{85}V", TextLayout::new()),
790            (vec![('A', 0, 0), ('V', 3, 0)], UVec2::new(7, 6))
791        );
792    }
793
794    #[test]
795    fn markup_colors_runs_and_takes_no_room() {
796        let font = font();
797        let mut out = Vec::new();
798        let size = font.layout("A{c:#f80}V{/c}A", &TextLayout::new(), &mut out);
799        let orange = Color::rgb(0xff, 0x88, 0x00);
800        let runs: Vec<_> = out.iter().map(|glyph| glyph.run).collect();
801        assert_eq!(runs, [None, Some(orange), None]);
802        // The tags kern through: AVA as before.
803        let xs: Vec<i32> = out.iter().map(|glyph| glyph.position.x).collect();
804        assert_eq!(xs, [0, 3, 6]);
805        assert_eq!(size.x, 10);
806        assert_eq!(out[1].byte, 9, "V's place in the text");
807        // Each form of color, either case; a run lasts to the next tag or
808        // the end, across lines.
809        for (tag, color) in [
810            ("{c:#F80}", orange),
811            ("{c:#f808}", Color::rgba(0xff, 0x88, 0x00, 0x88)),
812            ("{c:#12aB34}", Color::rgb(0x12, 0xab, 0x34)),
813            ("{c:#12ab3456}", Color::rgba(0x12, 0xab, 0x34, 0x56)),
814        ] {
815            out.clear();
816            font.layout(
817                &format!("A{tag}V\nA{{c:#000}}A"),
818                &TextLayout::new(),
819                &mut out,
820            );
821            let runs: Vec<_> = out.iter().map(|glyph| glyph.run).collect();
822            assert_eq!(
823                runs,
824                [None, Some(color), Some(color), Some(Color::BLACK)],
825                "{tag}"
826            );
827        }
828        // `{/c}` with no run is a tag still.
829        assert_eq!(placed("{/c}A", TextLayout::new()).0, [('A', 0, 0)]);
830        // A tag in the spaces a line breaks at still starts its run.
831        out.clear();
832        font.layout("A {c:#f00} A", &wrapped(4), &mut out);
833        let lines: Vec<(u32, Option<Color>)> =
834            out.iter().map(|glyph| (glyph.line, glyph.run)).collect();
835        assert_eq!(lines, [(0, None), (1, Some(Color::rgb(255, 0, 0)))]);
836    }
837
838    #[test]
839    fn what_is_not_a_tag_is_drawn_as_it_is() {
840        let characters = |text: &str, markup: bool| -> String {
841            let layout = TextLayout {
842                markup,
843                ..TextLayout::new()
844            };
845            placed(text, layout).0.iter().map(|&(c, _, _)| c).collect()
846        };
847        assert_eq!(characters("{{c:#f00}A", true), "{c:#f00}A");
848        assert_eq!(characters("{{", true), "{");
849        assert_eq!(characters("}}", true), "}}");
850        for text in [
851            "{c:#f0}",
852            "{c:#f0000}",
853            "{c:#ff00000}",
854            "{c:#gg0}",
855            "{C:#f00}",
856            "{c: #f00}",
857            "{c:#f00",
858            "{/C}",
859            "{",
860        ] {
861            assert_eq!(characters(text, true), text, "{text}");
862        }
863        // After a `{` that starts no tag, a tag may still follow.
864        let font = font();
865        let mut out = Vec::new();
866        font.layout("{c:{c:#f00}A", &TextLayout::new(), &mut out);
867        let drawn: String = out.iter().map(|glyph| glyph.character).collect();
868        assert_eq!(drawn, "{c:A");
869        assert_eq!(out[3].run, Some(Color::rgb(255, 0, 0)));
870        // Off, every character is drawn.
871        assert_eq!(characters("{c:#f00}A{/c}{{", false), "{c:#f00}A{/c}{{");
872        // A tag split by a line is no tag, and the `\n` still breaks.
873        assert_eq!(placed("{c:#f\n00}", TextLayout::new()).1.y, 12);
874    }
875
876    #[test]
877    fn a_run_s_color_keeps_its_rgb_and_takes_the_text_s_alpha_too() {
878        let text = Color::rgba(10, 20, 30, 128);
879        assert_eq!(run_color(text, None), text);
880        assert_eq!(
881            run_color(text, Some(Color::rgb(255, 0, 0))),
882            Color::rgba(255, 0, 0, 128)
883        );
884        assert_eq!(
885            run_color(text, Some(Color::rgba(0, 255, 0, 128))),
886            Color::rgba(0, 255, 0, 64)
887        );
888        assert_eq!(
889            run_color(Color::WHITE, Some(Color::rgba(1, 2, 3, 77))),
890            Color::rgba(1, 2, 3, 77)
891        );
892        // Rounded: 200 × 200 / 255 is 156.9.
893        assert_eq!(
894            run_color(Color::rgba(0, 0, 0, 200), Some(Color::rgba(1, 2, 3, 200))),
895            Color::rgba(1, 2, 3, 157)
896        );
897    }
898
899    #[test]
900    fn escaped_text_draws_as_written() {
901        assert_eq!(Escaped("a{b}{{c").to_string(), "a{{b}{{{{c");
902        assert_eq!(Escaped("").to_string(), "");
903        let name = "{c:#f00}Eve{/c}";
904        let text = format!("{{c:#0f0}}{}{{/c}}", Escaped(name));
905        let font = font();
906        let mut out = Vec::new();
907        font.layout(&text, &TextLayout::new(), &mut out);
908        let drawn: String = out.iter().map(|glyph| glyph.character).collect();
909        assert_eq!(drawn, name);
910        assert!(
911            out.iter()
912                .all(|glyph| glyph.run == Some(Color::rgb(0, 255, 0)))
913        );
914    }
915
916    #[test]
917    fn measure_and_layout_agree_and_every_text_ends() {
918        const PIECES: &[&str] = &[
919            "A",
920            "V",
921            "i",
922            " ",
923            "  ",
924            "\u{a0}",
925            "\n",
926            "\r",
927            "\t",
928            "\u{85}",
929            "B",
930            "é",
931            "{",
932            "}",
933            "{{",
934            "{c:#f00}",
935            "{c:#12345678}",
936            "{/c}",
937            "{c:#zz}",
938        ];
939        let font = font();
940        check(
941            "layout",
942            3_000,
943            |rng| {
944                let length = rng.range(0..24u32);
945                let text: String = (0..length)
946                    .map(|_| PIECES[rng.range(0..PIECES.len() as u32) as usize])
947                    .collect();
948                let max_width = match rng.range(0..3u32) {
949                    0 => None,
950                    _ => Some(rng.range(0..20u32)),
951                };
952                let align = [Align::Left, Align::Center, Align::Right][rng.range(0..3u32) as usize];
953                let markup = rng.range(0..4u32) != 0;
954                (text, max_width, align, markup)
955            },
956            |(text, max_width, align, markup)| {
957                let layout = TextLayout {
958                    max_width: *max_width,
959                    align: *align,
960                    markup: *markup,
961                };
962                let mut out = Vec::new();
963                let size = font.layout(text, &layout, &mut out);
964                if size != font.measure(text, &layout) {
965                    return Err(format!("measured {:?}", font.measure(text, &layout)));
966                }
967                let lines = size.y / font.line_height();
968                if out.iter().any(|glyph| glyph.line >= lines) {
969                    return Err(format!("a glyph past {lines} lines"));
970                }
971                if out.windows(2).any(|pair| pair[0].byte >= pair[1].byte) {
972                    return Err("out of the text's order".to_string());
973                }
974                let at = |byte: usize| text.get(byte..).and_then(|rest| rest.chars().next());
975                if out
976                    .iter()
977                    .any(|glyph| at(glyph.byte) != Some(glyph.character))
978                {
979                    return Err("a glyph's byte is not its character".to_string());
980                }
981                // The pen is in the block before each glyph but a space,
982                // which may go on past a line's end.
983                for glyph in out.iter().filter(|glyph| glyph.character != ' ') {
984                    let left = glyph.position.x - glyph.glyph.offset().x;
985                    if left < 0 || left as u32 > size.x {
986                        return Err(format!("{glyph:?} outside a block of {size:?}"));
987                    }
988                }
989                Ok(())
990            },
991        );
992    }
993}