sinomo-ui-text 0.6.0

Text shaping, font registration, and layout for SUI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
use std::{
    cell::RefCell,
    collections::{HashMap, HashSet},
    sync::atomic::{AtomicU64, Ordering},
    sync::{Arc, Mutex, OnceLock},
    time::Instant,
};

use sui_core::{Error, Result, Size};

use crate::{
    FontRegistry,
    cache::{TextLayoutCache, TextLayoutCacheSnapshot},
    flatten::FlattenedTextDocument,
    font::{FaceCacheKey, FontContext, ResolvedSpanInput, TextSystemState},
    layout::layout_document,
    model::{
        PersistentTextLayout, TextDocument, TextLayout, TextLayoutHandle, TextLayoutRegistry,
        TextLayoutRequest, TextMeasurement, TextRun, TextStyle,
    },
};

#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct RuntimeTextTimingDiagnostics {
    /// All measured requests, including size-only requests.
    pub request_count: usize,
    pub size_only_request_count: usize,
    pub size_only_time_us: u64,
    /// Full-layout cache results; size-only requests use the preparation caches.
    pub cache_hit_count: usize,
    pub cache_miss_count: usize,
    pub total_time_us: u64,
    pub prelookup_time_us: u64,
    pub cache_lookup_time_us: u64,
    pub miss_layout_time_us: u64,
}

thread_local! {
    static TEXT_TIMING_COLLECTOR: RefCell<Option<RuntimeTextTimingDiagnostics>> =
        const { RefCell::new(None) };
}

fn text_timing_enabled() -> bool {
    static ENABLED: OnceLock<bool> = OnceLock::new();
    *ENABLED.get_or_init(|| std::env::var_os("SUI_PROFILE_TEXT_TIMINGS").is_some())
}

pub fn begin_text_timing_collection() {
    if !text_timing_enabled() {
        return;
    }

    TEXT_TIMING_COLLECTOR.with(|collector| {
        *collector.borrow_mut() = Some(RuntimeTextTimingDiagnostics::default());
    });
}

pub fn take_text_timing_collection() -> RuntimeTextTimingDiagnostics {
    if !text_timing_enabled() {
        return RuntimeTextTimingDiagnostics::default();
    }

    TEXT_TIMING_COLLECTOR
        .with(|collector| collector.borrow_mut().take())
        .unwrap_or_default()
}

fn record_text_timing(
    total_time_us: u64,
    prelookup_time_us: u64,
    cache_lookup_time_us: u64,
    miss_layout_time_us: u64,
    cache_hit: bool,
) {
    if !text_timing_enabled() {
        return;
    }

    TEXT_TIMING_COLLECTOR.with(|collector| {
        let mut collector = collector.borrow_mut();
        let Some(diagnostics) = collector.as_mut() else {
            return;
        };
        diagnostics.request_count += 1;
        diagnostics.total_time_us += total_time_us;
        diagnostics.prelookup_time_us += prelookup_time_us;
        diagnostics.cache_lookup_time_us += cache_lookup_time_us;
        diagnostics.miss_layout_time_us += miss_layout_time_us;
        if cache_hit {
            diagnostics.cache_hit_count += 1;
        } else {
            diagnostics.cache_miss_count += 1;
        }
    });
}

fn record_size_timing(total_time_us: u64) {
    TEXT_TIMING_COLLECTOR.with(|collector| {
        if let Some(diagnostics) = collector.borrow_mut().as_mut() {
            diagnostics.request_count += 1;
            diagnostics.size_only_request_count += 1;
            diagnostics.total_time_us += total_time_us;
            diagnostics.size_only_time_us += total_time_us;
        }
    });
}

#[derive(Debug)]
pub struct TextSystem {
    state: OnceLock<std::result::Result<TextSystemState, String>>,
    font_context: Mutex<Option<CachedFontContext>>,
    #[cfg(test)]
    font_context_build_count: AtomicU64,
    layout_cache: Mutex<TextLayoutCache>,
    persistent_layouts: Mutex<Arc<TextLayoutRegistry>>,
    next_layout_handle: AtomicU64,
}

