use core::ops::Range;
use glam::Vec2;
use super::fallback::{self, Mapped};
use super::{Font, GlyphId};
pub const WRAP_EPSILON: f32 = 1.0 / 256.0;
#[must_use]
pub fn wrap_width(width: f32) -> f32 {
(width + WRAP_EPSILON).floor()
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TextAlign {
#[default]
Left,
Center,
Right,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PositionedGlyph {
pub glyph: GlyphId,
pub offset: Vec2,
}
#[derive(Clone, Debug, PartialEq)]
pub struct TextLine {
pub glyphs: Range<usize>,
pub width: f32,
pub baseline: f32,
pub offset: f32,
}
#[derive(Clone, Debug, PartialEq)]
pub struct TextLayout {
font: Font,
glyphs: Vec<PositionedGlyph>,
faces: Vec<u8>,
bytes: Vec<usize>,
text_len: usize,
lines: Vec<TextLine>,
line_height: f32,
}
#[derive(Clone, Debug, PartialEq)]
pub struct FaceRun<'a> {
pub font: &'a Font,
pub glyphs: &'a [PositionedGlyph],
pub text: Range<usize>,
}
struct Line {
first: usize,
pen: f32,
previous: Option<Mapped>,
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,
}
}
}
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 {
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
}
#[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,
});
}
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;
}
}
#[must_use]
pub fn glyphs(&self) -> &[PositionedGlyph] {
&self.glyphs
}
#[must_use]
pub fn faces(&self) -> &[u8] {
&self.faces
}
#[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
}
#[must_use]
pub fn lines(&self) -> &[TextLine] {
&self.lines
}
#[must_use]
pub const fn line_height(&self) -> f32 {
self.line_height
}
#[must_use]
pub fn width(&self) -> f32 {
self.lines
.iter()
.fold(0.0, |widest, line| widest.max(line.width))
}
#[must_use]
pub fn height(&self) -> f32 {
self.lines.len() as f32 * self.line_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";
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
}
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())
);
}
}
#[test]
fn lines_break_at_the_exact_places_for_fixed_widths() {
let font = Font::sans();
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"]),
(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:?}"));
}
}
#[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"));
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
);
}
#[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);
}
#[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);
}
}
}
#[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);
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);
}
#[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"
);
}
}