pretext 0.1.0

Native Unicode text preparation and paragraph layout engine for Pretext.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};

use ahash::AHashMap;
use fontdb::{Database, Family, Query, Source, Stretch, Style, Weight, ID};
use parking_lot::RwLock;

use crate::engine::TextStyleSpec;

pub type FontId = ID;

#[derive(Clone, Copy, Debug)]
struct CoverageRange {
    start: u32,
    end: u32,
}

struct CoverageCacheEntry {
    codepoints: Arc<[u32]>,
    ranges: Arc<[CoverageRange]>,
}

#[derive(Clone, Debug, Hash, PartialEq, Eq)]
enum CoverageCacheKey {
    Binary { hash: u64, len: usize, index: u32 },
    Path { path: PathBuf, index: u32 },
}

#[derive(Clone)]
pub struct LoadedFace {
    id: FontId,
    family_name: Arc<str>,
    data: Arc<[u8]>,
    face_index: u32,
}

impl LoadedFace {
    pub fn id(&self) -> FontId {
        self.id
    }

    pub fn family_name(&self) -> &str {
        &self.family_name
    }

    pub fn data(&self) -> &[u8] {
        &self.data
    }

    pub fn face_index(&self) -> u32 {
        self.face_index
    }

    pub fn units_per_em(&self) -> u16 {
        self.with_ttf_face(|face| face.units_per_em())
            .unwrap_or(1000)
    }

    pub fn has_glyph(&self, ch: char) -> bool {
        if !requires_glyph(ch) {
            return true;
        }
        self.with_ttf_face(|face| face.glyph_index(ch).is_some())
            .unwrap_or(false)
    }

    fn with_ttf_face<T>(&self, f: impl FnOnce(&ttf_parser::Face<'_>) -> T) -> Option<T> {
        let face = ttf_parser::Face::parse(&self.data, self.face_index).ok()?;
        Some(f(&face))
    }
}

pub struct FontCatalog {
    db: Database,
    faces: Vec<FontId>,
    default_face: Option<FontId>,
    char_to_font: RwLock<AHashMap<char, FontId>>,
    face_coverage: RwLock<AHashMap<FontId, Arc<[CoverageRange]>>>,
    loaded_faces: RwLock<AHashMap<FontId, Arc<LoadedFace>>>,
}

impl FontCatalog {
    pub fn new() -> Self {
        let mut db = Database::new();
        db.load_system_fonts();
        Self::build(&db)
    }

    pub fn with_font_data<I>(font_data: I) -> Self
    where
        I: IntoIterator<Item = Vec<u8>>,
    {
        Self::with_font_data_and_system_fonts(font_data, true)
    }

    pub fn with_font_data_and_system_fonts<I>(font_data: I, include_system_fonts: bool) -> Self
    where
        I: IntoIterator<Item = Vec<u8>>,
    {
        let mut db = Database::new();
        for data in font_data {
            db.load_font_data(data);
        }
        if include_system_fonts {
            db.load_system_fonts();
        }
        Self::build(&db)
    }

    pub fn build(db: &Database) -> Self {
        let faces: Vec<FontId> = db.faces().map(|face| face.id).collect();
        let default_face = faces.first().copied();
        let (char_to_font, face_coverage) = build_prewarmed_coverage_maps(db, &faces);
        Self {
            db: db.clone(),
            faces,
            default_face,
            char_to_font: RwLock::new(char_to_font),
            face_coverage: RwLock::new(face_coverage),
            loaded_faces: RwLock::new(AHashMap::new()),
        }
    }

    pub fn clear_runtime_caches(&self) {
        self.loaded_faces.write().clear();
    }

    pub fn resolve_style_chain(&self, style: &TextStyleSpec) -> Vec<FontId> {
        let mut resolved = Vec::new();
        for family in &style.families {
            let families = [Family::Name(family.as_str())];
            let query = Query {
                families: &families,
                weight: Weight(style.weight),
                stretch: Stretch::Normal,
                style: if style.italic {
                    Style::Italic
                } else {
                    Style::Normal
                },
            };
            if let Some(id) = self.db.query(&query) {
                if !resolved.contains(&id) {
                    resolved.push(id);
                }
            }
        }

        if resolved.is_empty() {
            if let Some(id) = self.default_face {
                resolved.push(id);
            }
        }

        resolved
    }

    pub fn font_for_char(&self, ch: char, preferred: &[FontId]) -> Option<FontId> {
        if !requires_glyph(ch) {
            return preferred.first().copied().or(self.default_face);
        }

        for id in preferred {
            if self.face_covers_char(*id, ch) {
                return Some(*id);
            }
        }

        if let Some(id) = self.char_to_font.read().get(&ch).copied() {
            return Some(id);
        }

        self.find_fallback_font_for_char(ch)
    }

