1use 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#[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 glyph_line_box(&self, style: &cranpose_ui::text::TextStyle) -> Option<(f32, f32)> {
181 let font = self.text_resources.fonts().resolve(style)?;
182 Some(crate::software_text_raster::font_glyph_line_box(
183 style, font,
184 ))
185 }
186
187 fn first_baseline(&self, style: &cranpose_ui::text::TextStyle) -> Option<f32> {
188 Some(self.line_box(style)?.baseline)
189 }
190
191 fn line_box(&self, style: &cranpose_ui::text::TextStyle) -> Option<cranpose_ui::text::LineBox> {
192 let font = self.text_resources.fonts().resolve(style)?;
193 Some(crate::software_text_raster::font_line_box(
194 style,
195 font,
196 resolve_font_size(style),
197 ))
198 }
199
200 fn measure(
201 &self,
202 text: &cranpose_ui::text::AnnotatedString,
203 style: &cranpose_ui::text::TextStyle,
204 ) -> TextMetrics {
205 let text_str = text.text.as_str();
206 let font_size = resolve_font_size(style);
207 let style_hash = style.measurement_hash();
208 self.lock_cache()
209 .get_or_measure(text_str, font_size, style_hash, |value, size| {
210 measure_text_impl(
211 value,
212 style,
213 size,
214 self.text_resources.fonts().resolve(style),
215 )
216 })
217 }
218
219 fn get_offset_for_position(
220 &self,
221 text: &cranpose_ui::text::AnnotatedString,
222 style: &cranpose_ui::text::TextStyle,
223 x: f32,
224 _y: f32,
225 ) -> usize {
226 let text = text.text.as_str();
227 if text.is_empty() {
228 return 0;
229 }
230
231 let Some(font) = self.text_resources.fonts().resolve(style) else {
232 let font_size = resolve_font_size(style);
233 return TextLayoutResult::monospaced(
234 text,
235 fallback_char_width(font_size),
236 fallback_line_height(font_size),
237 )
238 .get_offset_for_x(x);
239 };
240
241 text_offset_for_position_with_font(text, style, x, _y, font)
242 }
243
244 fn get_cursor_x_for_offset(
245 &self,
246 text: &cranpose_ui::text::AnnotatedString,
247 style: &cranpose_ui::text::TextStyle,
248 offset: usize,
249 ) -> f32 {
250 let text = text.text.as_str();
251 let clamped_offset = offset.min(text.len());
252 if clamped_offset == 0 {
253 return 0.0;
254 }
255
256 let Some(font) = self.text_resources.fonts().resolve(style) else {
257 return fallback_cursor_x_for_byte_offset(
258 text,
259 clamped_offset,
260 resolve_font_size(style),
261 );
262 };
263
264 cursor_x_for_offset_with_font(text, style, clamped_offset, font)
265 }
266
267 fn layout(
268 &self,
269 text: &cranpose_ui::text::AnnotatedString,
270 style: &cranpose_ui::text::TextStyle,
271 ) -> cranpose_ui::text_layout_result::TextLayoutResult {
272 let font_size = resolve_font_size(style);
273 let Some(font) = self.text_resources.fonts().resolve(style) else {
274 return TextLayoutResult::monospaced(
275 text.text.as_str(),
276 fallback_char_width(font_size),
277 fallback_line_height(font_size),
278 );
279 };
280
281 layout_text_with_font(text.text.as_str(), style, font)
282 }
283
284 fn choose_auto_hyphen_break(
285 &self,
286 line: &str,
287 style: &cranpose_ui::text::TextStyle,
288 segment_start_char: usize,
289 measured_break_char: usize,
290 ) -> Option<usize> {
291 self.hyphenation.choose_auto_hyphen_break(
292 line,
293 style,
294 segment_start_char,
295 measured_break_char,
296 )
297 }
298}
299
300fn measure_text_impl(
301 text: &str,
302 style: &cranpose_ui::text::TextStyle,
303 font_size: f32,
304 font: Option<&SoftwareTextFont>,
305) -> TextMetrics {
306 let Some(font) = font else {
307 return fallback_text_metrics(text, font_size);
308 };
309
310 measure_text_with_font(text, style, font_size, font)
311}
312
313#[cfg(test)]
314#[path = "tests/text_measure_tests.rs"]
315mod tests;