#[derive(Debug)]
struct CachedFontContext {
    registry_key: Vec<(sui_core::FontHandle, FaceCacheKey)>,
    // Constructing a cosmic-text FontSystem clones and indexes the complete
    // system font database. Keep that work outside individual layout misses.
    context: FontContext,
}

impl Default for TextSystem {
    fn default() -> Self {
        Self {
            state: OnceLock::new(),
            font_context: Mutex::new(None),
            #[cfg(test)]
            font_context_build_count: AtomicU64::new(0),
            layout_cache: Mutex::new(TextLayoutCache::default()),
            persistent_layouts: Mutex::new(Arc::new(TextLayoutRegistry::default())),
            next_layout_handle: AtomicU64::new(1),
        }
    }
}

impl TextSystem {
    pub fn new() -> Self {
        Self::default()
    }

    #[cfg(test)]
    pub(crate) fn with_bundled_fonts() -> Self {
        Self {
            state: OnceLock::from(Ok(
                TextSystemState::with_bundled_fonts().expect("bundled fonts should load")
            )),
            ..Self::default()
        }
    }

    pub fn measure_text(
        &self,
        text: impl Into<String>,
        style: TextStyle,
        font_registry: &FontRegistry,
    ) -> Result<TextMeasurement> {
        self.measure_document(
            TextDocument::from_plain_text(text.into(), style),
            font_registry,
        )
    }

    pub fn measure_document(
        &self,
        document: TextDocument,
        font_registry: &FontRegistry,
    ) -> Result<TextMeasurement> {
        Ok(self
            .layout_document(TextLayoutRequest::new(document), font_registry)?
            .measurement())
    }

    /// Measure advance width and natural line-box height without building SUI's
    /// glyph, caret, selection or ink-bounds geometry. Box height does not constrain
    /// the result; box width and paragraph wrapping determine the line breaks.
    pub fn measure_document_size(
        &self,
        request: TextLayoutRequest,
        font_registry: &FontRegistry,
    ) -> Result<Size> {
        let started = text_timing_enabled().then(Instant::now);
        let TextLayoutRequest { document, box_size } = request;
        let flattened = FlattenedTextDocument::new(document.into_normalized());
        let result = self.with_font_context(font_registry, |font_context| {
            let resolved_spans = self.resolve_span_inputs(&flattened, font_context)?;
            crate::layout::measure_document_size(
                &flattened,
                &resolved_spans,
                box_size,
                font_context,
            )
        });
        if let Some(started) = started {
            record_size_timing(started.elapsed().as_micros() as u64);
        }
        result
    }

    /// Size-only measurement of unconstrained plain text. Use measure_text when
    /// ink bounds, ascent, descent or cap height are also needed.
    pub fn measure_text_size(
        &self,
        text: impl Into<String>,
        style: TextStyle,
        font_registry: &FontRegistry,
    ) -> Result<Size> {
        self.measure_document_size(
            TextLayoutRequest::new(TextDocument::from_plain_text(text, style)),
            font_registry,
        )
    }

    pub fn preparation_cache_snapshot(&self) -> crate::TextPreparationCacheSnapshot {
        self.font_context
            .lock()
            .ok()
            .and_then(|cached| {
                cached
                    .as_ref()
                    .map(|cached| cached.context.preparation.snapshot())
            })
            .unwrap_or_default()
    }

    pub fn shape_text(
        &self,
        text: impl Into<String>,
        box_size: Size,
        style: TextStyle,
        font_registry: &FontRegistry,
    ) -> Result<TextLayout> {
        self.layout_document(
            TextLayoutRequest::new(TextDocument::from_plain_text(text.into(), style))
                .with_box_size(box_size),
            font_registry,
        )
    }

    pub fn layout_document(
        &self,
        request: TextLayoutRequest,
        font_registry: &FontRegistry,
    ) -> Result<TextLayout> {
        self.shape_text_internal(request, font_registry)
    }

    pub fn shape_text_persistent(
        &self,
        handle: Option<TextLayoutHandle>,
        text: impl Into<String>,
        box_size: Size,
        style: TextStyle,
        font_registry: &FontRegistry,
    ) -> Result<PersistentTextLayout> {
        let layout = self.shape_text(text, box_size, style, font_registry)?;
        Ok(self.pin_layout(handle, layout))
    }

