#![deny(missing_docs)]
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
pub struct ReadmeDoctests;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Mutex, OnceLock, RwLock};
use cosmic_text::{Attrs, Buffer, FontSystem, Metrics, Shaping, Style, Weight};
use frus_core::{fits, FontWeight, Point, Rect, ResolvedTextStyle, Size, TextRun, TextStyle};
use frus_core::DEFAULT_LINE_HEIGHT as LINE_HEIGHT_FACTOR;
#[cfg(feature = "bundled-sans")]
const DEJAVU_SANS: &[u8] = include_bytes!("../assets/DejaVuSans.ttf");
#[cfg(feature = "bundled-sans")]
const DEJAVU_SANS_BOLD: &[u8] = include_bytes!("../assets/DejaVuSans-Bold.ttf");
#[cfg(feature = "bundled-italic")]
const DEJAVU_SANS_OBLIQUE: &[u8] = include_bytes!("../assets/DejaVuSans-Oblique.ttf");
#[cfg(feature = "bundled-italic")]
const DEJAVU_SANS_BOLD_OBLIQUE: &[u8] = include_bytes!("../assets/DejaVuSans-BoldOblique.ttf");
#[cfg(feature = "bundled-mono")]
const DEJAVU_MONO: &[u8] = include_bytes!("../assets/DejaVuSansMono.ttf");
#[cfg(feature = "bundled-arabic")]
const NOTO_ARABIC: &[u8] = include_bytes!("../assets/NotoNaskhArabic-Regular.ttf");
#[cfg(feature = "bundled-arabic")]
const NOTO_ARABIC_BOLD: &[u8] = include_bytes!("../assets/NotoNaskhArabic-Bold.ttf");
#[cfg(feature = "bundled-sans")]
const SANS_FAMILY: &str = "DejaVu Sans";
#[cfg(feature = "bundled-mono")]
const MONO_FAMILY: &str = "DejaVu Sans Mono";
#[cfg(feature = "bundled-arabic")]
const ARABIC_FAMILY: &str = "Noto Naskh Arabic";
#[cfg(feature = "bundled-sans")]
static SANS: RwLock<Option<&'static str>> = RwLock::new(Some(SANS_FAMILY));
#[cfg(not(feature = "bundled-sans"))]
static SANS: RwLock<Option<&'static str>> = RwLock::new(None);
#[cfg(feature = "bundled-mono")]
static MONO: RwLock<Option<&'static str>> = RwLock::new(Some(MONO_FAMILY));
#[cfg(not(feature = "bundled-mono"))]
static MONO: RwLock<Option<&'static str>> = RwLock::new(None);
#[cfg(feature = "bundled-arabic")]
static ARABIC: RwLock<Option<&'static str>> = RwLock::new(Some(ARABIC_FAMILY));
#[cfg(not(feature = "bundled-arabic"))]
static ARABIC: RwLock<Option<&'static str>> = RwLock::new(None);
static ITALIC: AtomicBool = AtomicBool::new(cfg!(feature = "bundled-italic"));
static EXTRA_FONTS: Mutex<Vec<Vec<u8>>> = Mutex::new(Vec::new());
pub fn add_font(data: Vec<u8>) {
if let Some(system) = FONT_SYSTEM.get() {
if let Ok(mut system) = system.lock() {
system.db_mut().load_font_data(data.clone());
}
}
EXTRA_FONTS.lock().expect("font registry").push(data);
forget_measurements();
}
pub fn set_default_family(name: &'static str) {
*SANS.write().expect("family registry") = Some(name);
forget_measurements();
}
pub fn set_monospace_family(name: &'static str) {
*MONO.write().expect("family registry") = Some(name);
forget_measurements();
}
fn family_or_generic(
slot: &RwLock<Option<&'static str>>,
generic: cosmic_text::Family<'static>,
) -> cosmic_text::Family<'static> {
match *slot.read().expect("family registry") {
Some(name) => cosmic_text::Family::Name(name),
None => generic,
}
}
fn contains_arabic(text: &str) -> bool {
text.chars().any(|c| {
matches!(c as u32,
0x0600..=0x06FF | 0x0750..=0x077F | 0x08A0..=0x08FF | 0xFB50..=0xFDFF | 0xFE70..=0xFEFF)
})
}
pub fn family_for(text: &str) -> cosmic_text::Family<'static> {
if contains_arabic(text) {
match *ARABIC.read().expect("family registry") {
Some(name) => cosmic_text::Family::Name(name),
None => family_or_generic(&SANS, cosmic_text::Family::SansSerif),
}
} else {
family_or_generic(&SANS, cosmic_text::Family::SansSerif)
}
}
pub fn family_for_style(
text: &str,
family: Option<frus_core::FontFamily>,
) -> cosmic_text::Family<'static> {
use frus_core::FontFamily;
match family {
None => family_for(text),
Some(_) if contains_arabic(text) => family_for(text),
Some(FontFamily::SansSerif) => family_or_generic(&SANS, cosmic_text::Family::SansSerif),
Some(FontFamily::Serif) => cosmic_text::Family::Serif,
Some(FontFamily::Monospace) => monospace_family(),
Some(FontFamily::Named(name)) => cosmic_text::Family::Name(name),
}
}
pub fn monospace_family() -> cosmic_text::Family<'static> {
family_or_generic(&MONO, cosmic_text::Family::Monospace)
}
pub fn available_style(italic: bool) -> Style {
if italic && ITALIC.load(Ordering::Relaxed) {
Style::Italic
} else {
Style::Normal
}
}
#[cfg(target_os = "android")]
const ANDROID_FONT_DIR: &str = "/system/fonts";
#[cfg(any(target_os = "android", test))]
fn load_emoji_faces(db: &mut cosmic_text::fontdb::Database, dir: &std::path::Path) -> usize {
let Ok(entries) = std::fs::read_dir(dir) else {
return 0;
};
let mut taken = 0;
for path in entries.flatten().map(|entry| entry.path()) {
let name = path
.file_name()
.and_then(|name| name.to_str())
.map(str::to_ascii_lowercase)
.unwrap_or_default();
let font = [".ttf", ".otf", ".ttc"]
.iter()
.any(|extension| name.ends_with(extension));
if font && name.contains("emoji") && db.load_font_file(&path).is_ok() {
taken += 1;
}
}
taken
}
pub fn new_font_system() -> FontSystem {
let mut font_system = FontSystem::new();
let db = font_system.db_mut();
#[cfg(target_os = "android")]
load_emoji_faces(db, std::path::Path::new(ANDROID_FONT_DIR));
#[cfg(feature = "bundled-sans")]
{
db.load_font_data(DEJAVU_SANS.to_vec());
db.load_font_data(DEJAVU_SANS_BOLD.to_vec());
}
#[cfg(feature = "bundled-italic")]
{
db.load_font_data(DEJAVU_SANS_OBLIQUE.to_vec());
db.load_font_data(DEJAVU_SANS_BOLD_OBLIQUE.to_vec());
}
#[cfg(feature = "bundled-mono")]
db.load_font_data(DEJAVU_MONO.to_vec());
#[cfg(feature = "bundled-arabic")]
{
db.load_font_data(NOTO_ARABIC.to_vec());
db.load_font_data(NOTO_ARABIC_BOLD.to_vec());
}
for face in EXTRA_FONTS.lock().expect("font registry").iter() {
db.load_font_data(face.clone());
}
if let Some(sans) = *SANS.read().expect("family registry") {
db.set_sans_serif_family(sans);
db.set_serif_family(sans);
db.set_cursive_family(sans);
db.set_fantasy_family(sans);
}
if let Some(mono) = *MONO.read().expect("family registry") {
db.set_monospace_family(mono);
}
ITALIC.store(has_italic_face(db), Ordering::Relaxed);
font_system
}
fn has_italic_face(db: &cosmic_text::fontdb::Database) -> bool {
let sans = *SANS.read().expect("family registry");
db.faces().any(|face| {
face.style != cosmic_text::fontdb::Style::Normal
&& match sans {
Some(name) => face.families.iter().any(|(family, _)| family == name),
None => true,
}
})
}
static FONT_SYSTEM: OnceLock<Mutex<FontSystem>> = OnceLock::new();
fn font_system() -> &'static Mutex<FontSystem> {
FONT_SYSTEM.get_or_init(|| Mutex::new(new_font_system()))
}
#[derive(PartialEq, Eq, Hash)]
struct MeasureKey {
text: String,
size: u32,
weight: u16,
italic: bool,
max_width: Option<u32>,
line_h: u32,
family: Option<frus_core::FontFamily>,
}
const CACHE_CAP: usize = 2048;
#[derive(Default)]
struct MeasureCache {
current: std::collections::HashMap<MeasureKey, Size>,
previous: std::collections::HashMap<MeasureKey, Size>,
}
static MEASURE_CACHE: Mutex<Option<MeasureCache>> = Mutex::new(None);
fn forget_measurements() {
if let Ok(mut cache) = MEASURE_CACHE.lock() {
*cache = None;
}
}
pub fn available_weight(weight: FontWeight) -> u16 {
if weight.to_u16() < 550 {
400
} else {
700
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
struct BaselineKey {
size: u32,
weight: u16,
italic: bool,
}
static BASELINES: std::sync::LazyLock<
std::sync::Mutex<std::collections::HashMap<BaselineKey, f32>>,
> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
pub fn line_height(size_px: f32) -> f32 {
size_px * LINE_HEIGHT_FACTOR
}
pub fn baseline(size_px: f32, weight: FontWeight, italic: bool) -> f32 {
let _ = font_system();
let key = BaselineKey {
size: size_px.to_bits(),
weight: available_weight(weight),
italic: available_style(italic) == Style::Italic,
};
if let Some(cached) = BASELINES.lock().expect("baseline cache").get(&key) {
return *cached;
}
let line_h = line_height(size_px);
let mut font_system = font_system().lock().expect("FontSystem lock");
let metrics = Metrics::new(size_px, line_h);
let mut buffer = Buffer::new(&mut font_system, metrics);
let probe = "Hg";
let attrs = Attrs::new()
.family(family_for(probe))
.weight(Weight(available_weight(weight)))
.style(available_style(italic));
buffer.set_text(probe, &attrs, Shaping::Advanced, None);
buffer.shape_until_scroll(&mut font_system, false);
let baseline = buffer
.layout_runs()
.next()
.map(|run| run.line_y)
.unwrap_or(size_px);
drop(font_system);
BASELINES
.lock()
.expect("baseline cache")
.insert(key, baseline);
baseline
}
pub fn baseline_of_runs(runs: &[TextRun]) -> Option<f32> {
runs.iter()
.map(|run| baseline(run.size, run.weight, run.italic))
.fold(None, |acc: Option<f32>, b| {
Some(acc.map_or(b, |a| a.max(b)))
})
}
pub fn measure(text: &str, size_px: f32) -> Size {
measure_styled(text, size_px, FontWeight::Regular, false)
}
pub fn measure_style(text: &str, style: TextStyle) -> Size {
measure_resolved(text, &style.resolved())
}
pub fn measure_resolved(text: &str, style: &ResolvedTextStyle) -> Size {
measure_wrapped_resolved(text, style, None)
}
pub fn line_box(min: f32, style: &ResolvedTextStyle, padding: f32) -> f32 {
min.max(fits(style.line_height() + padding))
}
pub fn measure_wrapped_resolved(
text: &str,
style: &ResolvedTextStyle,
max_width: Option<f32>,
) -> Size {
measure_at(
text,
style.size,
style.weight,
style.italic,
max_width,
style.line_height(),
style.family,
)
}
pub fn measure_styled(text: &str, size_px: f32, weight: FontWeight, italic: bool) -> Size {
measure_wrapped(text, size_px, weight, italic, None)
}
pub fn measure_wrapped(
text: &str,
size_px: f32,
weight: FontWeight,
italic: bool,
max_width: Option<f32>,
) -> Size {
measure_at(
text,
size_px,
weight,
italic,
max_width,
line_height(size_px),
None,
)
}
fn measure_at(
text: &str,
size_px: f32,
weight: FontWeight,
italic: bool,
max_width: Option<f32>,
line_h: f32,
family: Option<frus_core::FontFamily>,
) -> Size {
if text.is_empty() {
return Size::new(0.0, fits(line_h));
}
let _ = font_system();
let key = MeasureKey {
text: text.to_string(),
size: size_px.to_bits(),
weight: available_weight(weight),
italic: available_style(italic) == Style::Italic,
max_width: max_width.map(f32::to_bits),
line_h: line_h.to_bits(),
family,
};
if let Some(size) = cached_measurement(&key) {
return size;
}
let mut font_system = font_system().lock().expect("FontSystem lock");
let metrics = Metrics::new(size_px, line_h);
let mut buffer = Buffer::new(&mut font_system, metrics);
buffer.set_size(max_width, None);
let attrs = Attrs::new()
.family(family_for_style(text, family))
.weight(Weight(available_weight(weight)))
.style(available_style(italic));
buffer.set_text(text, &attrs, Shaping::Advanced, None);
buffer.shape_until_scroll(&mut font_system, false);
let mut width = 0.0_f32;
let mut lines = 0.0_f32;
for run in buffer.layout_runs() {
width = width.max(run.line_w);
lines += 1.0;
}
let width = match max_width {
Some(max) => fits(width).min(max),
None => fits(width),
};
let measured = Size::new(width, fits(lines.max(1.0) * line_h));
remember_measurement(key, measured);
measured
}
fn cached_measurement(key: &MeasureKey) -> Option<Size> {
let mut guard = MEASURE_CACHE.lock().ok()?;
let cache = guard.as_mut()?;
if let Some(size) = cache.current.get(key) {
return Some(*size);
}
let size = *cache.previous.get(key)?;
cache.current.insert(
MeasureKey {
text: key.text.clone(),
..*key
},
size,
);
Some(size)
}
fn remember_measurement(key: MeasureKey, size: Size) {
let Ok(mut guard) = MEASURE_CACHE.lock() else {
return;
};
let cache = guard.get_or_insert_with(MeasureCache::default);
if cache.current.len() >= CACHE_CAP {
cache.previous = std::mem::take(&mut cache.current);
}
cache.current.insert(key, size);
}
pub fn line_spans(
text: &str,
size_px: f32,
weight: FontWeight,
italic: bool,
max_width: Option<f32>,
soft_wrap: bool,
) -> Vec<std::ops::Range<usize>> {
let mut font_system = font_system().lock().expect("FontSystem lock");
let metrics = Metrics::new(size_px, line_height(size_px));
let mut buffer = Buffer::new(&mut font_system, metrics);
if !soft_wrap {
buffer.set_wrap(cosmic_text::Wrap::None);
}
buffer.set_size(max_width, None);
let attrs = Attrs::new()
.family(family_for(text))
.weight(Weight(available_weight(weight)))
.style(available_style(italic));
buffer.set_text(text, &attrs, Shaping::Advanced, None);
buffer.shape_until_scroll(&mut font_system, false);
let mut line_start = Vec::new();
let mut at = 0usize;
for line in &buffer.lines {
line_start.push(at);
at += line.text().len() + 1;
}
let mut spans = Vec::new();
for run in buffer.layout_runs() {
let base = line_start.get(run.line_i).copied().unwrap_or(0);
let start = run.glyphs.iter().map(|g| g.start).min();
let end = run.glyphs.iter().map(|g| g.end).max();
match (start, end) {
(Some(start), Some(end)) => spans.push(base + start..base + end),
_ => spans.push(base..base),
}
}
if spans.is_empty() {
spans.push(0..0);
}
spans
}
pub fn measure_runs(runs: &[TextRun]) -> Size {
measure_runs_wrapped(runs, None)
}
pub fn measure_runs_wrapped(runs: &[TextRun], max_width: Option<f32>) -> Size {
if runs.iter().all(|r| r.text.is_empty()) {
return Size::new(0.0, 0.0);
}
let base = runs.iter().map(|r| r.size).fold(0.0_f32, f32::max);
let mut font_system = font_system().lock().expect("FontSystem lock");
let metrics = Metrics::new(base, line_height(base));
let mut buffer = Buffer::new(&mut font_system, metrics);
buffer.set_size(max_width, None);
let spans = runs.iter().map(|run| {
(
run.text.as_str(),
Attrs::new()
.family(family_for(&run.text))
.weight(Weight(available_weight(run.weight)))
.style(available_style(run.italic))
.metrics(Metrics::new(run.size, line_height(run.size))),
)
});
buffer.set_rich_text(spans, &Attrs::new(), Shaping::Advanced, None);
buffer.shape_until_scroll(&mut font_system, false);
let mut width = 0.0_f32;
let mut height = 0.0_f32;
for run in buffer.layout_runs() {
width = width.max(run.line_w);
height = height.max(run.line_top + run.line_height);
}
let width = match max_width {
Some(max) => fits(width).min(max),
None => fits(width),
};
Size::new(width, fits(height))
}
pub fn runs_cut_at(
runs: &[TextRun],
max_width: Option<f32>,
soft_wrap: bool,
max_lines: usize,
) -> Option<usize> {
if runs.iter().all(|r| r.text.is_empty()) {
return None;
}
let base = runs.iter().map(|r| r.size).fold(0.0_f32, f32::max);
let mut font_system = font_system().lock().expect("FontSystem lock");
let metrics = Metrics::new(base, line_height(base));
let mut buffer = Buffer::new(&mut font_system, metrics);
if !soft_wrap {
buffer.set_wrap(cosmic_text::Wrap::None);
}
buffer.set_size(max_width, None);
let spans = runs.iter().map(|run| {
(
run.text.as_str(),
Attrs::new()
.family(family_for(&run.text))
.weight(Weight(available_weight(run.weight)))
.style(available_style(run.italic))
.metrics(Metrics::new(run.size, line_height(run.size))),
)
});
buffer.set_rich_text(spans, &Attrs::new(), Shaping::Advanced, None);
buffer.shape_until_scroll(&mut font_system, false);
let mut line_start = Vec::new();
let mut at = 0usize;
for line in &buffer.lines {
line_start.push(at);
at += line.text().len() + 1;
}
for (index, run) in buffer.layout_runs().enumerate() {
if index < max_lines {
continue;
}
let start = run.glyphs.iter().map(|g| g.start).min().unwrap_or(0);
return Some(line_start.get(run.line_i).copied().unwrap_or(0) + start);
}
None
}
struct LayoutLine {
start_char: usize,
offsets: Vec<f32>,
top: f32,
height: f32,
}
pub struct TextLayout {
lines: Vec<LayoutLine>,
size: Size,
chars: usize,
}
impl TextLayout {
pub fn new(text: &str, size_px: f32, weight: FontWeight, italic: bool) -> Self {
Self::wrapped(text, size_px, weight, italic, None)
}
pub fn wrapped(
text: &str,
size_px: f32,
weight: FontWeight,
italic: bool,
max_width: Option<f32>,
) -> Self {
let fallback_h = line_height(size_px);
let mut lines: Vec<LayoutLine> = Vec::new();
let mut width = 0.0_f32;
let mut height = 0.0_f32;
if !text.is_empty() {
let hard: Vec<&str> = text.split('\n').collect();
let mut line_byte_start = Vec::with_capacity(hard.len());
{
let mut b = 0usize;
for l in &hard {
line_byte_start.push(b);
b += l.len() + 1; }
}
let mut font_system = font_system().lock().expect("FontSystem lock");
let metrics = Metrics::new(size_px, fallback_h);
let mut buffer = Buffer::new(&mut font_system, metrics);
buffer.set_size(max_width, None);
let attrs = Attrs::new()
.family(family_for(text))
.weight(Weight(available_weight(weight)))
.style(available_style(italic));
buffer.set_text(text, &attrs, Shaping::Advanced, None);
buffer.shape_until_scroll(&mut font_system, false);
let runs: Vec<_> = buffer.layout_runs().collect();
for (idx, run) in runs.iter().enumerate() {
let line_text = hard[run.line_i];
let first_of_line = idx == 0 || runs[idx - 1].line_i != run.line_i;
let lo = if first_of_line {
0
} else {
run.glyphs.iter().map(|g| g.start).min().unwrap_or(0)
};
let hi = runs
.get(idx + 1)
.filter(|r| r.line_i == run.line_i)
.and_then(|r| r.glyphs.iter().map(|g| g.start).min())
.unwrap_or(line_text.len());
let span = &line_text[lo..hi];
let char_bytes: Vec<usize> = span.char_indices().map(|(b, _)| lo + b).collect();
let n = char_bytes.len();
let mut offsets = vec![f32::NAN; n + 1];
offsets[0] = 0.0;
for glyph in run.glyphs.iter() {
let covered: Vec<usize> = (0..n)
.filter(|&i| char_bytes[i] >= glyph.start && char_bytes[i] < glyph.end)
.collect();
let k = covered.len().max(1) as f32;
for (j, &i) in covered.iter().enumerate() {
offsets[i] = glyph.x + glyph.w * (j as f32 / k);
}
if let Some(next) = (0..=n).find(|&i| {
let b = if i == n {
lo + span.len()
} else {
char_bytes[i]
};
b == glyph.end
}) {
offsets[next] = glyph.x + glyph.w;
}
}
for i in 1..=n {
if offsets[i].is_nan() {
offsets[i] = offsets[i - 1];
}
}
let start_char = text[..line_byte_start[run.line_i] + lo].chars().count();
width = width.max(run.line_w);
height = height.max(run.line_top + run.line_height);
lines.push(LayoutLine {
start_char,
offsets,
top: run.line_top,
height: run.line_height,
});
}
}
if lines.is_empty() {
lines.push(LayoutLine {
start_char: 0,
offsets: vec![0.0],
top: 0.0,
height: fallback_h,
});
height = fallback_h;
}
let chars = text.chars().count();
Self {
lines,
size: Size::new(width, height),
chars,
}
}
pub fn size(&self) -> Size {
self.size
}
fn line_of(&self, index: usize) -> &LayoutLine {
self.lines
.iter()
.rev()
.find(|line| index >= line.start_char)
.unwrap_or(&self.lines[0])
}
pub fn caret_rect(&self, index: usize) -> Rect {
let index = index.min(self.chars);
let line = self.line_of(index);
let local = (index - line.start_char).min(line.offsets.len() - 1);
Rect::new(line.offsets[local], line.top, 0.0, line.height)
}
pub fn hit_test(&self, point: Point) -> usize {
let line = self
.lines
.iter()
.find(|line| point.y < line.top + line.height)
.unwrap_or(self.lines.last().expect("at least one line"));
let mut best = 0;
let mut best_dist = f32::MAX;
for (i, x) in line.offsets.iter().enumerate() {
let dist = (x - point.x).abs();
if dist < best_dist {
best_dist = dist;
best = i;
}
}
(line.start_char + best).min(self.chars)
}
pub fn selection_rects(&self, start: usize, end: usize) -> Vec<Rect> {
let (start, end) = (start.min(self.chars), end.min(self.chars));
if start >= end {
return Vec::new();
}
let mut rects = Vec::new();
for line in &self.lines {
let line_len = line.offsets.len() - 1;
let lo = start.max(line.start_char);
let hi = end.min(line.start_char + line_len);
if lo >= hi {
continue;
}
let x0 = line.offsets[lo - line.start_char];
let x1 = line.offsets[hi - line.start_char];
if x1 > x0 {
rects.push(Rect::new(x0, line.top, x1 - x0, line.height));
}
}
rects
}
}
#[cfg(test)]
mod tests {
#[test]
fn line_spans_break_where_the_shaper_breaks() {
let text = "one two three four five six seven eight";
let spans = line_spans(text, 14.0, FontWeight::Regular, false, Some(80.0), true);
assert!(spans.len() > 1, "it wrapped: {spans:?}");
let words: Vec<&str> = spans
.iter()
.flat_map(|s| text[s.clone()].split_whitespace())
.collect();
assert_eq!(words, text.split_whitespace().collect::<Vec<_>>());
for span in &spans {
let w = measure_styled(&text[span.clone()], 14.0, FontWeight::Regular, false).width;
assert!(
w <= 80.5,
"each line fits: {:?} at {w}",
&text[span.clone()]
);
}
}
#[test]
fn the_spans_run_forwards() {
let text = "one two three four five six seven eight";
let spans = line_spans(text, 14.0, FontWeight::Regular, false, Some(80.0), true);
for pair in spans.windows(2) {
assert!(pair[0].end <= pair[1].start, "{pair:?}");
}
}
#[test]
fn without_wrapping_there_is_one_line() {
let text = "one two three four five six seven eight";
let spans = line_spans(text, 14.0, FontWeight::Regular, false, Some(40.0), false);
assert_eq!(spans.len(), 1);
assert_eq!(&text[spans[0].clone()], text);
}
use super::*;
#[test]
fn empty_text_has_zero_width() {
let size = measure("", 16.0);
assert_eq!(size.width, 0.0);
assert!(size.height > 0.0);
}
#[test]
fn non_empty_text_has_positive_size() {
let size = measure("Bonjour", 24.0);
assert!(size.width > 0.0, "width = {}", size.width);
assert!(size.height > 0.0, "height = {}", size.height);
}
#[test]
fn rich_runs_measure_mixed_styles() {
use frus_core::Color;
let run = |text: &str, size: f32, weight: FontWeight| TextRun {
text: text.to_string(),
size,
weight,
italic: false,
color: Color::WHITE,
decoration: frus_core::TextDecoration::NONE,
decoration_color: None,
};
let plain = measure_runs(&[run("normal", 16.0, FontWeight::Regular)]);
let mixed = measure_runs(&[
run("normal", 16.0, FontWeight::Regular),
run(" BOLD", 24.0, FontWeight::Bold),
]);
assert!(mixed.width > plain.width);
assert!(
mixed.height >= line_height(24.0) - 1.0,
"height driven by the 24px run: {}",
mixed.height
);
assert_eq!(measure_runs(&[]), Size::new(0.0, 0.0));
}
#[test]
fn wrapped_text_grows_taller_within_the_width() {
let text = "a text that is long enough to wrap onto several lines";
let free = measure_wrapped(text, 16.0, FontWeight::Regular, false, None);
let narrow = measure_wrapped(text, 16.0, FontWeight::Regular, false, Some(120.0));
assert!(
narrow.width <= 120.0,
"wrapped within the width: {}",
narrow.width
);
assert!(narrow.height > free.height, "wrapping grows the height");
}
#[test]
fn layout_offsets_are_monotonic_and_match_size() {
let layout = TextLayout::new("Bonjour le monde", 18.0, FontWeight::Regular, false);
let mut prev = -1.0;
for i in 0..=16 {
let x = layout.caret_rect(i).x;
assert!(x >= prev, "offset decreasing at boundary {i}");
prev = x;
}
assert!((layout.caret_rect(16).x - layout.size().width).abs() < 0.5);
assert_eq!(layout.caret_rect(99).x, layout.caret_rect(16).x);
}
#[test]
fn hit_test_roundtrips_caret_positions() {
let layout = TextLayout::new("Bonjour", 18.0, FontWeight::Regular, false);
for i in 0..=7 {
let caret = layout.caret_rect(i);
let hit = layout.hit_test(Point::new(caret.x, caret.y + 1.0));
assert_eq!(hit, i, "caret->hit round trip at boundary {i}");
}
assert_eq!(layout.hit_test(Point::new(-100.0, 0.0)), 0);
assert_eq!(layout.hit_test(Point::new(10_000.0, 0.0)), 7);
}
#[test]
fn selection_rects_cover_the_range() {
let layout = TextLayout::new("Bonjour", 18.0, FontWeight::Regular, false);
let rects = layout.selection_rects(2, 5);
assert_eq!(rects.len(), 1);
let r = rects[0];
assert!((r.x - layout.caret_rect(2).x).abs() < 0.01);
assert!((r.x + r.width - layout.caret_rect(5).x).abs() < 0.01);
assert!(r.height > 0.0);
assert!(layout.selection_rects(3, 3).is_empty());
assert!(layout.selection_rects(5, 2).is_empty());
}
#[test]
fn multiline_layout_maps_lines_and_indices() {
let layout = TextLayout::new("ab\ncd", 18.0, FontWeight::Regular, false);
let first = layout.caret_rect(0);
let second = layout.caret_rect(3);
assert!(second.y > first.y, "the 2nd line sits lower");
assert_eq!(second.x, 0.0, "second line starts at x = 0");
let hit = layout.hit_test(Point::new(0.0, second.y + 1.0));
assert_eq!(hit, 3);
}
#[test]
fn soft_wrap_indexes_chars_correctly_across_lines() {
let text = "aaaa bbbb cccc dddd"; let layout = TextLayout::wrapped(text, 18.0, FontWeight::Regular, false, Some(60.0));
assert!(
layout.size().height > line_height(18.0) * 2.0,
"several visual lines"
);
let mut prev_y = -1.0;
for &start in &[0usize, 5, 10, 15] {
let c = layout.caret_rect(start);
assert!(c.x < 1.0, "word start {start} at x about 0 (x={})", c.x);
assert!(c.y > prev_y, "lines of increasing y at {start}");
prev_y = c.y;
}
let c = layout.caret_rect(11);
assert_eq!(layout.hit_test(Point::new(c.x, c.y + 1.0)), 11);
assert_eq!(layout.caret_rect(19).x, layout.caret_rect(99).x);
assert_eq!(layout.caret_rect(19).y, layout.caret_rect(99).y);
}
#[test]
fn empty_layout_keeps_caret_at_origin() {
let layout = TextLayout::new("", 18.0, FontWeight::Regular, false);
let caret = layout.caret_rect(0);
assert_eq!(caret.x, 0.0);
assert!(caret.height > 0.0, "wrapped line height");
assert_eq!(layout.hit_test(Point::new(50.0, 0.0)), 0);
}
#[test]
#[cfg(all(
feature = "bundled-sans",
feature = "bundled-italic",
feature = "bundled-mono"
))]
fn embedded_only_font_system_shapes_every_style() {
let mut db = cosmic_text::fontdb::Database::new();
db.load_font_data(DEJAVU_SANS.to_vec());
db.load_font_data(DEJAVU_SANS_BOLD.to_vec());
db.load_font_data(DEJAVU_SANS_OBLIQUE.to_vec());
db.load_font_data(DEJAVU_SANS_BOLD_OBLIQUE.to_vec());
db.load_font_data(DEJAVU_MONO.to_vec());
db.set_sans_serif_family(SANS_FAMILY);
db.set_serif_family(SANS_FAMILY);
db.set_cursive_family(SANS_FAMILY);
db.set_fantasy_family(SANS_FAMILY);
db.set_monospace_family(MONO_FAMILY);
let mut fs = FontSystem::new_with_locale_and_db("en-TG".to_string(), db);
for weight in [
FontWeight::Regular,
FontWeight::Medium,
FontWeight::SemiBold,
FontWeight::Bold,
] {
for italic in [false, true] {
let attrs = Attrs::new()
.weight(Weight(available_weight(weight)))
.style(if italic { Style::Italic } else { Style::Normal });
let mut buffer = Buffer::new(&mut fs, Metrics::new(20.0, 24.0));
buffer.set_size(None, None);
buffer.set_text("Nothing to show", &attrs, Shaping::Advanced, None);
buffer.shape_until_scroll(&mut fs, false); let w: f32 = buffer.layout_runs().map(|r| r.line_w).fold(0.0, f32::max);
assert!(w > 0.0, "weight {weight:?} italic {italic}: nothing shaped");
}
}
}
struct FontDir(std::path::PathBuf);
impl FontDir {
fn new(tag: &str) -> Self {
let dir = std::env::temp_dir().join(format!("frus-fonts-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("a scratch font directory");
Self(dir)
}
fn put(&self, name: &str, bytes: &[u8]) {
std::fs::write(self.0.join(name), bytes).expect("a scratch font file");
}
}
impl Drop for FontDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
#[cfg(feature = "bundled-sans")]
fn only_the_emoji_faces_are_taken_from_a_font_directory() {
let dir = FontDir::new("filter");
dir.put("NotoColorEmoji.ttf", DEJAVU_SANS);
dir.put("Roboto-Regular.ttf", DEJAVU_SANS);
dir.put("emoji-notes.txt", DEJAVU_SANS);
let mut db = cosmic_text::fontdb::Database::new();
assert_eq!(load_emoji_faces(&mut db, &dir.0), 1, "one file taken");
assert_eq!(db.faces().count(), 1, "and one face in the database");
assert_eq!(load_emoji_faces(&mut db, &dir.0.join("absent")), 0);
}
#[test]
#[cfg(feature = "bundled-sans")]
fn an_emoji_is_drawn_from_the_emoji_face_the_runs_font_lacks() {
let emoji = std::path::Path::new("C:\\Windows\\Fonts\\seguiemj.ttf");
if !emoji.exists() {
eprintln!("no colour emoji font at {}; skipped", emoji.display());
return;
}
let mut db = cosmic_text::fontdb::Database::new();
db.load_font_data(DEJAVU_SANS.to_vec());
db.load_font_file(emoji).expect("the emoji font");
db.set_sans_serif_family(SANS_FAMILY);
let emoji_face = db
.faces()
.find(|face| face.post_script_name.contains("Emoji"))
.map(|face| face.id)
.expect("an emoji face");
let mut fs = FontSystem::new_with_locale_and_db("en-TG".to_string(), db);
let text = "Hi \u{1F44B}";
let at = text.find('\u{1F44B}').expect("the wave");
let mut buffer = Buffer::new(&mut fs, Metrics::new(40.0, 48.0));
buffer.set_size(None, None);
buffer.set_text(
text,
&Attrs::new().family(family_for(text)),
Shaping::Advanced,
None,
);
buffer.shape_until_scroll(&mut fs, false);
let (font, glyph) = buffer
.layout_runs()
.flat_map(|run| run.glyphs.iter())
.find(|glyph| glyph.start == at)
.map(|glyph| (glyph.font_id, glyph.glyph_id))
.expect("a glyph for the emoji");
assert_eq!(font, emoji_face, "the emoji comes from the emoji face");
assert_ne!(glyph, 0, "and is a real glyph, not the empty box");
}
#[test]
#[cfg(all(feature = "bundled-sans", feature = "bundled-arabic"))]
fn arabic_shapes_with_embedded_only_font_system() {
let mut db = cosmic_text::fontdb::Database::new();
db.load_font_data(DEJAVU_SANS.to_vec());
db.load_font_data(NOTO_ARABIC.to_vec());
db.load_font_data(NOTO_ARABIC_BOLD.to_vec());
db.set_sans_serif_family(SANS_FAMILY);
let mut fs = FontSystem::new_with_locale_and_db("en-TG".to_string(), db);
let text = "مهامي";
let attrs = Attrs::new().family(family_for(text));
let mut buffer = Buffer::new(&mut fs, Metrics::new(40.0, 48.0));
buffer.set_size(None, None);
buffer.set_text(text, &attrs, Shaping::Advanced, None);
buffer.shape_until_scroll(&mut fs, false);
let mut glyphs = 0usize;
let mut real = 0usize; for run in buffer.layout_runs() {
for g in run.glyphs.iter() {
glyphs += 1;
if g.glyph_id != 0 {
real += 1;
}
}
}
assert!(glyphs > 0, "no glyph shaped for Arabic");
assert!(
real > 0,
"only .notdef ({glyphs} glyphs, 0 real): Family::Name(\"{ARABIC_FAMILY}\") did not resolve the Naskh face"
);
}
#[test]
#[cfg(all(feature = "bundled-sans", feature = "bundled-arabic"))]
fn rtl_right_aligns_to_buffer_width() {
let mut db = cosmic_text::fontdb::Database::new();
db.load_font_data(DEJAVU_SANS.to_vec());
db.load_font_data(NOTO_ARABIC.to_vec());
db.set_sans_serif_family(SANS_FAMILY);
let mut fs = FontSystem::new_with_locale_and_db("en-TG".to_string(), db);
let text = "العربية";
let attrs = Attrs::new().family(family_for(text));
let mut first_glyph_x = |width: Option<f32>| {
let mut buffer = Buffer::new(&mut fs, Metrics::new(40.0, 48.0));
buffer.set_size(width, Some(200.0));
buffer.set_text(text, &attrs, Shaping::Advanced, None);
buffer.shape_until_scroll(&mut fs, false);
buffer
.layout_runs()
.flat_map(|r| r.glyphs.iter().map(|g| g.x))
.fold(f32::MAX, f32::min)
};
let wide = first_glyph_x(Some(1080.0));
let free = first_glyph_x(None);
assert!(wide > 500.0, "a wide RTL run should push right (x={wide})");
assert!(
free < 50.0,
"an unconstrained RTL run should start left (x={free})"
);
}
#[test]
#[cfg(all(feature = "bundled-sans", feature = "bundled-arabic"))]
fn arabic_falls_back_to_the_embedded_naskh_face() {
let hello = "مرحبا بالعالم"; let m = measure(hello, 24.0);
assert!(m.width > 60.0, "Arabic must shape (width {})", m.width);
assert!(m.height > 0.0);
let latin = measure("Hello", 24.0);
assert!(latin.width > 0.0);
let mixed = measure("قيمة 42 نقطة", 24.0);
assert!(mixed.width > 0.0, "mixed bidi text was not shaped");
}
#[test]
fn weights_snap_to_embedded_faces() {
assert_eq!(available_weight(FontWeight::Regular), 400);
assert_eq!(available_weight(FontWeight::Medium), 400);
assert_eq!(available_weight(FontWeight::SemiBold), 700);
assert_eq!(available_weight(FontWeight::Bold), 700);
let text = "Titre de section";
let regular = measure_styled(text, 20.0, FontWeight::Regular, false);
let medium = measure_styled(text, 20.0, FontWeight::Medium, false);
assert_eq!(medium.width, regular.width);
let semibold = measure_styled(text, 20.0, FontWeight::SemiBold, false);
let bold = measure_styled(text, 20.0, FontWeight::Bold, false);
assert_eq!(semibold.width, bold.width);
assert!(bold.width > regular.width);
}
#[test]
fn the_natural_width_is_never_rounded_down_below_the_text() {
for text in ["Write code", "Bonjour le monde", "A", "iiiii"] {
for size in [12.0_f32, 15.0, 20.0, 24.0] {
let natural = measure_styled(text, size, FontWeight::Bold, false);
assert_eq!(
natural.width,
natural.width.ceil(),
"a whole number for {text:?} at {size}: {}",
natural.width
);
let at_its_width =
measure_wrapped(text, size, FontWeight::Bold, false, Some(natural.width));
assert_eq!(
at_its_width.height, natural.height,
"{text:?} at {size} wrapped inside its own width"
);
}
}
}
#[test]
fn the_natural_height_is_a_whole_number_too() {
for text in ["Write code", "one two three four five six seven eight", "A"] {
for size in [12.0_f32, 15.0, 20.0, 24.0] {
for width in [None, Some(60.0), Some(120.0)] {
let measured = measure_wrapped(text, size, FontWeight::Bold, false, width);
assert_eq!(
measured.height,
measured.height.ceil(),
"a whole number for {text:?} at {size} in {width:?}: {}",
measured.height
);
}
}
}
let empty = measure_styled("", 16.0, FontWeight::Regular, false);
assert_eq!(empty.height, empty.height.ceil(), "{}", empty.height);
assert!(empty.height >= line_height(16.0));
}
#[test]
fn a_constrained_measurement_never_exceeds_its_constraint() {
let measured = measure_wrapped(
"A rather long sentence that has to wrap somewhere",
18.0,
FontWeight::Regular,
false,
Some(120.0),
);
assert!(measured.width <= 120.0, "{}", measured.width);
}
#[test]
fn italic_measures_whether_or_not_an_oblique_face_is_bundled() {
let measured = measure_styled("Slanted", 16.0, FontWeight::Regular, true);
assert!(measured.width > 0.0, "nothing shaped");
}
#[test]
fn italic_is_only_asked_for_when_a_face_can_answer() {
let _ = measure("x", 12.0);
assert_eq!(
available_style(false),
Style::Normal,
"upright asked for italic"
);
assert_eq!(
available_style(true) == Style::Italic,
ITALIC.load(Ordering::Relaxed),
"italic asked for without a face to answer it"
);
}
#[test]
fn bold_measures_wider_than_regular() {
let regular = measure_styled("Bonjour le monde", 24.0, FontWeight::Regular, false);
let bold = measure_styled("Bonjour le monde", 24.0, FontWeight::Bold, false);
assert!(
bold.width > regular.width,
"gras {} <= normal {}",
bold.width,
regular.width
);
}
#[test]
fn a_cached_measurement_is_the_measurement() {
for (text, size) in [("Open", 15.0_f32), ("Task number 42 — due Friday", 13.0)] {
let first = measure(text, size);
let second = measure(text, size);
assert_eq!(
first, second,
"{text:?} measured differently the second time"
);
let styled = measure_styled(text, size, FontWeight::Bold, false);
assert_eq!(
styled,
measure_styled(text, size, FontWeight::Bold, false),
"{text:?} bold measured differently the second time"
);
let wrapped = measure_wrapped(text, size, FontWeight::Regular, false, Some(60.0));
assert_eq!(
wrapped,
measure_wrapped(text, size, FontWeight::Regular, false, Some(60.0)),
"{text:?} wrapped measured differently the second time"
);
assert!(
wrapped.height >= first.height,
"wrapping to 60 px should not make {text:?} shorter"
);
}
}
#[test]
fn a_string_still_in_use_survives_the_rotation() {
let kept = measure("still here", 14.0);
for i in 0..(CACHE_CAP * 2 + 64) {
measure(&format!("filler {i}"), 14.0);
if i % 512 == 0 {
assert_eq!(kept, measure("still here", 14.0), "lost at {i}");
}
}
assert_eq!(kept, measure("still here", 14.0));
}
#[test]
fn registering_a_font_forgets_what_was_measured() {
let before = measure("forget me", 15.0);
forget_measurements();
let after = measure("forget me", 15.0);
assert_eq!(before, after, "the same faces must measure the same");
}
#[test]
fn a_baseline_sits_where_a_line_of_text_does() {
let size = 20.0;
let b = baseline(size, FontWeight::Regular, false);
let line = line_height(size);
assert!(b > 0.0 && b < line, "inside the line box: {b} of {line}");
assert!(b > line * 0.5, "and below its middle: {b} of {line}");
}
#[test]
fn a_bigger_face_has_a_lower_baseline() {
let small = baseline(12.0, FontWeight::Regular, false);
let large = baseline(24.0, FontWeight::Regular, false);
assert!(large > small * 1.5, "{small} then {large}");
}
#[test]
fn mixed_runs_take_the_tallest_baseline() {
let run = |text: &str, size: f32| TextRun {
text: text.into(),
size,
weight: FontWeight::Regular,
italic: false,
color: frus_core::Color::WHITE,
decoration: frus_core::TextDecoration::default(),
decoration_color: None,
};
let runs = vec![run("small", 12.0), run("large", 24.0)];
let mixed = baseline_of_runs(&runs).expect("two runs");
assert!((mixed - baseline(24.0, FontWeight::Regular, false)).abs() < 0.01);
}
#[test]
fn a_named_line_height_reaches_the_measurement() {
let words = "one two three four five six seven eight nine ten";
let plain = ResolvedTextStyle::exact(16.0);
let open = ResolvedTextStyle {
height: Some(2.4),
..plain
};
let a = measure_wrapped_resolved(words, &plain, Some(80.0));
let b = measure_wrapped_resolved(words, &open, Some(80.0));
assert!(a.height > 0.0 && b.height > 0.0);
assert_eq!(
a.width, b.width,
"the line height changes the stacking, never the letters"
);
let ratio = b.height / a.height;
assert!(
(ratio - 2.0).abs() < 0.01,
"doubling the line height doubles the block: {ratio}"
);
}
#[test]
fn two_line_heights_do_not_share_a_cached_answer() {
let words = "cached words that wrap across a couple of lines here";
let packed = ResolvedTextStyle {
height: Some(1.0),
..ResolvedTextStyle::exact(14.0)
};
let open = ResolvedTextStyle {
height: Some(2.0),
..ResolvedTextStyle::exact(14.0)
};
let first = measure_wrapped_resolved(words, &packed, Some(90.0));
let second = measure_wrapped_resolved(words, &open, Some(90.0));
assert_eq!(measure_wrapped_resolved(words, &open, Some(90.0)), second);
assert_eq!(measure_wrapped_resolved(words, &packed, Some(90.0)), first);
assert!(second.height > first.height);
}
#[test]
fn a_line_box_follows_the_height_it_was_given() {
let open = ResolvedTextStyle {
height: Some(3.0),
..ResolvedTextStyle::exact(16.0)
};
assert_eq!(line_box(32.0, &ResolvedTextStyle::exact(16.0), 0.0), 32.0);
assert_eq!(
line_box(32.0, &open, 0.0),
48.0,
"the content wins over the floor"
);
}
#[test]
fn a_named_family_reaches_the_measurement() {
let words = "The quick brown fox";
let plain = ResolvedTextStyle::exact(16.0);
let mono = ResolvedTextStyle {
family: Some(frus_core::FontFamily::Monospace),
..plain
};
let a = measure_wrapped_resolved(words, &plain, None);
let b = measure_wrapped_resolved(words, &mono, None);
assert!(a.width > 0.0 && b.width > 0.0);
assert_ne!(
a.width, b.width,
"a monospaced face sets these words to a different width"
);
}
#[test]
fn arabic_keeps_its_face_whatever_was_named() {
let arabic = "\u{0645}\u{0631}\u{062d}\u{0628}\u{0627}";
let named = family_for_style(arabic, Some(frus_core::FontFamily::Monospace));
assert_eq!(
format!("{named:?}"),
format!("{:?}", family_for(arabic)),
"the script wins over the name"
);
let latin = family_for_style("hello", Some(frus_core::FontFamily::Monospace));
assert_eq!(format!("{latin:?}"), format!("{:?}", monospace_family()));
}
#[test]
fn two_families_do_not_share_a_cached_answer() {
let words = "shared words in two faces";
let plain = ResolvedTextStyle::exact(15.0);
let mono = ResolvedTextStyle {
family: Some(frus_core::FontFamily::Monospace),
..plain
};
let first = measure_wrapped_resolved(words, &plain, None);
let second = measure_wrapped_resolved(words, &mono, None);
assert_eq!(measure_wrapped_resolved(words, &mono, None), second);
assert_eq!(measure_wrapped_resolved(words, &plain, None), first);
assert_ne!(first.width, second.width);
}
}