Skip to main content

sui_text/
system.rs

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    /// All measured requests, including size-only requests.
26    pub request_count: usize,
27    pub size_only_request_count: usize,
28    pub size_only_time_us: u64,
29    /// Full-layout cache results; size-only requests use the preparation caches.
30    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    // Constructing a cosmic-text FontSystem clones and indexes the complete
123    // system font database. Keep that work outside individual layout misses.
124    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    /// Measure advance width and natural line-box height without building SUI's
179    /// glyph, caret, selection or ink-bounds geometry. Box height does not constrain
180    /// the result; box width and paragraph wrapping determine the line breaks.
181    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 flattened = FlattenedTextDocument::new(document.into_normalized());
189        let result = self.with_font_context(font_registry, |font_context| {
190            let resolved_spans = self.resolve_span_inputs(&flattened, font_context)?;
191            crate::layout::measure_document_size(
192                &flattened,
193                &resolved_spans,
194                box_size,
195                font_context,
196            )
197        });
198        if let Some(started) = started {
199            record_size_timing(started.elapsed().as_micros() as u64);
200        }
201        result
202    }
203
204    /// Size-only measurement of unconstrained plain text. Use measure_text when
205    /// ink bounds, ascent, descent or cap height are also needed.
206    pub fn measure_text_size(
207        &self,
208        text: impl Into<String>,
209        style: TextStyle,
210        font_registry: &FontRegistry,
211    ) -> Result<Size> {
212        self.measure_document_size(
213            TextLayoutRequest::new(TextDocument::from_plain_text(text, style)),
214            font_registry,
215        )
216    }
217
218    pub fn preparation_cache_snapshot(&self) -> crate::TextPreparationCacheSnapshot {
219        self.font_context
220            .lock()
221            .ok()
222            .and_then(|cached| {
223                cached
224                    .as_ref()
225                    .map(|cached| cached.context.preparation.snapshot())
226            })
227            .unwrap_or_default()
228    }
229
230    pub fn shape_text(
231        &self,
232        text: impl Into<String>,
233        box_size: Size,
234        style: TextStyle,
235        font_registry: &FontRegistry,
236    ) -> Result<TextLayout> {
237        self.layout_document(
238            TextLayoutRequest::new(TextDocument::from_plain_text(text.into(), style))
239                .with_box_size(box_size),
240            font_registry,
241        )
242    }
243
244    pub fn layout_document(
245        &self,
246        request: TextLayoutRequest,
247        font_registry: &FontRegistry,
248    ) -> Result<TextLayout> {
249        self.shape_text_internal(request, font_registry)
250    }
251
252    pub fn shape_text_persistent(
253        &self,
254        handle: Option<TextLayoutHandle>,
255        text: impl Into<String>,
256        box_size: Size,
257        style: TextStyle,
258        font_registry: &FontRegistry,
259    ) -> Result<PersistentTextLayout> {
260        let layout = self.shape_text(text, box_size, style, font_registry)?;
261        Ok(self.pin_layout(handle, layout))
262    }
263
264    pub fn layout_document_persistent(
265        &self,
266        handle: Option<TextLayoutHandle>,
267        request: TextLayoutRequest,
268        font_registry: &FontRegistry,
269    ) -> Result<PersistentTextLayout> {
270        let layout = self.layout_document(request, font_registry)?;
271        Ok(self.pin_layout(handle, layout))
272    }
273
274    pub fn shape_text_run(
275        &self,
276        run: &TextRun,
277        font_registry: &FontRegistry,
278    ) -> Result<TextLayout> {
279        self.shape_text(
280            run.text.clone(),
281            run.rect.size,
282            run.style.clone(),
283            font_registry,
284        )
285    }
286
287    pub fn shape_text_run_persistent(
288        &self,
289        handle: Option<TextLayoutHandle>,
290        run: &TextRun,
291        font_registry: &FontRegistry,
292    ) -> Result<PersistentTextLayout> {
293        let layout = self.shape_text_run(run, font_registry)?;
294        Ok(self.pin_layout(handle, layout))
295    }
296
297    pub fn adopt_layout(&self, layout: TextLayout) -> PersistentTextLayout {
298        let handle = TextLayoutHandle::from_layout_id(layout.id());
299        self.store_persistent_layout(handle, layout)
300    }
301
302    pub fn touch_persistent_layout(&self, layout: &PersistentTextLayout) {
303        self.store_persistent_layout(layout.handle(), layout.layout().clone());
304    }
305
306    pub fn text_layout_registry(&self) -> Arc<TextLayoutRegistry> {
307        match self.persistent_layouts.lock() {
308            Ok(registry) => Arc::clone(&registry),
309            Err(poisoned) => Arc::clone(&poisoned.into_inner()),
310        }
311    }
312
313    pub fn retain_persistent_layouts(&self, handles: &HashSet<TextLayoutHandle>) {
314        match self.persistent_layouts.lock() {
315            Ok(mut registry) => Arc::make_mut(&mut registry).retain_handles(handles),
316            Err(poisoned) => {
317                let mut registry = poisoned.into_inner();
318                Arc::make_mut(&mut registry).retain_handles(handles);
319            }
320        }
321    }
322
323    pub fn layout_cache_snapshot(&self) -> TextLayoutCacheSnapshot {
324        self.layout_cache
325            .lock()
326            .ok()
327            .map(|cache| cache.snapshot())
328            .unwrap_or_default()
329    }
330
331    fn shape_text_internal(
332        &self,
333        request: TextLayoutRequest,
334        font_registry: &FontRegistry,
335    ) -> Result<TextLayout> {
336        let total_started = text_timing_enabled().then(Instant::now);
337        let TextLayoutRequest { document, box_size } = request;
338        let normalized_document = document.into_normalized();
339        let span_face_keys = self.resolve_span_face_keys(&normalized_document, font_registry)?;
340        let prelookup_time_us = total_started
341            .as_ref()
342            .map(|started| started.elapsed().as_micros() as u64)
343            .unwrap_or(0);
344
345        let lookup_started = text_timing_enabled().then(Instant::now);
346        if let Some(cached) = self.cached_layout(&normalized_document, &span_face_keys, box_size)? {
347            let cache_lookup_time_us = lookup_started
348                .as_ref()
349                .map(|started| started.elapsed().as_micros() as u64)
350                .unwrap_or(0);
351            let total_time_us = total_started
352                .as_ref()
353                .map(|started| started.elapsed().as_micros() as u64)
354                .unwrap_or(0);
355            record_text_timing(
356                total_time_us,
357                prelookup_time_us,
358                cache_lookup_time_us,
359                0,
360                true,
361            );
362            return Ok(cached.with_document(normalized_document));
363        }
364
365        let cache_lookup_time_us = lookup_started
366            .as_ref()
367            .map(|started| started.elapsed().as_micros() as u64)
368            .unwrap_or(0);
369
370        let layout_started = text_timing_enabled().then(Instant::now);
371        let flattened = FlattenedTextDocument::new(normalized_document.clone());
372        let layout_id = crate::cache::TextLayoutCacheKey::stable_layout_id(
373            &normalized_document,
374            &span_face_keys,
375            box_size,
376        );
377        let layout = self.with_font_context(font_registry, |font_context| {
378            let resolved_spans = self.resolve_span_inputs(&flattened, font_context)?;
379            layout_document(flattened, resolved_spans, box_size, font_context, layout_id)
380        })?;
381        let miss_layout_time_us = layout_started
382            .as_ref()
383            .map(|started| started.elapsed().as_micros() as u64)
384            .unwrap_or(0);
385        self.store_layout(
386            &normalized_document,
387            &span_face_keys,
388            box_size,
389            layout.clone(),
390        )?;
391        let total_time_us = total_started
392            .as_ref()
393            .map(|started| started.elapsed().as_micros() as u64)
394            .unwrap_or(0);
395        record_text_timing(
396            total_time_us,
397            prelookup_time_us,
398            cache_lookup_time_us,
399            miss_layout_time_us,
400            false,
401        );
402        Ok(layout.with_document(normalized_document))
403    }
404
405    fn pin_layout(
406        &self,
407        handle: Option<TextLayoutHandle>,
408        layout: TextLayout,
409    ) -> PersistentTextLayout {
410        let handle = handle.unwrap_or_else(|| self.alloc_layout_handle());
411        self.store_persistent_layout(handle, layout)
412    }
413
414    fn alloc_layout_handle(&self) -> TextLayoutHandle {
415        TextLayoutHandle::new(
416            self.next_layout_handle
417                .fetch_add(1, Ordering::Relaxed)
418                .max(1),
419        )
420    }
421
422    fn store_persistent_layout(
423        &self,
424        handle: TextLayoutHandle,
425        layout: TextLayout,
426    ) -> PersistentTextLayout {
427        match self.persistent_layouts.lock() {
428            Ok(mut registry) => Arc::make_mut(&mut registry).insert(handle, layout.clone()),
429            Err(poisoned) => {
430                let mut registry = poisoned.into_inner();
431                Arc::make_mut(&mut registry).insert(handle, layout.clone());
432            }
433        }
434        PersistentTextLayout::new(handle, layout)
435    }
436
437    fn resolve_span_inputs(
438        &self,
439        flattened: &FlattenedTextDocument,
440        font_context: &FontContext,
441    ) -> Result<Vec<ResolvedSpanInput>> {
442        flattened
443            .spans
444            .iter()
445            .map(|span| font_context.resolve_span(span.id.clone(), span.text.clone(), &span.style))
446            .collect()
447    }
448
449    fn resolve_span_face_keys(
450        &self,
451        document: &TextDocument,
452        font_registry: &FontRegistry,
453    ) -> Result<Vec<FaceCacheKey>> {
454        let state = self.text_system_state()?;
455        let default_face_key = state.default_face_key();
456        let total_spans = document
457            .paragraphs
458            .iter()
459            .map(|paragraph| paragraph.spans.len())
460            .sum();
461        let mut keys = Vec::with_capacity(total_spans);
462        let mut explicit_face_keys = HashMap::new();
463
464        for paragraph in &document.paragraphs {
465            for span in &paragraph.spans {
466                let face_key = match span.style.font {
467                    Some(handle) => {
468                        if let Some(face_key) = explicit_face_keys.get(&handle).copied() {
469                            face_key
470                        } else {
471                            let font = font_registry.get(handle).ok_or_else(|| {
472                                Error::new(format!(
473                                    "font handle {} is not registered",
474                                    handle.get()
475                                ))
476                            })?;
477                            let face_key = FaceCacheKey::from_registered_font(font);
478                            explicit_face_keys.insert(handle, face_key);
479                            face_key
480                        }
481                    }
482                    None => default_face_key,
483                };
484                keys.push(face_key);
485            }
486        }
487
488        Ok(keys)
489    }
490
491    fn cached_layout(
492        &self,
493        document: &TextDocument,
494        span_face_keys: &[FaceCacheKey],
495        box_size: Option<Size>,
496    ) -> Result<Option<TextLayout>> {
497        let mut cache = self
498            .layout_cache
499            .lock()
500            .map_err(|_| Error::new("text layout cache lock was poisoned"))?;
501        Ok(cache.get(document, span_face_keys, box_size))
502    }
503
504    fn store_layout(
505        &self,
506        document: &TextDocument,
507        span_face_keys: &[FaceCacheKey],
508        box_size: Option<Size>,
509        layout: TextLayout,
510    ) -> Result<()> {
511        let mut cache = self
512            .layout_cache
513            .lock()
514            .map_err(|_| Error::new("text layout cache lock was poisoned"))?;
515        cache.insert(document, span_face_keys, box_size, layout);
516        Ok(())
517    }
518
519    fn text_system_state(&self) -> Result<&TextSystemState> {
520        let state = self
521            .state
522            .get_or_init(|| TextSystemState::new().map_err(|error| error.to_string()));
523        match state {
524            Ok(state) => Ok(state),
525            Err(message) => Err(Error::new(message.clone())),
526        }
527    }
528
529    fn with_font_context<T>(
530        &self,
531        font_registry: &FontRegistry,
532        operation: impl FnOnce(&mut FontContext) -> Result<T>,
533    ) -> Result<T> {
534        let registry_key = font_registry.cache_key();
535        let mut cached = self
536            .font_context
537            .lock()
538            .map_err(|_| Error::new("text font context cache lock was poisoned"))?;
539        let rebuild = cached
540            .as_ref()
541            .is_none_or(|cached| cached.registry_key != registry_key);
542        if rebuild {
543            *cached = Some(CachedFontContext {
544                registry_key,
545                context: self
546                    .text_system_state()?
547                    .build_font_context(font_registry)?,
548            });
549            #[cfg(test)]
550            self.font_context_build_count
551                .fetch_add(1, Ordering::Relaxed);
552        }
553
554        operation(
555            &mut cached
556                .as_mut()
557                .expect("font context was initialized")
558                .context,
559        )
560    }
561
562    #[cfg(test)]
563    pub(crate) fn font_context_build_count(&self) -> u64 {
564        self.font_context_build_count.load(Ordering::Relaxed)
565    }
566}
567
568#[cfg(test)]
569#[path = "tests/preparation.rs"]
570mod preparation_tests;
571
572#[cfg(test)]
573mod cache_tests {
574    use super::*;
575
576    #[test]
577    fn layout_cache_evicts_lru_entries_without_invalidating_pinned_layouts() {
578        let system = TextSystem {
579            layout_cache: Mutex::new(TextLayoutCache::with_limits(2, usize::MAX)),
580            ..TextSystem::default()
581        };
582        let fonts = FontRegistry::new();
583        let shape = |text| {
584            system
585                .shape_text(text, Size::new(200.0, 40.0), TextStyle::default(), &fonts)
586                .unwrap()
587        };
588        let pinned = system.adopt_layout(shape("pinned"));
589        shape("hot");
590        shape("hot");
591        shape("new");
592        assert_eq!(system.layout_cache_snapshot().entries, 2);
593        let before = system.layout_cache_snapshot();
594        shape("hot");
595        assert_eq!(system.layout_cache_snapshot().hits, before.hits + 1);
596        shape("pinned");
597        assert_eq!(system.layout_cache_snapshot().misses, before.misses + 1);
598        assert_eq!(
599            system.text_layout_registry().get(pinned.handle()),
600            Some(pinned.layout())
601        );
602        assert_eq!(pinned.layout().text(), "pinned");
603    }
604
605    #[test]
606    fn oversized_layouts_do_not_evict_small_reusable_layouts() {
607        let system = TextSystem {
608            layout_cache: Mutex::new(TextLayoutCache::with_limits(10, 16 * 1024)),
609            ..TextSystem::default()
610        };
611        let fonts = FontRegistry::new();
612        system
613            .measure_text("hot", TextStyle::default(), &fonts)
614            .unwrap();
615        assert_eq!(system.layout_cache_snapshot().entries, 1);
616        system
617            .measure_text(
618                "large document ".repeat(1_000),
619                TextStyle::default(),
620                &fonts,
621            )
622            .unwrap();
623        assert_eq!(system.layout_cache_snapshot().entries, 1);
624        system
625            .measure_text("hot", TextStyle::default(), &fonts)
626            .unwrap();
627        assert_eq!(system.layout_cache_snapshot().hits, 1);
628    }
629
630    #[test]
631    fn layout_byte_budget_bounds_changing_text_before_the_entry_limit() {
632        let system = TextSystem {
633            layout_cache: Mutex::new(TextLayoutCache::with_limits(100, 16 * 1024)),
634            ..TextSystem::default()
635        };
636        let fonts = FontRegistry::new();
637        for index in 0..100 {
638            system
639                .measure_text(
640                    format!("temporary status {index}"),
641                    TextStyle::default(),
642                    &fonts,
643                )
644                .unwrap();
645        }
646        let snapshot = system.layout_cache_snapshot();
647        assert!(snapshot.entries > 0 && snapshot.entries < 100);
648        assert_eq!(snapshot.misses, 100);
649    }
650}