    pub fn face_for_char(&self, ch: char, preferred: &[FontId]) -> Option<Arc<LoadedFace>> {
        self.font_for_char(ch, preferred)
            .and_then(|id| self.load_face(id))
            .or_else(|| self.default_face())
    }

    pub fn face_for_cluster(&self, cluster: &str, preferred: &[FontId]) -> Option<Arc<LoadedFace>> {
        self.candidate_ids(preferred)
            .into_iter()
            .find_map(|id| {
                self.face_covers_cluster(id, cluster)
                    .then(|| self.load_face(id))
                    .flatten()
            })
            .or_else(|| self.default_face())
    }

    pub(crate) fn best_face_for_run(
        &self,
        run_text: &str,
        preferred: &[FontId],
    ) -> Option<Arc<LoadedFace>> {
        let mut best: Option<(usize, FontId)> = None;
        let chars: Vec<char> = run_text.chars().collect();

        for id in self.candidate_ids(preferred) {
            let score = chars
                .iter()
                .filter(|&&ch| self.face_covers_char(id, ch))
                .count();
            if score == chars.len() {
                return self.load_face(id).or_else(|| self.default_face());
            }
            if best
                .as_ref()
                .map(|(best_score, _)| score > *best_score)
                .unwrap_or(true)
            {
                best = Some((score, id));
            }
        }

        best.and_then(|(_, id)| self.load_face(id))
            .or_else(|| self.default_face())
    }

    pub fn load_face(&self, id: FontId) -> Option<Arc<LoadedFace>> {
        if let Some(face) = self.loaded_faces.read().get(&id) {
            return Some(face.clone());
        }

        let family_name: Arc<str> = self
            .db
            .face(id)
            .and_then(|face| face.families.first().map(|family| family.0.clone()))
            .unwrap_or_else(|| "Unknown".to_owned())
            .into();

        let (data, face_index) = self
            .db
            .with_face_data(id, |data, face_index| (Arc::<[u8]>::from(data), face_index))?;
        let face = Arc::new(LoadedFace {
            id,
            family_name,
            data,
            face_index,
        });
        self.loaded_faces.write().insert(id, face.clone());
        Some(face)
    }

    fn candidate_ids(&self, preferred: &[FontId]) -> Vec<FontId> {
        let mut ids = Vec::with_capacity(preferred.len() + self.faces.len());
        for id in preferred.iter().copied().chain(self.faces.iter().copied()) {
            if !ids.contains(&id) {
                ids.push(id);
            }
        }
        ids
    }

    fn default_face(&self) -> Option<Arc<LoadedFace>> {
        self.default_face.and_then(|id| self.load_face(id))
    }

    fn find_fallback_font_for_char(&self, ch: char) -> Option<FontId> {
        let fallback = self
            .faces
            .iter()
            .copied()
            .find(|id| self.face_covers_char(*id, ch))
            .or(self.default_face);

        if let Some(id) = fallback {
            self.char_to_font.write().entry(ch).or_insert(id);
        }

        fallback
    }

    fn face_covers_cluster(&self, id: FontId, cluster: &str) -> bool {
        cluster.chars().all(|ch| self.face_covers_char(id, ch))
    }

    fn face_covers_char(&self, id: FontId, ch: char) -> bool {
        if !requires_glyph(ch) {
            return true;
        }

        self.coverage_ranges_for_face(id)
            .as_deref()
            .map(|ranges| coverage_contains(ranges, ch))
            .unwrap_or_else(|| {
                self.load_face(id)
                    .map(|face| face.has_glyph(ch))
                    .unwrap_or(false)
            })
    }

    fn coverage_ranges_for_face(&self, id: FontId) -> Option<Arc<[CoverageRange]>> {
        if let Some(ranges) = self.face_coverage.read().get(&id).cloned() {
            return Some(ranges);
        }

        let entry = coverage_entry_for_face(&self.db, id)?;
        {
            let mut face_coverage = self.face_coverage.write();
            if let Some(ranges) = face_coverage.get(&id).cloned() {
                return Some(ranges);
            }
            face_coverage.insert(id, entry.ranges.clone());
        }
        self.seed_char_to_font(id, entry.codepoints.as_ref());
        Some(entry.ranges.clone())
    }

