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    line_height_ratio: f32,
359    font_family: Option<&str>,
360    font_weight: u16,
361    font_style: u8,
362    letter_spacing: f32,
363) -> Vec<ShapedGlyph> {
364    use parley::style::StyleProperty;
365    use parley::FontWeight;
366    use parley::layout::PositionedLayoutItem;
367
368    let Engine {
369        ref mut font_cx,
370        ref mut layout_cx,
371        ..
372    } = *eng;
373    let mut builder = layout_cx.ranged_builder(font_cx, text, 1.0, true);
374    builder.push_default(StyleProperty::FontSize(px));
375    builder.push_default(StyleProperty::LineHeight(parley::LineHeight::FontSizeRelative(line_height_ratio)));
376    builder.push_default(StyleProperty::FontWeight(FontWeight::new(font_weight as f32)));
377    builder.push_default(StyleProperty::FontStyle(match font_style {
378        1 => parley::FontStyle::Italic,
379        _ => parley::FontStyle::Normal,
380    }));
381    builder.push_default(StyleProperty::LetterSpacing(letter_spacing));
382
383    if let Some(family) = font_family {
384        use parley::style::{FontFamilyName, GenericFamily};
385        let names: &[FontFamilyName] = match family {
386            "monospace" => &[
387                FontFamilyName::named("JetBrains Mono"),
388                GenericFamily::Monospace.into(),
389            ],
390            "sans-serif" => &[
391                FontFamilyName::named("Open Sans"),
392                GenericFamily::SansSerif.into(),
393            ],
394            "emoji" => &[
395                FontFamilyName::named("Noto Color Emoji"),
396                GenericFamily::Emoji.into(),
397            ],
398            "serif" => &[GenericFamily::Serif.into()],
399            "cursive" => &[GenericFamily::Cursive.into()],
400            "fantasy" => &[GenericFamily::Fantasy.into()],
401            "system-ui" => &[GenericFamily::SystemUi.into()],
402            "math" => &[GenericFamily::Math.into()],
403            _ => &[FontFamilyName::named(family)],
404        };
405        builder.push(names, 0..text.len());
406    }
407
408    let mut layout = builder.build(text);
409    layout.break_all_lines(None);
410    layout.align(
411        parley::Alignment::Start,
412        parley::AlignmentOptions::default(),
413    );
414
415    let mut out: Vec<ShapedGlyph> = Vec::new();
416    for line in layout.lines() {
417        for item in line.items() {
418            let PositionedLayoutItem::GlyphRun(glyph_run) = item else { continue };
419            let font_data = glyph_run.run().font();
420            let fid = eng.ensure_font(font_data);
421            log::debug!("[shape] run: fid={} font_data_len={}", fid, font_data.data.as_ref().len());
422            for g in glyph_run.positioned_glyphs() {
423                let gid = g.id as u16;
424                let key = key_from_pair(fid, gid);
425                eng.key_map.insert(key, (fid, gid));
426
427                let (w, h, left, top) = eng
428                    .raster_placement(fid, gid, px)
429                    .unwrap_or((0.0, 0.0, 0.0, 0.0));
430
431                log::debug!(
432                    "[shape] glyph: gid={} px={} x={:.1} y={:.1} advance={:.1} bitmap={}x{} {}x{}",
433                    gid, px, g.x, g.y, g.advance, w, h, left, top,
434                );
435
436                out.push(ShapedGlyph {
437                    key,
438                    px,
439                    x: g.x,
440                    y: g.y,
441                    w,
442                    h,
443                    bearing_x: left,
444                    bearing_y: top,
445                    advance: g.advance + letter_spacing,
446                });
447            }
448        }
449    }
450    out
451}
452
453pub fn shape_line(
454    text: &str,
455    px: f32,
456    line_height_ratio: f32,
457    font_family: Option<&str>,
458    font_weight: u16,
459    font_style: u8,
460    letter_spacing: f32,
461) -> Vec<ShapedGlyph> {
462    let mut eng = engine().lock().unwrap();
463    shape_line_inner(&mut eng, text, px, line_height_ratio, font_family, font_weight, font_style, letter_spacing)
464}
465
466pub fn rasterize(key: GlyphKey, px: f32) -> Option<GlyphBitmap> {
467    use swash::scale::{Render, Source, StrikeWith};
468    let mut eng = engine().lock().unwrap();
469    let &(fid, gid) = eng.key_map.get(&key)?;
470    let cache_key = (fid, gid, px.to_bits());
471    if let Some(cached) = eng.glyph_cache.get(&cache_key) {
472        log::debug!("[rasterize] HIT fid={} gid={} px={} => {}x{}", fid, gid, px, cached.0, cached.1);
473        return Some(GlyphBitmap {
474            key,
475            w: cached.0,
476            h: cached.1,
477            content: cached.4,
478            data: cached.5.clone(),
479        });
480    }
481    let data_bytes = eng
482        .font_registry
483        .iter()
484        .find(|r| r.id == fid)?
485        .data_bytes
486        .clone();
487    let font = swash::FontRef::from_index(&data_bytes, 0)?;
488    let mut scaler = eng
489        .swash_cx
490        .builder(font)
491        .size(px)
492        .hint(true)
493        .build();
494    let image = Render::new(&[
495        Source::Outline,
496        Source::ColorBitmap(StrikeWith::BestFit),
497        Source::ColorOutline(0),
498    ])
499    .render(&mut scaler, gid)?;
500    log::debug!("[rasterize] MISS fid={} gid={} px={} => {}x{}", fid, gid, px, image.placement.width, image.placement.height);
501    let bitmap = GlyphBitmap {
502        key,
503        w: image.placement.width,
504        h: image.placement.height,
505        content: image.content,
506        data: image.data,
507    };
508    eng.glyph_cache.insert(
509        cache_key,
510        (
511            bitmap.w,
512            bitmap.h,
513            image.placement.left,
514            image.placement.top,
515            bitmap.content,
516            bitmap.data.clone(),
517        ),
518    );
519    eng.trim_glyph_cache();
520    Some(bitmap)
521}
522
523pub fn lookup_cache_key(key: GlyphKey, px: f32) -> Option<CacheKey> {
524    let eng = engine().lock().unwrap();
525    let &(fid, gid) = eng.key_map.get(&key)?;
526    Some(CacheKey {
527        font_id: fid,
528        glyph_id: gid,
529        font_size_bits: px.to_bits(),
530    })
531}
532
533fn extract_outlines_for(
534    data_bytes: &[u8],
535    glyph_id: u16,
536) -> Option<Box<[Command]>> {
537    let font = skrifa::FontRef::new(data_bytes).ok()?;
538    let mut pen = OutlinePenCollector(Vec::new());
539    font.outline_glyphs()
540        .get(skrifa::GlyphId::new(glyph_id as u32))?
541        .draw(skrifa::instance::Size::new(1.0), &mut pen)
542        .ok()?;
543    Some(pen.0.into_boxed_slice())
544}
545
546pub fn extract_outline_commands(cache_key: CacheKey) -> Option<Box<[Command]>> {
547    let eng = engine().lock().unwrap();
548    let record = eng
549        .font_registry
550        .iter()
551        .find(|r| r.id == cache_key.font_id)?;
552    extract_outlines_for(&record.data_bytes, cache_key.glyph_id)
553}
554
555pub fn lookup_and_extract_outline(
556    key: GlyphKey,
557    px: f32,
558) -> Option<(CacheKey, Box<[Command]>)> {
559    let eng = engine().lock().unwrap();
560    let &(fid, gid) = eng.key_map.get(&key)?;
561    let record = eng.font_registry.iter().find(|r| r.id == fid)?;
562    let ck = CacheKey {
563        font_id: fid,
564        glyph_id: gid,
565        font_size_bits: px.to_bits(),
566    };
567    let cmds = extract_outlines_for(&record.data_bytes, gid)?;
568    Some((ck, cmds))
569}
570
571struct OutlinePenCollector(Vec<Command>);
572
573impl OutlinePen for OutlinePenCollector {
574    fn move_to(&mut self, x: f32, y: f32) {
575        self.0.push(Command::MoveTo(x, y));
576    }
577    fn line_to(&mut self, x: f32, y: f32) {
578        self.0.push(Command::LineTo(x, y));
579    }
580    fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) {
581        self.0.push(Command::QuadTo(cx0, cy0, x, y));
582    }
583    fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {
584        self.0.push(Command::CurveTo(cx0, cy0, cx1, cy1, x, y));
585    }
586    fn close(&mut self) {
587        self.0.push(Command::Close);
588    }
589}
590
591#[derive(Clone)]
592pub struct TextMetrics {
593    pub positions: Vec<f32>,
594    pub byte_offsets: Vec<usize>,
595}
596
597pub fn metrics_for_textfield(
598    text: &str,
599    px: f32,
600    font_family: Option<&str>,
601    font_weight: u16,
602    font_style: u8,
603    letter_spacing: f32,
604) -> TextMetrics {
605    let family_hash = font_family.map(fast_hash).unwrap_or(0);
606    let key = (
607        fast_hash(text),
608        (px * 100.0) as u32,
609        family_hash,
610        font_weight,
611        font_style,
612        (letter_spacing * 100.0) as i32,
613    );
614    if let Some(m) = metrics_cache().lock().unwrap().get(&key).cloned() {
615        return m;
616    }
617    let mut eng = engine().lock().unwrap();
618
619    use parley::style::StyleProperty;
620    use parley::FontWeight;
621
622    let Engine {
623        ref mut font_cx,
624        ref mut layout_cx,
625        ..
626    } = *eng;
627    let mut builder = layout_cx.ranged_builder(font_cx, text, 1.0, true);
628    builder.push_default(StyleProperty::FontSize(px));
629    builder.push_default(StyleProperty::FontWeight(FontWeight::new(font_weight as f32)));
630    builder.push_default(StyleProperty::FontStyle(match font_style {
631        1 => parley::FontStyle::Italic,
632        _ => parley::FontStyle::Normal,
633    }));
634    builder.push_default(StyleProperty::LetterSpacing(letter_spacing));
635    if let Some(family) = font_family {
636        use parley::style::{FontFamilyName, GenericFamily};
637        let names: &[FontFamilyName] = match family {
638            "monospace" => &[
639                FontFamilyName::named("JetBrains Mono"),
640                GenericFamily::Monospace.into(),
641            ],
642            "sans-serif" => &[
643                FontFamilyName::named("Open Sans"),
644                GenericFamily::SansSerif.into(),
645            ],
646            "emoji" => &[
647                FontFamilyName::named("Noto Color Emoji"),
648                GenericFamily::Emoji.into(),
649            ],
650            "serif" => &[GenericFamily::Serif.into()],
651            "cursive" => &[GenericFamily::Cursive.into()],
652            "fantasy" => &[GenericFamily::Fantasy.into()],
653            "system-ui" => &[GenericFamily::SystemUi.into()],
654            "math" => &[GenericFamily::Math.into()],
655            _ => &[FontFamilyName::named(family)],
656        };
657        builder.push(names, 0..text.len());
658    }
659
660    let mut layout = builder.build(text);
661    layout.break_all_lines(None);
662    layout.align(
663        parley::Alignment::Start,
664        parley::AlignmentOptions::default(),
665    );
666
667    let mut edges: Vec<(usize, f32)> = Vec::new();
668    let mut last_x = 0.0f32;
669    let mut glyph_idx = 0usize;
670    for line in layout.lines() {
671        for item in line.items() {
672            let parley::layout::PositionedLayoutItem::GlyphRun(glyph_run) = item else { continue };
673            let run_offset = glyph_run.offset();
674            let run = glyph_run.run();
675            let mut cluster_offset = run_offset;
676            for cluster in run.clusters() {
677                let range = cluster.text_range();
678                for g in cluster.glyphs() {
679                    let shift = glyph_idx as f32 * letter_spacing;
680                    let x_pos = cluster_offset + g.x;
681                    let right = x_pos + shift + g.advance + letter_spacing;
682                    last_x = right.max(last_x);
683                    edges.push((range.end, right));
684                    glyph_idx += 1;
685                    cluster_offset += g.advance;
686                }
687            }
688        }
689    }
690    if edges.last().map(|e| e.0) != Some(text.len()) {
691        edges.push((text.len(), last_x));
692    }
693
694    let mut positions = Vec::with_capacity(text.graphemes(true).count() + 1);
695    let mut byte_offsets = Vec::with_capacity(positions.capacity());
696    positions.push(0.0);
697    byte_offsets.push(0);
698    let mut last_byte = 0usize;
699    for (b, _) in text.grapheme_indices(true) {
700        positions.push(
701            positions.last().copied().unwrap_or(0.0) + width_between(&edges, last_byte, b),
702        );
703        byte_offsets.push(b);
704        last_byte = b;
705    }
706    if *byte_offsets.last().unwrap_or(&0) != text.len() {
707        positions.push(
708            positions.last().copied().unwrap_or(0.0) + width_between(&edges, last_byte, text.len()),
709        );
710        byte_offsets.push(text.len());
711    }
712    let m = TextMetrics {
713        positions,
714        byte_offsets,
715    };
716    metrics_cache().lock().unwrap().put(key, m.clone());
717    m
718}
719
720fn width_between(edges: &[(usize, f32)], start_b: usize, end_b: usize) -> f32 {
721    let x0 = lookup_right(edges, start_b);
722    let x1 = lookup_right(edges, end_b);
723    (x1 - x0).max(0.0)
724}
725fn lookup_right(edges: &[(usize, f32)], b: usize) -> f32 {
726    match edges.binary_search_by_key(&b, |e| e.0) {
727        Ok(i) => edges[i].1,
728        Err(i) => {
729            if i == 0 {
730                0.0
731            } else {
732                edges[i - 1].1
733            }
734        }
735    }
736}
737
738pub fn wrap_lines(
739    text: &str,
740    px: f32,
741    max_width: f32,
742    max_lines: Option<usize>,
743    soft_wrap: bool,
744    font_weight: u16,
745    font_style: u8,
746    letter_spacing: f32,
747) -> (Vec<String>, bool) {
748    if text.is_empty() || max_width <= 0.0 {
749        return (vec![String::new()], false);
750    }
751    if !soft_wrap {
752        return (vec![text.to_string()], false);
753    }
754
755    let max_lines_key: u16 = match max_lines {
756        None => 0,
757        Some(n) => {
758            let n = n.min(u16::MAX as usize - 1) as u16;
759            n.saturating_add(1)
760        }
761    };
762    let key = (
763        fast_hash(text),
764        (px * 100.0) as u32,
765        (max_width * 100.0) as u32,
766        max_lines_key,
767        soft_wrap,
768        font_weight,
769        font_style,
770        (letter_spacing * 100.0) as i32,
771    );
772    if let Some(h) = wrap_cache().lock().unwrap().get(&key).cloned() {
773        return h;
774    }
775
776    let m = metrics_for_textfield(text, px, None, font_weight, font_style, letter_spacing);
777    if let Some(&last) = m.positions.last()
778        && last <= max_width + 0.5
779    {
780        return (vec![text.to_string()], false);
781    }
782
783    let width_of = |start_b: usize, end_b: usize| -> f32 {
784        let i0 = match m.byte_offsets.binary_search(&start_b) {
785            Ok(i) | Err(i) => i,
786        };
787        let i1 = match m.byte_offsets.binary_search(&end_b) {
788            Ok(i) | Err(i) => i,
789        };
790        (m.positions.get(i1).copied().unwrap_or(0.0) - m.positions.get(i0).copied().unwrap_or(0.0))
791            .max(0.0)
792    };
793
794    let mut out: Vec<String> = Vec::new();
795    let mut truncated = false;
796
797    let mut line_start = 0usize;
798    let mut best_break = line_start;
799
800    for tok in text.split_word_bounds() {
801        let tok_start = best_break;
802        let tok_end = tok_start + tok.len();
803        let w = width_of(line_start, tok_end);
804
805        if w <= max_width + 0.5 {
806            best_break = tok_end;
807            continue;
808        }
809
810        if best_break > line_start {
811            out.push(text[line_start..best_break].trim_end().to_string());
812            line_start = best_break;
813        } else {
814            let mut cut = tok_start;
815            for g in tok.grapheme_indices(true) {
816                let next = tok_start + g.0 + g.1.len();
817                if width_of(line_start, next) <= max_width + 0.5 {
818                    cut = next;
819                } else {
820                    break;
821                }
822            }
823            if cut == line_start {
824                if let Some((ofs, grapheme)) = tok.grapheme_indices(true).next() {
825                    cut = tok_start + ofs + grapheme.len();
826                }
827            }
828            out.push(text[line_start..cut].to_string());
829            line_start = cut;
830        }
831
832        if let Some(ml) = max_lines
833            && out.len() >= ml
834        {
835            truncated = true;
836            line_start = line_start.min(text.len());
837            break;
838        }
839
840        best_break = line_start;
841
842        if line_start < tok_end {
843            if width_of(line_start, tok_end) <= max_width + 0.5 {
844                best_break = tok_end;
845            }
846        }
847    }
848
849    if line_start < text.len() && max_lines.is_none_or(|ml| out.len() < ml) {
850        out.push(text[line_start..].trim_end().to_string());
851    }
852
853    let res = (out, truncated);
854
855    wrap_cache().lock().unwrap().put(key, res.clone());
856    res
857}
858
859pub fn wrap_line_ranges(
860    text: &str,
861    px: f32,
862    max_width: f32,
863    max_lines: Option<usize>,
864    soft_wrap: bool,
865    font_weight: u16,
866    font_style: u8,
867    letter_spacing: f32,
868) -> (Vec<(usize, usize)>, bool) {
869    if text.is_empty() || max_width <= 0.0 {
870        return (vec![(0, 0)], false);
871    }
872    if !soft_wrap {
873        let mut out = Vec::new();
874        let mut start = 0usize;
875        for (i, ch) in text.char_indices() {
876            if ch == '\n' {
877                out.push((start, i));
878                start = i + 1;
879            }
880        }
881        out.push((start, text.len()));
882        return (out, false);
883    }
884
885    let max_lines_key: u16 = match max_lines {
886        None => 0,
887        Some(n) => {
888            let n = n.min(u16::MAX as usize - 1) as u16;
889            n.saturating_add(1)
890        }
891    };
892    let key = (
893        fast_hash(text),
894        (px * 100.0) as u32,
895        (max_width * 100.0) as u32,
896        max_lines_key,
897        soft_wrap,
898        font_weight,
899        font_style,
900        (letter_spacing * 100.0) as i32,
901    );
902    if let Some(v) = wrap_ranges_cache().lock().unwrap().get(&key).cloned() {
903        return v;
904    }
905
906    let m = metrics_for_textfield(text, px, None, font_weight, font_style, letter_spacing);
907
908    let width_of = |start_b: usize, end_b: usize| -> f32 {
909        let i0 = match m.byte_offsets.binary_search(&start_b) {
910            Ok(i) | Err(i) => i,
911        };
912        let i1 = match m.byte_offsets.binary_search(&end_b) {
913            Ok(i) | Err(i) => i,
914        };
915        (m.positions.get(i1).copied().unwrap_or(0.0) - m.positions.get(i0).copied().unwrap_or(0.0))
916            .max(0.0)
917    };
918
919    let mut out: Vec<(usize, usize)> = Vec::new();
920    let mut truncated = false;
921
922    let mut line0_start = 0usize;
923    for (i, ch) in text.char_indices() {
924        if ch == '\n' {
925            let (mut ranges, tr) = wrap_one_hard_line_ranges(
926                text,
927                line0_start,
928                i,
929                max_width,
930                max_lines.map(|ml| ml.saturating_sub(out.len())),
931                &width_of,
932            );
933            out.append(&mut ranges);
934            if tr {
935                truncated = true;
936                break;
937            }
938            line0_start = i + 1;
939
940            if let Some(ml) = max_lines
941                && out.len() >= ml
942            {
943                truncated = true;
944                break;
945            }
946        }
947    }
948    if !truncated {
949        let (mut ranges, tr) = wrap_one_hard_line_ranges(
950            text,
951            line0_start,
952            text.len(),
953            max_width,
954            max_lines.map(|ml| ml.saturating_sub(out.len())),
955            &width_of,
956        );
957        out.append(&mut ranges);
958        truncated = tr;
959    }
960
961    if out.is_empty() {
962        out.push((0, 0));
963    }
964
965    let res = (out, truncated);
966    wrap_ranges_cache().lock().unwrap().put(key, res.clone());
967    res
968}
969
970fn wrap_one_hard_line_ranges(
971    text: &str,
972    start: usize,
973    end: usize,
974    max_width: f32,
975    max_lines: Option<usize>,
976    width_of: &dyn Fn(usize, usize) -> f32,
977) -> (Vec<(usize, usize)>, bool) {
978    let mut out = Vec::new();
979    let mut t = false;
980
981    if start >= end {
982        out.push((start, start));
983        return (out, false);
984    }
985
986    if width_of(start, end) <= max_width + 0.5 {
987        out.push((start, end));
988        return (out, false);
989    }
990
991    let mut line_start = start;
992    let mut best_break = line_start;
993    let mut unconsumed_start = start;
994
995    for tok in text[line_start..end].split_word_bounds() {
996        let tok_abs_start = unconsumed_start;
997        let tok_abs_end = tok_abs_start + tok.len();
998        unconsumed_start = tok_abs_end;
999
1000        let w = width_of(line_start, tok_abs_end);
1001        if w <= max_width + 0.5 {
1002            best_break = tok_abs_end;
1003            continue;
1004        }
1005
1006        if best_break > line_start {
1007            out.push((line_start, best_break));
1008            line_start = best_break;
1009        } else {
1010            let mut cut = tok_abs_start;
1011            for (ofs, g) in tok.grapheme_indices(true) {
1012                let next = tok_abs_start + ofs + g.len();
1013                if width_of(line_start, next) <= max_width + 0.5 {
1014                    cut = next;
1015                } else {
1016                    break;
1017                }
1018            }
1019            if cut == line_start
1020                && let Some((ofs, gr)) = tok.grapheme_indices(true).next()
1021            {
1022                cut = tok_abs_start + ofs + gr.len();
1023            }
1024            out.push((line_start, cut));
1025            line_start = cut;
1026        }
1027
1028        if let Some(ml) = max_lines
1029            && out.len() >= ml
1030        {
1031            t = true;
1032            break;
1033        }
1034
1035        best_break = line_start;
1036    }
1037
1038    if !t && line_start < end && max_lines.is_none_or(|ml| out.len() < ml) {
1039        out.push((line_start, end));
1040    }
1041
1042    (out, t)
1043}
1044
1045pub fn ellipsize_line(
1046    text: &str,
1047    px: f32,
1048    max_width: f32,
1049    font_weight: u16,
1050    font_style: u8,
1051    letter_spacing: f32,
1052) -> String {
1053    if text.is_empty() || max_width <= 0.0 {
1054        return String::new();
1055    }
1056    let key = (
1057        fast_hash(text),
1058        (px * 100.0) as u32,
1059        (max_width * 100.0) as u32,
1060        font_weight,
1061        font_style,
1062        (letter_spacing * 100.0) as i32,
1063    );
1064    if let Some(s) = ellip_cache().lock().unwrap().get(&key).cloned() {
1065        return s;
1066    }
1067    let m = metrics_for_textfield(text, px, None, font_weight, font_style, letter_spacing);
1068    if let Some(&last) = m.positions.last()
1069        && last <= max_width + 0.5
1070    {
1071        return text.to_string();
1072    }
1073    let _el = "…";
1074    let e_w = ellipsis_width(px, letter_spacing);
1075    if e_w >= max_width {
1076        return String::new();
1077    }
1078    let mut cut_i = 0usize;
1079    for i in 0..m.positions.len() {
1080        if m.positions[i] + e_w <= max_width {
1081            cut_i = i;
1082        } else {
1083            break;
1084        }
1085    }
1086    let byte = m
1087        .byte_offsets
1088        .get(cut_i)
1089        .copied()
1090        .unwrap_or(0)
1091        .min(text.len());
1092    let mut out = String::with_capacity(byte + 3);
1093    out.push_str(&text[..byte]);
1094    out.push('…');
1095
1096    let s = out;
1097    ellip_cache().lock().unwrap().put(key, s.clone());
1098
1099    s
1100}
1101
1102fn ellipsis_width(px: f32, letter_spacing: f32) -> f32 {
1103    static ELLIP_W_LRU: OnceCell<Mutex<Lru<(u32, i32), f32>>> = OnceCell::new();
1104    let cache = ELLIP_W_LRU.get_or_init(|| Mutex::new(Lru::new(64)));
1105    let key = ((px * 100.0) as u32, (letter_spacing * 100.0) as i32);
1106    if let Some(w) = cache.lock().unwrap().get(&key).copied() {
1107        return w;
1108    }
1109    let w =
1110        if let Some(g) = crate::shape_line("…", px, px, None, 400, 0, letter_spacing).last() {
1111            g.x + g.advance
1112        } else {
1113            0.0
1114        };
1115    cache.lock().unwrap().put(key, w);
1116    w
1117}