Skip to main content

cranpose_render_common/
text_measure.rs

1//! Shared CPU [`TextMeasurer`] used by the software rasterizer backends
2//! (pixels, vulkan). Both backends draw text by rasterizing glyphs directly
3//! into a pixel buffer rather than through a GPU glyph atlas, so they share
4//! one font-backed measurer plus its fallback-metrics path for when no font
5//! is installed.
6
7use std::{
8    borrow::Borrow,
9    hash::{Hash, Hasher},
10    rc::Rc,
11    sync::{Mutex, MutexGuard, PoisonError},
12};
13
14use cranpose_ui::{TextMeasurer, TextMetrics, text_layout_result::TextLayoutResult};
15
16use crate::{
17    bounded_lru_cache::BoundedLruCache,
18    software_text_raster::{
19        SoftwareTextFont, SoftwareTextFontSet, cursor_x_for_offset_with_font,
20        layout_text_with_font, measure_text_with_font, text_offset_for_position_with_font,
21    },
22    text_hyphenation::HyphenationDictionaryStore,
23};
24
25/// Renderer-owned text resources: the resolved font used for software
26/// rasterization and measurement, if any.
27#[derive(Clone)]
28pub struct SoftwareTextResources {
29    fonts: SoftwareTextFontSet,
30}
31
32impl SoftwareTextResources {
33    pub fn default_font() -> Self {
34        Self {
35            fonts: SoftwareTextFontSet::from_fonts_or_default(&[]),
36        }
37    }
38
39    pub fn fonts(&self) -> &SoftwareTextFontSet {
40        &self.fonts
41    }
42}
43
44impl Default for SoftwareTextResources {
45    fn default() -> Self {
46        Self::default_font()
47    }
48}
49
50pub fn fallback_char_width(font_size: f32) -> f32 {
51    font_size.max(1.0) * 0.55
52}
53
54pub fn fallback_line_height(font_size: f32) -> f32 {
55    font_size.max(1.0) * 1.2
56}
57
58pub fn fallback_text_metrics(text: &str, font_size: f32) -> TextMetrics {
59    let line_height = fallback_line_height(font_size);
60    let mut line_count = 0usize;
61    let mut max_chars = 0usize;
62    for line in text.split('\n') {
63        line_count += 1;
64        max_chars = max_chars.max(line.chars().count());
65    }
66    let line_count = line_count.max(1);
67    TextMetrics {
68        width: max_chars as f32 * fallback_char_width(font_size),
69        height: line_count as f32 * line_height,
70        line_height,
71        line_count,
72    }
73}
74
75pub fn fallback_cursor_x_for_byte_offset(text: &str, byte_offset: usize, font_size: f32) -> f32 {
76    let clamped = byte_offset.min(text.len());
77    let char_count = if clamped == text.len() {
78        text.chars().count()
79    } else {
80        text.char_indices()
81            .take_while(|(index, _)| *index < clamped)
82            .count()
83    };
84    char_count as f32 * fallback_char_width(font_size)
85}
86
87pub struct CachedFontTextMeasurer {
88    text_resources: SoftwareTextResources,
89    cache: Mutex<TextMetricsCache>,
90    hyphenation: HyphenationDictionaryStore,
91}
92
93#[derive(Clone)]
94struct TextKey {
95    text: Rc<str>,
96    font_size_bits: u32,
97    style_hash: u64,
98}
99
100impl PartialEq for TextKey {
101    fn eq(&self, other: &Self) -> bool {
102        (Rc::ptr_eq(&self.text, &other.text) || *self.text == *other.text)
103            && self.font_size_bits == other.font_size_bits
104            && self.style_hash == other.style_hash
105    }
106}
107
108impl Eq for TextKey {}
109
110impl Hash for TextKey {
111    fn hash<H: Hasher>(&self, state: &mut H) {
112        self.text.hash(state);
113        self.font_size_bits.hash(state);
114        self.style_hash.hash(state);
115    }
116}
117
118impl Borrow<str> for TextKey {
119    fn borrow(&self) -> &str {
120        &self.text
121    }
122}
123
124struct TextMetricsCache {
125    map: BoundedLruCache<TextKey, TextMetrics>,
126}
127
128impl TextMetricsCache {
129    fn new(capacity: usize) -> Self {
130        Self {
131            map: BoundedLruCache::with_capacity_at_least_one(capacity),
132        }
133    }
134
135    fn get_or_measure<F>(
136        &mut self,
137        text: &str,
138        font_size: f32,
139        style_hash: u64,
140        measure: F,
141    ) -> TextMetrics
142    where
143        F: FnOnce(&str, f32) -> TextMetrics,
144    {
145        let key = TextKey {
146            text: Rc::from(text),
147            font_size_bits: font_size.to_bits(),
148            style_hash,
149        };
150
151        if let Some(metrics) = self.map.get(&key).copied() {
152            return metrics;
153        }
154
155        let metrics = measure(text, font_size);
156        self.map.put(key, metrics);
157        metrics
158    }
159}
160
161impl CachedFontTextMeasurer {
162    pub fn with_text_resources(text_resources: SoftwareTextResources, capacity: usize) -> Self {
163        Self {
164            text_resources,
165            cache: Mutex::new(TextMetricsCache::new(capacity)),
166            hyphenation: HyphenationDictionaryStore::new(),
167        }
168    }
169
170    fn lock_cache(&self) -> MutexGuard<'_, TextMetricsCache> {
171        self.cache.lock().unwrap_or_else(PoisonError::into_inner)
172    }
173}
174
175fn resolve_font_size(style: &cranpose_ui::text::TextStyle) -> f32 {
176    style.resolve_font_size(14.0)
177}
178
179impl TextMeasurer for CachedFontTextMeasurer {
180    fn measure(
181        &self,
182        text: &cranpose_ui::text::AnnotatedString,
183        style: &cranpose_ui::text::TextStyle,
184    ) -> TextMetrics {
185        let text_str = text.text.as_str();
186        let font_size = resolve_font_size(style);
187        let style_hash = style.measurement_hash();
188        self.lock_cache()
189            .get_or_measure(text_str, font_size, style_hash, |value, size| {
190                measure_text_impl(
191                    value,
192                    style,
193                    size,
194                    self.text_resources.fonts().resolve(style),
195                )
196            })
197    }
198
199    fn get_offset_for_position(
200        &self,
201        text: &cranpose_ui::text::AnnotatedString,
202        style: &cranpose_ui::text::TextStyle,
203        x: f32,
204        _y: f32,
205    ) -> usize {
206        let text = text.text.as_str();
207        if text.is_empty() {
208            return 0;
209        }
210
211        let Some(font) = self.text_resources.fonts().resolve(style) else {
212            let font_size = resolve_font_size(style);
213            return TextLayoutResult::monospaced(
214                text,
215                fallback_char_width(font_size),
216                fallback_line_height(font_size),
217            )
218            .get_offset_for_x(x);
219        };
220
221        text_offset_for_position_with_font(text, style, x, _y, font)
222    }
223
224    fn get_cursor_x_for_offset(
225        &self,
226        text: &cranpose_ui::text::AnnotatedString,
227        style: &cranpose_ui::text::TextStyle,
228        offset: usize,
229    ) -> f32 {
230        let text = text.text.as_str();
231        let clamped_offset = offset.min(text.len());
232        if clamped_offset == 0 {
233            return 0.0;
234        }
235
236        let Some(font) = self.text_resources.fonts().resolve(style) else {
237            return fallback_cursor_x_for_byte_offset(
238                text,
239                clamped_offset,
240                resolve_font_size(style),
241            );
242        };
243
244        cursor_x_for_offset_with_font(text, style, clamped_offset, font)
245    }
246
247    fn layout(
248        &self,
249        text: &cranpose_ui::text::AnnotatedString,
250        style: &cranpose_ui::text::TextStyle,
251    ) -> cranpose_ui::text_layout_result::TextLayoutResult {
252        let font_size = resolve_font_size(style);
253        let Some(font) = self.text_resources.fonts().resolve(style) else {
254            return TextLayoutResult::monospaced(
255                text.text.as_str(),
256                fallback_char_width(font_size),
257                fallback_line_height(font_size),
258            );
259        };
260
261        layout_text_with_font(text.text.as_str(), style, font)
262    }
263
264    fn choose_auto_hyphen_break(
265        &self,
266        line: &str,
267        style: &cranpose_ui::text::TextStyle,
268        segment_start_char: usize,
269        measured_break_char: usize,
270    ) -> Option<usize> {
271        self.hyphenation.choose_auto_hyphen_break(
272            line,
273            style,
274            segment_start_char,
275            measured_break_char,
276        )
277    }
278}
279
280fn measure_text_impl(
281    text: &str,
282    style: &cranpose_ui::text::TextStyle,
283    font_size: f32,
284    font: Option<&SoftwareTextFont>,
285) -> TextMetrics {
286    let Some(font) = font else {
287        return fallback_text_metrics(text, font_size);
288    };
289
290    measure_text_with_font(text, style, font_size, font)
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296
297    #[test]
298    fn fallback_text_metrics_cover_empty_and_multiline_text() {
299        let empty = fallback_text_metrics("", 10.0);
300        assert_eq!(empty.line_count, 1);
301        assert_eq!(empty.width, 0.0);
302        assert_eq!(empty.height, fallback_line_height(10.0));
303
304        let multiline = fallback_text_metrics("ab\ncde", 10.0);
305        assert_eq!(multiline.line_count, 2);
306        assert_eq!(multiline.width, 3.0 * fallback_char_width(10.0));
307        assert_eq!(multiline.height, 2.0 * fallback_line_height(10.0));
308    }
309
310    #[test]
311    fn fallback_cursor_position_handles_non_boundary_byte_offsets() {
312        let text = "éx";
313        let width = fallback_char_width(12.0);
314        assert_eq!(fallback_cursor_x_for_byte_offset(text, 0, 12.0), 0.0);
315        assert_eq!(fallback_cursor_x_for_byte_offset(text, 1, 12.0), width);
316        assert_eq!(
317            fallback_cursor_x_for_byte_offset(text, text.len(), 12.0),
318            width * 2.0
319        );
320    }
321
322    #[test]
323    fn cached_font_text_metrics_cache_recovers_after_poison() {
324        let measurer =
325            CachedFontTextMeasurer::with_text_resources(SoftwareTextResources::default(), 8);
326        let text = cranpose_ui::text::AnnotatedString::from("Recovered software text");
327
328        let poison_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
329            let _guard = measurer
330                .cache
331                .lock()
332                .unwrap_or_else(PoisonError::into_inner);
333            panic!("poison software text metrics cache for recovery test");
334        }));
335
336        assert!(poison_result.is_err());
337
338        let metrics = measurer.measure(&text, &cranpose_ui::text::TextStyle::default());
339        assert!(metrics.width > 0.0);
340        assert!(metrics.height > 0.0);
341    }
342}