1use std::sync::Arc;
6
7use nativeview_abi::{NvTextParagraphView, xxh64};
8use nativeview_store::{Length, NodeId, NodeStore, Rgba, StrSpan};
9use nativeview_tables::tables::{
10 FontStyle, OverflowWrap, TextAlign, TextDecoration, Typography, VerticalAlign, WhiteSpace,
11 WordBreak,
12};
13
14use crate::paragraph::measure::{
15 default_measure_paragraph, heuristic_hit_test_paragraph, heuristic_measure_paragraph,
16};
17
18#[derive(Debug, Clone, Copy, PartialEq)]
22pub struct TextStyle<F> {
23 pub color: Rgba,
24 pub font_family: F,
26 pub font_size: f32,
28 pub font_weight: u16,
30 pub font_style: FontStyle,
31 pub letter_spacing: f32,
33 pub line_height: Length,
35 pub white_space: WhiteSpace,
36 pub word_break: WordBreak,
37 pub overflow_wrap: OverflowWrap,
38 pub text_align: TextAlign,
39 pub text_decoration: TextDecoration,
40 pub vertical_align: VerticalAlign,
41 pub max_lines: u32,
43}
44
45#[derive(Debug, Clone, Copy, Default)]
49pub struct ResolvedFamily {
50 pub span: StrSpan,
51 pub hash: u64,
52}
53
54impl ResolvedFamily {
55 #[inline]
57 pub fn new(store: &NodeStore, span: StrSpan) -> Self {
58 let text = store.text(span);
59 Self { span, hash: if text.is_empty() { 0 } else { xxh64(text.as_bytes(), 0) } }
60 }
61}
62
63impl PartialEq for ResolvedFamily {
64 #[inline]
65 fn eq(&self, other: &Self) -> bool {
66 self.hash == other.hash
67 }
68}
69
70pub type ResolvedTextStyle = TextStyle<ResolvedFamily>;
72
73impl<F: Default> Default for TextStyle<F> {
74 fn default() -> Self {
75 Self {
76 color: Rgba::BLACK,
77 font_family: F::default(),
78 font_size: HeuristicTextMeasurer::DEFAULT_FONT_SIZE,
79 font_weight: 400,
80 font_style: FontStyle::Normal,
81 letter_spacing: 0.0,
82 line_height: Length::AUTO,
83 white_space: WhiteSpace::Normal,
84 word_break: WordBreak::Normal,
85 overflow_wrap: OverflowWrap::Normal,
86 text_align: TextAlign::Start,
87 text_decoration: TextDecoration::EMPTY,
88 vertical_align: VerticalAlign::Baseline,
89 max_lines: 0,
90 }
91 }
92}
93
94impl<F> TextStyle<F> {
95 #[inline]
97 pub fn map_family<'s, G>(&'s self, f: impl FnOnce(&'s F) -> G) -> TextStyle<G> {
98 TextStyle {
99 color: self.color,
100 font_family: f(&self.font_family),
101 font_size: self.font_size,
102 font_weight: self.font_weight,
103 font_style: self.font_style,
104 letter_spacing: self.letter_spacing,
105 line_height: self.line_height,
106 white_space: self.white_space,
107 word_break: self.word_break,
108 overflow_wrap: self.overflow_wrap,
109 text_align: self.text_align,
110 text_decoration: self.text_decoration,
111 vertical_align: self.vertical_align,
112 max_lines: self.max_lines,
113 }
114 }
115
116 #[inline]
118 pub fn wraps(&self) -> bool {
119 !matches!(self.white_space, WhiteSpace::NoWrap | WhiteSpace::Pre)
120 }
121
122 #[inline]
124 pub fn line_height_points(&self) -> Option<f32> {
125 let lh = if self.line_height.is_percent() {
126 self.line_height.value() * self.font_size / 100.0
127 } else {
128 self.line_height.resolve(self.font_size)?
129 };
130 (lh.is_finite() && lh > 0.0).then_some(lh)
131 }
132}
133
134impl<F: PartialEq> TextStyle<F> {
135 #[inline]
138 pub fn measure_eq(&self, other: &Self) -> bool {
139 self.font_family == other.font_family
140 && self.font_size.to_bits() == other.font_size.to_bits()
141 && self.font_weight == other.font_weight
142 && self.font_style == other.font_style
143 && self.letter_spacing.to_bits() == other.letter_spacing.to_bits()
144 && self.line_height == other.line_height
145 && self.white_space == other.white_space
146 && self.word_break == other.word_break
147 && self.overflow_wrap == other.overflow_wrap
148 && self.vertical_align == other.vertical_align
149 && self.max_lines == other.max_lines
150 }
151
152 #[inline]
155 pub fn style_eq(&self, other: &Self) -> bool {
156 self.measure_eq(other)
157 && self.color == other.color
158 && self.text_align == other.text_align
159 && self.text_decoration == other.text_decoration
160 }
161}
162
163impl<F: AsRef<str>> TextStyle<F> {
164 #[inline]
166 pub fn borrowed(&self) -> TextStyle<&str> {
167 self.map_family(AsRef::as_ref)
168 }
169}
170
171impl TextStyle<&str> {
172 pub fn sized(font_size: f32) -> Self {
174 Self {
175 font_size,
176 ..Self::default()
177 }
178 }
179}
180
181impl ResolvedTextStyle {
182 #[inline]
184 pub fn in_store<'a>(&self, store: &'a NodeStore) -> TextStyle<&'a str> {
185 self.map_family(|family| store.text(family.span))
186 }
187}
188
189#[inline]
193pub fn resolve_inherited_text(
194 store: &NodeStore,
195 id: NodeId,
196 mut parent: ResolvedTextStyle,
197) -> ResolvedTextStyle {
198 let Some(t) = store.try_row::<Typography>(id) else {
199 return parent;
200 };
201 if t.is_color_explicit() {
202 parent.color = t.color();
203 }
204 let fs = t.font_size();
205 if t.is_font_size_explicit() && fs.is_finite() && fs >= 0.0 {
206 parent.font_size = fs;
207 }
208 if t.is_font_weight_explicit() {
209 parent.font_weight = t.font_weight();
210 }
211 let lh = t.line_height();
212 if t.is_line_height_explicit() && (lh.is_auto() || (lh.value().is_finite() && lh.value() >= 0.0)) {
214 parent.line_height = lh;
215 }
216 let ls = t.letter_spacing();
217 if t.is_letter_spacing_explicit() && ls.is_finite() {
218 parent.letter_spacing = ls;
219 }
220 if t.is_font_family_explicit() {
221 parent.font_family = ResolvedFamily::new(store, t.font_family_span());
222 }
223 if t.is_max_lines_explicit() {
224 parent.max_lines = t.max_lines().map_or(0, |n| u32::from(n.get()));
225 }
226 if t.is_font_style_explicit() {
227 parent.font_style = t.font_style();
228 }
229 if t.is_white_space_explicit() {
230 parent.white_space = t.white_space();
231 }
232 if t.is_word_break_explicit() {
233 parent.word_break = t.word_break();
234 }
235 if t.is_overflow_wrap_explicit() {
236 parent.overflow_wrap = t.overflow_wrap();
237 }
238 if t.is_text_align_explicit() {
239 parent.text_align = t.text_align();
240 }
241 if t.is_text_decoration_explicit() {
242 parent.text_decoration = t.text_decoration();
243 }
244 if t.is_vertical_align_explicit() {
245 parent.vertical_align = t.vertical_align();
246 }
247 parent
248}
249
250pub trait TextMeasurer: Send + Sync {
252 fn measure(&self, text: &str, style: &TextStyle<&str>, max_width: Option<f32>) -> (f32, f32);
256
257 fn measure_paragraph(
259 &self,
260 paragraph: &NvTextParagraphView,
261 max_width: Option<f32>,
262 ) -> (f32, f32) {
263 default_measure_paragraph(self, paragraph, max_width)
264 }
265
266 fn hit_test_paragraph(
269 &self,
270 paragraph: &NvTextParagraphView,
271 box_width: f32,
272 local_x: f32,
273 local_y: f32,
274 ) -> Option<NodeId> {
275 heuristic_hit_test_paragraph(paragraph, box_width, local_x, local_y)
276 }
277}
278
279#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
284pub struct HeuristicTextMeasurer;
285
286impl HeuristicTextMeasurer {
287 pub const CHAR_WIDTH_FACTOR: f32 = 0.58;
288 pub const LINE_HEIGHT_FACTOR: f32 = 1.35;
289 pub const DEFAULT_FONT_SIZE: f32 = 16.0;
290}
291
292impl TextMeasurer for HeuristicTextMeasurer {
293 fn measure(&self, text: &str, style: &TextStyle<&str>, max_width: Option<f32>) -> (f32, f32) {
294 if text.is_empty() || style.font_size == 0.0 {
295 return (0.0, 0.0);
296 }
297 let fs = if style.font_size.is_finite() && style.font_size > 0.0 {
298 style.font_size
299 } else {
300 Self::DEFAULT_FONT_SIZE
301 };
302 let sized = TextStyle { font_size: fs, ..*style };
303 let char_w = (fs * Self::CHAR_WIDTH_FACTOR + style.letter_spacing).max(0.0);
304 let line_h = sized.line_height_points().unwrap_or(fs * Self::LINE_HEIGHT_FACTOR);
305 let height = |lines: f32| {
306 let lines = lines.max(1.0);
307 let capped = if style.max_lines > 0 { lines.min(style.max_lines as f32) } else { lines };
308 capped * line_h
309 };
310 let line_widths = || text.split('\n').map(|line| line.chars().count() as f32 * char_w);
311
312 match max_width.filter(|_| style.wraps()) {
313 Some(mw) if !mw.is_finite() || mw <= 0.0 => {
314 (0.0, height(text.split('\n').count() as f32))
316 }
317 Some(mw) => {
318 let wrap_eps = (mw * 1e-5).max(1e-5);
322 let (mut max_line_w, mut total_lines) = (0.0f32, 0.0f32);
323 for raw_w in line_widths() {
324 if raw_w > mw + wrap_eps {
325 max_line_w = max_line_w.max(mw);
326 total_lines += ((raw_w - wrap_eps) / mw).ceil().max(1.0);
327 } else {
328 max_line_w = max_line_w.max(raw_w);
329 total_lines += 1.0;
330 }
331 }
332 (max_line_w.max(1.0).min(mw), height(total_lines))
333 }
334 None => {
335 let (max_line_w, lines) =
336 line_widths().fold((0.0f32, 0.0f32), |(w, n), lw| (w.max(lw), n + 1.0));
337 (max_line_w.max(1.0), height(lines))
338 }
339 }
340 }
341
342 fn measure_paragraph(
343 &self,
344 paragraph: &NvTextParagraphView,
345 max_width: Option<f32>,
346 ) -> (f32, f32) {
347 heuristic_measure_paragraph(paragraph, max_width)
348 }
349
350 fn hit_test_paragraph(
351 &self,
352 paragraph: &NvTextParagraphView,
353 box_width: f32,
354 local_x: f32,
355 local_y: f32,
356 ) -> Option<NodeId> {
357 heuristic_hit_test_paragraph(paragraph, box_width, local_x, local_y)
358 }
359}
360
361impl<F> TextMeasurer for F
362where
363 F: Fn(&str, &TextStyle<&str>, Option<f32>) -> (f32, f32) + Send + Sync,
364{
365 fn measure(&self, text: &str, style: &TextStyle<&str>, max_width: Option<f32>) -> (f32, f32) {
366 (self)(text, style, max_width)
367 }
368}
369
370impl<T: TextMeasurer + ?Sized> TextMeasurer for Arc<T> {
371 fn measure(&self, text: &str, style: &TextStyle<&str>, max_width: Option<f32>) -> (f32, f32) {
372 (**self).measure(text, style, max_width)
373 }
374
375 fn measure_paragraph(
376 &self,
377 paragraph: &NvTextParagraphView,
378 max_width: Option<f32>,
379 ) -> (f32, f32) {
380 (**self).measure_paragraph(paragraph, max_width)
381 }
382
383 fn hit_test_paragraph(
384 &self,
385 paragraph: &NvTextParagraphView,
386 box_width: f32,
387 local_x: f32,
388 local_y: f32,
389 ) -> Option<NodeId> {
390 (**self).hit_test_paragraph(paragraph, box_width, local_x, local_y)
391 }
392}
393
394#[cfg(test)]
395mod tests {
396 use super::*;
397
398 fn sized(fs: f32) -> TextStyle<&'static str> {
399 TextStyle::sized(fs)
400 }
401
402 #[test]
403 fn heuristic_text_measurer_matches_single_line_and_wraps() {
404 let m = HeuristicTextMeasurer;
405
406 assert_eq!(m.measure("", &sized(16.0), None), (0.0, 0.0));
408
409 let (w, h) = m.measure("Hello World", &sized(20.0), None);
411 assert!((w - 11.0 * 20.0 * 0.58).abs() < 1e-4);
412 assert!((h - 20.0 * 1.35).abs() < 1e-4);
413
414 let (ww, wh) = m.measure("01234567890123456789", &sized(20.0), Some(100.0));
416 assert!((ww - 100.0).abs() < 1e-4);
417 assert!((wh - 3.0 * 20.0 * 1.35).abs() < 1e-4);
419
420 let (nw, nh) = m.measure("Line 1\nLine 2", &sized(16.0), None);
422 assert!((nw - 6.0 * 16.0 * 0.58).abs() < 1e-4);
423 assert!((nh - 2.0 * 16.0 * 1.35).abs() < 1e-4);
424
425 let (single_w, single_h) = m.measure("8", &sized(11.0), None);
428 let round_trip_mw = (single_w + 18.0_f32) - 18.0_f32;
429 assert_eq!(m.measure("8", &sized(11.0), Some(round_trip_mw)).1, single_h);
430
431 let custom: Arc<dyn TextMeasurer> =
433 Arc::new(|text: &str, s: &TextStyle<&str>, _mw: Option<f32>| {
434 (text.len() as f32 * s.font_size, s.font_size * 2.0)
435 });
436 assert_eq!(custom.measure("abc", &sized(10.0), None), (30.0, 20.0));
437 }
438
439 #[test]
440 fn heuristic_text_measurer_honours_the_resolved_typography() {
441 let m = HeuristicTextMeasurer;
442 let text = "0123456789";
443 let base = m.measure(text, &sized(20.0), None);
444
445 let spaced = TextStyle { letter_spacing: 2.0, ..sized(20.0) };
447 assert!((m.measure(text, &spaced, None).0 - (base.0 + 10.0 * 2.0)).abs() < 1e-3);
448
449 for ws in [WhiteSpace::NoWrap, WhiteSpace::Pre] {
451 let s = TextStyle { white_space: ws, ..sized(20.0) };
452 assert_eq!(m.measure(text, &s, Some(50.0)), base, "{ws:?}");
453 assert_eq!(m.measure(text, &s, Some(0.0)), base, "{ws:?}");
454 }
455 let pre_wrap = TextStyle { white_space: WhiteSpace::PreWrap, ..sized(20.0) };
456 assert!(m.measure(text, &pre_wrap, Some(50.0)).1 > base.1);
457
458 let points = TextStyle { line_height: Length::points(30.0), ..sized(20.0) };
460 assert_eq!(m.measure("a\nb", &points, None).1, 60.0);
461 let percent = TextStyle { line_height: Length::percent(150.0), ..sized(20.0) };
462 assert_eq!(m.measure("a\nb", &percent, None).1, 60.0);
463 assert_eq!(percent.line_height_points(), Some(30.0));
464 assert_eq!(sized(20.0).line_height_points(), None);
465
466 let two = TextStyle { max_lines: 2, ..points };
468 assert_eq!(m.measure(text, &two, Some(20.0)).1, 60.0);
469 assert_eq!(m.measure("a\nb\nc\nd", &two, None).1, 60.0);
470 }
471
472 #[test]
473 fn resolution_sanitizes_line_height_and_hashes_the_family() {
474 let mut store = NodeStore::new();
475 let mut tx = store.tx();
476 let [parent, nan, negative, family] = [(); 4].map(|_| tx.create());
477 tx.edit::<Typography>(parent).line_height(Length::points(18.0)).font_family("Inter");
478 tx.edit::<Typography>(nan)
480 .line_height(Length(f32::NAN.to_bits() & !0b11));
481 tx.edit::<Typography>(negative).line_height(Length::points(-4.0));
482 tx.edit::<Typography>(family).font_family("Arial");
483 tx.commit_into(&mut nativeview_store::ChangeSet::default());
484 let p = resolve_inherited_text(&store, parent, ResolvedTextStyle::default());
485 for child in [nan, negative] {
486 let r = resolve_inherited_text(&store, child, p);
487 assert_eq!(r.line_height, Length::points(18.0), "invalid heights inherit");
488 assert!(r.measure_eq(&r), "bitwise float equality is reflexive");
489 }
490 let inter = p.font_family;
491 assert_eq!(inter.hash, xxh64(b"Inter", 0));
492 let arial = resolve_inherited_text(&store, family, p);
493 assert!(!arial.measure_eq(&p), "same-length families differ by content");
494 assert!(arial.measure_eq(&TextStyle { color: Rgba::WHITE, ..arial }), "color is paint-only");
495 assert_eq!(ResolvedTextStyle::default().font_family.hash, 0);
496 }
497}