Skip to main content

sui_text/
prepared.rs

1//! Width-independent shaping and intrinsic metrics, owned by one FontContext.
2//! Eviction drops only preparatory state; published TextLayouts own their geometry.
3use std::{hash::Hash, mem::size_of};
4
5use cosmic_text::{AttrsOwned, FamilyOwned, LayoutLine, Metrics, ShapeLine, fontdb};
6
7use crate::model::{TextAlign, TextDirection, TextWrap, TextWritingMode};
8
9const PARAGRAPH_BYTES: usize = 16 * 1024 * 1024;
10const GLYPH_BYTES: usize = 4 * 1024 * 1024;
11
12/// Cache-owned storage only, excluding layouts retained by widgets and font data.
13#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
14pub struct PreparationCacheSnapshot {
15    pub entries: usize,
16    /// Conservatively charged payload capacity plus per-entry bookkeeping.
17    pub retained_bytes: usize,
18    pub hits: usize,
19    pub misses: usize,
20    pub evictions: usize,
21}
22
23#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
24pub struct TextPreparationCacheSnapshot {
25    pub paragraphs: PreparationCacheSnapshot,
26    pub glyphs: PreparationCacheSnapshot,
27}
28
29#[derive(Debug)]
30struct Entry<V> {
31    value: V,
32    bytes: usize,
33}
34
35#[derive(Debug)]
36pub(crate) struct ByteCache<K: Hash + Eq, V> {
37    entries: lru::LruCache<K, Entry<V>>,
38    max_entries: usize,
39    max_bytes: usize,
40    stats: PreparationCacheSnapshot,
41}
42
43impl<K: Hash + Eq, V> ByteCache<K, V> {
44    pub(crate) fn new(max_entries: usize, max_bytes: usize) -> Self {
45        Self {
46            entries: lru::LruCache::unbounded(),
47            max_entries,
48            max_bytes,
49            stats: Default::default(),
50        }
51    }
52
53    pub(crate) fn snapshot(&self) -> PreparationCacheSnapshot {
54        PreparationCacheSnapshot {
55            entries: self.entries.len(),
56            ..self.stats
57        }
58    }
59
60    pub(crate) fn take(&mut self, key: &K) -> Option<V> {
61        if let Some(entry) = self.entries.pop(key) {
62            self.stats.hits += 1;
63            self.stats.retained_bytes -= entry.bytes;
64            Some(entry.value)
65        } else {
66            self.stats.misses += 1;
67            None
68        }
69    }
70
71    pub(crate) fn get(&mut self, key: &K) -> Option<&V> {
72        if let Some(entry) = self.entries.get(key) {
73            self.stats.hits += 1;
74            Some(&entry.value)
75        } else {
76            self.stats.misses += 1;
77            None
78        }
79    }
80
81    pub(crate) fn insert(&mut self, key: K, value: V, payload_bytes: usize) {
82        // Charge LRU links and spare hash-table buckets as well as key/value storage.
83        let bytes = payload_bytes
84            .saturating_add(size_of::<K>() + size_of::<Entry<V>>() + size_of::<[usize; 8]>());
85        if bytes > self.max_bytes || self.max_entries == 0 {
86            return;
87        }
88        if let Some(old) = self.entries.pop(&key) {
89            self.stats.retained_bytes -= old.bytes;
90        }
91        while self.entries.len() >= self.max_entries
92            || self.stats.retained_bytes > self.max_bytes - bytes
93        {
94            let Some((_, old)) = self.entries.pop_lru() else {
95                break;
96            };
97            self.stats.retained_bytes -= old.bytes;
98            self.stats.evictions += 1;
99        }
100        self.entries.put(key, Entry { value, bytes });
101        self.stats.retained_bytes += bytes;
102    }
103}
104
105#[derive(Debug, Clone, PartialEq, Eq, Hash)]
106pub(crate) struct PreparedSpanKey {
107    pub text: String,
108    pub attrs: AttrsOwned,
109}
110
111/// Exact equality, including full feature settings, rather than hashed style identity.
112/// Font IDs/fallbacks belong to the enclosing FontContext. Span metadata is local
113/// to the paragraph, so moving an unchanged paragraph does not invalidate shaping.
114#[derive(Debug, Clone, PartialEq, Eq, Hash)]
115pub(crate) struct PreparedParagraphKey {
116    pub direction: TextDirection,
117    pub writing_mode: TextWritingMode,
118    pub defaults: AttrsOwned,
119    pub spans: Vec<PreparedSpanKey>,
120}
121
122impl PreparedParagraphKey {
123    pub(crate) fn allocated_bytes(&self) -> usize {
124        attrs_bytes(&self.defaults)
125            + allocation_bytes(&self.spans)
126            + self
127                .spans
128                .iter()
129                .map(|span| span.text.capacity() + attrs_bytes(&span.attrs))
130                .sum::<usize>()
131    }
132}
133
134fn attrs_bytes(attrs: &AttrsOwned) -> usize {
135    // FamilyOwned uses SmolStr: charge its full bytes plus Arc headers even when inline.
136    let family = match &attrs.family_owned {
137        FamilyOwned::Name(name) => name.len() + 2 * size_of::<usize>(),
138        _ => 0,
139    };
140    family + allocation_bytes(&attrs.font_features.features)
141}
142
143/// Alignment and wrapping affect line layout, not glyph shaping. Keep them here
144/// so measurement and painting can share a shape without sharing stale lines.
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub(crate) struct PreparedLineLayoutKey {
147    pub width: Option<u32>,
148    pub align: TextAlign,
149    pub wrap: TextWrap,
150}
151
152#[derive(Debug)]
153pub(crate) struct PreparedParagraphState {
154    pub shape: ShapeLine,
155    pub metrics: Metrics,
156    pub lines: Vec<LayoutLine>,
157    /// None means not laid out yet; a key with no width is unconstrained.
158    pub layout_key: Option<PreparedLineLayoutKey>,
159}
160
161impl PreparedParagraphState {
162    pub(crate) fn allocated_bytes(&self) -> usize {
163        // Shapes are built without ellipsizing or decorations. ShapeLine's private
164        // ellipsis_span stays None. Count actual Vec capacities, not text length:
165        // a grapheme can produce multiple glyphs, and narrow widths grow line arrays.
166        allocation_bytes(&self.shape.spans)
167            + self
168                .shape
169                .spans
170                .iter()
171                .map(|span| {
172                    allocation_bytes(&span.words)
173                        + allocation_bytes(&span.decoration_spans)
174                        + span
175                            .words
176                            .iter()
177                            .map(|word| allocation_bytes(&word.glyphs))
178                            .sum::<usize>()
179                })
180                .sum::<usize>()
181            + allocation_bytes(&self.lines)
182            + self
183                .lines
184                .iter()
185                .map(|line| allocation_bytes(&line.glyphs) + allocation_bytes(&line.decorations))
186                .sum::<usize>()
187    }
188}
189
190fn allocation_bytes<T>(values: &Vec<T>) -> usize {
191    values.capacity().saturating_mul(size_of::<T>())
192}
193
194#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
195pub(crate) struct GlyphMetricsKey {
196    pub font: fontdb::ID,
197    pub glyph: u16,
198}
199
200#[derive(Debug, Clone, Copy)]
201pub(crate) struct IntrinsicGlyphMetrics {
202    pub units_per_em: f32,
203    pub cap_height: Option<f32>,
204    pub bounds: Option<ttf_parser::Rect>,
205}
206
207#[derive(Debug)]
208pub(crate) struct PreparationCaches {
209    pub paragraphs: ByteCache<PreparedParagraphKey, PreparedParagraphState>,
210    pub glyphs: ByteCache<GlyphMetricsKey, IntrinsicGlyphMetrics>,
211    /// Size-only results, which depend on this context's fonts.
212    pub sizes: crate::cache::TextSizeCache,
213}
214
215impl Default for PreparationCaches {
216    fn default() -> Self {
217        Self {
218            paragraphs: ByteCache::new(512, PARAGRAPH_BYTES),
219            glyphs: ByteCache::new(32_768, GLYPH_BYTES),
220            sizes: crate::cache::TextSizeCache::default(),
221        }
222    }
223}
224
225impl PreparationCaches {
226    pub(crate) fn snapshot(&self) -> TextPreparationCacheSnapshot {
227        TextPreparationCacheSnapshot {
228            paragraphs: self.paragraphs.snapshot(),
229            glyphs: self.glyphs.snapshot(),
230        }
231    }
232}
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237
238    #[test]
239    fn byte_budget_evicts_lru_and_rejects_oversized_entries_without_flushing() {
240        let mut cache = ByteCache::new(100, 1_024);
241        cache.insert(1, "first", 300);
242        cache.insert(2, "second", 300);
243        assert_eq!(cache.get(&1), Some(&"first"));
244        cache.insert(3, "third", 300);
245        assert_eq!(cache.get(&2), None);
246        cache.insert(4, "oversized", 1_025);
247        assert_eq!(cache.get(&1), Some(&"first"));
248        assert_eq!(cache.get(&3), Some(&"third"));
249        assert!(cache.snapshot().retained_bytes <= 1_024);
250        assert_eq!(cache.snapshot().evictions, 1);
251        let bytes = cache.snapshot().retained_bytes;
252        let taken = cache.take(&3).unwrap();
253        assert!(cache.snapshot().retained_bytes < bytes);
254        cache.insert(3, taken, 300);
255        assert_eq!(cache.snapshot().retained_bytes, bytes);
256    }
257
258    #[test]
259    fn entry_budget_and_replacement_accounting_remain_bounded() {
260        let mut cache = ByteCache::new(2, usize::MAX);
261        for key in 0..100 {
262            cache.insert(key, (), 0);
263        }
264        assert_eq!(cache.snapshot().entries, 2);
265        assert_eq!(cache.snapshot().evictions, 98);
266        let bytes = cache.snapshot().retained_bytes;
267        cache.insert(99, (), 0);
268        assert_eq!(cache.snapshot().retained_bytes, bytes);
269    }
270}