use core::ops::Range;
use glam::Vec2;
use super::bidi::Bidi;
use super::shape::ShapedGlyph;
use super::{Font, GlyphId};
mod carets;
mod fill;
use carets::line_stops;
pub(crate) use carets::{Carets, caret_stops};
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]
Start,
End,
Left,
Center,
Right,
}
impl TextAlign {
pub(crate) fn share(self, rtl: bool) -> f32 {
match (self, rtl) {
(Self::Left, _) | (Self::Start, false) | (Self::End, true) => 0.0,
(Self::Center, _) => 0.5,
(Self::Right, _) | (Self::Start, true) | (Self::End, false) => 1.0,
}
}
}
fn aligned_offset(line: &TextLine, rtl: bool, width: f32, align: TextAlign) -> f32 {
let room = (width - line.width).max(0.0);
room * align.share(rtl)
}
#[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, Copy, Debug, PartialEq)]
pub struct Caret {
pub line: usize,
pub x: f32,
pub top: f32,
pub height: f32,
}
#[derive(Clone, Debug, PartialEq)]
struct LineBytes {
paragraph: Range<usize>,
line: Range<usize>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct TextLayout {
font: Font,
size: f32,
text: String,
glyphs: Vec<PositionedGlyph>,
faces: Vec<u8>,
bytes: Vec<usize>,
advances: Vec<(f32, bool)>,
spaces: Vec<(usize, f32)>,
lines: Vec<TextLine>,
line_bytes: Vec<LineBytes>,
rtl: Vec<bool>,
line_height: f32,
}
#[derive(Clone, Debug, PartialEq)]
pub struct FaceRun<'a> {
pub font: &'a Font,
pub glyphs: &'a [PositionedGlyph],
pub text: Range<usize>,
}
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))
})
}
impl TextLayout {
#[must_use]
pub fn new(font: &Font, text: &str, size: f32, line_height: f32, wrap: Option<f32>) -> Self {
Self::lay_out(font, text, size, line_height, wrap, false)
}
#[must_use]
pub fn nowrap(font: &Font, text: &str, size: f32, line_height: f32) -> Self {
Self::lay_out(font, text, size, line_height, None, true)
}
fn lay_out(
font: &Font,
text: &str,
size: f32,
line_height: f32,
wrap: Option<f32>,
keep_spaces: bool,
) -> Self {
let metrics = font.metrics();
let scale = metrics.scale(size);
let wrap = wrap.map(wrap_width);
let mut layout = Self {
font: font.clone(),
size,
text: text.to_owned(),
glyphs: Vec::with_capacity(text.len()),
faces: Vec::with_capacity(text.len()),
bytes: Vec::with_capacity(text.len()),
advances: Vec::new(),
spaces: Vec::new(),
lines: Vec::new(),
line_bytes: Vec::new(),
rtl: Vec::new(),
line_height,
};
let mut shaped: Vec<ShapedGlyph> = Vec::with_capacity(text.len());
fill::fill(
&mut layout,
&mut shaped,
font,
size,
wrap,
keep_spaces,
text,
);
layout.advances = shaped
.iter()
.map(|glyph| (glyph.advance, glyph.unsafe_to_break))
.collect();
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
}
pub fn align(&mut self, width: f32, align: TextAlign) {
for (line, &rtl) in self.lines.iter_mut().zip(&self.rtl) {
let offset = aligned_offset(line, rtl, width, align);
for glyph in &mut self.glyphs[line.glyphs.clone()] {
glyph.offset.x += offset - line.offset;
}
line.offset = offset;
}
}
pub(crate) fn is_aligned(&self, width: f32, align: TextAlign) -> bool {
self.lines
.iter()
.zip(&self.rtl)
.all(|(line, &rtl)| aligned_offset(line, rtl, width, align) - line.offset == 0.0)
}
#[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 fn caret(&self, byte: usize) -> Caret {
let index = self
.line_bytes
.partition_point(|bytes| bytes.line.start <= byte)
.saturating_sub(1);
let LineBytes { paragraph, line } = &self.line_bytes[index];
let at = self
.text
.floor_char_boundary(byte.clamp(line.start, line.end));
let text = &self.text[paragraph.clone()];
let mut carets = Carets::default();
line_stops(
&self.font,
text,
Bidi::new(text).as_ref(),
line.start - paragraph.start..line.end - paragraph.start,
self.size,
&mut carets,
);
let chars = self.text[line.start..at].chars().count();
Caret {
line: index,
x: self.lines[index].offset + carets.stops[chars],
top: index as f32 * self.line_height,
height: self.line_height,
}
}
pub(crate) fn lays_out(&self, font: &Font, text: &str, size: f32, line_height: f32) -> bool {
self.font == *font
&& self.font.fallback().iter().eq(font.fallback())
&& self.size.to_bits() == size.to_bits()
&& self.line_height.to_bits() == line_height.to_bits()
&& self.text == text
}
pub(crate) fn shaped_advances(&self) -> impl Iterator<Item = (usize, f32, bool)> + '_ {
self.bytes
.iter()
.zip(&self.advances)
.map(|(&byte, &(advance, unsafe_to_break))| (byte, advance, unsafe_to_break))
}
pub(crate) fn space_runs(&self) -> &[(usize, f32)] {
&self.spaces
}
#[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;