use core::ops::Range;
use glam::Vec2;
use crate::font::layout::{PositionedGlyph, TextAlign, wrap_width};
use crate::font::shape::{ShapedGlyph, shape};
use crate::font::{Font, FontId, GlyphId, cluster};
use crate::text::{ASCENDER, FontAtlas, LINE_HEIGHT};
#[derive(Clone, Copy, Debug)]
pub(crate) enum RunFont<'a> {
Parsed(&'a Font),
Bitmap(f32),
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct InlineRun<'a> {
pub text: &'a str,
pub font: RunFont<'a>,
pub size: f32,
pub above: f32,
pub below: f32,
}
impl<'a> InlineRun<'a> {
pub fn new(text: &'a str, font: RunFont<'a>, size: f32, line_height: f32) -> Self {
let (above, below) = match font {
RunFont::Parsed(font) => {
let metrics = font.metrics();
let scale = metrics.scale(size);
let (ascent, descent) = (metrics.ascent * scale, metrics.descent * scale);
let above = (line_height - (ascent - descent)) * 0.5 + ascent;
(above, line_height - above)
}
RunFont::Bitmap(scale) => {
let above = ASCENDER as f32 * scale;
(above, LINE_HEIGHT * scale - above)
}
};
Self {
text,
font,
size,
above,
below,
}
}
fn shaping_key(&self) -> Option<(FontId, u32)> {
match self.font {
RunFont::Parsed(font) => Some((font.id(), self.size.to_bits())),
RunFont::Bitmap(_) => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Wrap {
None,
MinContent,
Width(f32),
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct InlineGlyph {
pub run: usize,
pub start: usize,
pub end: usize,
pub glyph: GlyphId,
pub face: u8,
pub drawn: bool,
pub breakable: bool,
pub x: f32,
pub advance: f32,
pub shift: Vec2,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Fragment {
pub run: usize,
pub line: usize,
pub glyphs: Range<usize>,
pub text: Range<usize>,
pub x: f32,
pub width: f32,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct InlineLine {
pub fragments: Range<usize>,
pub top: f32,
pub baseline: f32,
pub height: f32,
pub width: f32,
pub offset: f32,
}
#[derive(Clone, Debug, Default)]
pub(crate) struct InlineLayout {
glyphs: Vec<InlineGlyph>,
fragments: Vec<Fragment>,
lines: Vec<InlineLine>,
}
type Segment = (usize, Range<usize>);
enum Token {
Word(Vec<Segment>),
Space(Segment),
Newline(usize),
}
fn tokens(runs: &[InlineRun<'_>]) -> Vec<Token> {
let mut tokens = Vec::new();
let mut word: Vec<Segment> = Vec::new();
for (run, input) in runs.iter().enumerate() {
for bytes in cluster::clusters(input.text) {
match input.text[bytes.start..].chars().next() {
Some(c @ (' ' | '\n')) => {
if !word.is_empty() {
tokens.push(Token::Word(core::mem::take(&mut word)));
}
tokens.push(if c == ' ' {
Token::Space((run, bytes))
} else {
Token::Newline(run)
});
}
first => {
match word.last_mut() {
Some((last, range)) if *last == run && range.end == bytes.start => {
range.end = bytes.end;
}
_ => word.push((run, bytes)),
}
if first == Some('-') {
tokens.push(Token::Word(core::mem::take(&mut word)));
}
}
}
}
}
if !word.is_empty() {
tokens.push(Token::Word(word));
}
tokens
}
fn split(segments: &[Segment], run: usize, byte: usize) -> (Vec<Segment>, Vec<Segment>) {
let (mut before, mut after) = (Vec::new(), Vec::new());
for (at, range) in segments {
if (*at, range.end) <= (run, byte) {
before.push((*at, range.clone()));
} else if (*at, range.start) >= (run, byte) {
after.push((*at, range.clone()));
} else {
before.push((*at, range.start..byte));
after.push((*at, byte..range.end));
}
}
(before, after)
}
struct Line {
first: usize,
end: usize,
pen: f32,
has_word: bool,
}
impl Line {
const fn new(first: usize) -> Self {
Self {
first,
end: first,
pen: 0.0,
has_word: false,
}
}
}
impl InlineLayout {
pub fn new(runs: &[InlineRun<'_>], wrap: Wrap, atlas: &FontAtlas) -> Self {
let mut layout = Self::default();
if runs.is_empty() {
return layout;
}
let limit = match wrap {
Wrap::None => None,
Wrap::MinContent => Some(0.0),
Wrap::Width(width) => Some(wrap_width(width)),
};
let word_limit = limit.filter(|_| matches!(wrap, Wrap::Width(_)));
let mut finished: Vec<(Range<usize>, usize)> = Vec::new();
let mut line = Line::new(0);
let mut last_run = 0;
for token in tokens(runs) {
match token {
Token::Newline(run) => {
finished.push((line.first..line.end, run));
last_run = run;
line = Line::new(layout.glyphs.len());
}
Token::Space(segment) => {
last_run = segment.0;
let start = layout.glyphs.len();
layout.push(runs, atlas, core::slice::from_ref(&segment), false);
line.pen = layout.place_from(line.pen, start);
}
Token::Word(segments) => {
if let Some(&(run, _)) = segments.last() {
last_run = run;
}
let start = layout.glyphs.len();
layout.push(runs, atlas, &segments, true);
let mut right = layout.place_from(line.pen, start);
if line.has_word && limit.is_some_and(|limit| right > limit) {
finished.push((line.first..line.end, last_run));
line = Line::new(start);
right = layout.place_from(0.0, start);
}
let mut word_start = start;
let mut rest = segments;
while let Some(limit) = word_limit
&& right > limit
&& let Some(fits) = layout.break_before(word_start, limit)
{
let pen = layout.glyphs[word_start].x;
let at = layout.glyphs[fits];
let (before, after) = split(&rest, at.run, at.start);
layout.glyphs.truncate(word_start);
layout.push(runs, atlas, &before, true);
let fits = layout.glyphs.len();
layout.place_from(pen, word_start);
finished.push((line.first..fits, last_run));
layout.push(runs, atlas, &after, true);
line = Line::new(fits);
word_start = fits;
rest = after;
right = layout.place_from(0.0, fits);
}
line.pen = right;
line.end = layout.glyphs.len();
line.has_word = true;
}
}
}
finished.push((line.first..line.end, last_run));
layout.finish(runs, &finished);
layout
}
fn break_before(&self, word_start: usize, limit: f32) -> Option<usize> {
let mut breaks =
(word_start + 1..self.glyphs.len()).filter(|&at| self.glyphs[at].breakable);
let first = breaks.next()?;
let fits = |at: usize| {
let before = &self.glyphs[at - 1];
before.x + before.advance <= limit
};
if !fits(first) {
return Some(first);
}
Some(breaks.take_while(|&at| fits(at)).last().unwrap_or(first))
}
fn push(
&mut self,
runs: &[InlineRun<'_>],
atlas: &FontAtlas,
segments: &[Segment],
drawn: bool,
) {
let mut at = 0;
while at < segments.len() {
let (run, bytes) = &segments[at];
let input = &runs[*run];
let RunFont::Parsed(font) = input.font else {
if let RunFont::Bitmap(scale) = input.font {
self.push_bitmap(input, *run, bytes.clone(), scale, atlas, drawn);
}
at += 1;
continue;
};
let key = input.shaping_key();
let together = segments[at..]
.iter()
.take_while(|(run, _)| runs[*run].shaping_key() == key)
.count();
self.push_shaped(runs, font, input.size, &segments[at..at + together], drawn);
at += together;
}
}
fn push_shaped(
&mut self,
runs: &[InlineRun<'_>],
font: &Font,
size: f32,
segments: &[Segment],
drawn: bool,
) {
let mut shaped: Vec<ShapedGlyph> = Vec::new();
let mut starts = Vec::with_capacity(segments.len());
if let [(run, bytes)] = segments {
shape(font, size, runs[*run].text, bytes.clone(), &mut shaped);
} else {
let mut joined = String::new();
for (run, bytes) in segments {
starts.push(joined.len());
joined.push_str(&runs[*run].text[bytes.clone()]);
}
shape(font, size, &joined, 0..joined.len(), &mut shaped);
}
let locate = |byte: usize| {
if starts.is_empty() {
let (run, bytes) = &segments[0];
return (*run, byte, bytes.end);
}
let index = starts.partition_point(|&start| start <= byte) - 1;
let (run, bytes) = &segments[index];
(*run, bytes.start + byte - starts[index], bytes.end)
};
for (index, glyph) in shaped.iter().enumerate() {
let (run, start, segment_end) = locate(glyph.cluster);
let next = shaped[index + 1..]
.iter()
.find(|next| next.cluster != glyph.cluster)
.map(|next| locate(next.cluster));
let end = match next {
Some((next_run, next_start, _)) if next_run == run => next_start,
_ => segment_end,
};
let breakable = index == 0 || shaped[index - 1].cluster != glyph.cluster;
self.glyphs.push(InlineGlyph {
run,
start,
end,
glyph: glyph.glyph,
face: glyph.face,
drawn,
breakable,
x: 0.0,
advance: glyph.advance,
shift: glyph.offset,
});
}
}
fn push_bitmap(
&mut self,
input: &InlineRun<'_>,
run: usize,
bytes: Range<usize>,
scale: f32,
atlas: &FontAtlas,
drawn: bool,
) {
for cluster in cluster::clusters(&input.text[bytes.clone()]) {
let cluster = bytes.start + cluster.start..bytes.start + cluster.end;
for (at, c) in input.text[cluster.clone()].char_indices() {
let start = cluster.start + at;
self.glyphs.push(InlineGlyph {
run,
start,
end: start + c.len_utf8(),
glyph: GlyphId::NOTDEF,
face: 0,
drawn: drawn && c != ' ',
breakable: at == 0,
x: 0.0,
advance: atlas.glyph(c).advance * scale,
shift: Vec2::ZERO,
});
}
}
}
fn place_from(&mut self, pen: f32, start: usize) -> f32 {
let mut pen = pen;
for glyph in &mut self.glyphs[start..] {
glyph.x = pen;
pen += glyph.advance;
}
pen
}
fn finish(&mut self, runs: &[InlineRun<'_>], finished: &[(Range<usize>, usize)]) {
let mut top = 0.0;
for (index, (glyphs, fallback)) in finished.iter().enumerate() {
let first = self.fragments.len();
let mut at = glyphs.start;
while at < glyphs.end {
let run = self.glyphs[at].run;
let start = at;
while at < glyphs.end && self.glyphs[at].run == run {
at += 1;
}
let (head, tail) = (self.glyphs[start], self.glyphs[at - 1]);
self.fragments.push(Fragment {
run,
line: index,
glyphs: start..at,
text: head.start..tail.end,
x: head.x,
width: tail.x + tail.advance - head.x,
});
}
let fragments = first..self.fragments.len();
let mut on_line: Vec<&InlineRun<'_>> = self.fragments[fragments.clone()]
.iter()
.map(|fragment| &runs[fragment.run])
.collect();
if on_line.is_empty() {
on_line.push(&runs[*fallback]);
}
let above = on_line.iter().fold(0.0f32, |most, run| most.max(run.above));
let below = on_line.iter().fold(0.0f32, |most, run| most.max(run.below));
let width = self.fragments[fragments.clone()]
.last()
.map_or(0.0, |last| last.x + last.width);
self.lines.push(InlineLine {
fragments,
top,
baseline: top + above,
height: above + below,
width,
offset: 0.0,
});
top += above + below;
}
}
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,
};
let shift = offset - line.offset;
for fragment in &mut self.fragments[line.fragments.clone()] {
fragment.x += shift;
for glyph in &mut self.glyphs[fragment.glyphs.clone()] {
glyph.x += shift;
}
}
line.offset = offset;
}
}
pub fn fragments(&self) -> &[Fragment] {
&self.fragments
}
pub fn lines(&self) -> &[InlineLine] {
&self.lines
}
pub fn face_runs(&self, fragment: &Fragment) -> Vec<(u8, Vec<PositionedGlyph>, Range<usize>)> {
let baseline = self.lines[fragment.line].baseline;
let mut runs: Vec<(u8, Vec<PositionedGlyph>, Range<usize>)> = Vec::new();
for glyph in &self.glyphs[fragment.glyphs.clone()] {
if !glyph.drawn {
continue;
}
let positioned = PositionedGlyph {
glyph: glyph.glyph,
offset: Vec2::new(glyph.x, baseline) + glyph.shift,
};
match runs.last_mut() {
Some((face, glyphs, _)) if *face == glyph.face => glyphs.push(positioned),
_ => {
if let Some((_, _, text)) = runs.last_mut() {
text.end = glyph.start;
}
runs.push((glyph.face, vec![positioned], glyph.start..fragment.text.end));
}
}
}
if let Some((_, _, text)) = runs.first_mut() {
text.start = fragment.text.start;
}
runs
}
pub fn measure(&self) -> Vec2 {
let widest = self
.lines
.iter()
.fold(0.0f32, |widest, line| widest.max(line.width));
Vec2::new(
widest.ceil(),
self.lines.iter().map(|line| line.height).sum(),
)
}
}
#[cfg(all(test, feature = "parsed-font"))]
mod tests {
use super::*;
use crate::font::fixtures;
const SIZE: f32 = 16.0;
fn lines(layout: &InlineLayout, runs: &[InlineRun<'_>]) -> Vec<(String, f32)> {
layout
.lines()
.iter()
.map(|line| {
let text = layout.fragments()[line.fragments.clone()]
.iter()
.map(|fragment| &runs[fragment.run].text[fragment.text.clone()])
.collect();
(text, line.width)
})
.collect()
}
#[test]
fn an_overlong_word_never_breaks_inside_a_cluster() {
let run = InlineRun::new(
"hh\u{301}h\u{301}",
RunFont::Parsed(Font::sans()),
SIZE,
20.0,
);
let runs = [run];
let layout = InlineLayout::new(&runs, Wrap::Width(1.0), &FontAtlas::built_in());
let texts: Vec<String> = lines(&layout, &runs)
.into_iter()
.map(|(text, _)| text)
.collect();
assert_eq!(texts, ["h", "h\u{301}", "h\u{301}"]);
}
#[test]
fn a_mark_is_drawn_at_the_shapers_offset() {
let font = Font::sans();
let runs = [InlineRun::new(
"xh\u{301}",
RunFont::Parsed(font),
SIZE,
20.0,
)];
let layout = InlineLayout::new(&runs, Wrap::None, &FontAtlas::built_in());
let mut shaped = Vec::new();
shape(font, SIZE, "xh\u{301}", 0..4, &mut shaped);
let fragment = &layout.fragments()[0];
let (_, glyphs, _) = &layout.face_runs(fragment)[0];
let baseline = layout.lines()[0].baseline;
let pen = shaped[0].advance + shaped[1].advance;
assert_ne!(
shaped[2].offset,
Vec2::ZERO,
"the font does not move the mark"
);
assert_eq!(
glyphs[2].offset,
Vec2::new(pen, baseline) + shaped[2].offset
);
assert_eq!(fragment.width, pen);
}
#[test]
fn a_broken_word_is_shaped_again_on_each_side() {
let hearts = fixtures::shaped();
let run = InlineRun::new(
"\u{2764}\u{2764}\u{2764}",
RunFont::Parsed(&hearts),
SIZE,
20.0,
);
let runs = [run];
let whole = InlineLayout::new(&runs, Wrap::None, &FontAtlas::built_in());
assert_eq!(
lines(&whole, &runs)[0].1,
13.0 + 13.0 + 16.0,
"the hearts kern"
);
let broken = InlineLayout::new(&runs, Wrap::Width(20.0), &FontAtlas::built_in());
let widths: Vec<f32> = lines(&broken, &runs)
.into_iter()
.map(|(_, width)| width)
.collect();
assert_eq!(widths, [16.0, 16.0, 16.0]);
}
}