    pub fn layout_document_persistent(
        &self,
        handle: Option<TextLayoutHandle>,
        request: TextLayoutRequest,
        font_registry: &FontRegistry,
    ) -> Result<PersistentTextLayout> {
        let layout = self.layout_document(request, font_registry)?;
        Ok(self.pin_layout(handle, layout))
    }

    pub fn shape_text_run(
        &self,
        run: &TextRun,
        font_registry: &FontRegistry,
    ) -> Result<TextLayout> {
        self.shape_text(
            run.text.clone(),
            run.rect.size,
            run.style.clone(),
            font_registry,
        )
    }

    pub fn shape_text_run_persistent(
        &self,
        handle: Option<TextLayoutHandle>,
        run: &TextRun,
        font_registry: &FontRegistry,
    ) -> Result<PersistentTextLayout> {
        let layout = self.shape_text_run(run, font_registry)?;
        Ok(self.pin_layout(handle, layout))
    }

    pub fn adopt_layout(&self, layout: TextLayout) -> PersistentTextLayout {
        let handle = TextLayoutHandle::from_layout_id(layout.id());
        self.store_persistent_layout(handle, layout)
    }

    pub fn touch_persistent_layout(&self, layout: &PersistentTextLayout) {
        self.store_persistent_layout(layout.handle(), layout.layout().clone());
    }

    pub fn text_layout_registry(&self) -> Arc<TextLayoutRegistry> {
        match self.persistent_layouts.lock() {
            Ok(registry) => Arc::clone(&registry),
            Err(poisoned) => Arc::clone(&poisoned.into_inner()),
        }
    }

    pub fn retain_persistent_layouts(&self, handles: &HashSet<TextLayoutHandle>) {
        match self.persistent_layouts.lock() {
            Ok(mut registry) => Arc::make_mut(&mut registry).retain_handles(handles),
            Err(poisoned) => {
                let mut registry = poisoned.into_inner();
                Arc::make_mut(&mut registry).retain_handles(handles);
            }
        }
    }

    pub fn layout_cache_snapshot(&self) -> TextLayoutCacheSnapshot {
        self.layout_cache
            .lock()
            .ok()
            .map(|cache| cache.snapshot())
            .unwrap_or_default()
    }

    fn shape_text_internal(
        &self,
        request: TextLayoutRequest,
        font_registry: &FontRegistry,
    ) -> Result<TextLayout> {
        let total_started = text_timing_enabled().then(Instant::now);
        let TextLayoutRequest { document, box_size } = request;
        let normalized_document = document.into_normalized();
        let span_face_keys = self.resolve_span_face_keys(&normalized_document, font_registry)?;
        let prelookup_time_us = total_started
            .as_ref()
            .map(|started| started.elapsed().as_micros() as u64)
            .unwrap_or(0);

        let lookup_started = text_timing_enabled().then(Instant::now);
        if let Some(cached) = self.cached_layout(&normalized_document, &span_face_keys, box_size)? {
            let cache_lookup_time_us = lookup_started
                .as_ref()
                .map(|started| started.elapsed().as_micros() as u64)
                .unwrap_or(0);
            let total_time_us = total_started
                .as_ref()
                .map(|started| started.elapsed().as_micros() as u64)
                .unwrap_or(0);
            record_text_timing(
                total_time_us,
                prelookup_time_us,
                cache_lookup_time_us,
                0,
                true,
            );
            return Ok(cached.with_document(normalized_document));
        }

        let cache_lookup_time_us = lookup_started
            .as_ref()
            .map(|started| started.elapsed().as_micros() as u64)
            .unwrap_or(0);

        let layout_started = text_timing_enabled().then(Instant::now);
        let flattened = FlattenedTextDocument::new(normalized_document.clone());
        let layout_id = crate::cache::TextLayoutCacheKey::stable_layout_id(
            &normalized_document,
            &span_face_keys,
            box_size,
        );
        let layout = self.with_font_context(font_registry, |font_context| {
            let resolved_spans = self.resolve_span_inputs(&flattened, font_context)?;
            layout_document(flattened, resolved_spans, box_size, font_context, layout_id)
        })?;
        let miss_layout_time_us = layout_started
            .as_ref()
            .map(|started| started.elapsed().as_micros() as u64)
            .unwrap_or(0);
        self.store_layout(
            &normalized_document,
            &span_face_keys,
            box_size,
            layout.clone(),
        )?;
        let total_time_us = total_started
            .as_ref()
            .map(|started| started.elapsed().as_micros() as u64)
            .unwrap_or(0);
        record_text_timing(
            total_time_us,
            prelookup_time_us,
            cache_lookup_time_us,
            miss_layout_time_us,
            false,
        );
        Ok(layout.with_document(normalized_document))
    }

