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},
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
172            .lock()
173            .unwrap_or_else(|poisoned| poisoned.into_inner())
174    }
175}
176
177fn resolve_font_size(style: &cranpose_ui::text::TextStyle) -> f32 {
178    style.resolve_font_size(14.0)
179}
180
181impl TextMeasurer for CachedFontTextMeasurer {
182    fn measure(
183        &self,
184        text: &cranpose_ui::text::AnnotatedString,
185        style: &cranpose_ui::text::TextStyle,
186    ) -> TextMetrics {
187        let text_str = text.text.as_str();
188        let font_size = resolve_font_size(style);
189        let style_hash = style.measurement_hash();
190        self.lock_cache()
191            .get_or_measure(text_str, font_size, style_hash, |value, size| {
192                measure_text_impl(
193                    value,
194                    style,
195                    size,
196                    self.text_resources.fonts().resolve(style),
197                )
198            })
199    }
200
201    fn get_offset_for_position(
202        &self,
203        text: &cranpose_ui::text::AnnotatedString,
204        style: &cranpose_ui::text::TextStyle,
205        x: f32,
206        _y: f32,
207    ) -> usize {
208        let text = text.text.as_str();
209        if text.is_empty() {
210            return 0;
211        }
212
213        let Some(font) = self.text_resources.fonts().resolve(style) else {
214            let font_size = resolve_font_size(style);
215            return TextLayoutResult::monospaced(
216                text,
217                fallback_char_width(font_size),
218                fallback_line_height(font_size),
219            )
220            .get_offset_for_x(x);
221        };
222
223        text_offset_for_position_with_font(text, style, x, _y, font)
224    }
225
226    fn get_cursor_x_for_offset(
227        &self,
228        text: &cranpose_ui::text::AnnotatedString,
229        style: &cranpose_ui::text::TextStyle,
230        offset: usize,
231    ) -> f32 {
232        let text = text.text.as_str();
233        let clamped_offset = offset.min(text.len());
234        if clamped_offset == 0 {
235            return 0.0;
236        }
237
238        let Some(font) = self.text_resources.fonts().resolve(style) else {
239            return fallback_cursor_x_for_byte_offset(
240                text,
241                clamped_offset,
242                resolve_font_size(style),
243            );
244        };
245
246        cursor_x_for_offset_with_font(text, style, clamped_offset, font)
247    }
248
249    fn layout(
250        &self,
251        text: &cranpose_ui::text::AnnotatedString,
252        style: &cranpose_ui::text::TextStyle,
253    ) -> cranpose_ui::text_layout_result::TextLayoutResult {
254        let font_size = resolve_font_size(style);
255        let Some(font) = self.text_resources.fonts().resolve(style) else {
256            return TextLayoutResult::monospaced(
257                text.text.as_str(),
258                fallback_char_width(font_size),
259                fallback_line_height(font_size),
260            );
261        };
262
263        layout_text_with_font(text.text.as_str(), style, font)
264    }
265
266    fn choose_auto_hyphen_break(
267        &self,
268        line: &str,
269        style: &cranpose_ui::text::TextStyle,
270        segment_start_char: usize,
271        measured_break_char: usize,
272    ) -> Option<usize> {
273        self.hyphenation.choose_auto_hyphen_break(
274            line,
275            style,
276            segment_start_char,
277            measured_break_char,
278        )
279    }
280}
281
282fn measure_text_impl(
283    text: &str,
284    style: &cranpose_ui::text::TextStyle,
285    font_size: f32,
286    font: Option<&SoftwareTextFont>,
287) -> TextMetrics {
288    let Some(font) = font else {
289        return fallback_text_metrics(text, font_size);
290    };
291
292    measure_text_with_font(text, style, font_size, font)
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298
299    #[test]
300    fn fallback_text_metrics_cover_empty_and_multiline_text() {
301        let empty = fallback_text_metrics("", 10.0);
302        assert_eq!(empty.line_count, 1);
303        assert_eq!(empty.width, 0.0);
304        assert_eq!(empty.height, fallback_line_height(10.0));
305
306        let multiline = fallback_text_metrics("ab\ncde", 10.0);
307        assert_eq!(multiline.line_count, 2);
308        assert_eq!(multiline.width, 3.0 * fallback_char_width(10.0));
309        assert_eq!(multiline.height, 2.0 * fallback_line_height(10.0));
310    }
311
312    #[test]
313    fn fallback_cursor_position_handles_non_boundary_byte_offsets() {
314        let text = "éx";
315        let width = fallback_char_width(12.0);
316        assert_eq!(fallback_cursor_x_for_byte_offset(text, 0, 12.0), 0.0);
317        assert_eq!(fallback_cursor_x_for_byte_offset(text, 1, 12.0), width);
318        assert_eq!(
319            fallback_cursor_x_for_byte_offset(text, text.len(), 12.0),
320            width * 2.0
321        );
322    }
323
324    #[test]
325    fn cached_font_text_metrics_cache_recovers_after_poison() {
326        let measurer =
327            CachedFontTextMeasurer::with_text_resources(SoftwareTextResources::default(), 8);
328        let text = cranpose_ui::text::AnnotatedString::from("Recovered software text");
329
330        let poison_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
331            let _guard = measurer
332                .cache
333                .lock()
334                .unwrap_or_else(|poisoned| poisoned.into_inner());
335            panic!("poison software text metrics cache for recovery test");
336        }));
337
338        assert!(poison_result.is_err());
339
340        let metrics = measurer.measure(&text, &cranpose_ui::text::TextStyle::default());
341        assert!(metrics.width > 0.0);
342        assert!(metrics.height > 0.0);
343    }
344}