1use std::fmt;
24
25use nadir_core::{Color, IVec2, UVec2};
26
27use crate::{Font, Glyph};
28
29#[non_exhaustive]
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
32pub struct TextLayout {
33 pub max_width: Option<u32>,
41 pub align: Align,
43 pub markup: bool,
47}
48
49impl TextLayout {
50 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
68pub enum Align {
69 #[default]
71 Left,
72 Center,
74 Right,
76}
77
78#[non_exhaustive]
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81pub struct PlacedGlyph {
82 pub character: char,
84 pub byte: usize,
86 pub glyph: Glyph,
89 pub position: IVec2,
92 pub run: Option<Color>,
94 pub missing: bool,
96 pub line: u32,
98}
99
100#[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 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 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 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 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 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 let mut spaces: Option<(usize, i64)> = None;
221 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 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 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
395pub(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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
409struct Line {
410 end: usize,
413 next: usize,
415 width: i64,
417 last: bool,
419}
420
421#[derive(Clone, Copy, Debug)]
423struct Placement {
424 start: usize,
426 line: Line,
427 left: i64,
429 top: i64,
430 index: u32,
432}
433
434enum Kind {
436 Break,
438 Nothing,
440 Glyph {
443 glyph: Glyph,
444 missing: bool,
445 character: char,
446 },
447}
448
449#[derive(Clone, Copy, Debug, PartialEq, Eq)]
451enum Token {
452 Char(char),
453 Color(Color),
455 End,
457}
458
459struct Tokens<'a> {
461 text: &'a str,
462 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
498fn 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
526fn saturate_u32(value: i64) -> u32 {
528 value.clamp(0, i64::from(u32::MAX)) as u32
529}
530
531fn 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 fn font() -> Font {
547 decoded(FONT).expect("a font")
548 }
549
550 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 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 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 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 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 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 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 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 let (center, _) = placed(text, aligned(Align::Center, None));
661 assert_eq!(center[2], ('i', 2 + 1, 1));
662 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 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 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 let (glyphs, _) = placed("A A", wrapped(8));
684 assert_eq!(glyphs, [('A', 0, 0), ('A', 0, 1)]);
685 let (glyphs, size) = placed("A ", wrapped(4));
687 assert_eq!(glyphs.len(), 7);
688 assert_eq!(size, UVec2::new(4, 6));
689 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 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 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 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 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 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 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 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 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 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 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 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 assert_eq!(placed("{/c}A", TextLayout::new()).0, [('A', 0, 0)]);
830 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 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 assert_eq!(characters("{c:#f00}A{/c}{{", false), "{c:#f00}A{/c}{{");
872 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 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 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}