    fn seed_char_to_font(&self, id: FontId, codepoints: &[u32]) {
        let mut char_to_font = self.char_to_font.write();
        for &codepoint in codepoints {
            if let Some(ch) = char::from_u32(codepoint) {
                char_to_font.entry(ch).or_insert(id);
            }
        }
    }
}

fn requires_glyph(ch: char) -> bool {
    !matches!(ch, '\n' | '\r' | '\t' | '\u{200B}' | '\u{2060}')
}

fn coverage_cache() -> &'static RwLock<AHashMap<CoverageCacheKey, Arc<CoverageCacheEntry>>> {
    static CACHE: OnceLock<RwLock<AHashMap<CoverageCacheKey, Arc<CoverageCacheEntry>>>> =
        OnceLock::new();
    CACHE.get_or_init(|| RwLock::new(AHashMap::new()))
}

fn build_prewarmed_coverage_maps(
    db: &Database,
    faces: &[FontId],
) -> (
    AHashMap<char, FontId>,
    AHashMap<FontId, Arc<[CoverageRange]>>,
) {
    let mut char_to_font = AHashMap::new();
    let mut face_coverage = AHashMap::new();

    for id in faces {
        if !should_prewarm_face(db, *id) {
            continue;
        }

        let Some(entry) = coverage_entry_for_face(db, *id) else {
            continue;
        };

        for &codepoint in entry.codepoints.iter() {
            if let Some(ch) = char::from_u32(codepoint) {
                char_to_font.entry(ch).or_insert(*id);
            }
        }

        face_coverage.insert(*id, entry.ranges.clone());
    }

    (char_to_font, face_coverage)
}

fn should_prewarm_face(db: &Database, id: FontId) -> bool {
    matches!(db.face(id), Some(face) if matches!(&face.source, Source::Binary(_)))
}

fn coverage_entry_for_face(db: &Database, id: FontId) -> Option<Arc<CoverageCacheEntry>> {
    let info = db.face(id)?;

    match &info.source {
        Source::Binary(_) => db
            .with_face_data(id, |data, face_index| {
                let key = CoverageCacheKey::Binary {
                    hash: hash_bytes(data),
                    len: data.len(),
                    index: face_index,
                };
                coverage_entry_with_key(key, || build_coverage_entry(data, face_index))
            })
            .flatten(),
        Source::File(path) | Source::SharedFile(path, _) => coverage_entry_with_key(
            CoverageCacheKey::Path {
                path: path.clone(),
                index: info.index,
            },
            || {
                db.with_face_data(id, |data, face_index| {
                    build_coverage_entry(data, face_index)
                })
                .flatten()
            },
        ),
    }
}

fn coverage_entry_with_key(
    key: CoverageCacheKey,
    build: impl FnOnce() -> Option<CoverageCacheEntry>,
) -> Option<Arc<CoverageCacheEntry>> {
    if let Some(entry) = coverage_cache().read().get(&key).cloned() {
        return Some(entry);
    }

    let entry = Arc::new(build()?);
    let mut cache = coverage_cache().write();
    Some(cache.entry(key).or_insert_with(|| entry.clone()).clone())
}

fn build_coverage_entry(data: &[u8], face_index: u32) -> Option<CoverageCacheEntry> {
    let codepoints: Arc<[u32]> = collect_face_codepoints(data, face_index)?.into();
    let ranges = collapse_codepoints_to_ranges(&codepoints);
    Some(CoverageCacheEntry { codepoints, ranges })
}

fn collect_face_codepoints(data: &[u8], face_index: u32) -> Option<Vec<u32>> {
    let face = ttf_parser::Face::parse(data, face_index).ok()?;
    let cmap = face.tables().cmap?;
    let mut codepoints = Vec::new();

    for subtable in cmap.subtables {
        if !subtable.is_unicode() {
            continue;
        }

        subtable.codepoints(|codepoint| {
            if char::from_u32(codepoint).is_some() && subtable.glyph_index(codepoint).is_some() {
                codepoints.push(codepoint);
            }
        });
    }

    codepoints.sort_unstable();
    codepoints.dedup();
    Some(codepoints)
}

fn collapse_codepoints_to_ranges(codepoints: &[u32]) -> Arc<[CoverageRange]> {
    let Some(&first) = codepoints.first() else {
        return Arc::from(Vec::<CoverageRange>::new());
    };

    let mut ranges = Vec::new();
    let mut start = first;
    let mut end = first;

    for &codepoint in &codepoints[1..] {
        if codepoint == end.saturating_add(1) {
            end = codepoint;
            continue;
        }

        ranges.push(CoverageRange { start, end });
        start = codepoint;
        end = codepoint;
    }

    ranges.push(CoverageRange { start, end });
    Arc::from(ranges)
}

