1use std::{
2 cell::RefCell,
3 collections::{HashMap, HashSet},
4 sync::atomic::{AtomicU64, Ordering},
5 sync::{Arc, Mutex, OnceLock},
6 time::Instant,
7};
8
9use sui_core::{Error, Result, Size};
10
11use crate::{
12 FontRegistry,
13 cache::{TextLayoutCache, TextLayoutCacheSnapshot},
14 flatten::FlattenedTextDocument,
15 font::{FaceCacheKey, FontContext, ResolvedSpanInput, TextSystemState},
16 layout::layout_document,
17 model::{
18 PersistentTextLayout, TextDocument, TextLayout, TextLayoutHandle, TextLayoutRegistry,
19 TextLayoutRequest, TextMeasurement, TextRun, TextStyle,
20 },
21};
22
23#[derive(Debug, Clone, Copy, PartialEq, Default)]
24pub struct RuntimeTextTimingDiagnostics {
25 pub request_count: usize,
27 pub size_only_request_count: usize,
28 pub size_only_time_us: u64,
29 pub cache_hit_count: usize,
31 pub cache_miss_count: usize,
32 pub total_time_us: u64,
33 pub prelookup_time_us: u64,
34 pub cache_lookup_time_us: u64,
35 pub miss_layout_time_us: u64,
36}
37
38thread_local! {
39 static TEXT_TIMING_COLLECTOR: RefCell<Option<RuntimeTextTimingDiagnostics>> =
40 const { RefCell::new(None) };
41}
42
43fn text_timing_enabled() -> bool {
44 static ENABLED: OnceLock<bool> = OnceLock::new();
45 *ENABLED.get_or_init(|| std::env::var_os("SUI_PROFILE_TEXT_TIMINGS").is_some())
46}
47
48pub fn begin_text_timing_collection() {
49 if !text_timing_enabled() {
50 return;
51 }
52
53 TEXT_TIMING_COLLECTOR.with(|collector| {
54 *collector.borrow_mut() = Some(RuntimeTextTimingDiagnostics::default());
55 });
56}
57
58pub fn take_text_timing_collection() -> RuntimeTextTimingDiagnostics {
59 if !text_timing_enabled() {
60 return RuntimeTextTimingDiagnostics::default();
61 }
62
63 TEXT_TIMING_COLLECTOR
64 .with(|collector| collector.borrow_mut().take())
65 .unwrap_or_default()
66}
67
68fn record_text_timing(
69 total_time_us: u64,
70 prelookup_time_us: u64,
71 cache_lookup_time_us: u64,
72 miss_layout_time_us: u64,
73 cache_hit: bool,
74) {
75 if !text_timing_enabled() {
76 return;
77 }
78
79 TEXT_TIMING_COLLECTOR.with(|collector| {
80 let mut collector = collector.borrow_mut();
81 let Some(diagnostics) = collector.as_mut() else {
82 return;
83 };
84 diagnostics.request_count += 1;
85 diagnostics.total_time_us += total_time_us;
86 diagnostics.prelookup_time_us += prelookup_time_us;
87 diagnostics.cache_lookup_time_us += cache_lookup_time_us;
88 diagnostics.miss_layout_time_us += miss_layout_time_us;
89 if cache_hit {
90 diagnostics.cache_hit_count += 1;
91 } else {
92 diagnostics.cache_miss_count += 1;
93 }
94 });
95}
96
97fn record_size_timing(total_time_us: u64) {
98 TEXT_TIMING_COLLECTOR.with(|collector| {
99 if let Some(diagnostics) = collector.borrow_mut().as_mut() {
100 diagnostics.request_count += 1;
101 diagnostics.size_only_request_count += 1;
102 diagnostics.total_time_us += total_time_us;
103 diagnostics.size_only_time_us += total_time_us;
104 }
105 });
106}
107
108#[derive(Debug)]
109pub struct TextSystem {
110 state: OnceLock<std::result::Result<TextSystemState, String>>,
111 font_context: Mutex<Option<CachedFontContext>>,
112 #[cfg(test)]
113 font_context_build_count: AtomicU64,
114 layout_cache: Mutex<TextLayoutCache>,
115 persistent_layouts: Mutex<Arc<TextLayoutRegistry>>,
116 next_layout_handle: AtomicU64,
117}
118
119#[derive(Debug)]
120struct CachedFontContext {
121 registry_key: Vec<(sui_core::FontHandle, FaceCacheKey)>,
122 context: FontContext,
125}
126
127impl Default for TextSystem {
128 fn default() -> Self {
129 Self {
130 state: OnceLock::new(),
131 font_context: Mutex::new(None),
132 #[cfg(test)]
133 font_context_build_count: AtomicU64::new(0),
134 layout_cache: Mutex::new(TextLayoutCache::default()),
135 persistent_layouts: Mutex::new(Arc::new(TextLayoutRegistry::default())),
136 next_layout_handle: AtomicU64::new(1),
137 }
138 }
139}
140
141impl TextSystem {
142 pub fn new() -> Self {
143 Self::default()
144 }
145
146 #[cfg(test)]
147 pub(crate) fn with_bundled_fonts() -> Self {
148 Self {
149 state: OnceLock::from(Ok(
150 TextSystemState::with_bundled_fonts().expect("bundled fonts should load")
151 )),
152 ..Self::default()
153 }
154 }
155
156 pub fn measure_text(
157 &self,
158 text: impl Into<String>,
159 style: TextStyle,
160 font_registry: &FontRegistry,
161 ) -> Result<TextMeasurement> {
162 self.measure_document(
163 TextDocument::from_plain_text(text.into(), style),
164 font_registry,
165 )
166 }
167
168 pub fn measure_document(
169 &self,
170 document: TextDocument,
171 font_registry: &FontRegistry,
172 ) -> Result<TextMeasurement> {
173 Ok(self
174 .layout_document(TextLayoutRequest::new(document), font_registry)?
175 .measurement())
176 }
177
178 pub fn measure_document_size(
182 &self,
183 request: TextLayoutRequest,
184 font_registry: &FontRegistry,
185 ) -> Result<Size> {
186 let started = text_timing_enabled().then(Instant::now);
187 let TextLayoutRequest { document, box_size } = request;
188 let document = document.into_normalized();
189 let width = box_size
191 .map(|size| size.width)
192 .filter(|width| width.is_finite())
193 .map(|width| width.max(0.0));
194 let span_face_keys = self.resolve_span_face_keys(&document, font_registry)?;
195 let result = self.with_font_context(font_registry, |font_context| {
196 let sizes = &mut font_context.preparation.sizes;
197 if let Some(size) = sizes.get(&document, &span_face_keys, width) {
198 return Ok(size);
199 }
200 let slot = sizes.slot(&document, &span_face_keys, width);
201 let flattened = FlattenedTextDocument::new(document);
202 let resolved_spans = self.resolve_span_inputs(&flattened, font_context)?;
203 let size = crate::layout::measure_document_size(
204 &flattened,
205 &resolved_spans,
206 box_size,
207 font_context,
208 )?;
209 font_context.preparation.sizes.insert(slot, size);
210 Ok(size)
211 });
212 if let Some(started) = started {
213 record_size_timing(started.elapsed().as_micros() as u64);
214 }
215 result
216 }
217
218 pub fn measure_text_size(
221 &self,
222 text: impl Into<String>,
223 style: TextStyle,
224 font_registry: &FontRegistry,
225 ) -> Result<Size> {
226 self.measure_document_size(
227 TextLayoutRequest::new(TextDocument::from_plain_text(text, style)),
228 font_registry,
229 )
230 }
231
232 pub fn preparation_cache_snapshot(&self) -> crate::TextPreparationCacheSnapshot {
233 self.font_context
234 .lock()
235 .ok()
236 .and_then(|cached| {
237 cached
238 .as_ref()
239 .map(|cached| cached.context.preparation.snapshot())
240 })
241 .unwrap_or_default()
242 }
243
244 pub fn shape_text(
245 &self,
246 text: impl Into<String>,
247 box_size: Size,
248 style: TextStyle,
249 font_registry: &FontRegistry,
250 ) -> Result<TextLayout> {
251 self.layout_document(
252 TextLayoutRequest::new(TextDocument::from_plain_text(text.into(), style))
253 .with_box_size(box_size),
254 font_registry,
255 )
256 }
257
258 pub fn layout_document(
259 &self,
260 request: TextLayoutRequest,
261 font_registry: &FontRegistry,
262 ) -> Result<TextLayout> {
263 self.shape_text_internal(request, font_registry)
264 }
265
266 pub fn shape_text_persistent(
267 &self,
268 handle: Option<TextLayoutHandle>,
269 text: impl Into<String>,
270 box_size: Size,
271 style: TextStyle,
272 font_registry: &FontRegistry,
273 ) -> Result<PersistentTextLayout> {
274 let layout = self.shape_text(text, box_size, style, font_registry)?;
275 Ok(self.pin_layout(handle, layout))
276 }
277
278 pub fn layout_document_persistent(
279 &self,
280 handle: Option<TextLayoutHandle>,
281 request: TextLayoutRequest,
282 font_registry: &FontRegistry,
283 ) -> Result<PersistentTextLayout> {
284 let layout = self.layout_document(request, font_registry)?;
285 Ok(self.pin_layout(handle, layout))
286 }
287
288 pub fn shape_text_run(
289 &self,
290 run: &TextRun,
291 font_registry: &FontRegistry,
292 ) -> Result<TextLayout> {
293 self.shape_text(
294 run.text.clone(),
295 run.rect.size,
296 run.style.clone(),
297 font_registry,
298 )
299 }
300
301 pub fn shape_text_run_persistent(
302 &self,
303 handle: Option<TextLayoutHandle>,
304 run: &TextRun,
305 font_registry: &FontRegistry,
306 ) -> Result<PersistentTextLayout> {
307 let layout = self.shape_text_run(run, font_registry)?;
308 Ok(self.pin_layout(handle, layout))
309 }
310
311 pub fn adopt_layout(&self, layout: TextLayout) -> PersistentTextLayout {
312 let handle = TextLayoutHandle::from_layout_id(layout.id());
313 self.store_persistent_layout(handle, layout)
314 }
315
316 pub fn touch_persistent_layout(&self, layout: &PersistentTextLayout) {
317 self.store_persistent_layout(layout.handle(), layout.layout().clone());
318 }
319
320 pub fn text_layout_registry(&self) -> Arc<TextLayoutRegistry> {
321 match self.persistent_layouts.lock() {
322 Ok(registry) => Arc::clone(®istry),
323 Err(poisoned) => Arc::clone(&poisoned.into_inner()),
324 }
325 }
326
327 pub fn retain_persistent_layouts(&self, handles: &HashSet<TextLayoutHandle>) {
328 match self.persistent_layouts.lock() {
329 Ok(mut registry) => Arc::make_mut(&mut registry).retain_handles(handles),
330 Err(poisoned) => {
331 let mut registry = poisoned.into_inner();
332 Arc::make_mut(&mut registry).retain_handles(handles);
333 }
334 }
335 }
336
337 pub fn layout_cache_snapshot(&self) -> TextLayoutCacheSnapshot {
338 self.layout_cache
339 .lock()
340 .ok()
341 .map(|cache| cache.snapshot())
342 .unwrap_or_default()
343 }
344
345 fn shape_text_internal(
346 &self,
347 request: TextLayoutRequest,
348 font_registry: &FontRegistry,
349 ) -> Result<TextLayout> {
350 let total_started = text_timing_enabled().then(Instant::now);
351 let TextLayoutRequest { document, box_size } = request;
352 let normalized_document = document.into_normalized();
353 let span_face_keys = self.resolve_span_face_keys(&normalized_document, font_registry)?;
354 let prelookup_time_us = total_started
355 .as_ref()
356 .map(|started| started.elapsed().as_micros() as u64)
357 .unwrap_or(0);
358
359 let lookup_started = text_timing_enabled().then(Instant::now);
360 if let Some(cached) = self.cached_layout(&normalized_document, &span_face_keys, box_size)? {
361 let cache_lookup_time_us = lookup_started
362 .as_ref()
363 .map(|started| started.elapsed().as_micros() as u64)
364 .unwrap_or(0);
365 let total_time_us = total_started
366 .as_ref()
367 .map(|started| started.elapsed().as_micros() as u64)
368 .unwrap_or(0);
369 record_text_timing(
370 total_time_us,
371 prelookup_time_us,
372 cache_lookup_time_us,
373 0,
374 true,
375 );
376 return Ok(cached.with_document(normalized_document));
377 }
378
379 let cache_lookup_time_us = lookup_started
380 .as_ref()
381 .map(|started| started.elapsed().as_micros() as u64)
382 .unwrap_or(0);
383
384 let layout_started = text_timing_enabled().then(Instant::now);
385 let flattened = FlattenedTextDocument::new(normalized_document.clone());
386 let layout_id = crate::cache::TextLayoutCacheKey::stable_layout_id(
387 &normalized_document,
388 &span_face_keys,
389 box_size,
390 );
391 let layout = self.with_font_context(font_registry, |font_context| {
392 let resolved_spans = self.resolve_span_inputs(&flattened, font_context)?;
393 layout_document(flattened, resolved_spans, box_size, font_context, layout_id)
394 })?;
395 let miss_layout_time_us = layout_started
396 .as_ref()
397 .map(|started| started.elapsed().as_micros() as u64)
398 .unwrap_or(0);
399 self.store_layout(
400 &normalized_document,
401 &span_face_keys,
402 box_size,
403 layout.clone(),
404 )?;
405 let total_time_us = total_started
406 .as_ref()
407 .map(|started| started.elapsed().as_micros() as u64)
408 .unwrap_or(0);
409 record_text_timing(
410 total_time_us,
411 prelookup_time_us,
412 cache_lookup_time_us,
413 miss_layout_time_us,
414 false,
415 );
416 Ok(layout.with_document(normalized_document))
417 }
418
419 fn pin_layout(
420 &self,
421 handle: Option<TextLayoutHandle>,
422 layout: TextLayout,
423 ) -> PersistentTextLayout {
424 let handle = handle.unwrap_or_else(|| self.alloc_layout_handle());
425 self.store_persistent_layout(handle, layout)
426 }
427
428 fn alloc_layout_handle(&self) -> TextLayoutHandle {
429 TextLayoutHandle::new(
430 self.next_layout_handle
431 .fetch_add(1, Ordering::Relaxed)
432 .max(1),
433 )
434 }
435
436 fn store_persistent_layout(
437 &self,
438 handle: TextLayoutHandle,
439 layout: TextLayout,
440 ) -> PersistentTextLayout {
441 match self.persistent_layouts.lock() {
442 Ok(mut registry) => Arc::make_mut(&mut registry).insert(handle, layout.clone()),
443 Err(poisoned) => {
444 let mut registry = poisoned.into_inner();
445 Arc::make_mut(&mut registry).insert(handle, layout.clone());
446 }
447 }
448 PersistentTextLayout::new(handle, layout)
449 }
450
451 fn resolve_span_inputs(
452 &self,
453 flattened: &FlattenedTextDocument,
454 font_context: &mut FontContext,
455 ) -> Result<Vec<ResolvedSpanInput>> {
456 flattened
457 .spans
458 .iter()
459 .map(|span| font_context.resolve_span(span.id.clone(), span.text.clone(), &span.style))
460 .collect()
461 }
462
463 fn resolve_span_face_keys(
464 &self,
465 document: &TextDocument,
466 font_registry: &FontRegistry,
467 ) -> Result<Vec<FaceCacheKey>> {
468 let state = self.text_system_state()?;
469 let default_face_key = state.default_face_key();
470 let total_spans = document
471 .paragraphs
472 .iter()
473 .map(|paragraph| paragraph.spans.len())
474 .sum();
475 let mut keys = Vec::with_capacity(total_spans);
476 let mut explicit_face_keys = HashMap::new();
477
478 for paragraph in &document.paragraphs {
479 for span in ¶graph.spans {
480 let face_key = match span.style.font {
481 Some(handle) => {
482 if let Some(face_key) = explicit_face_keys.get(&handle).copied() {
483 face_key
484 } else {
485 let font = font_registry.get(handle).ok_or_else(|| {
486 Error::new(format!(
487 "font handle {} is not registered",
488 handle.get()
489 ))
490 })?;
491 let face_key = FaceCacheKey::from_registered_font(font);
492 explicit_face_keys.insert(handle, face_key);
493 face_key
494 }
495 }
496 None => default_face_key,
497 };
498 keys.push(face_key);
499 }
500 }
501
502 Ok(keys)
503 }
504
505 fn cached_layout(
506 &self,
507 document: &TextDocument,
508 span_face_keys: &[FaceCacheKey],
509 box_size: Option<Size>,
510 ) -> Result<Option<TextLayout>> {
511 let mut cache = self
512 .layout_cache
513 .lock()
514 .map_err(|_| Error::new("text layout cache lock was poisoned"))?;
515 Ok(cache.get(document, span_face_keys, box_size))
516 }
517
518 fn store_layout(
519 &self,
520 document: &TextDocument,
521 span_face_keys: &[FaceCacheKey],
522 box_size: Option<Size>,
523 layout: TextLayout,
524 ) -> Result<()> {
525 let mut cache = self
526 .layout_cache
527 .lock()
528 .map_err(|_| Error::new("text layout cache lock was poisoned"))?;
529 cache.insert(document, span_face_keys, box_size, layout);
530 Ok(())
531 }
532
533 fn text_system_state(&self) -> Result<&TextSystemState> {
534 let state = self
535 .state
536 .get_or_init(|| TextSystemState::new().map_err(|error| error.to_string()));
537 match state {
538 Ok(state) => Ok(state),
539 Err(message) => Err(Error::new(message.clone())),
540 }
541 }
542
543 fn with_font_context<T>(
544 &self,
545 font_registry: &FontRegistry,
546 operation: impl FnOnce(&mut FontContext) -> Result<T>,
547 ) -> Result<T> {
548 let mut cached = self
549 .font_context
550 .lock()
551 .map_err(|_| Error::new("text font context cache lock was poisoned"))?;
552 let rebuild = cached
554 .as_ref()
555 .is_none_or(|cached| !font_registry.matches_cache_key(&cached.registry_key));
556 if rebuild {
557 *cached = Some(CachedFontContext {
558 registry_key: font_registry.cache_key(),
559 context: self
560 .text_system_state()?
561 .build_font_context(font_registry)?,
562 });
563 #[cfg(test)]
564 self.font_context_build_count
565 .fetch_add(1, Ordering::Relaxed);
566 }
567
568 operation(
569 &mut cached
570 .as_mut()
571 .expect("font context was initialized")
572 .context,
573 )
574 }
575
576 #[cfg(test)]
577 pub(crate) fn font_context_build_count(&self) -> u64 {
578 self.font_context_build_count.load(Ordering::Relaxed)
579 }
580}
581
582#[cfg(test)]
583#[path = "tests/preparation.rs"]
584mod preparation_tests;
585
586#[cfg(test)]
587mod cache_tests {
588 use super::*;
589
590 #[test]
591 fn layout_cache_evicts_lru_entries_without_invalidating_pinned_layouts() {
592 let system = TextSystem {
593 layout_cache: Mutex::new(TextLayoutCache::with_limits(2, usize::MAX)),
594 ..TextSystem::default()
595 };
596 let fonts = FontRegistry::new();
597 let shape = |text| {
598 system
599 .shape_text(text, Size::new(200.0, 40.0), TextStyle::default(), &fonts)
600 .unwrap()
601 };
602 let pinned = system.adopt_layout(shape("pinned"));
603 shape("hot");
604 shape("hot");
605 shape("new");
606 assert_eq!(system.layout_cache_snapshot().entries, 2);
607 let before = system.layout_cache_snapshot();
608 shape("hot");
609 assert_eq!(system.layout_cache_snapshot().hits, before.hits + 1);
610 shape("pinned");
611 assert_eq!(system.layout_cache_snapshot().misses, before.misses + 1);
612 assert_eq!(
613 system.text_layout_registry().get(pinned.handle()),
614 Some(pinned.layout())
615 );
616 assert_eq!(pinned.layout().text(), "pinned");
617 }
618
619 #[test]
620 fn oversized_layouts_do_not_evict_small_reusable_layouts() {
621 let system = TextSystem {
622 layout_cache: Mutex::new(TextLayoutCache::with_limits(10, 16 * 1024)),
623 ..TextSystem::default()
624 };
625 let fonts = FontRegistry::new();
626 system
627 .measure_text("hot", TextStyle::default(), &fonts)
628 .unwrap();
629 assert_eq!(system.layout_cache_snapshot().entries, 1);
630 system
631 .measure_text(
632 "large document ".repeat(1_000),
633 TextStyle::default(),
634 &fonts,
635 )
636 .unwrap();
637 assert_eq!(system.layout_cache_snapshot().entries, 1);
638 system
639 .measure_text("hot", TextStyle::default(), &fonts)
640 .unwrap();
641 assert_eq!(system.layout_cache_snapshot().hits, 1);
642 }
643
644 #[test]
645 fn layout_byte_budget_bounds_changing_text_before_the_entry_limit() {
646 let system = TextSystem {
647 layout_cache: Mutex::new(TextLayoutCache::with_limits(100, 16 * 1024)),
648 ..TextSystem::default()
649 };
650 let fonts = FontRegistry::new();
651 for index in 0..100 {
652 system
653 .measure_text(
654 format!("temporary status {index}"),
655 TextStyle::default(),
656 &fonts,
657 )
658 .unwrap();
659 }
660 let snapshot = system.layout_cache_snapshot();
661 assert!(snapshot.entries > 0 && snapshot.entries < 100);
662 assert_eq!(snapshot.misses, 100);
663 }
664}