1use crate::typography::{
4 InlineFormattingContext, InlineLayoutOptions, InlineLayoutResult, VerticalAlignment,
5 WhiteSpaceMode,
6};
7
8pub type TextMeasurementCallback = fn(&str, f32, f32, Option<f32>, bool) -> (f32, f32);
10
11pub type StyledTextMeasurementCallback = fn(
13 &str,
14 f32,
15 f32,
16 Option<f32>,
17 bool,
18 strata_style::types::FontWeight,
19 strata_style::types::FontStyle,
20) -> (f32, f32);
21
22pub type FamilyTextMeasurementCallback =
24 fn(&str, f32, f32, Option<f32>, bool, strata_primitives::AtomId) -> (f32, f32);
25
26pub type FamilyStyledTextMeasurementCallback = fn(
28 &str,
29 f32,
30 f32,
31 Option<f32>,
32 bool,
33 strata_primitives::AtomId,
34 strata_style::types::FontWeight,
35 strata_style::types::FontStyle,
36) -> (f32, f32);
37
38pub type FontMetricsCallback = fn(strata_primitives::AtomId, f32, bool) -> (f32, f32, f32);
40
41static TEXT_MEASURER: std::sync::RwLock<Option<TextMeasurementCallback>> =
42 std::sync::RwLock::new(None);
43static STYLED_TEXT_MEASURER: std::sync::RwLock<Option<StyledTextMeasurementCallback>> =
44 std::sync::RwLock::new(None);
45static FAMILY_TEXT_MEASURER: std::sync::RwLock<Option<FamilyTextMeasurementCallback>> =
46 std::sync::RwLock::new(None);
47static FAMILY_STYLED_TEXT_MEASURER: std::sync::RwLock<Option<FamilyStyledTextMeasurementCallback>> =
48 std::sync::RwLock::new(None);
49static FONT_METRICS: std::sync::RwLock<Option<FontMetricsCallback>> = std::sync::RwLock::new(None);
50static FONT_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
51
52pub fn font_generation() -> u64 {
55 FONT_GENERATION.load(std::sync::atomic::Ordering::Relaxed)
56}
57
58fn bump_font_generation() {
59 FONT_GENERATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
60}
61
62pub fn register_text_measurer(measurer: TextMeasurementCallback) {
64 if let Ok(mut lock) = TEXT_MEASURER.write() {
65 *lock = Some(measurer);
66 }
67 bump_font_generation();
68}
69
70pub fn register_styled_text_measurer(measurer: StyledTextMeasurementCallback) {
72 if let Ok(mut lock) = STYLED_TEXT_MEASURER.write() {
73 *lock = Some(measurer);
74 }
75 bump_font_generation();
76}
77
78pub fn register_family_text_measurer(measurer: FamilyTextMeasurementCallback) {
80 if let Ok(mut lock) = FAMILY_TEXT_MEASURER.write() {
81 *lock = Some(measurer);
82 }
83 bump_font_generation();
84}
85
86pub fn register_family_styled_text_measurer(measurer: FamilyStyledTextMeasurementCallback) {
88 if let Ok(mut lock) = FAMILY_STYLED_TEXT_MEASURER.write() {
89 *lock = Some(measurer);
90 }
91 bump_font_generation();
92}
93
94pub fn register_font_metrics(metrics: FontMetricsCallback) {
96 if let Ok(mut lock) = FONT_METRICS.write() {
97 *lock = Some(metrics);
98 }
99 bump_font_generation();
100}
101
102pub fn get_text_measurer() -> Option<TextMeasurementCallback> {
104 TEXT_MEASURER.read().ok().and_then(|lock| *lock)
105}
106
107pub fn get_styled_text_measurer() -> Option<StyledTextMeasurementCallback> {
109 STYLED_TEXT_MEASURER.read().ok().and_then(|lock| *lock)
110}
111
112pub fn get_family_text_measurer() -> Option<FamilyTextMeasurementCallback> {
114 FAMILY_TEXT_MEASURER.read().ok().and_then(|lock| *lock)
115}
116
117pub fn get_family_styled_text_measurer() -> Option<FamilyStyledTextMeasurementCallback> {
119 FAMILY_STYLED_TEXT_MEASURER
120 .read()
121 .ok()
122 .and_then(|lock| *lock)
123}
124
125pub fn get_font_metrics() -> Option<FontMetricsCallback> {
127 FONT_METRICS.read().ok().and_then(|lock| *lock)
128}
129
130pub fn is_monospace_family(font_family: strata_primitives::AtomId) -> bool {
131 if font_family == strata_primitives::AtomId::FONT_MONO {
132 return true;
133 }
134 if let Some(family_str) = strata_primitives::atom::resolve(font_family) {
135 family_str.contains("mono")
136 || family_str.contains("monospace")
137 || family_str.contains("Courier")
138 || family_str.contains("Consolas")
139 || family_str.contains("DejaVu Sans Mono")
140 } else {
141 false
142 }
143}
144
145#[derive(Clone, Copy, PartialEq, Eq)]
146struct MeasureCacheKey {
147 text_hash: u64,
148 text_len: usize,
149 font_size_bits: u32,
150 line_height_bits: u32,
151 max_width_bits: u32,
152 is_monospace: bool,
153}
154
155#[derive(Clone, Copy)]
156struct MeasureCacheEntry {
157 key: MeasureCacheKey,
158 bounds: (f32, f32),
159}
160
161const CACHE_SIZE: usize = 1024;
162
163#[derive(Clone, Copy, PartialEq, Eq, Hash)]
164struct StyledMeasureKey {
165 text_hash: u64,
166 text_len: usize,
167 font_size_bits: u32,
168 line_height_bits: u32,
169 max_width_bits: u32,
170 flags: u32,
171 font_family: u32,
172 font_weight: u8,
173 font_style: u8,
174 generation: u64,
175}
176
177const STYLED_CACHE_LIMIT: usize = 16_384;
178
179thread_local! {
180 static MEASURE_CACHE: std::cell::RefCell<[Option<MeasureCacheEntry>; CACHE_SIZE]> = const { std::cell::RefCell::new([None; CACHE_SIZE]) };
181 static STYLED_MEASURE_CACHE: std::cell::RefCell<std::collections::HashMap<StyledMeasureKey, (f32, f32)>> =
182 std::cell::RefCell::new(std::collections::HashMap::new());
183 static TEXT_CACHE_HITS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
184 static TEXT_CACHE_MISSES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
185}
186
187pub fn text_measure_cache_stats() -> (u64, u64) {
189 let hits = TEXT_CACHE_HITS.with(|c| c.get());
190 let misses = TEXT_CACHE_MISSES.with(|c| c.get());
191 (hits, misses)
192}
193
194fn hash_text(text: &str) -> u64 {
195 use std::hash::Hasher;
196 let mut hasher = std::collections::hash_map::DefaultHasher::new();
197 hasher.write(text.as_bytes());
198 hasher.finish()
199}
200
201#[allow(clippy::too_many_arguments)]
202fn styled_measure_key(
203 text_hash: u64,
204 text_len: usize,
205 font_size: f32,
206 line_height_multiplier: f32,
207 max_width: Option<f32>,
208 is_monospace: bool,
209 font_family: Option<strata_primitives::AtomId>,
210 font_weight: strata_style::types::FontWeight,
211 font_style: strata_style::types::FontStyle,
212) -> StyledMeasureKey {
213 let flags = (is_monospace as u32) | ((max_width.is_some() as u32) << 1);
214 StyledMeasureKey {
215 text_hash,
216 text_len,
217 font_size_bits: font_size.to_bits(),
218 line_height_bits: line_height_multiplier.to_bits(),
219 max_width_bits: max_width.map(|w| w.to_bits()).unwrap_or(u32::MAX),
220 flags,
221 font_family: font_family.map(|f| f.0).unwrap_or(u32::MAX),
222 font_weight: font_weight as u8,
223 font_style: font_style as u8,
224 generation: font_generation(),
225 }
226}
227
228fn styled_cache_get(key: &StyledMeasureKey) -> Option<(f32, f32)> {
229 let hit = STYLED_MEASURE_CACHE.with(|cache| cache.borrow().get(key).copied());
230 if hit.is_some() {
231 TEXT_CACHE_HITS.with(|c| c.set(c.get().wrapping_add(1)));
232 } else {
233 TEXT_CACHE_MISSES.with(|c| c.set(c.get().wrapping_add(1)));
234 }
235 hit
236}
237
238fn styled_cache_put(key: StyledMeasureKey, bounds: (f32, f32)) {
239 STYLED_MEASURE_CACHE.with(|cache| {
240 let mut map = cache.borrow_mut();
241 if map.len() >= STYLED_CACHE_LIMIT {
242 map.clear();
243 }
244 map.insert(key, bounds);
245 });
246}
247
248pub fn measure_text_bounds(
250 text: &str,
251 font_size: f32,
252 line_height_multiplier: f32,
253 max_width: Option<f32>,
254) -> (f32, f32) {
255 measure_text_bounds_ext(text, font_size, line_height_multiplier, max_width, false)
256}
257
258pub fn measure_text_bounds_with_white_space(
265 text: &str,
266 font_size: f32,
267 line_height_multiplier: f32,
268 max_width: Option<f32>,
269 is_monospace: bool,
270 white_space: strata_style::types::WhiteSpace,
271) -> (f32, f32) {
272 if text.is_empty() {
273 return (0.0, font_size * line_height_multiplier);
274 }
275 let mode = match white_space {
276 strata_style::types::WhiteSpace::Normal => WhiteSpaceMode::Normal,
277 strata_style::types::WhiteSpace::NoWrap => WhiteSpaceMode::NoWrap,
278 strata_style::types::WhiteSpace::Pre => WhiteSpaceMode::Pre,
279 strata_style::types::WhiteSpace::PreWrap => WhiteSpaceMode::PreWrap,
280 strata_style::types::WhiteSpace::PreLine => WhiteSpaceMode::PreLine,
281 };
282 let ifc = InlineFormattingContext::new();
283 let options = InlineLayoutOptions {
284 font_size,
285 line_height: Some(font_size * line_height_multiplier),
286 max_width,
287 white_space: mode,
288 vertical_align: VerticalAlignment::Baseline,
289 is_monospace,
290 exclusion_space: None,
291 bfc_offset_y: 0.0,
292 };
293 let result = ifc.layout_text(text, &options);
294 let line_h = font_size * line_height_multiplier;
295 let total_height = result.line_count.max(1) as f32 * line_h;
296 (result.total_width, total_height)
297}
298
299pub fn measure_text_bounds_ext(
301 text: &str,
302 font_size: f32,
303 line_height_multiplier: f32,
304 max_width: Option<f32>,
305 is_monospace: bool,
306) -> (f32, f32) {
307 if text.is_empty() {
308 return (0.0, font_size * line_height_multiplier);
309 }
310
311 if let Some(measurer) = get_text_measurer() {
312 let key = styled_measure_key(
313 hash_text(text),
314 text.len(),
315 font_size,
316 line_height_multiplier,
317 max_width,
318 is_monospace,
319 None,
320 strata_style::types::FontWeight::Normal,
321 strata_style::types::FontStyle::Normal,
322 );
323 if let Some(hit) = styled_cache_get(&key) {
324 return hit;
325 }
326 let bounds = measurer(
327 text,
328 font_size,
329 line_height_multiplier,
330 max_width,
331 is_monospace,
332 );
333 styled_cache_put(key, bounds);
334 return bounds;
335 }
336
337 use std::hash::Hasher;
338 let mut hasher = std::collections::hash_map::DefaultHasher::new();
339 hasher.write(text.as_bytes());
340 let text_hash = hasher.finish();
341
342 let font_size_bits = font_size.to_bits();
343 let line_height_bits = line_height_multiplier.to_bits();
344 let max_width_bits = max_width.map(|w| w.to_bits()).unwrap_or(u32::MAX);
345
346 let key = MeasureCacheKey {
347 text_hash,
348 text_len: text.len(),
349 font_size_bits,
350 line_height_bits,
351 max_width_bits,
352 is_monospace,
353 };
354
355 let mono_bit = if is_monospace { 1u64 } else { 0u64 };
356 let idx =
357 ((text_hash ^ (font_size_bits as u64) ^ ((max_width_bits as u64) << 16) ^ (mono_bit << 24))
358 as usize)
359 % CACHE_SIZE;
360
361 let cached = MEASURE_CACHE.with(|cache| {
362 let cell = cache.borrow();
363 if let Some(entry) = &cell[idx] {
364 if entry.key == key {
365 return Some(entry.bounds);
366 }
367 }
368 None
369 });
370
371 if let Some(bounds) = cached {
372 TEXT_CACHE_HITS.with(|c| c.set(c.get().wrapping_add(1)));
373 return bounds;
374 }
375 TEXT_CACHE_MISSES.with(|c| c.set(c.get().wrapping_add(1)));
376
377 let ifc = InlineFormattingContext::new();
378 let explicit_lh = font_size * line_height_multiplier;
379 let options = InlineLayoutOptions {
380 font_size,
381 line_height: Some(explicit_lh),
382 max_width,
383 white_space: WhiteSpaceMode::Normal,
384 vertical_align: VerticalAlignment::Baseline,
385 is_monospace,
386 exclusion_space: None,
387 bfc_offset_y: 0.0,
388 };
389
390 let result = ifc.layout_text(text, &options);
391 let single_line_height = font_size * line_height_multiplier;
392 let total_height = result.line_count.max(1) as f32 * single_line_height;
393 let bounds = (result.total_width, total_height);
394
395 MEASURE_CACHE.with(|cache| {
396 let mut cell = cache.borrow_mut();
397 cell[idx] = Some(MeasureCacheEntry { key, bounds });
398 });
399
400 bounds
401}
402
403pub fn measure_text_bounds_with_family(
409 text: &str,
410 font_size: f32,
411 line_height_multiplier: f32,
412 max_width: Option<f32>,
413 is_monospace: bool,
414 font_family: strata_primitives::AtomId,
415) -> (f32, f32) {
416 if text.is_empty() {
417 return (0.0, font_size * line_height_multiplier);
418 }
419
420 if let Some(measurer) = get_family_text_measurer() {
421 let key = styled_measure_key(
422 hash_text(text),
423 text.len(),
424 font_size,
425 line_height_multiplier,
426 max_width,
427 is_monospace,
428 Some(font_family),
429 strata_style::types::FontWeight::Normal,
430 strata_style::types::FontStyle::Normal,
431 );
432 if let Some(hit) = styled_cache_get(&key) {
433 return hit;
434 }
435 let bounds = measurer(
436 text,
437 font_size,
438 line_height_multiplier,
439 max_width,
440 is_monospace,
441 font_family,
442 );
443 styled_cache_put(key, bounds);
444 return bounds;
445 }
446
447 measure_text_bounds_ext(
448 text,
449 font_size,
450 line_height_multiplier,
451 max_width,
452 is_monospace,
453 )
454}
455
456#[allow(clippy::too_many_arguments)]
461pub fn measure_text_bounds_styled_with_family(
462 text: &str,
463 font_size: f32,
464 line_height_multiplier: f32,
465 max_width: Option<f32>,
466 is_monospace: bool,
467 font_family: strata_primitives::AtomId,
468 font_weight: strata_style::types::FontWeight,
469 font_style: strata_style::types::FontStyle,
470) -> (f32, f32) {
471 if text.is_empty() {
472 return (0.0, font_size * line_height_multiplier);
473 }
474
475 if let Some(measurer) = get_family_styled_text_measurer() {
476 let key = styled_measure_key(
477 hash_text(text),
478 text.len(),
479 font_size,
480 line_height_multiplier,
481 max_width,
482 is_monospace,
483 Some(font_family),
484 font_weight,
485 font_style,
486 );
487 if let Some(hit) = styled_cache_get(&key) {
488 return hit;
489 }
490 let bounds = measurer(
491 text,
492 font_size,
493 line_height_multiplier,
494 max_width,
495 is_monospace,
496 font_family,
497 font_weight,
498 font_style,
499 );
500 styled_cache_put(key, bounds);
501 return bounds;
502 }
503
504 if let Some(font) =
505 crate::typography::opentype::lookup_font_for_style(font_family, font_weight, font_style)
506 {
507 let key = styled_measure_key(
508 hash_text(text),
509 text.len(),
510 font_size,
511 line_height_multiplier,
512 max_width,
513 is_monospace,
514 Some(font_family),
515 font_weight,
516 font_style,
517 );
518 if let Some(hit) = styled_cache_get(&key) {
519 return hit;
520 }
521
522 let mut total_w = 0.0f32;
523 let mut prev_gid: Option<u16> = None;
524 for c in text.chars() {
525 let gid = font.glyph_id(c);
526 let adv = font.glyph_advance(gid, font_size);
527 if let Some(pg) = prev_gid {
528 let kern = font.pair_kerning(pg, gid, font_size);
529 total_w += kern;
530 }
531 total_w += adv;
532 prev_gid = Some(gid);
533 }
534
535 let total_h = font_size * line_height_multiplier;
536 let bounds = (total_w, total_h);
537 styled_cache_put(key, bounds);
538 return bounds;
539 }
540
541 measure_text_bounds_with_family(
542 text,
543 font_size,
544 line_height_multiplier,
545 max_width,
546 is_monospace,
547 font_family,
548 )
549}
550
551pub fn layout_inline_text(text: &str, options: &InlineLayoutOptions) -> InlineLayoutResult {
553 let ifc = InlineFormattingContext::new();
554 ifc.layout_text(text, options)
555}