fn coverage_contains(ranges: &[CoverageRange], ch: char) -> bool {
    let target = ch as u32;
    let mut low = 0usize;
    let mut high = ranges.len();

    while low < high {
        let mid = low + (high - low) / 2;
        let range = &ranges[mid];
        if target < range.start {
            high = mid;
        } else if target > range.end {
            low = mid + 1;
        } else {
            return true;
        }
    }

    false
}

fn hash_bytes(bytes: &[u8]) -> u64 {
    use std::hash::{Hash, Hasher};

    let mut state = ahash::AHasher::default();
    bytes.hash(&mut state);
    state.finish()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn bundled_font_data() -> Vec<Vec<u8>> {
        vec![
            include_bytes!("../../../demos/app/assets/fonts/NotoSans-Regular.ttf").to_vec(),
            include_bytes!("../../../demos/app/assets/fonts/NotoSansArabic-Regular.ttf").to_vec(),
            include_bytes!("../../../demos/app/assets/fonts/NotoSansCJK-Regular.ttc").to_vec(),
            include_bytes!("../../../demos/app/assets/fonts/NotoSansMyanmar-Regular.ttf").to_vec(),
            include_bytes!("../../../demos/app/assets/fonts/NotoEmoji-Regular.ttf").to_vec(),
            include_bytes!("../../../demos/app/assets/fonts/NotoColorEmoji.ttf").to_vec(),
            include_bytes!("../../../demos/app/assets/fonts/Noto-COLRv1.ttf").to_vec(),
            include_bytes!("../../../demos/app/assets/fonts/NotoSansMono-Regular.ttf").to_vec(),
        ]
    }

    fn file_backed_face_with_glyph(catalog: &FontCatalog, ch: char) -> Option<FontId> {
        catalog.faces.iter().copied().find(|id| {
            let Some(face_info) = catalog.db.face(*id) else {
                return false;
            };
            if !matches!(
                &face_info.source,
                Source::File(_) | Source::SharedFile(_, _)
            ) {
                return false;
            }

            catalog
                .db
                .with_face_data(*id, |data, face_index| {
                    ttf_parser::Face::parse(data, face_index)
                        .ok()
                        .and_then(|face| face.glyph_index(ch))
                        .is_some()
                })
                .unwrap_or(false)
        })
    }

    #[test]
    fn build_only_prewarms_binary_face_coverage() {
        let catalog = FontCatalog::with_font_data_and_system_fonts(bundled_font_data(), true);
        let expected_binary_count = catalog
            .faces
            .iter()
            .copied()
            .filter(|id| should_prewarm_face(&catalog.db, *id))
            .count();

        assert_eq!(catalog.face_coverage.read().len(), expected_binary_count);

        if let Some(file_backed) = file_backed_face_with_glyph(&catalog, 'A') {
            assert!(!catalog.face_coverage.read().contains_key(&file_backed));
        }
    }

    #[test]
    fn file_backed_face_coverage_is_built_lazily() {
        let catalog = FontCatalog::with_font_data_and_system_fonts(bundled_font_data(), true);
        let Some(file_backed) = file_backed_face_with_glyph(&catalog, 'A') else {
            return;
        };

        let before = catalog.face_coverage.read().len();
        assert!(!catalog.face_coverage.read().contains_key(&file_backed));
        assert!(catalog.face_covers_char(file_backed, 'A'));
        assert!(catalog.face_coverage.read().contains_key(&file_backed));
        assert_eq!(catalog.face_coverage.read().len(), before + 1);
    }

    #[test]
    fn best_face_for_run_only_loads_selected_face_data() {
        let catalog = FontCatalog::with_font_data_and_system_fonts(bundled_font_data(), true);
        let style = TextStyleSpec {
            families: vec![
                "Helvetica".to_owned(),
                "Arial".to_owned(),
                "Noto Sans".to_owned(),
            ],
            size_px: 16.0,
            weight: 400,
            italic: false,
        };
        let preferred = catalog.resolve_style_chain(&style);

        assert_eq!(catalog.loaded_faces.read().len(), 0);
        let face = catalog
            .best_face_for_run("Hello", &preferred)
            .expect("expected a face for ASCII run");
        let cached = catalog
            .loaded_faces
            .read()
            .get(&face.id())
            .cloned()
            .expect("expected the selected face to be cached");

        assert_eq!(catalog.loaded_faces.read().len(), 1);
        assert!(Arc::ptr_eq(&cached, &face));
    }
}