Skip to main content

repose_text/
lib.rs

1use font_awl::FontProvider;
2use once_cell::sync::OnceCell;
3use rapidhash::{HashMapExt, RapidHashMap, fast::RapidHasher};
4use skrifa::outline::OutlinePen;
5use skrifa::MetadataProvider;
6
7use std::sync::atomic::{AtomicU64, Ordering};
8use std::{
9    collections::{HashMap, VecDeque},
10    hash::{Hash, Hasher},
11    sync::Mutex,
12};
13use unicode_segmentation::UnicodeSegmentation;
14
15static FRAME_COUNTER: AtomicU64 = AtomicU64::new(0);
16
17pub fn begin_frame() {
18    FRAME_COUNTER.fetch_add(1, Ordering::Relaxed);
19}
20
21pub fn current_frame() -> u64 {
22    FRAME_COUNTER.load(Ordering::Relaxed)
23}
24
25const GLYPH_CACHE_CAP: usize = 4096;
26const WRAP_CACHE_CAP: usize = 1024;
27const ELLIP_CACHE_CAP: usize = 2048;
28
29static METRICS_LRU: OnceCell<Mutex<Lru<(u64, u32, u64, u16, u8, i32), TextMetrics>>> =
30    OnceCell::new();
31fn metrics_cache() -> &'static Mutex<Lru<(u64, u32, u64, u16, u8, i32), TextMetrics>> {
32    METRICS_LRU.get_or_init(|| Mutex::new(Lru::new(4096)))
33}
34
35struct Lru<K, V> {
36    map: RapidHashMap<K, V>,
37    order: VecDeque<K>,
38    cap: usize,
39}
40impl<K: std::hash::Hash + Eq + Clone, V> Lru<K, V> {
41    fn new(cap: usize) -> Self {
42        Self {
43            map: RapidHashMap::new(),
44            order: VecDeque::new(),
45            cap,
46        }
47    }
48    fn get(&mut self, k: &K) -> Option<&V> {
49        if self.map.contains_key(k) {
50            if let Some(pos) = self.order.iter().position(|x| x == k) {
51                let key = self.order.remove(pos).unwrap();
52                self.order.push_back(key);
53            }
54        }
55        self.map.get(k)
56    }
57    fn put(&mut self, k: K, v: V) {
58        if self.map.contains_key(&k) {
59            self.map.insert(k.clone(), v);
60            if let Some(pos) = self.order.iter().position(|x| x == &k) {
61                let key = self.order.remove(pos).unwrap();
62                self.order.push_back(key);
63            }
64            return;
65        }
66        if self.map.len() >= self.cap
67            && let Some(old) = self.order.pop_front()
68        {
69            self.map.remove(&old);
70        }
71        self.order.push_back(k.clone());
72        self.map.insert(k, v);
73    }
74}
75
76static WRAP_LRU: OnceCell<
77    Mutex<Lru<(u64, u32, u32, u16, bool, u16, u8, i32), (Vec<String>, bool)>>,
78> = OnceCell::new();
79
80static WRAP_RANGES_LRU: OnceCell<
81    Mutex<Lru<(u64, u32, u32, u16, bool, u16, u8, i32), (Vec<(usize, usize)>, bool)>>,
82> = OnceCell::new();
83
84static ELLIP_LRU: OnceCell<Mutex<Lru<(u64, u32, u32, u16, u8, i32), String>>> = OnceCell::new();
85
86fn wrap_cache() -> &'static Mutex<Lru<(u64, u32, u32, u16, bool, u16, u8, i32), (Vec<String>, bool)>>
87{
88    WRAP_LRU.get_or_init(|| Mutex::new(Lru::new(WRAP_CACHE_CAP)))
89}
90
91fn wrap_ranges_cache()
92-> &'static Mutex<Lru<(u64, u32, u32, u16, bool, u16, u8, i32), (Vec<(usize, usize)>, bool)>> {
93    WRAP_RANGES_LRU.get_or_init(|| Mutex::new(Lru::new(WRAP_CACHE_CAP)))
94}
95
96fn ellip_cache() -> &'static Mutex<Lru<(u64, u32, u32, u16, u8, i32), String>> {
97    ELLIP_LRU.get_or_init(|| Mutex::new(Lru::new(ELLIP_CACHE_CAP)))
98}
99
100fn fast_hash(s: &str) -> u64 {
101    let mut h = RapidHasher::default();
102    s.len().hash(&mut h);
103    s.hash(&mut h);
104    h.finish()
105}
106
107#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
108pub struct GlyphKey(pub u64);
109
110/// Cache key for the renderer's glyph slug cache — uniquely identifies a
111/// specific glyph in a specific font face.
112#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
113pub struct CacheKey {
114    pub font_id: u64,
115    pub glyph_id: u16,
116    pub font_size_bits: u32,
117}
118
119/// Vector path command for glyph outlines.
120#[derive(Clone, Debug)]
121pub enum Command {
122    MoveTo(f32, f32),
123    LineTo(f32, f32),
124    QuadTo(f32, f32, f32, f32),
125    CurveTo(f32, f32, f32, f32, f32, f32),
126    Close,
127}
128
129pub struct ShapedGlyph {
130    pub key: GlyphKey,
131    pub px: f32,
132    pub x: f32,
133    pub y: f32,
134    pub w: f32,
135    pub h: f32,
136    pub bearing_x: f32,
137    pub bearing_y: f32,
138    pub advance: f32,
139}
140
141pub use swash::scale::image::Content as SwashContent;
142
143pub struct GlyphBitmap {
144    pub key: GlyphKey,
145    pub w: u32,
146    pub h: u32,
147    pub content: SwashContent,
148    pub data: Vec<u8>,
149}
150
151struct FontRecord {
152    id: u64,
153    data: parley::FontData,
154    data_bytes: Vec<u8>,
155}
156
157struct Engine {
158    font_cx: parley::FontContext,
159    layout_cx: parley::LayoutContext<()>,
160    swash_cx: swash::scale::ScaleContext,
161    key_map: HashMap<GlyphKey, (u64, u16)>,
162    font_registry: Vec<FontRecord>,
163    next_font_id: u64,
164    /// Cache of rendered glyphs keyed by (font_id, glyph_id, font_size_bits).
165    /// Contains (width, height, left, top, content, data).
166    glyph_cache: HashMap<(u64, u16, u32), (u32, u32, i32, i32, swash::scale::image::Content, Vec<u8>)>,
167}
168
169impl Engine {
170    fn ensure_font(&mut self, fd: &parley::FontData) -> u64 {
171        if let Some(existing) = self
172            .font_registry
173            .iter()
174            .find(|r| r.data == *fd)
175        {
176            log::debug!("[font] reuse id={} len={}", existing.id, fd.data.as_ref().len());
177            return existing.id;
178        }
179        let id = self.next_font_id;
180        self.next_font_id += 1;
181        let bytes = fd.data.as_ref().to_vec();
182        log::debug!("[font] register id={} len={}", id, bytes.len());
183        self.font_registry.push(FontRecord {
184            id,
185            data: fd.clone(),
186            data_bytes: bytes,
187        });
188        id
189    }
190
191    fn trim_glyph_cache(&mut self) {
192        if self.glyph_cache.len() > GLYPH_CACHE_CAP {
193            let to_remove = self.glyph_cache.len() - GLYPH_CACHE_CAP;
194            let keys: Vec<_> = self.glyph_cache.keys().take(to_remove).copied().collect();
195            for k in keys {
196                self.glyph_cache.remove(&k);
197            }
198        }
199    }
200
201    fn raster_placement(
202        &mut self,
203        font_id: u64,
204        glyph_id: u16,
205        px: f32,
206    ) -> Option<(f32, f32, f32, f32)> {
207        use swash::scale::{Render, Source, StrikeWith};
208        let cache_key = (font_id, glyph_id, px.to_bits());
209        if let Some(cached) = self.glyph_cache.get(&cache_key) {
210            log::debug!("[raster_placement] HIT fid={} gid={} px={} => {}x{} {}x{}", font_id, glyph_id, px, cached.0, cached.1, cached.2, cached.3);
211            return Some((cached.0 as f32, cached.1 as f32, cached.2 as f32, cached.3 as f32));
212        }
213        let data_bytes = self
214            .font_registry
215            .iter()
216            .find(|r| r.id == font_id)?
217            .data_bytes
218            .clone();
219        let font = swash::FontRef::from_index(&data_bytes, 0)?;
220        let mut scaler = self
221            .swash_cx
222            .builder(font)
223            .size(px)
224            .hint(true)
225            .build();
226        let image = Render::new(&[
227            Source::Outline,
228            Source::ColorBitmap(StrikeWith::BestFit),
229            Source::ColorOutline(0),
230        ])
231        .render(&mut scaler, glyph_id)?;
232        log::debug!("[raster_placement] MISS fid={} gid={} px={} => {}x{} {}x{}", font_id, glyph_id, px, image.placement.width, image.placement.height, image.placement.left, image.placement.top);
233        self.glyph_cache.insert(
234            cache_key,
235            (
236                image.placement.width,
237                image.placement.height,
238                image.placement.left,
239                image.placement.top,
240                image.content,
241                image.data,
242            ),
243        );
244        self.trim_glyph_cache();
245        Some((
246            image.placement.width as f32,
247            image.placement.height as f32,
248            image.placement.left as f32,
249            image.placement.top as f32,
250        ))
251    }
252}
253
254static ENGINE: OnceCell<Mutex<Engine>> = OnceCell::new();
255
256pub static FONT_PROVIDER: OnceCell<Mutex<font_awl::Provider>> = OnceCell::new();
257
258fn init_engine_sync() -> Engine {
259    let mut provider = font_awl::Provider::new();
260    provider.load_bundled_fonts();
261    #[cfg(not(target_arch = "wasm32"))]
262    if let Err(e) = provider.load_system_fonts_best_effort() {
263        log::warn!("font-awl: failed to load system fonts: {e}");
264    }
265
266    let mut font_cx = provider.new_parley_context();
267    let layout_cx = parley::LayoutContext::new();
268
269    static MATERIAL_SYMBOLS_TTF: &[u8] =
270        include_bytes!("assets/MaterialSymbolsOutlined.ttf");
271    let blob: parley::fontique::Blob<u8> = MATERIAL_SYMBOLS_TTF.to_vec().into();
272    font_cx.collection.register_fonts(blob, None);
273
274    let _ = FONT_PROVIDER.set(Mutex::new(provider));
275
276    Engine {
277        font_cx,
278        layout_cx,
279        swash_cx: swash::scale::ScaleContext::new(),
280        key_map: HashMap::new(),
281        font_registry: Vec::new(),
282        next_font_id: 1,
283        glyph_cache: HashMap::new(),
284    }
285}
286
287#[cfg(target_arch = "wasm32")]
288pub async fn init_fonts_wasm() {
289    let mut provider = font_awl::Provider::new();
290    provider.load_bundled_fonts();
291    if let Err(e) = provider.load_web_fonts().await {
292        log::warn!("font-awl: failed to load web fonts: {e}");
293    }
294    let _ = FONT_PROVIDER.set(Mutex::new(provider));
295
296    if let Some(eng) = ENGINE.get() {
297        let mut eng = eng.lock().unwrap();
298        // Register web fonts into the existing engine's collection
299        // by re-building font_cx from the updated provider
300        if let Some(provider_lock) = FONT_PROVIDER.get() {
301            let p = provider_lock.lock().unwrap();
302            eng.font_cx = p.new_parley_context();
303        }
304    }
305}
306
307fn engine() -> &'static Mutex<Engine> {
308    ENGINE.get_or_init(|| Mutex::new(init_engine_sync()))
309}
310
311pub fn register_font_data(bytes: &[u8]) {
312    let mut eng = engine().lock().unwrap();
313    let blob: parley::fontique::Blob<u8> = bytes.to_vec().into();
314    eng.font_cx.collection.register_fonts(blob.clone(), None);
315    if let Some(provider_lock) = FONT_PROVIDER.get() {
316        let mut p = provider_lock.lock().unwrap();
317        p.collection_mut().register_fonts(blob, None);
318    }
319}
320
321/// Load a font from a file path and register it into the global font system.
322///
323/// Returns an error if the file cannot be read.
324pub fn load_font_file(path: impl AsRef<std::path::Path>) -> std::io::Result<()> {
325    let bytes = std::fs::read(path)?;
326    register_font_data(&bytes);
327    Ok(())
328}
329
330/// Extract the family name from raw font bytes.
331///
332/// Tries the typographic family name first, falling back to the standard family name.
333/// Returns `None` if the font data is invalid or contains no names.
334pub fn font_family_name(bytes: &[u8]) -> Option<String> {
335    use skrifa::string::StringId;
336    let font = skrifa::FontRef::new(bytes).ok()?;
337    font.localized_strings(StringId::TYPOGRAPHIC_FAMILY_NAME)
338        .english_or_first()
339        .map(|s| s.to_string())
340        .or_else(|| {
341            font.localized_strings(StringId::FAMILY_NAME)
342                .english_or_first()
343                .map(|s| s.to_string())
344        })
345}
346
347fn key_from_pair(font_id: u64, glyph_id: u16) -> GlyphKey {
348    let mut h = RapidHasher::default();
349    font_id.hash(&mut h);
350    glyph_id.hash(&mut h);
351    GlyphKey(h.finish())
352}
353
354fn shape_line_inner(
355    eng: &mut Engine,
356    text: &str,
357    px: f32,
358    font_family: Option<&str>,
359    font_weight: u16,
360    font_style: u8,
361    letter_spacing: f32,
362) -> Vec<ShapedGlyph> {
363    use parley::style::StyleProperty;
364    use parley::FontWeight;
365    use parley::layout::PositionedLayoutItem;
366
367    let Engine {
368        ref mut font_cx,
369        ref mut layout_cx,
370        ..
371    } = *eng;
372    let mut builder = layout_cx.ranged_builder(font_cx, text, 1.0, true);
373    builder.push_default(StyleProperty::FontSize(px));
374    builder.push_default(StyleProperty::FontWeight(FontWeight::new(font_weight as f32)));
375    builder.push_default(StyleProperty::FontStyle(match font_style {
376        1 => parley::FontStyle::Italic,
377        _ => parley::FontStyle::Normal,
378    }));
379    builder.push_default(StyleProperty::LetterSpacing(letter_spacing));
380
381    if let Some(family) = font_family {
382        use parley::style::{FontFamilyName, GenericFamily};
383        let names: &[FontFamilyName] = match family {
384            "monospace" => &[
385                FontFamilyName::named("JetBrains Mono"),
386                GenericFamily::Monospace.into(),
387            ],
388            "sans-serif" => &[
389                FontFamilyName::named("Open Sans"),
390                GenericFamily::SansSerif.into(),
391            ],
392            "emoji" => &[
393                FontFamilyName::named("Noto Color Emoji"),
394                GenericFamily::Emoji.into(),
395            ],
396            "serif" => &[GenericFamily::Serif.into()],
397            "cursive" => &[GenericFamily::Cursive.into()],
398            "fantasy" => &[GenericFamily::Fantasy.into()],
399            "system-ui" => &[GenericFamily::SystemUi.into()],
400            "math" => &[GenericFamily::Math.into()],
401            _ => &[FontFamilyName::named(family)],
402        };
403        builder.push(names, 0..text.len());
404    }
405
406    let mut layout = builder.build(text);
407    layout.break_all_lines(None);
408    layout.align(
409        parley::Alignment::Start,
410        parley::AlignmentOptions::default(),
411    );
412
413    let mut out: Vec<ShapedGlyph> = Vec::new();
414    for line in layout.lines() {
415        for item in line.items() {
416            let PositionedLayoutItem::GlyphRun(glyph_run) = item else { continue };
417            let font_data = glyph_run.run().font();
418            let fid = eng.ensure_font(font_data);
419            log::debug!("[shape] run: fid={} font_data_len={}", fid, font_data.data.as_ref().len());
420            for g in glyph_run.positioned_glyphs() {
421                let gid = g.id as u16;
422                let key = key_from_pair(fid, gid);
423                eng.key_map.insert(key, (fid, gid));
424
425                let (w, h, left, top) = eng
426                    .raster_placement(fid, gid, px)
427                    .unwrap_or((0.0, 0.0, 0.0, 0.0));
428
429                log::debug!(
430                    "[shape] glyph: gid={} px={} x={:.1} y={:.1} advance={:.1} bitmap={}x{} {}x{}",
431                    gid, px, g.x, g.y, g.advance, w, h, left, top,
432                );
433
434                out.push(ShapedGlyph {
435                    key,
436                    px,
437                    x: g.x,
438                    y: g.y,
439                    w,
440                    h,
441                    bearing_x: left,
442                    bearing_y: top,
443                    advance: g.advance + letter_spacing,
444                });
445            }
446        }
447    }
448    out
449}
450
451pub fn shape_line(
452    text: &str,
453    px: f32,
454    font_family: Option<&str>,
455    font_weight: u16,
456    font_style: u8,
457    letter_spacing: f32,
458) -> Vec<ShapedGlyph> {
459    let mut eng = engine().lock().unwrap();
460    shape_line_inner(&mut eng, text, px, font_family, font_weight, font_style, letter_spacing)
461}
462
463pub fn rasterize(key: GlyphKey, px: f32) -> Option<GlyphBitmap> {
464    use swash::scale::{Render, Source, StrikeWith};
465    let mut eng = engine().lock().unwrap();
466    let &(fid, gid) = eng.key_map.get(&key)?;
467    let cache_key = (fid, gid, px.to_bits());
468    if let Some(cached) = eng.glyph_cache.get(&cache_key) {
469        log::debug!("[rasterize] HIT fid={} gid={} px={} => {}x{}", fid, gid, px, cached.0, cached.1);
470        return Some(GlyphBitmap {
471            key,
472            w: cached.0,
473            h: cached.1,
474            content: cached.4,
475            data: cached.5.clone(),
476        });
477    }
478    let data_bytes = eng
479        .font_registry
480        .iter()
481        .find(|r| r.id == fid)?
482        .data_bytes
483        .clone();
484    let font = swash::FontRef::from_index(&data_bytes, 0)?;
485    let mut scaler = eng
486        .swash_cx
487        .builder(font)
488        .size(px)
489        .hint(true)
490        .build();
491    let image = Render::new(&[
492        Source::Outline,
493        Source::ColorBitmap(StrikeWith::BestFit),
494        Source::ColorOutline(0),
495    ])
496    .render(&mut scaler, gid)?;
497    log::debug!("[rasterize] MISS fid={} gid={} px={} => {}x{}", fid, gid, px, image.placement.width, image.placement.height);
498    let bitmap = GlyphBitmap {
499        key,
500        w: image.placement.width,
501        h: image.placement.height,
502        content: image.content,
503        data: image.data,
504    };
505    eng.glyph_cache.insert(
506        cache_key,
507        (
508            bitmap.w,
509            bitmap.h,
510            image.placement.left,
511            image.placement.top,
512            bitmap.content,
513            bitmap.data.clone(),
514        ),
515    );
516    eng.trim_glyph_cache();
517    Some(bitmap)
518}
519
520pub fn lookup_cache_key(key: GlyphKey, px: f32) -> Option<CacheKey> {
521    let eng = engine().lock().unwrap();
522    let &(fid, gid) = eng.key_map.get(&key)?;
523    Some(CacheKey {
524        font_id: fid,
525        glyph_id: gid,
526        font_size_bits: px.to_bits(),
527    })
528}
529
530fn extract_outlines_for(
531    data_bytes: &[u8],
532    glyph_id: u16,
533) -> Option<Box<[Command]>> {
534    let font = skrifa::FontRef::new(data_bytes).ok()?;
535    let mut pen = OutlinePenCollector(Vec::new());
536    font.outline_glyphs()
537        .get(skrifa::GlyphId::new(glyph_id as u32))?
538        .draw(skrifa::instance::Size::new(1.0), &mut pen)
539        .ok()?;
540    Some(pen.0.into_boxed_slice())
541}
542
543pub fn extract_outline_commands(cache_key: CacheKey) -> Option<Box<[Command]>> {
544    let eng = engine().lock().unwrap();
545    let record = eng
546        .font_registry
547        .iter()
548        .find(|r| r.id == cache_key.font_id)?;
549    extract_outlines_for(&record.data_bytes, cache_key.glyph_id)
550}
551
552pub fn lookup_and_extract_outline(
553    key: GlyphKey,
554    px: f32,
555) -> Option<(CacheKey, Box<[Command]>)> {
556    let eng = engine().lock().unwrap();
557    let &(fid, gid) = eng.key_map.get(&key)?;
558    let record = eng.font_registry.iter().find(|r| r.id == fid)?;
559    let ck = CacheKey {
560        font_id: fid,
561        glyph_id: gid,
562        font_size_bits: px.to_bits(),
563    };
564    let cmds = extract_outlines_for(&record.data_bytes, gid)?;
565    Some((ck, cmds))
566}
567
568struct OutlinePenCollector(Vec<Command>);
569
570impl OutlinePen for OutlinePenCollector {
571    fn move_to(&mut self, x: f32, y: f32) {
572        self.0.push(Command::MoveTo(x, y));
573    }
574    fn line_to(&mut self, x: f32, y: f32) {
575        self.0.push(Command::LineTo(x, y));
576    }
577    fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) {
578        self.0.push(Command::QuadTo(cx0, cy0, x, y));
579    }
580    fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {
581        self.0.push(Command::CurveTo(cx0, cy0, cx1, cy1, x, y));
582    }
583    fn close(&mut self) {
584        self.0.push(Command::Close);
585    }
586}
587
588#[derive(Clone)]
589pub struct TextMetrics {
590    pub positions: Vec<f32>,
591    pub byte_offsets: Vec<usize>,
592}
593
594pub fn metrics_for_textfield(
595    text: &str,
596    px: f32,
597    font_family: Option<&str>,
598    font_weight: u16,
599    font_style: u8,
600    letter_spacing: f32,
601) -> TextMetrics {
602    let family_hash = font_family.map(fast_hash).unwrap_or(0);
603    let key = (
604        fast_hash(text),
605        (px * 100.0) as u32,
606        family_hash,
607        font_weight,
608        font_style,
609        (letter_spacing * 100.0) as i32,
610    );
611    if let Some(m) = metrics_cache().lock().unwrap().get(&key).cloned() {
612        return m;
613    }
614    let mut eng = engine().lock().unwrap();
615
616    use parley::style::StyleProperty;
617    use parley::FontWeight;
618
619    let Engine {
620        ref mut font_cx,
621        ref mut layout_cx,
622        ..
623    } = *eng;
624    let mut builder = layout_cx.ranged_builder(font_cx, text, 1.0, true);
625    builder.push_default(StyleProperty::FontSize(px));
626    builder.push_default(StyleProperty::FontWeight(FontWeight::new(font_weight as f32)));
627    builder.push_default(StyleProperty::FontStyle(match font_style {
628        1 => parley::FontStyle::Italic,
629        _ => parley::FontStyle::Normal,
630    }));
631    builder.push_default(StyleProperty::LetterSpacing(letter_spacing));
632    if let Some(family) = font_family {
633        use parley::style::{FontFamilyName, GenericFamily};
634        let names: &[FontFamilyName] = match family {
635            "monospace" => &[
636                FontFamilyName::named("JetBrains Mono"),
637                GenericFamily::Monospace.into(),
638            ],
639            "sans-serif" => &[
640                FontFamilyName::named("Open Sans"),
641                GenericFamily::SansSerif.into(),
642            ],
643            "emoji" => &[
644                FontFamilyName::named("Noto Color Emoji"),
645                GenericFamily::Emoji.into(),
646            ],
647            "serif" => &[GenericFamily::Serif.into()],
648            "cursive" => &[GenericFamily::Cursive.into()],
649            "fantasy" => &[GenericFamily::Fantasy.into()],
650            "system-ui" => &[GenericFamily::SystemUi.into()],
651            "math" => &[GenericFamily::Math.into()],
652            _ => &[FontFamilyName::named(family)],
653        };
654        builder.push(names, 0..text.len());
655    }
656
657    let mut layout = builder.build(text);
658    layout.break_all_lines(None);
659    layout.align(
660        parley::Alignment::Start,
661        parley::AlignmentOptions::default(),
662    );
663
664    let mut edges: Vec<(usize, f32)> = Vec::new();
665    let mut last_x = 0.0f32;
666    let mut glyph_idx = 0usize;
667    for line in layout.lines() {
668        for item in line.items() {
669            let parley::layout::PositionedLayoutItem::GlyphRun(glyph_run) = item else { continue };
670            let run_offset = glyph_run.offset();
671            let run = glyph_run.run();
672            let mut cluster_offset = run_offset;
673            for cluster in run.clusters() {
674                let range = cluster.text_range();
675                for g in cluster.glyphs() {
676                    let shift = glyph_idx as f32 * letter_spacing;
677                    let x_pos = cluster_offset + g.x;
678                    let right = x_pos + shift + g.advance + letter_spacing;
679                    last_x = right.max(last_x);
680                    edges.push((range.end, right));
681                    glyph_idx += 1;
682                    cluster_offset += g.advance;
683                }
684            }
685        }
686    }
687    if edges.last().map(|e| e.0) != Some(text.len()) {
688        edges.push((text.len(), last_x));
689    }
690
691    let mut positions = Vec::with_capacity(text.graphemes(true).count() + 1);
692    let mut byte_offsets = Vec::with_capacity(positions.capacity());
693    positions.push(0.0);
694    byte_offsets.push(0);
695    let mut last_byte = 0usize;
696    for (b, _) in text.grapheme_indices(true) {
697        positions.push(
698            positions.last().copied().unwrap_or(0.0) + width_between(&edges, last_byte, b),
699        );
700        byte_offsets.push(b);
701        last_byte = b;
702    }
703    if *byte_offsets.last().unwrap_or(&0) != text.len() {
704        positions.push(
705            positions.last().copied().unwrap_or(0.0) + width_between(&edges, last_byte, text.len()),
706        );
707        byte_offsets.push(text.len());
708    }
709    let m = TextMetrics {
710        positions,
711        byte_offsets,
712    };
713    metrics_cache().lock().unwrap().put(key, m.clone());
714    m
715}
716
717fn width_between(edges: &[(usize, f32)], start_b: usize, end_b: usize) -> f32 {
718    let x0 = lookup_right(edges, start_b);
719    let x1 = lookup_right(edges, end_b);
720    (x1 - x0).max(0.0)
721}
722fn lookup_right(edges: &[(usize, f32)], b: usize) -> f32 {
723    match edges.binary_search_by_key(&b, |e| e.0) {
724        Ok(i) => edges[i].1,
725        Err(i) => {
726            if i == 0 {
727                0.0
728            } else {
729                edges[i - 1].1
730            }
731        }
732    }
733}
734
735pub fn wrap_lines(
736    text: &str,
737    px: f32,
738    max_width: f32,
739    max_lines: Option<usize>,
740    soft_wrap: bool,
741    font_weight: u16,
742    font_style: u8,
743    letter_spacing: f32,
744) -> (Vec<String>, bool) {
745    if text.is_empty() || max_width <= 0.0 {
746        return (vec![String::new()], false);
747    }
748    if !soft_wrap {
749        return (vec![text.to_string()], false);
750    }
751
752    let max_lines_key: u16 = match max_lines {
753        None => 0,
754        Some(n) => {
755            let n = n.min(u16::MAX as usize - 1) as u16;
756            n.saturating_add(1)
757        }
758    };
759    let key = (
760        fast_hash(text),
761        (px * 100.0) as u32,
762        (max_width * 100.0) as u32,
763        max_lines_key,
764        soft_wrap,
765        font_weight,
766        font_style,
767        (letter_spacing * 100.0) as i32,
768    );
769    if let Some(h) = wrap_cache().lock().unwrap().get(&key).cloned() {
770        return h;
771    }
772
773    let m = metrics_for_textfield(text, px, None, font_weight, font_style, letter_spacing);
774    if let Some(&last) = m.positions.last()
775        && last <= max_width + 0.5
776    {
777        return (vec![text.to_string()], false);
778    }
779
780    let width_of = |start_b: usize, end_b: usize| -> f32 {
781        let i0 = match m.byte_offsets.binary_search(&start_b) {
782            Ok(i) | Err(i) => i,
783        };
784        let i1 = match m.byte_offsets.binary_search(&end_b) {
785            Ok(i) | Err(i) => i,
786        };
787        (m.positions.get(i1).copied().unwrap_or(0.0) - m.positions.get(i0).copied().unwrap_or(0.0))
788            .max(0.0)
789    };
790
791    let mut out: Vec<String> = Vec::new();
792    let mut truncated = false;
793
794    let mut line_start = 0usize;
795    let mut best_break = line_start;
796
797    for tok in text.split_word_bounds() {
798        let tok_start = best_break;
799        let tok_end = tok_start + tok.len();
800        let w = width_of(line_start, tok_end);
801
802        if w <= max_width + 0.5 {
803            best_break = tok_end;
804            continue;
805        }
806
807        if best_break > line_start {
808            out.push(text[line_start..best_break].trim_end().to_string());
809            line_start = best_break;
810        } else {
811            let mut cut = tok_start;
812            for g in tok.grapheme_indices(true) {
813                let next = tok_start + g.0 + g.1.len();
814                if width_of(line_start, next) <= max_width + 0.5 {
815                    cut = next;
816                } else {
817                    break;
818                }
819            }
820            if cut == line_start {
821                if let Some((ofs, grapheme)) = tok.grapheme_indices(true).next() {
822                    cut = tok_start + ofs + grapheme.len();
823                }
824            }
825            out.push(text[line_start..cut].to_string());
826            line_start = cut;
827        }
828
829        if let Some(ml) = max_lines
830            && out.len() >= ml
831        {
832            truncated = true;
833            line_start = line_start.min(text.len());
834            break;
835        }
836
837        best_break = line_start;
838
839        if line_start < tok_end {
840            if width_of(line_start, tok_end) <= max_width + 0.5 {
841                best_break = tok_end;
842            }
843        }
844    }
845
846    if line_start < text.len() && max_lines.is_none_or(|ml| out.len() < ml) {
847        out.push(text[line_start..].trim_end().to_string());
848    }
849
850    let res = (out, truncated);
851
852    wrap_cache().lock().unwrap().put(key, res.clone());
853    res
854}
855
856pub fn wrap_line_ranges(
857    text: &str,
858    px: f32,
859    max_width: f32,
860    max_lines: Option<usize>,
861    soft_wrap: bool,
862    font_weight: u16,
863    font_style: u8,
864    letter_spacing: f32,
865) -> (Vec<(usize, usize)>, bool) {
866    if text.is_empty() || max_width <= 0.0 {
867        return (vec![(0, 0)], false);
868    }
869    if !soft_wrap {
870        let mut out = Vec::new();
871        let mut start = 0usize;
872        for (i, ch) in text.char_indices() {
873            if ch == '\n' {
874                out.push((start, i));
875                start = i + 1;
876            }
877        }
878        out.push((start, text.len()));
879        return (out, false);
880    }
881
882    let max_lines_key: u16 = match max_lines {
883        None => 0,
884        Some(n) => {
885            let n = n.min(u16::MAX as usize - 1) as u16;
886            n.saturating_add(1)
887        }
888    };
889    let key = (
890        fast_hash(text),
891        (px * 100.0) as u32,
892        (max_width * 100.0) as u32,
893        max_lines_key,
894        soft_wrap,
895        font_weight,
896        font_style,
897        (letter_spacing * 100.0) as i32,
898    );
899    if let Some(v) = wrap_ranges_cache().lock().unwrap().get(&key).cloned() {
900        return v;
901    }
902
903    let m = metrics_for_textfield(text, px, None, font_weight, font_style, letter_spacing);
904
905    let width_of = |start_b: usize, end_b: usize| -> f32 {
906        let i0 = match m.byte_offsets.binary_search(&start_b) {
907            Ok(i) | Err(i) => i,
908        };
909        let i1 = match m.byte_offsets.binary_search(&end_b) {
910            Ok(i) | Err(i) => i,
911        };
912        (m.positions.get(i1).copied().unwrap_or(0.0) - m.positions.get(i0).copied().unwrap_or(0.0))
913            .max(0.0)
914    };
915
916    let mut out: Vec<(usize, usize)> = Vec::new();
917    let mut truncated = false;
918
919    let mut line0_start = 0usize;
920    for (i, ch) in text.char_indices() {
921        if ch == '\n' {
922            let (mut ranges, tr) = wrap_one_hard_line_ranges(
923                text,
924                line0_start,
925                i,
926                max_width,
927                max_lines.map(|ml| ml.saturating_sub(out.len())),
928                &width_of,
929            );
930            out.append(&mut ranges);
931            if tr {
932                truncated = true;
933                break;
934            }
935            line0_start = i + 1;
936
937            if let Some(ml) = max_lines
938                && out.len() >= ml
939            {
940                truncated = true;
941                break;
942            }
943        }
944    }
945    if !truncated {
946        let (mut ranges, tr) = wrap_one_hard_line_ranges(
947            text,
948            line0_start,
949            text.len(),
950            max_width,
951            max_lines.map(|ml| ml.saturating_sub(out.len())),
952            &width_of,
953        );
954        out.append(&mut ranges);
955        truncated = tr;
956    }
957
958    if out.is_empty() {
959        out.push((0, 0));
960    }
961
962    let res = (out, truncated);
963    wrap_ranges_cache().lock().unwrap().put(key, res.clone());
964    res
965}
966
967fn wrap_one_hard_line_ranges(
968    text: &str,
969    start: usize,
970    end: usize,
971    max_width: f32,
972    max_lines: Option<usize>,
973    width_of: &dyn Fn(usize, usize) -> f32,
974) -> (Vec<(usize, usize)>, bool) {
975    let mut out = Vec::new();
976    let mut t = false;
977
978    if start >= end {
979        out.push((start, start));
980        return (out, false);
981    }
982
983    if width_of(start, end) <= max_width + 0.5 {
984        out.push((start, end));
985        return (out, false);
986    }
987
988    let mut line_start = start;
989    let mut best_break = line_start;
990    let mut unconsumed_start = start;
991
992    for tok in text[line_start..end].split_word_bounds() {
993        let tok_abs_start = unconsumed_start;
994        let tok_abs_end = tok_abs_start + tok.len();
995        unconsumed_start = tok_abs_end;
996
997        let w = width_of(line_start, tok_abs_end);
998        if w <= max_width + 0.5 {
999            best_break = tok_abs_end;
1000            continue;
1001        }
1002
1003        if best_break > line_start {
1004            out.push((line_start, best_break));
1005            line_start = best_break;
1006        } else {
1007            let mut cut = tok_abs_start;
1008            for (ofs, g) in tok.grapheme_indices(true) {
1009                let next = tok_abs_start + ofs + g.len();
1010                if width_of(line_start, next) <= max_width + 0.5 {
1011                    cut = next;
1012                } else {
1013                    break;
1014                }
1015            }
1016            if cut == line_start
1017                && let Some((ofs, gr)) = tok.grapheme_indices(true).next()
1018            {
1019                cut = tok_abs_start + ofs + gr.len();
1020            }
1021            out.push((line_start, cut));
1022            line_start = cut;
1023        }
1024
1025        if let Some(ml) = max_lines
1026            && out.len() >= ml
1027        {
1028            t = true;
1029            break;
1030        }
1031
1032        best_break = line_start;
1033    }
1034
1035    if !t && line_start < end && max_lines.is_none_or(|ml| out.len() < ml) {
1036        out.push((line_start, end));
1037    }
1038
1039    (out, t)
1040}
1041
1042pub fn ellipsize_line(
1043    text: &str,
1044    px: f32,
1045    max_width: f32,
1046    font_weight: u16,
1047    font_style: u8,
1048    letter_spacing: f32,
1049) -> String {
1050    if text.is_empty() || max_width <= 0.0 {
1051        return String::new();
1052    }
1053    let key = (
1054        fast_hash(text),
1055        (px * 100.0) as u32,
1056        (max_width * 100.0) as u32,
1057        font_weight,
1058        font_style,
1059        (letter_spacing * 100.0) as i32,
1060    );
1061    if let Some(s) = ellip_cache().lock().unwrap().get(&key).cloned() {
1062        return s;
1063    }
1064    let m = metrics_for_textfield(text, px, None, font_weight, font_style, letter_spacing);
1065    if let Some(&last) = m.positions.last()
1066        && last <= max_width + 0.5
1067    {
1068        return text.to_string();
1069    }
1070    let _el = "…";
1071    let e_w = ellipsis_width(px, letter_spacing);
1072    if e_w >= max_width {
1073        return String::new();
1074    }
1075    let mut cut_i = 0usize;
1076    for i in 0..m.positions.len() {
1077        if m.positions[i] + e_w <= max_width {
1078            cut_i = i;
1079        } else {
1080            break;
1081        }
1082    }
1083    let byte = m
1084        .byte_offsets
1085        .get(cut_i)
1086        .copied()
1087        .unwrap_or(0)
1088        .min(text.len());
1089    let mut out = String::with_capacity(byte + 3);
1090    out.push_str(&text[..byte]);
1091    out.push('…');
1092
1093    let s = out;
1094    ellip_cache().lock().unwrap().put(key, s.clone());
1095
1096    s
1097}
1098
1099fn ellipsis_width(px: f32, letter_spacing: f32) -> f32 {
1100    static ELLIP_W_LRU: OnceCell<Mutex<Lru<(u32, i32), f32>>> = OnceCell::new();
1101    let cache = ELLIP_W_LRU.get_or_init(|| Mutex::new(Lru::new(64)));
1102    let key = ((px * 100.0) as u32, (letter_spacing * 100.0) as i32);
1103    if let Some(w) = cache.lock().unwrap().get(&key).copied() {
1104        return w;
1105    }
1106    let w =
1107        if let Some(g) = crate::shape_line("…", px, None, 400, 0, letter_spacing).last() {
1108            g.x + g.advance
1109        } else {
1110            0.0
1111        };
1112    cache.lock().unwrap().put(key, w);
1113    w
1114}