use std::sync::Arc;
use nativeview_abi::{NvTextParagraphView, xxh64};
use nativeview_store::{Length, NodeId, NodeStore, Rgba, StrSpan};
use nativeview_tables::tables::{
FontStyle, OverflowWrap, TextAlign, TextDecoration, Typography, VerticalAlign, WhiteSpace,
WordBreak,
};
use crate::paragraph::measure::{
default_measure_paragraph, heuristic_hit_test_paragraph, heuristic_measure_paragraph,
};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TextStyle<F> {
pub color: Rgba,
pub font_family: F,
pub font_size: f32,
pub font_weight: u16,
pub font_style: FontStyle,
pub letter_spacing: f32,
pub line_height: Length,
pub white_space: WhiteSpace,
pub word_break: WordBreak,
pub overflow_wrap: OverflowWrap,
pub text_align: TextAlign,
pub text_decoration: TextDecoration,
pub vertical_align: VerticalAlign,
pub max_lines: u32,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct ResolvedFamily {
pub span: StrSpan,
pub hash: u64,
}
impl ResolvedFamily {
#[inline]
pub fn new(store: &NodeStore, span: StrSpan) -> Self {
let text = store.text(span);
Self { span, hash: if text.is_empty() { 0 } else { xxh64(text.as_bytes(), 0) } }
}
}
impl PartialEq for ResolvedFamily {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.hash == other.hash
}
}
pub type ResolvedTextStyle = TextStyle<ResolvedFamily>;
impl<F: Default> Default for TextStyle<F> {
fn default() -> Self {
Self {
color: Rgba::BLACK,
font_family: F::default(),
font_size: HeuristicTextMeasurer::DEFAULT_FONT_SIZE,
font_weight: 400,
font_style: FontStyle::Normal,
letter_spacing: 0.0,
line_height: Length::AUTO,
white_space: WhiteSpace::Normal,
word_break: WordBreak::Normal,
overflow_wrap: OverflowWrap::Normal,
text_align: TextAlign::Start,
text_decoration: TextDecoration::EMPTY,
vertical_align: VerticalAlign::Baseline,
max_lines: 0,
}
}
}
impl<F> TextStyle<F> {
#[inline]
pub fn map_family<'s, G>(&'s self, f: impl FnOnce(&'s F) -> G) -> TextStyle<G> {
TextStyle {
color: self.color,
font_family: f(&self.font_family),
font_size: self.font_size,
font_weight: self.font_weight,
font_style: self.font_style,
letter_spacing: self.letter_spacing,
line_height: self.line_height,
white_space: self.white_space,
word_break: self.word_break,
overflow_wrap: self.overflow_wrap,
text_align: self.text_align,
text_decoration: self.text_decoration,
vertical_align: self.vertical_align,
max_lines: self.max_lines,
}
}
#[inline]
pub fn wraps(&self) -> bool {
!matches!(self.white_space, WhiteSpace::NoWrap | WhiteSpace::Pre)
}
#[inline]
pub fn line_height_points(&self) -> Option<f32> {
let lh = if self.line_height.is_percent() {
self.line_height.value() * self.font_size / 100.0
} else {
self.line_height.resolve(self.font_size)?
};
(lh.is_finite() && lh > 0.0).then_some(lh)
}
}
impl<F: PartialEq> TextStyle<F> {
#[inline]
pub fn measure_eq(&self, other: &Self) -> bool {
self.font_family == other.font_family
&& self.font_size.to_bits() == other.font_size.to_bits()
&& self.font_weight == other.font_weight
&& self.font_style == other.font_style
&& self.letter_spacing.to_bits() == other.letter_spacing.to_bits()
&& self.line_height == other.line_height
&& self.white_space == other.white_space
&& self.word_break == other.word_break
&& self.overflow_wrap == other.overflow_wrap
&& self.vertical_align == other.vertical_align
&& self.max_lines == other.max_lines
}
#[inline]
pub fn style_eq(&self, other: &Self) -> bool {
self.measure_eq(other)
&& self.color == other.color
&& self.text_align == other.text_align
&& self.text_decoration == other.text_decoration
}
}
impl<F: AsRef<str>> TextStyle<F> {
#[inline]
pub fn borrowed(&self) -> TextStyle<&str> {
self.map_family(AsRef::as_ref)
}
}
impl TextStyle<&str> {
pub fn sized(font_size: f32) -> Self {
Self {
font_size,
..Self::default()
}
}
}
impl ResolvedTextStyle {
#[inline]
pub fn in_store<'a>(&self, store: &'a NodeStore) -> TextStyle<&'a str> {
self.map_family(|family| store.text(family.span))
}
}
#[inline]
pub fn resolve_inherited_text(
store: &NodeStore,
id: NodeId,
mut parent: ResolvedTextStyle,
) -> ResolvedTextStyle {
let Some(t) = store.try_row::<Typography>(id) else {
return parent;
};
if t.is_color_explicit() {
parent.color = t.color();
}
let fs = t.font_size();
if t.is_font_size_explicit() && fs.is_finite() && fs >= 0.0 {
parent.font_size = fs;
}
if t.is_font_weight_explicit() {
parent.font_weight = t.font_weight();
}
let lh = t.line_height();
if t.is_line_height_explicit() && (lh.is_auto() || (lh.value().is_finite() && lh.value() >= 0.0)) {
parent.line_height = lh;
}
let ls = t.letter_spacing();
if t.is_letter_spacing_explicit() && ls.is_finite() {
parent.letter_spacing = ls;
}
if t.is_font_family_explicit() {
parent.font_family = ResolvedFamily::new(store, t.font_family_span());
}
if t.is_max_lines_explicit() {
parent.max_lines = t.max_lines().map_or(0, |n| u32::from(n.get()));
}
if t.is_font_style_explicit() {
parent.font_style = t.font_style();
}
if t.is_white_space_explicit() {
parent.white_space = t.white_space();
}
if t.is_word_break_explicit() {
parent.word_break = t.word_break();
}
if t.is_overflow_wrap_explicit() {
parent.overflow_wrap = t.overflow_wrap();
}
if t.is_text_align_explicit() {
parent.text_align = t.text_align();
}
if t.is_text_decoration_explicit() {
parent.text_decoration = t.text_decoration();
}
if t.is_vertical_align_explicit() {
parent.vertical_align = t.vertical_align();
}
parent
}
pub trait TextMeasurer: Send + Sync {
fn measure(&self, text: &str, style: &TextStyle<&str>, max_width: Option<f32>) -> (f32, f32);
fn measure_paragraph(
&self,
paragraph: &NvTextParagraphView,
max_width: Option<f32>,
) -> (f32, f32) {
default_measure_paragraph(self, paragraph, max_width)
}
fn hit_test_paragraph(
&self,
paragraph: &NvTextParagraphView,
box_width: f32,
local_x: f32,
local_y: f32,
) -> Option<NodeId> {
heuristic_hit_test_paragraph(paragraph, box_width, local_x, local_y)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct HeuristicTextMeasurer;
impl HeuristicTextMeasurer {
pub const CHAR_WIDTH_FACTOR: f32 = 0.58;
pub const LINE_HEIGHT_FACTOR: f32 = 1.35;
pub const DEFAULT_FONT_SIZE: f32 = 16.0;
}
impl TextMeasurer for HeuristicTextMeasurer {
fn measure(&self, text: &str, style: &TextStyle<&str>, max_width: Option<f32>) -> (f32, f32) {
if text.is_empty() || style.font_size == 0.0 {
return (0.0, 0.0);
}
let fs = if style.font_size.is_finite() && style.font_size > 0.0 {
style.font_size
} else {
Self::DEFAULT_FONT_SIZE
};
let sized = TextStyle { font_size: fs, ..*style };
let char_w = (fs * Self::CHAR_WIDTH_FACTOR + style.letter_spacing).max(0.0);
let line_h = sized.line_height_points().unwrap_or(fs * Self::LINE_HEIGHT_FACTOR);
let height = |lines: f32| {
let lines = lines.max(1.0);
let capped = if style.max_lines > 0 { lines.min(style.max_lines as f32) } else { lines };
capped * line_h
};
let line_widths = || text.split('\n').map(|line| line.chars().count() as f32 * char_w);
match max_width.filter(|_| style.wraps()) {
Some(mw) if !mw.is_finite() || mw <= 0.0 => {
(0.0, height(text.split('\n').count() as f32))
}
Some(mw) => {
let wrap_eps = (mw * 1e-5).max(1e-5);
let (mut max_line_w, mut total_lines) = (0.0f32, 0.0f32);
for raw_w in line_widths() {
if raw_w > mw + wrap_eps {
max_line_w = max_line_w.max(mw);
total_lines += ((raw_w - wrap_eps) / mw).ceil().max(1.0);
} else {
max_line_w = max_line_w.max(raw_w);
total_lines += 1.0;
}
}
(max_line_w.max(1.0).min(mw), height(total_lines))
}
None => {
let (max_line_w, lines) =
line_widths().fold((0.0f32, 0.0f32), |(w, n), lw| (w.max(lw), n + 1.0));
(max_line_w.max(1.0), height(lines))
}
}
}
fn measure_paragraph(
&self,
paragraph: &NvTextParagraphView,
max_width: Option<f32>,
) -> (f32, f32) {
heuristic_measure_paragraph(paragraph, max_width)
}
fn hit_test_paragraph(
&self,
paragraph: &NvTextParagraphView,
box_width: f32,
local_x: f32,
local_y: f32,
) -> Option<NodeId> {
heuristic_hit_test_paragraph(paragraph, box_width, local_x, local_y)
}
}
impl<F> TextMeasurer for F
where
F: Fn(&str, &TextStyle<&str>, Option<f32>) -> (f32, f32) + Send + Sync,
{
fn measure(&self, text: &str, style: &TextStyle<&str>, max_width: Option<f32>) -> (f32, f32) {
(self)(text, style, max_width)
}
}
impl<T: TextMeasurer + ?Sized> TextMeasurer for Arc<T> {
fn measure(&self, text: &str, style: &TextStyle<&str>, max_width: Option<f32>) -> (f32, f32) {
(**self).measure(text, style, max_width)
}
fn measure_paragraph(
&self,
paragraph: &NvTextParagraphView,
max_width: Option<f32>,
) -> (f32, f32) {
(**self).measure_paragraph(paragraph, max_width)
}
fn hit_test_paragraph(
&self,
paragraph: &NvTextParagraphView,
box_width: f32,
local_x: f32,
local_y: f32,
) -> Option<NodeId> {
(**self).hit_test_paragraph(paragraph, box_width, local_x, local_y)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sized(fs: f32) -> TextStyle<&'static str> {
TextStyle::sized(fs)
}
#[test]
fn heuristic_text_measurer_matches_single_line_and_wraps() {
let m = HeuristicTextMeasurer;
assert_eq!(m.measure("", &sized(16.0), None), (0.0, 0.0));
let (w, h) = m.measure("Hello World", &sized(20.0), None);
assert!((w - 11.0 * 20.0 * 0.58).abs() < 1e-4);
assert!((h - 20.0 * 1.35).abs() < 1e-4);
let (ww, wh) = m.measure("01234567890123456789", &sized(20.0), Some(100.0));
assert!((ww - 100.0).abs() < 1e-4);
assert!((wh - 3.0 * 20.0 * 1.35).abs() < 1e-4);
let (nw, nh) = m.measure("Line 1\nLine 2", &sized(16.0), None);
assert!((nw - 6.0 * 16.0 * 0.58).abs() < 1e-4);
assert!((nh - 2.0 * 16.0 * 1.35).abs() < 1e-4);
let (single_w, single_h) = m.measure("8", &sized(11.0), None);
let round_trip_mw = (single_w + 18.0_f32) - 18.0_f32;
assert_eq!(m.measure("8", &sized(11.0), Some(round_trip_mw)).1, single_h);
let custom: Arc<dyn TextMeasurer> =
Arc::new(|text: &str, s: &TextStyle<&str>, _mw: Option<f32>| {
(text.len() as f32 * s.font_size, s.font_size * 2.0)
});
assert_eq!(custom.measure("abc", &sized(10.0), None), (30.0, 20.0));
}
#[test]
fn heuristic_text_measurer_honours_the_resolved_typography() {
let m = HeuristicTextMeasurer;
let text = "0123456789";
let base = m.measure(text, &sized(20.0), None);
let spaced = TextStyle { letter_spacing: 2.0, ..sized(20.0) };
assert!((m.measure(text, &spaced, None).0 - (base.0 + 10.0 * 2.0)).abs() < 1e-3);
for ws in [WhiteSpace::NoWrap, WhiteSpace::Pre] {
let s = TextStyle { white_space: ws, ..sized(20.0) };
assert_eq!(m.measure(text, &s, Some(50.0)), base, "{ws:?}");
assert_eq!(m.measure(text, &s, Some(0.0)), base, "{ws:?}");
}
let pre_wrap = TextStyle { white_space: WhiteSpace::PreWrap, ..sized(20.0) };
assert!(m.measure(text, &pre_wrap, Some(50.0)).1 > base.1);
let points = TextStyle { line_height: Length::points(30.0), ..sized(20.0) };
assert_eq!(m.measure("a\nb", &points, None).1, 60.0);
let percent = TextStyle { line_height: Length::percent(150.0), ..sized(20.0) };
assert_eq!(m.measure("a\nb", &percent, None).1, 60.0);
assert_eq!(percent.line_height_points(), Some(30.0));
assert_eq!(sized(20.0).line_height_points(), None);
let two = TextStyle { max_lines: 2, ..points };
assert_eq!(m.measure(text, &two, Some(20.0)).1, 60.0);
assert_eq!(m.measure("a\nb\nc\nd", &two, None).1, 60.0);
}
#[test]
fn resolution_sanitizes_line_height_and_hashes_the_family() {
let mut store = NodeStore::new();
let mut tx = store.tx();
let [parent, nan, negative, family] = [(); 4].map(|_| tx.create());
tx.edit::<Typography>(parent).line_height(Length::points(18.0)).font_family("Inter");
tx.edit::<Typography>(nan)
.line_height(Length(f32::NAN.to_bits() & !0b11));
tx.edit::<Typography>(negative).line_height(Length::points(-4.0));
tx.edit::<Typography>(family).font_family("Arial");
tx.commit_into(&mut nativeview_store::ChangeSet::default());
let p = resolve_inherited_text(&store, parent, ResolvedTextStyle::default());
for child in [nan, negative] {
let r = resolve_inherited_text(&store, child, p);
assert_eq!(r.line_height, Length::points(18.0), "invalid heights inherit");
assert!(r.measure_eq(&r), "bitwise float equality is reflexive");
}
let inter = p.font_family;
assert_eq!(inter.hash, xxh64(b"Inter", 0));
let arial = resolve_inherited_text(&store, family, p);
assert!(!arial.measure_eq(&p), "same-length families differ by content");
assert!(arial.measure_eq(&TextStyle { color: Rgba::WHITE, ..arial }), "color is paint-only");
assert_eq!(ResolvedTextStyle::default().font_family.hash, 0);
}
}