use std::path::{Path, PathBuf};
use resvg::tiny_skia::{Path as SkPath, PathBuilder};
use ttf_parser::{Face, GlyphId, OutlineBuilder};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Fit {
pub lines: Vec<String>,
pub size: i32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Metrics {
pub ascent: i32,
pub descent: i32,
}
pub struct TextFitter {
path: PathBuf,
data: Vec<u8>,
}
impl TextFitter {
pub fn new(font_path: impl AsRef<Path>) -> laravel::Result<Self> {
let path = font_path.as_ref();
if !path.is_file() {
return Err(laravel::Error::msg(format!(
"Laracards: font file not found at {}.",
path.display()
)));
}
let data = std::fs::read(path)?;
Face::parse(&data, 0).map_err(|error| {
laravel::Error::msg(format!("Laracards: {} is not a usable font: {error}.", path.display()))
})?;
Ok(Self {
path: path.to_path_buf(),
data,
})
}
pub fn font_path(&self) -> &Path {
&self.path
}
fn face(&self) -> Face<'_> {
Face::parse(&self.data, 0).expect("the face was parsed when the fitter was built")
}
pub fn metrics(&self, size: i32) -> Metrics {
let face = self.face();
let scale = f64::from(size) / f64::from(face.units_per_em());
let reach = |character: char| {
face.glyph_index(character)
.and_then(|glyph| face.glyph_bounding_box(glyph))
};
let (mut top, mut bottom) = (f64::from(face.ascender()), f64::from(face.descender()));
if let (Some(h), Some(g)) = (reach('H'), reach('g')) {
top = f64::from(h.y_max.max(g.y_max));
bottom = f64::from(h.y_min.min(g.y_min));
}
Metrics {
ascent: (top * scale).ceil().max(0.0) as i32,
descent: (-bottom * scale).ceil().max(0.0) as i32,
}
}
pub fn fit(&self, text: &str, max_width: i32, max_lines: usize, sizes: &[i32]) -> Fit {
let text = text.split_whitespace().collect::<Vec<_>>().join(" ");
let smallest = sizes.last().copied().unwrap_or(0);
if text.is_empty() {
return Fit {
lines: Vec::new(),
size: smallest,
};
}
for &size in sizes {
let lines = self.wrap(&text, max_width, size);
if lines.len() <= max_lines {
return Fit { lines, size };
}
}
let mut lines: Vec<String> = self
.wrap(&text, max_width, smallest)
.into_iter()
.take(max_lines)
.collect();
if let Some(last) = lines.last_mut() {
*last = self.ellipsize(last, max_width, smallest);
}
Fit { lines, size: smallest }
}
pub fn wrap(&self, text: &str, max_width: i32, size: i32) -> Vec<String> {
let mut lines = Vec::new();
let mut current = String::new();
for word in text.split(' ') {
let candidate = if current.is_empty() {
word.to_owned()
} else {
format!("{current} {word}")
};
if self.width(&candidate, size) <= max_width {
current = candidate;
continue;
}
if !current.is_empty() {
lines.push(std::mem::take(&mut current));
}
if self.width(word, size) > max_width {
let mut pieces = self.break_word(word, max_width, size);
current = pieces.pop().unwrap_or_default();
lines.extend(pieces);
continue;
}
current = word.to_owned();
}
if !current.is_empty() {
lines.push(current);
}
lines
}
pub fn width(&self, text: &str, size: i32) -> i32 {
if text.is_empty() {
return 0;
}
let face = self.face();
self.advance(&face, text, size).ceil() as i32
}
fn advance(&self, face: &Face<'_>, text: &str, size: i32) -> f64 {
let scale = f64::from(size) / f64::from(face.units_per_em());
let mut total = 0.0;
let mut previous: Option<GlyphId> = None;
for character in text.chars() {
let glyph = face.glyph_index(character).unwrap_or(GlyphId(0));
if let Some(left) = previous {
total += f64::from(Self::kerning(face, left, glyph)) * scale;
}
total += f64::from(face.glyph_hor_advance(glyph).unwrap_or(0)) * scale;
previous = Some(glyph);
}
total
}
fn kerning(face: &Face<'_>, left: GlyphId, right: GlyphId) -> i16 {
face.tables()
.kern
.and_then(|table| {
table
.subtables
.into_iter()
.filter(|subtable| subtable.horizontal && !subtable.variable)
.find_map(|subtable| subtable.glyphs_kerning(left, right))
})
.unwrap_or(0)
}
pub fn outline(&self, text: &str, size: i32) -> Option<SkPath> {
let face = self.face();
let scale = size as f32 / f32::from(face.units_per_em());
let mut builder = Outline {
path: PathBuilder::new(),
scale,
origin: 0.0,
};
let mut previous: Option<GlyphId> = None;
for character in text.chars() {
let glyph = face.glyph_index(character).unwrap_or(GlyphId(0));
if let Some(left) = previous {
builder.origin += f32::from(Self::kerning(&face, left, glyph)) * scale;
}
face.outline_glyph(glyph, &mut builder);
builder.origin += f32::from(face.glyph_hor_advance(glyph).unwrap_or(0)) * scale;
previous = Some(glyph);
}
builder.path.finish()
}
fn break_word(&self, word: &str, max_width: i32, size: i32) -> Vec<String> {
let mut pieces = Vec::new();
let mut current = String::new();
for character in word.chars() {
if !current.is_empty() && self.width(&format!("{current}{character}"), size) > max_width {
pieces.push(std::mem::take(&mut current));
current.push(character);
continue;
}
current.push(character);
}
if !current.is_empty() {
pieces.push(current);
}
pieces
}
fn ellipsize(&self, line: &str, max_width: i32, size: i32) -> String {
let mut line = line.trim_end_matches([' ', '.', ',', ';', ':']).to_owned();
while !line.is_empty() && self.width(&format!("{line}..."), size) > max_width {
line.pop();
}
format!("{}...", line.trim_end())
}
}
struct Outline {
path: PathBuilder,
scale: f32,
origin: f32,
}
impl Outline {
fn x(&self, x: f32) -> f32 {
self.origin + x * self.scale
}
fn y(&self, y: f32) -> f32 {
-y * self.scale
}
}
impl OutlineBuilder for Outline {
fn move_to(&mut self, x: f32, y: f32) {
self.path.move_to(self.x(x), self.y(y));
}
fn line_to(&mut self, x: f32, y: f32) {
self.path.line_to(self.x(x), self.y(y));
}
fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
self.path.quad_to(self.x(x1), self.y(y1), self.x(x), self.y(y));
}
fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
self.path
.cubic_to(self.x(x1), self.y(y1), self.x(x2), self.y(y2), self.x(x), self.y(y));
}
fn close(&mut self) {
self.path.close();
}
}