use core::ops::Range;
use glam::Vec2;
use super::shape::{ShapedGlyph, shape};
use super::{Font, GlyphId, cluster};
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,
width: f32,
has_word: bool,
}
impl Line {
const fn new(first: usize) -> Self {
Self {
first,
pen: 0.0,
width: 0.0,
has_word: false,
}
}
}
fn pieces(paragraph: &str) -> impl Iterator<Item = (Range<usize>, bool)> + '_ {
let mut chars = paragraph.char_indices().peekable();
core::iter::from_fn(move || {
let (start, c) = chars.next()?;
let spaces = c == ' ';
let mut end = start + c.len_utf8();
while let Some(&(at, c)) = chars.peek() {
if (c == ' ') != spaces {
break;
}
end = at + c.len_utf8();
chars.next();
}
Some((start..end, spaces))
})
}
fn place(glyphs: &mut [PositionedGlyph], shaped: &[ShapedGlyph], pen: f32) -> f32 {
let mut pen = pen;
for (positioned, shaped) in glyphs.iter_mut().zip(shaped) {
positioned.offset.x = pen + shaped.offset.x;
pen += shaped.advance;
}
pen
}
pub(crate) fn caret_stops(font: &Font, text: &str, size: f32, out: &mut Vec<f32>) {
out.clear();
let mut shaped_clusters: Vec<(usize, f32, f32)> = Vec::new();
let mut shaped = Vec::new();
let mut pen = 0.0;
for (piece, _) in pieces(text) {
shaped.clear();
shape(font, size, text, piece, &mut shaped);
for glyph in &shaped {
match shaped_clusters.last_mut() {
Some((start, _, width)) if *start == glyph.cluster => *width += glyph.advance,
_ => shaped_clusters.push((glyph.cluster, pen, glyph.advance)),
}
pen += glyph.advance;
}
}
let starts: Vec<usize> = cluster::clusters(text).map(|range| range.start).collect();
let mut stops = starts.iter().map(|&start| {
let at = shaped_clusters.partition_point(|&(first, _, _)| first <= start);
let Some(&(first, left, width)) = at.checked_sub(1).map(|at| &shaped_clusters[at]) else {
return 0.0;
};
let end = shaped_clusters
.get(at)
.map_or(text.len(), |&(next, _, _)| next);
let sharing =
&starts[starts.partition_point(|&s| s < first)..starts.partition_point(|&s| s < end)];
let lead = usize::from(sharing.first() != Some(&first));
let index = sharing.partition_point(|&s| s < start) + lead;
left + width * index as f32 / (sharing.len() + lead) as f32
});
let mut current = 0.0;
let mut next_start = starts.iter().peekable();
for (byte, _) in text.char_indices() {
if next_start.next_if(|&&start| start == byte).is_some() {
current = stops.next().unwrap_or(current);
}
out.push(current);
}
out.push(pen);
}
impl TextLayout {
#[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 shaped: Vec<ShapedGlyph> = Vec::with_capacity(text.len());
let mut paragraph_start = 0;
for paragraph in text.split('\n') {
let mut line = Line::new(layout.glyphs.len());
for (piece, spaces) in pieces(paragraph) {
let word_start = shaped.len();
shape(font, size, paragraph, piece, &mut shaped);
if spaces {
line.pen += shaped[word_start..]
.iter()
.map(|glyph| glyph.advance)
.sum::<f32>();
shaped.truncate(word_start);
continue;
}
for glyph in &shaped[word_start..] {
layout.glyphs.push(PositionedGlyph {
glyph: glyph.glyph,
offset: Vec2::ZERO,
});
layout.faces.push(glyph.face);
layout.bytes.push(paragraph_start + glyph.cluster);
}
let word = word_start..shaped.len();
let mut right = place(
&mut layout.glyphs[word.clone()],
&shaped[word.clone()],
line.pen,
);
if line.has_word && wrap.is_some_and(|wrap| right > wrap) {
layout.finish_line(&line, word_start);
line = Line::new(word_start);
right = place(&mut layout.glyphs[word.clone()], &shaped[word], 0.0);
}
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 at in line.glyphs.clone() {
layout.glyphs[at].offset.y = line.baseline + shaped[at].offset.y;
}
}
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;