    fn pin_layout(
        &self,
        handle: Option<TextLayoutHandle>,
        layout: TextLayout,
    ) -> PersistentTextLayout {
        let handle = handle.unwrap_or_else(|| self.alloc_layout_handle());
        self.store_persistent_layout(handle, layout)
    }

    fn alloc_layout_handle(&self) -> TextLayoutHandle {
        TextLayoutHandle::new(
            self.next_layout_handle
                .fetch_add(1, Ordering::Relaxed)
                .max(1),
        )
    }

    fn store_persistent_layout(
        &self,
        handle: TextLayoutHandle,
        layout: TextLayout,
    ) -> PersistentTextLayout {
        match self.persistent_layouts.lock() {
            Ok(mut registry) => Arc::make_mut(&mut registry).insert(handle, layout.clone()),
            Err(poisoned) => {
                let mut registry = poisoned.into_inner();
                Arc::make_mut(&mut registry).insert(handle, layout.clone());
            }
        }
        PersistentTextLayout::new(handle, layout)
    }

    fn resolve_span_inputs(
        &self,
        flattened: &FlattenedTextDocument,
        font_context: &FontContext,
    ) -> Result<Vec<ResolvedSpanInput>> {
        flattened
            .spans
            .iter()
            .map(|span| font_context.resolve_span(span.id.clone(), span.text.clone(), &span.style))
            .collect()
    }

    fn resolve_span_face_keys(
        &self,
        document: &TextDocument,
        font_registry: &FontRegistry,
    ) -> Result<Vec<FaceCacheKey>> {
        let state = self.text_system_state()?;
        let default_face_key = state.default_face_key();
        let total_spans = document
            .paragraphs
            .iter()
            .map(|paragraph| paragraph.spans.len())
            .sum();
        let mut keys = Vec::with_capacity(total_spans);
        let mut explicit_face_keys = HashMap::new();

        for paragraph in &document.paragraphs {
            for span in &paragraph.spans {
                let face_key = match span.style.font {
                    Some(handle) => {
                        if let Some(face_key) = explicit_face_keys.get(&handle).copied() {
                            face_key
                        } else {
                            let font = font_registry.get(handle).ok_or_else(|| {
                                Error::new(format!(
                                    "font handle {} is not registered",
                                    handle.get()
                                ))
                            })?;
                            let face_key = FaceCacheKey::from_registered_font(font);
                            explicit_face_keys.insert(handle, face_key);
                            face_key
                        }
                    }
                    None => default_face_key,
                };
                keys.push(face_key);
            }
        }

        Ok(keys)
    }

    fn cached_layout(
        &self,
        document: &TextDocument,
        span_face_keys: &[FaceCacheKey],
        box_size: Option<Size>,
    ) -> Result<Option<TextLayout>> {
        let mut cache = self
            .layout_cache
            .lock()
            .map_err(|_| Error::new("text layout cache lock was poisoned"))?;
        Ok(cache.get(document, span_face_keys, box_size))
    }

    fn store_layout(
        &self,
        document: &TextDocument,
        span_face_keys: &[FaceCacheKey],
        box_size: Option<Size>,
        layout: TextLayout,
    ) -> Result<()> {
        let mut cache = self
            .layout_cache
            .lock()
            .map_err(|_| Error::new("text layout cache lock was poisoned"))?;
        cache.insert(document, span_face_keys, box_size, layout);
        Ok(())
    }

