use core::ops::Range;
use glam::Vec2;
use crate::font::fallback::{Mapped, map_char};
use crate::font::layout::{PositionedGlyph, TextAlign, advance_pen, wrap_width};
use crate::font::{Font, FontId, GlyphId};
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 kerning_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 byte: usize,
pub c: char,
pub glyph: GlyphId,
pub face: u8,
pub drawn: bool,
pub x: f32,
pub advance: f32,
}
#[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>,
}
enum Token {
Word(Vec<(usize, usize, char)>),
Space(usize, usize),
Newline(usize),
}
fn tokens(runs: &[InlineRun<'_>]) -> Vec<Token> {
let mut tokens = Vec::new();
let mut word = Vec::new();
for (run, input) in runs.iter().enumerate() {
for (byte, c) in input.text.char_indices() {
match c {
' ' | '\n' => {
if !word.is_empty() {
tokens.push(Token::Word(core::mem::take(&mut word)));
}
tokens.push(if c == ' ' {
Token::Space(run, byte)
} else {
Token::Newline(run)
});
}
_ => {
word.push((run, byte, c));
if c == '-' {
tokens.push(Token::Word(core::mem::take(&mut word)));
}
}
}
}
}
if !word.is_empty() {
tokens.push(Token::Word(word));
}
tokens
}
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(run, byte) => {
layout.push(runs, atlas, run, byte, ' ');
line.pen =
layout.place_from(runs, line.pen, layout.glyphs.len() - 1, line.first);
last_run = run;
}
Token::Word(chars) => {
let start = layout.glyphs.len();
for &(run, byte, c) in &chars {
layout.push(runs, atlas, run, byte, c);
last_run = run;
}
let mut right = layout.place_from(runs, line.pen, start, line.first);
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(runs, 0.0, start, start);
}
let mut word_start = start;
while let Some(limit) = word_limit
&& right > limit
&& layout.glyphs.len() - word_start > 1
{
let fits = (word_start + 1..layout.glyphs.len())
.take_while(|&at| {
let glyph = &layout.glyphs[at];
glyph.x + glyph.advance <= limit
})
.last()
.map_or(word_start + 1, |at| at + 1);
finished.push((line.first..fits, last_run));
line = Line::new(fits);
word_start = fits;
right = layout.place_from(runs, 0.0, fits, 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 push(
&mut self,
runs: &[InlineRun<'_>],
atlas: &FontAtlas,
run: usize,
byte: usize,
c: char,
) {
let input = &runs[run];
let (mapped, advance) = match input.font {
RunFont::Parsed(font) => {
let next = input.text[byte + c.len_utf8()..].chars().next();
match map_char(font, c, next) {
Some(mapped) => (
Some(mapped),
advance_pen(font, input.size, 0.0, None, mapped).1,
),
None => (None, 0.0),
}
}
RunFont::Bitmap(scale) => (
Some(Mapped {
face: 0,
glyph: GlyphId::NOTDEF,
}),
atlas.glyph(c).advance * scale,
),
};
self.glyphs.push(InlineGlyph {
run,
byte,
c,
glyph: mapped.map_or(GlyphId::NOTDEF, |mapped| mapped.glyph),
face: mapped.map_or(0, |mapped| mapped.face),
drawn: c != ' ' && mapped.is_some(),
x: 0.0,
advance,
});
}
fn place_from(
&mut self,
runs: &[InlineRun<'_>],
pen: f32,
start: usize,
line_first: usize,
) -> f32 {
let mut pen = pen;
for at in start..self.glyphs.len() {
let glyph = self.glyphs[at];
if at > line_first {
let previous = self.glyphs[at - 1];
let (before, after) = (&runs[previous.run], &runs[glyph.run]);
if let (Some(key), RunFont::Parsed(font)) = (after.kerning_key(), after.font)
&& before.kerning_key() == Some(key)
&& previous.face == glyph.face
{
let face = font.face(glyph.face);
pen += face.kerning(previous.glyph, glyph.glyph)
* face.metrics().scale(after.size);
}
}
self.glyphs[at].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.byte..tail.byte + tail.c.len_utf8(),
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),
};
match runs.last_mut() {
Some((face, glyphs, _)) if *face == glyph.face => glyphs.push(positioned),
_ => {
if let Some((_, _, text)) = runs.last_mut() {
text.end = glyph.byte;
}
runs.push((glyph.face, vec![positioned], glyph.byte..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(),
)
}
}