use std::cell::Cell;
use std::rc::Rc;
use cosmic_text::fontdb::Source;
use super::{Harness, capture_logs, node_at, rect_at};
use crate::text::{Fonts, TextNode};
use crate::{Align, Content, Font, Rect, Row, Style, Text, TextSystem, Window};
fn dejavu() -> Option<&'static [u8]> {
font_file("DejaVuSans.ttf")
}
fn font_file(name: &str) -> Option<&'static [u8]> {
for dir in [
"/usr/share/fonts/dejavu",
"/usr/share/fonts/truetype/dejavu",
"/usr/share/fonts/TTF",
"/usr/share/fonts/noto-emoji",
] {
if let Ok(bytes) = std::fs::read(format!("{dir}/{name}")) {
return Some(Box::leak(bytes.into_boxed_slice()));
}
}
eprintln!("skipped: {name} isn't in any of the usual places");
None
}
fn text_window(h: &mut Harness, content: &str, font: Font) -> Window {
let row = Row::new()
.align(Align::Start)
.child(Text::new(content.to_owned()).style(Style::new().font(font)));
h.window(h.panel().child(row), 600.0, 60.0)
}
fn drawn_from_bundled(window: &Window, text: &TextSystem, path: &[usize]) -> bool {
let view = window.view();
let Content::Text(shown) = node_at(view.root(), path).content() else {
panic!("a text node has text content");
};
let fonts = text.font_system();
let mut glyphs = shown
.runs()
.flat_map(|run| run.glyphs.into_owned())
.peekable();
glyphs.peek().is_some()
&& glyphs.all(|glyph| {
fonts
.db()
.face(glyph.font_id)
.is_some_and(|face| matches!(face.source, Source::Binary(_)))
})
}
#[test]
fn measuring_agrees_with_a_text() {
for font in [
Font::new("sans-serif", 15.0),
Font::new("sans-serif", 13.0).weight(700),
Font::new("No Such Family 1234", 13.0),
] {
let mut h = Harness::new();
let window = text_window(&mut h, "clicked 12 times", font);
let laid_out = rect_at(&window, &[0, 0]);
let measured = h.cx.measure_text("clicked 12 times", font);
assert!(measured.width > 20.0, "{measured:?}");
assert_eq!(measured.width.ceil(), laid_out.width, "{font:?}");
assert_eq!(measured.height, laid_out.height, "{font:?}");
assert_eq!(measured.line_height, measured.height);
assert!(
measured.ascent > 0.0 && measured.descent > 0.0,
"{measured:?}"
);
}
}
#[test]
fn an_empty_string_is_one_empty_line() {
let h = Harness::new();
let measured = h.cx.measure_text("", Font::DEFAULT);
assert_eq!(measured.width, 0.0);
assert_eq!(measured.line_height, 16.0);
assert_eq!(measured.height, 16.0);
assert!(measured.ascent > 0.0, "{measured:?}");
}
#[test]
fn each_line_break_adds_a_line() {
let h = Harness::new();
let font = Font::DEFAULT;
let long = h.cx.measure_text("a longer second line", font);
let both = h.cx.measure_text("short\na longer second line", font);
assert_eq!(both.width, long.width);
assert_eq!(both.height, 2.0 * both.line_height);
let three = h.cx.measure_text("one\ntwo\n", font);
assert_eq!(three.height, 3.0 * three.line_height);
}
#[test]
fn a_binding_measures_while_its_window_lays_out() {
let mut h = Harness::new();
let geometry = h.cx.signal(Rect::default());
let seen = Rc::new(Cell::new((0.0, 0.0)));
let cx = h.cx.clone();
let record = Rc::clone(&seen);
let row = Row::new()
.align(Align::Start)
.geometry(geometry)
.child(Text::new(move || {
let width = cx.measure_text("abc", Font::DEFAULT).width;
record.set((geometry.get().width, width));
format!("{width}")
}));
h.window(h.panel().child(row), 400.0, 30.0);
let (row_width, measured) = seen.get();
assert_eq!(row_width, 400.0, "the binding didn't run after layout");
assert!(measured > 10.0, "measured {measured}");
}
#[test]
fn a_bundled_family_needs_no_fontconfig() {
let Some(bytes) = dejavu() else { return };
let mut fonts = Fonts::new();
fonts.add(bytes);
let mut node = TextNode::new();
node.set_content(String::from("clicked 12 times"));
node.prepare(Font::new("dejavu sans", 13.0), &mut fonts);
let measured = fonts.measure("clicked 12 times", Font::new("DejaVu Sans", 13.0));
assert!(measured.width > 20.0, "{measured:?}");
assert!(!fonts.fontconfig_started());
let glyphs: Vec<u16> = node
.runs()
.flat_map(|run| run.glyphs.into_owned())
.map(|glyph| glyph.glyph_id)
.collect();
assert!(glyphs.iter().all(|&id| id != 0), "{glyphs:?}");
node.set_content(String::from("a\u{4E00}"));
node.prepare(Font::new("DejaVu Sans", 13.0), &mut fonts);
assert!(fonts.fontconfig_started());
}
#[test]
fn bytes_that_hold_no_font_are_logged_and_ignored() {
let h = Harness::new();
let logs = capture_logs(|| h.cx.add_font(b"not a font"));
assert!(logs.contains("bundled font"), "{logs}");
let faces = h.text.font_system().db().len();
assert_eq!(faces, 0);
}
#[test]
fn a_font_added_later_shapes_laid_out_text_again() {
let Some(bytes) = dejavu() else { return };
let mut h = Harness::new();
let window = text_window(&mut h, "hello", Font::new("DejaVu Sans", 13.0));
assert!(!drawn_from_bundled(&window, &h.text, &[0, 0]));
assert!(!window.needs_layout());
h.cx.add_font(bytes);
assert!(window.needs_layout());
h.frame(&window);
assert!(drawn_from_bundled(&window, &h.text, &[0, 0]));
assert!(!window.needs_layout());
}
#[test]
fn a_font_added_later_repaints_text_that_kept_its_size() {
let Some(bold) = font_file("DejaVuSans-Bold.ttf") else {
return;
};
let mut h = Harness::new();
let style = Style::new()
.font(Font::new("DejaVu Sans", 13.0))
.width(200.0);
let row = Row::new()
.align(Align::Start)
.child(Text::new("hello").style(style));
let window = h.window(h.panel().child(row), 600.0, 60.0);
window.take_damage();
let text = rect_at(&window, &[0, 0]);
h.cx.add_font(bold);
h.frame(&window);
let damage = window.take_damage();
assert!(
damage.iter().any(|area| area.union(text) == *area),
"{damage:?} misses {text:?}"
);
}
fn glyph_faces(node: &TextNode, fonts: &mut Fonts) -> Vec<(bool, u16)> {
let db = fonts.font_system().db();
node
.runs()
.flat_map(|run| run.glyphs.into_owned())
.filter_map(|glyph| db.face(glyph.font_id))
.map(|face| (matches!(face.source, Source::Binary(_)), face.weight.0))
.collect()
}
fn dejavu_text(fonts: &mut Fonts, weight: u16) -> TextNode {
let mut node = TextNode::new();
node.set_content(String::from("hello"));
node.prepare(Font::new("DejaVu Sans", 13.0).weight(weight), fonts);
node
}
#[test]
fn a_bundled_bold_leaves_regular_text_to_fontconfig() {
let Some(bold) = font_file("DejaVuSans-Bold.ttf") else {
return;
};
let mut fonts = Fonts::new();
fonts.add(bold);
let node = dejavu_text(&mut fonts, 700);
assert!(!fonts.fontconfig_started());
assert!(
glyph_faces(&node, &mut fonts)
.iter()
.all(|&face| face == (true, 700))
);
let node = dejavu_text(&mut fonts, 400);
assert!(fonts.fontconfig_started());
let faces = glyph_faces(&node, &mut fonts);
assert!(faces.iter().all(|&face| face == (false, 400)), "{faces:?}");
}
#[test]
fn a_bundled_regular_keeps_the_installed_bold() {
let Some(regular) = dejavu() else { return };
let mut fonts = Fonts::new();
dejavu_text(&mut fonts, 400);
dejavu_text(&mut fonts, 700);
fonts.add(regular);
let faces = glyph_faces(&dejavu_text(&mut fonts, 700), &mut fonts);
assert!(faces.iter().all(|&face| face == (false, 700)), "{faces:?}");
let faces = glyph_faces(&dejavu_text(&mut fonts, 400), &mut fonts);
assert!(faces.iter().all(|&face| face == (true, 400)), "{faces:?}");
}
#[test]
fn a_bundled_variable_font_serves_the_weights_it_spans() {
let Some(emoji) = font_file("NotoEmoji-VariableFont_wght.ttf") else {
return;
};
let mut fonts = Fonts::new();
fonts.add(emoji);
for weight in [300, 600, 700] {
let font = Font::new("Noto Emoji", 13.0).weight(weight);
assert_eq!(fonts.family(&font).as_deref(), Some("Noto Emoji"));
}
assert!(!fonts.fontconfig_started());
fonts.family(&Font::new("Noto Emoji", 13.0).weight(900));
assert!(fonts.fontconfig_started());
}
#[test]
fn a_replaced_face_is_never_read_back() {
let Some(regular) = dejavu() else { return };
let mut fonts = Fonts::new();
dejavu_text(&mut fonts, 400);
let path = fonts
.font_system()
.db()
.faces()
.find_map(|face| match &face.source {
Source::File(path) | Source::SharedFile(path, _) => Some(path.clone()),
Source::Binary(_) => None,
})
.expect("fontconfig loaded a file");
fonts.loaded.clear();
fonts.add(regular);
let name = fonts.load((path, 0));
assert_eq!(name.as_deref(), Some("DejaVu Sans"));
let files = fonts
.font_system()
.db()
.faces()
.filter(|face| !matches!(face.source, Source::Binary(_)))
.count();
assert_eq!(files, 0, "the replaced face was read again");
}
#[test]
fn measuring_takes_letter_spacing_as_a_text_does() {
let plain = Font::new("sans-serif", 13.0);
let spaced = plain.letter_spacing(2.0);
let mut h = Harness::new();
let window = text_window(&mut h, "clicked 12 times", spaced);
let laid_out = rect_at(&window, &[0, 0]);
let wide = h.cx.measure_text("clicked 12 times", spaced);
let narrow = h.cx.measure_text("clicked 12 times", plain);
assert!(wide.width > narrow.width + 20.0, "{wide:?} {narrow:?}");
assert_eq!(wide.width.ceil(), laid_out.width);
}
#[test]
fn a_bundled_upright_face_leaves_italic_to_fontconfig() {
let Some(regular) = dejavu() else { return };
let Some(oblique) = font_file("DejaVuSans-Oblique.ttf") else {
return;
};
let slanted = |fonts: &mut Fonts, italic: bool| {
let font = Font::new("DejaVu Sans", 13.0);
let mut node = TextNode::new();
node.set_content(String::from("hello"));
node.prepare(if italic { font.italic() } else { font }, fonts);
let db = fonts.font_system().db();
let faces: Vec<_> = node
.runs()
.flat_map(|run| run.glyphs.into_owned())
.filter_map(|glyph| db.face(glyph.font_id))
.map(|face| (matches!(face.source, Source::Binary(_)), face.style))
.collect();
faces
};
let mut fonts = Fonts::new();
fonts.add(regular);
assert!(
slanted(&mut fonts, false)
.iter()
.all(|&(bundled, _)| bundled)
);
assert!(!fonts.fontconfig_started());
let faces = slanted(&mut fonts, true);
assert!(fonts.fontconfig_started());
assert!(
faces
.iter()
.all(|&(bundled, style)| !bundled && style != cosmic_text::fontdb::Style::Normal),
"{faces:?}"
);
let mut fonts = Fonts::new();
fonts.add(oblique);
let faces = slanted(&mut fonts, true);
assert!(faces.iter().all(|&(bundled, _)| bundled), "{faces:?}");
assert!(!fonts.fontconfig_started());
}
fn rasterized(window: &Window, text: &TextSystem) -> (f32, f32, f32, f32) {
let view = window.view();
let Content::Text(shown) = node_at(view.root(), &[0, 0]).content() else {
panic!("a text node has text content");
};
let mut fonts = text.font_system();
let mut cache = cosmic_text::SwashCache::new();
let mut bounds = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);
for run in shown.runs() {
for glyph in run.glyphs.iter() {
let physical = glyph.physical((0.0, 0.0), 1.0);
let mut key = physical.cache_key;
key.flags |= cosmic_text::CacheKeyFlags::DISABLE_HINTING;
let image = cache
.get_image_uncached(&mut fonts, key)
.expect("the glyph rasterizes");
let left = (physical.x + image.placement.left) as f32;
let top = (physical.y - image.placement.top) as f32 + run.line_y;
bounds.0 = bounds.0.min(left);
bounds.1 = bounds.1.min(top);
bounds.2 = bounds.2.max(left + image.placement.width as f32);
bounds.3 = bounds.3.max(top + image.placement.height as f32);
}
}
bounds
}
#[test]
fn ink_is_the_box_the_glyphs_draw() {
for (content, font) in [
("f", Font::new("sans-serif", 40.0).italic()),
("j", Font::new("sans-serif", 40.0)),
("Hello", Font::new("sans-serif", 18.0)),
] {
let mut h = Harness::new();
let window = text_window(&mut h, content, font);
let measured = h.cx.measure_text(content, font);
let ink = measured.ink;
let (left, top, right, bottom) = rasterized(&window, &h.text);
let near = |ink: f32, pixel: f32| (ink - pixel).abs() <= 1.0;
assert!(near(ink.x, left), "{content}: {ink:?} vs left {left}");
assert!(near(ink.y, top), "{content}: {ink:?} vs top {top}");
assert!(near(ink.right(), right), "{content}: {ink:?} vs {right}");
assert!(near(ink.bottom(), bottom), "{content}: {ink:?} vs {bottom}");
assert!(ink.width > 0.0 && ink.height > 0.0, "{ink:?}");
}
let h = Harness::new();
let italic = h
.cx
.measure_text("f", Font::new("sans-serif", 40.0).italic());
assert!(italic.ink.x < 0.0, "{italic:?}");
assert!(italic.ink.right() > italic.width, "{italic:?}");
let j = h.cx.measure_text("j", Font::new("sans-serif", 40.0));
assert!(j.ink.x < 0.0, "{j:?}");
}
#[test]
fn ink_takes_each_line_and_no_blank() {
let h = Harness::new();
let font = Font::new("sans-serif", 20.0);
for blank in ["", " ", " \t ", "\n"] {
assert_eq!(
h.cx.measure_text(blank, font).ink,
Rect::default(),
"{blank:?}"
);
}
let one = h.cx.measure_text("x", font);
let two = h.cx.measure_text("x\nx", font);
assert_eq!(two.ink.x, one.ink.x);
assert_eq!(two.ink.y, one.ink.y);
assert_eq!(two.ink.width, one.ink.width);
assert_eq!(two.ink.height, one.ink.height + one.line_height);
let spaced = h.cx.measure_text(" x", font);
let space = h.cx.measure_text(" ", font).width;
assert!(
(spaced.ink.x - (one.ink.x + space)).abs() < 0.01,
"{spaced:?}"
);
}
#[test]
fn a_curves_box_holds_where_it_turns_not_its_control_points() {
let bounds = |points: &[(f32, f32)]| {
let mut found = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);
let mut add = |x: f32, y: f32| {
found = (
found.0.min(x),
found.1.min(y),
found.2.max(x),
found.3.max(y),
);
};
add(points[0].0, points[0].1);
crate::text::curve_extremes(points, &mut add);
found
};
assert_eq!(
bounds(&[(0.0, 0.0), (5.0, 10.0), (10.0, 0.0)]),
(0.0, 0.0, 10.0, 5.0)
);
assert_eq!(
bounds(&[(0.0, 0.0), (0.0, 10.0), (10.0, 10.0), (10.0, 0.0)]),
(0.0, 0.0, 10.0, 7.5)
);
let (left, _, right, _) = bounds(&[(0.0, 0.0), (-6.0, 4.0), (16.0, 4.0), (10.0, 0.0)]);
assert!(left < -1.0 && left > -6.0, "{left}");
assert!(right > 11.0 && right < 16.0, "{right}");
assert_eq!(bounds(&[(0.0, 0.0), (3.0, -4.0)]), (0.0, -4.0, 3.0, 0.0));
}
#[test]
fn a_color_bitmap_glyphs_ink_is_its_pixels() {
let Some(bytes) = font_file("NotoColorEmoji.ttf") else {
return;
};
let h = Harness::new();
h.cx.add_font(bytes);
let measured = h.cx.measure_text("😀", Font::new("Noto Color Emoji", 20.0));
let ink = measured.ink;
assert!(ink.width > 10.0 && ink.height > 10.0, "{measured:?}");
assert!(ink.width <= measured.width + 2.0, "{measured:?}");
}
#[test]
fn a_colr_glyphs_ink_is_its_color_layers() {
let Ok(bytes) = std::fs::read("/opt/librewolf/fonts/TwemojiMozilla.ttf") else {
eprintln!("skipped: no Twemoji Mozilla");
return;
};
let h = Harness::new();
h.cx.add_font(Box::leak(bytes.into_boxed_slice()));
let measured = h.cx.measure_text("😀", Font::new("Twemoji Mozilla", 20.0));
let ink = measured.ink;
assert!(ink.width > 10.0 && ink.height > 10.0, "{measured:?}");
}
#[test]
fn measuring_glyphs_again_builds_no_outlines_until_a_font_is_added() {
let mut fonts = Fonts::new();
let font = Font::new("sans-serif", 18.0);
let first = fonts.measure("hello world", font);
let built = fonts.glyphs_built;
assert_eq!(built, (7, 1));
assert_eq!(fonts.measure("hello world", font), first);
fonts.measure("held lower", font);
assert_eq!(fonts.glyphs_built, built, "the same glyphs");
fonts.measure("hello", Font::new("sans-serif", 20.0));
assert_eq!(fonts.glyphs_built, (11, 1), "another size");
let Some(bytes) = dejavu() else { return };
fonts.add(bytes);
fonts.measure("hello", font);
assert_eq!(
fonts.glyphs_built,
(15, 1),
"measured again after a font came"
);
}
#[test]
fn the_ink_cache_keeps_at_most_its_cap() {
let mut fonts = Fonts::new();
for step in 0..=crate::text::INK_GLYPHS {
fonts.measure("x", Font::new("sans-serif", 8.0 + step as f32 / 64.0));
assert!(fonts.ink.len() <= crate::text::INK_GLYPHS);
}
assert_eq!(fonts.ink.len(), 1, "it started again at the cap");
}