    fn text_system_state(&self) -> Result<&TextSystemState> {
        let state = self
            .state
            .get_or_init(|| TextSystemState::new().map_err(|error| error.to_string()));
        match state {
            Ok(state) => Ok(state),
            Err(message) => Err(Error::new(message.clone())),
        }
    }

    fn with_font_context<T>(
        &self,
        font_registry: &FontRegistry,
        operation: impl FnOnce(&mut FontContext) -> Result<T>,
    ) -> Result<T> {
        let registry_key = font_registry.cache_key();
        let mut cached = self
            .font_context
            .lock()
            .map_err(|_| Error::new("text font context cache lock was poisoned"))?;
        let rebuild = cached
            .as_ref()
            .is_none_or(|cached| cached.registry_key != registry_key);
        if rebuild {
            *cached = Some(CachedFontContext {
                registry_key,
                context: self
                    .text_system_state()?
                    .build_font_context(font_registry)?,
            });
            #[cfg(test)]
            self.font_context_build_count
                .fetch_add(1, Ordering::Relaxed);
        }

        operation(
            &mut cached
                .as_mut()
                .expect("font context was initialized")
                .context,
        )
    }

    #[cfg(test)]
    pub(crate) fn font_context_build_count(&self) -> u64 {
        self.font_context_build_count.load(Ordering::Relaxed)
    }
}

#[cfg(test)]
#[path = "tests/preparation.rs"]
mod preparation_tests;

#[cfg(test)]
mod cache_tests {
    use super::*;

    #[test]
    fn layout_cache_evicts_lru_entries_without_invalidating_pinned_layouts() {
        let system = TextSystem {
            layout_cache: Mutex::new(TextLayoutCache::with_limits(2, usize::MAX)),
            ..TextSystem::default()
        };
        let fonts = FontRegistry::new();
        let shape = |text| {
            system
                .shape_text(text, Size::new(200.0, 40.0), TextStyle::default(), &fonts)
                .unwrap()
        };
        let pinned = system.adopt_layout(shape("pinned"));
        shape("hot");
        shape("hot");
        shape("new");
        assert_eq!(system.layout_cache_snapshot().entries, 2);
        let before = system.layout_cache_snapshot();
        shape("hot");
        assert_eq!(system.layout_cache_snapshot().hits, before.hits + 1);
        shape("pinned");
        assert_eq!(system.layout_cache_snapshot().misses, before.misses + 1);
        assert_eq!(
            system.text_layout_registry().get(pinned.handle()),
            Some(pinned.layout())
        );
        assert_eq!(pinned.layout().text(), "pinned");
    }

    #[test]
    fn oversized_layouts_do_not_evict_small_reusable_layouts() {
        let system = TextSystem {
            layout_cache: Mutex::new(TextLayoutCache::with_limits(10, 16 * 1024)),
            ..TextSystem::default()
        };
        let fonts = FontRegistry::new();
        system
            .measure_text("hot", TextStyle::default(), &fonts)
            .unwrap();
        assert_eq!(system.layout_cache_snapshot().entries, 1);
        system
            .measure_text(
                "large document ".repeat(1_000),
                TextStyle::default(),
                &fonts,
            )
            .unwrap();
        assert_eq!(system.layout_cache_snapshot().entries, 1);
        system
            .measure_text("hot", TextStyle::default(), &fonts)
            .unwrap();
        assert_eq!(system.layout_cache_snapshot().hits, 1);
    }

    #[test]
    fn layout_byte_budget_bounds_changing_text_before_the_entry_limit() {
        let system = TextSystem {
            layout_cache: Mutex::new(TextLayoutCache::with_limits(100, 16 * 1024)),
            ..TextSystem::default()
        };
        let fonts = FontRegistry::new();
        for index in 0..100 {
            system
                .measure_text(
                    format!("temporary status {index}"),
                    TextStyle::default(),
                    &fonts,
                )
                .unwrap();
        }
        let snapshot = system.layout_cache_snapshot();
        assert!(snapshot.entries > 0 && snapshot.entries < 100);
        assert_eq!(snapshot.misses, 100);
    }
}