use std::cell::RefCell;
use nadir_render::{Font, PlacedGlyph, TextLayout};
pub trait TextMetrics {
fn line_height(&self) -> f32;
fn caret_x(&self, text: &str, byte: usize) -> f32;
}
pub(crate) fn caret_in(glyphs: impl IntoIterator<Item = (usize, f32, f32)>, byte: usize) -> f32 {
let mut end = 0.0;
for (start, pen, advance) in glyphs {
if start >= byte {
return pen;
}
end = pen + advance;
}
end
}
#[derive(Debug)]
pub struct FontMetrics {
font: Font,
placed: RefCell<Vec<PlacedGlyph>>,
}
impl FontMetrics {
pub fn new(font: Font) -> Self {
Self {
font,
placed: RefCell::new(Vec::new()),
}
}
pub fn font(&self) -> &Font {
&self.font
}
}
impl TextMetrics for FontMetrics {
fn line_height(&self) -> f32 {
self.font.line_height() as f32
}
fn caret_x(&self, text: &str, byte: usize) -> f32 {
let mut layout = TextLayout::new();
layout.markup = false;
let mut placed = self.placed.borrow_mut();
placed.clear();
self.font.layout(text, &layout, &mut placed);
let glyphs = placed.iter().map(|placed| {
let pen = placed.position.x - placed.glyph.offset().x;
(placed.byte, pen as f32, placed.glyph.advance() as f32)
});
caret_in(glyphs, byte)
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
pub(crate) struct Fixed;
impl Fixed {
fn glyphs(text: &str) -> impl Iterator<Item = (usize, f32, f32)> + '_ {
let mut pen = 0.0;
let mut previous = None;
text.char_indices()
.filter(|(_, c)| !c.is_control())
.map(move |(byte, c)| {
if (previous, c) == (Some('A'), 'V') {
pen -= 1.0;
}
previous = Some(c);
let advance = if c == ' ' { 3.0 } else { 6.0 };
let glyph = (byte, pen, advance);
pen += advance;
glyph
})
}
}
impl TextMetrics for Fixed {
fn line_height(&self) -> f32 {
8.0
}
fn caret_x(&self, text: &str, byte: usize) -> f32 {
caret_in(Self::glyphs(text), byte)
}
}
#[test]
fn a_caret_is_at_the_pen_kerning_included_and_spaces_take_room() {
let text = "AV b ";
let at = |byte| Fixed.caret_x(text, byte);
assert_eq!(
[at(0), at(1), at(2), at(3), at(4), at(5)],
[0.0, 5.0, 11.0, 14.0, 20.0, 23.0]
);
assert_eq!(Fixed.caret_x("", 0), 0.0);
assert_eq!(caret_in([(0, 0.0, 6.0), (2, 6.0, 6.0)], 1), 6.0);
assert_eq!(caret_in([(0, 0.0, 6.0), (2, 6.0, 6.0)], 9), 12.0);
assert_eq!(Fixed.caret_x("éa", 2), 6.0);
}
}