text-typeset 1.6.2

Turns rich text documents into GPU-ready glyph quads
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
use harfrust::{Direction, Feature, FontRef, ShapeOptions, Tag, UnicodeBuffer};

use crate::font::registry::FontRegistry;
use crate::font::resolve::ResolvedFont;
use crate::shaping::run::{ShapedGlyph, ShapedRun};
use crate::types::FontFeature;

/// Convert public [`FontFeature`] toggles into harfrust [`Feature`]s,
/// applied across the whole shaped string (global range). Script-mandated
/// features apply regardless; these are the discretionary toggles.
pub fn to_harfrust_features(features: &[FontFeature]) -> Vec<Feature> {
    features
        .iter()
        .map(|f| Feature::new(Tag::new(&f.tag), f.value, ..))
        .collect()
}

/// Read units-per-em for a font face.
///
/// `harfrust::FontRef` is a thin wrapper over read-fonts and exposes
/// the `head` table only through the `read_fonts::TableProvider` trait,
/// which harfrust doesn't re-export. Since we already depend on swash
/// for `font_metrics_px` further down, we reuse swash's `Metrics` to
/// pull UPEM — one less dependency surface to maintain.
fn units_per_em(bytes: &[u8], face_index: u32) -> Option<u16> {
    let font_ref = swash::FontRef::from_index(bytes, face_index as usize)?;
    let upem = font_ref.metrics(&[]).units_per_em;
    if upem == 0 { None } else { Some(upem) }
}

/// Text direction for shaping.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TextDirection {
    /// Auto-detect from text content (default).
    #[default]
    Auto,
    LeftToRight,
    RightToLeft,
}

/// Shape a text string with the given resolved font.
///
/// Returns a ShapedRun with glyph IDs and pixel-space positions.
/// The `text_offset` is the byte offset of this text within the block
/// (used for cluster mapping back to document positions).
/// Shape a text string with automatic glyph fallback.
///
/// After shaping with the primary font, any .notdef glyphs (glyph_id==0)
/// are detected and re-shaped with fallback fonts. If no fallback font
/// covers a character, it remains as .notdef (renders as blank space
/// with correct advance).
pub fn shape_text(
    registry: &FontRegistry,
    resolved: &ResolvedFont,
    text: &str,
    text_offset: usize,
) -> Option<ShapedRun> {
    shape_text_with_fallback(
        registry,
        resolved,
        text,
        text_offset,
        TextDirection::Auto,
        &[],
    )
}

/// Shape text with an explicit direction and glyph fallback.
///
/// Like `shape_text`, but caller supplies the direction instead of letting
/// rustybuzz guess. Used by the bidi-aware layout path, which splits text
/// into directional runs before shaping.
pub fn shape_text_with_fallback(
    registry: &FontRegistry,
    resolved: &ResolvedFont,
    text: &str,
    text_offset: usize,
    direction: TextDirection,
    features: &[Feature],
) -> Option<ShapedRun> {
    let mut run = shape_text_directed(registry, resolved, text, text_offset, direction, features)?;

    // Check for .notdef glyphs and attempt fallback
    if run.glyphs.iter().any(|g| g.glyph_id == 0) && !text.is_empty() {
        apply_glyph_fallback(registry, resolved, text, text_offset, features, &mut run);
    }

    Some(run)
}

/// Re-shape .notdef glyphs using fallback fonts.
///
/// For each .notdef glyph, finds the source character via the cluster value,
/// queries all registered fonts for coverage, and if one covers it,
/// shapes that single character with the fallback font and replaces
/// the .notdef glyph with the result.
fn apply_glyph_fallback(
    registry: &FontRegistry,
    primary: &ResolvedFont,
    text: &str,
    text_offset: usize,
    features: &[Feature],
    run: &mut ShapedRun,
) {
    use crate::font::resolve::find_fallback_font;

    for glyph in &mut run.glyphs {
        if glyph.glyph_id != 0 {
            continue;
        }

        // Find the character that produced this .notdef
        let byte_offset = glyph.cluster as usize;
        let ch = match text.get(byte_offset..).and_then(|s| s.chars().next()) {
            Some(c) => c,
            None => continue,
        };

        // Find a fallback font that has this character
        let fallback_id = match find_fallback_font(registry, ch, primary.font_face_id) {
            Some(id) => id,
            None => continue, // no fallback available -leave as .notdef
        };

        let fallback_entry = match registry.get(fallback_id) {
            Some(e) => e,
            None => continue,
        };

        // Shape just this character with the fallback font
        let fallback_resolved = ResolvedFont {
            font_face_id: fallback_id,
            size_px: primary.size_px,
            face_index: fallback_entry.face_index,
            swash_cache_key: fallback_entry.swash_cache_key,
            scale_factor: primary.scale_factor,
            weight: primary.weight,
        };

        let char_str = &text[byte_offset..byte_offset + ch.len_utf8()];
        if let Some(fallback_run) = shape_text_directed(
            registry,
            &fallback_resolved,
            char_str,
            text_offset + byte_offset,
            TextDirection::Auto,
            features,
        ) {
            // Replace the .notdef glyph with the fallback glyph(s)
            if let Some(fb_glyph) = fallback_run.glyphs.first() {
                glyph.glyph_id = fb_glyph.glyph_id;
                glyph.x_advance = fb_glyph.x_advance;
                glyph.y_advance = fb_glyph.y_advance;
                glyph.x_offset = fb_glyph.x_offset;
                glyph.y_offset = fb_glyph.y_offset;
                glyph.font_face_id = fallback_id;
            }
        }
    }

    // Recompute total advance
    run.advance_width = run.glyphs.iter().map(|g| g.x_advance).sum();
}

/// Shape text with an explicit direction.
pub fn shape_text_directed(
    registry: &FontRegistry,
    resolved: &ResolvedFont,
    text: &str,
    text_offset: usize,
    direction: TextDirection,
    features: &[Feature],
) -> Option<ShapedRun> {
    let entry = registry.get(resolved.font_face_id)?;
    let font = FontRef::from_index(entry.bytes(), entry.face_index).ok()?;

    let upem = units_per_em(entry.bytes(), entry.face_index).unwrap_or(0) as f32;
    if upem == 0.0 {
        return None;
    }
    // Shape at physical ppem, then divide results by scale_factor so
    // downstream layout stays in logical pixels. See ResolvedFont.
    let sf = resolved.scale_factor.max(f32::MIN_POSITIVE);
    let physical_size = resolved.size_px * sf;
    let physical_scale = physical_size / upem;
    let inv_sf = 1.0 / sf;

    let mut buffer = UnicodeBuffer::new();
    buffer.push_str(text);
    match direction {
        TextDirection::LeftToRight => buffer.set_direction(Direction::LeftToRight),
        TextDirection::RightToLeft => buffer.set_direction(Direction::RightToLeft),
        // harfrust panics if direction is left Invalid; explicitly
        // guess script + language + direction from the buffer content.
        TextDirection::Auto => buffer.guess_segment_properties(),
    }

    // Resolve the concrete direction (Auto is now decided by the buffer).
    // Stored on the run so hit-testing knows RTL glyph order.
    let resolved_direction = if buffer.direction() == Direction::RightToLeft {
        TextDirection::RightToLeft
    } else {
        TextDirection::LeftToRight
    };

    // ShaperData preprocesses font tables for shaping. It's built once
    // per face and cached on the FontEntry, so repeated shape calls
    // (every relayout/keystroke) reuse the same preprocessed tables.
    let shaper_data = entry.shaper_data(&font);
    let shaper = shaper_data.shaper(&font).build();
    let glyph_buffer = shaper.shape(buffer, ShapeOptions::new().features(features));

    let infos = glyph_buffer.glyph_infos();
    let positions = glyph_buffer.glyph_positions();

    let mut glyphs = Vec::with_capacity(infos.len());
    let mut total_advance = 0.0f32;

    for (info, pos) in infos.iter().zip(positions.iter()) {
        let x_advance = pos.x_advance as f32 * physical_scale * inv_sf;
        let y_advance = pos.y_advance as f32 * physical_scale * inv_sf;
        let x_offset = pos.x_offset as f32 * physical_scale * inv_sf;
        let y_offset = pos.y_offset as f32 * physical_scale * inv_sf;

        glyphs.push(ShapedGlyph {
            glyph_id: info.glyph_id as u16,
            cluster: info.cluster,
            x_advance,
            y_advance,
            x_offset,
            y_offset,
            font_face_id: resolved.font_face_id,
        });

        total_advance += x_advance;
    }

    Some(ShapedRun {
        font_face_id: resolved.font_face_id,
        size_px: resolved.size_px,
        weight: resolved.weight,
        glyphs,
        advance_width: total_advance,
        text_range: text_offset..text_offset + text.len(),
        direction: resolved_direction,
        underline_style: crate::types::UnderlineStyle::None,
        overline: false,
        strikeout: false,
        is_link: false,
        foreground_color: None,
        underline_color: None,
        background_color: None,
        anchor_href: None,
        tooltip: None,
        vertical_alignment: crate::types::VerticalAlignment::Normal,
        image_name: None,
        image_height: 0.0,
    })
}

/// Shape a text string, reusing a UnicodeBuffer to avoid allocations.
pub fn shape_text_with_buffer(
    registry: &FontRegistry,
    resolved: &ResolvedFont,
    text: &str,
    text_offset: usize,
    buffer: UnicodeBuffer,
    features: &[Feature],
) -> Option<(ShapedRun, UnicodeBuffer)> {
    let entry = registry.get(resolved.font_face_id)?;
    let font = FontRef::from_index(entry.bytes(), entry.face_index).ok()?;

    let upem = units_per_em(entry.bytes(), entry.face_index).unwrap_or(0) as f32;
    if upem == 0.0 {
        return None;
    }
    let sf = resolved.scale_factor.max(f32::MIN_POSITIVE);
    let physical_size = resolved.size_px * sf;
    let physical_scale = physical_size / upem;
    let inv_sf = 1.0 / sf;

    let mut buffer = buffer;
    buffer.push_str(text);
    // Recycled buffers come back without segment properties; explicitly
    // guess them so harfrust doesn't panic on Direction::Invalid.
    buffer.guess_segment_properties();

    let resolved_direction = if buffer.direction() == Direction::RightToLeft {
        TextDirection::RightToLeft
    } else {
        TextDirection::LeftToRight
    };

    let shaper_data = entry.shaper_data(&font);
    let shaper = shaper_data.shaper(&font).build();
    let glyph_buffer = shaper.shape(buffer, ShapeOptions::new().features(features));

    let infos = glyph_buffer.glyph_infos();
    let positions = glyph_buffer.glyph_positions();

    let mut glyphs = Vec::with_capacity(infos.len());
    let mut total_advance = 0.0f32;

    for (info, pos) in infos.iter().zip(positions.iter()) {
        let x_advance = pos.x_advance as f32 * physical_scale * inv_sf;
        let y_advance = pos.y_advance as f32 * physical_scale * inv_sf;
        let x_offset = pos.x_offset as f32 * physical_scale * inv_sf;
        let y_offset = pos.y_offset as f32 * physical_scale * inv_sf;

        glyphs.push(ShapedGlyph {
            glyph_id: info.glyph_id as u16,
            cluster: info.cluster,
            x_advance,
            y_advance,
            x_offset,
            y_offset,
            font_face_id: resolved.font_face_id,
        });

        total_advance += x_advance;
    }

    let run = ShapedRun {
        font_face_id: resolved.font_face_id,
        size_px: resolved.size_px,
        weight: resolved.weight,
        glyphs,
        advance_width: total_advance,
        text_range: text_offset..text_offset + text.len(),
        direction: resolved_direction,
        underline_style: crate::types::UnderlineStyle::None,
        overline: false,
        strikeout: false,
        is_link: false,
        foreground_color: None,
        underline_color: None,
        background_color: None,
        anchor_href: None,
        tooltip: None,
        vertical_alignment: crate::types::VerticalAlignment::Normal,
        image_name: None,
        image_height: 0.0,
    };

    // Reclaim the buffer for reuse
    let recycled = glyph_buffer.clear();
    Some((run, recycled))
}

/// Get font metrics (ascent, descent, leading) scaled to logical pixels.
///
/// Scales at `size_px * scale_factor` (physical) and divides by
/// `scale_factor`, so callers always see logical-pixel metrics.
pub fn font_metrics_px(registry: &FontRegistry, resolved: &ResolvedFont) -> Option<FontMetricsPx> {
    let entry = registry.get(resolved.font_face_id)?;
    let font_ref = swash::FontRef::from_index(entry.bytes(), entry.face_index as usize)?;
    let sf = resolved.scale_factor.max(f32::MIN_POSITIVE);
    let physical_size = resolved.size_px * sf;
    let metrics = font_ref.metrics(&[]).scale(physical_size);
    let inv_sf = 1.0 / sf;

    Some(FontMetricsPx {
        ascent: metrics.ascent * inv_sf,
        descent: metrics.descent * inv_sf,
        leading: metrics.leading * inv_sf,
        underline_offset: metrics.underline_offset * inv_sf,
        strikeout_offset: metrics.strikeout_offset * inv_sf,
        stroke_size: metrics.stroke_size * inv_sf,
    })
}

/// A bidi run: a contiguous range of text with the same direction.
pub struct BidiRun {
    pub byte_range: std::ops::Range<usize>,
    pub direction: TextDirection,
    /// Visual order index (for reordering after line breaking).
    pub visual_order: usize,
}

/// Analyze text for bidirectional content and return directional runs
/// in **visual order** per UAX #9 (Unicode Bidirectional Algorithm, rule L2).
///
/// The returned runs can be shaped independently and concatenated left-to-right
/// to produce correctly-ordered mixed-script text (e.g. Latin embedded in
/// Arabic). For pure-LTR text, returns a single LTR run. For pure-RTL text,
/// returns a single RTL run.
pub fn bidi_runs(text: &str) -> Vec<BidiRun> {
    use unicode_bidi::BidiInfo;

    if text.is_empty() {
        return Vec::new();
    }

    let bidi_info = BidiInfo::new(text, None);
    let mut runs = Vec::new();

    for para in &bidi_info.paragraphs {
        let (levels, level_runs) = bidi_info.visual_runs(para, para.range.clone());
        for level_run in level_runs {
            if level_run.is_empty() {
                continue;
            }
            let level = levels[level_run.start];
            let direction = if level.is_rtl() {
                TextDirection::RightToLeft
            } else {
                TextDirection::LeftToRight
            };
            let visual_order = runs.len();
            runs.push(BidiRun {
                byte_range: level_run,
                direction,
                visual_order,
            });
        }
    }

    if runs.is_empty() {
        runs.push(BidiRun {
            byte_range: 0..text.len(),
            direction: TextDirection::LeftToRight,
            visual_order: 0,
        });
    }

    runs
}

pub struct FontMetricsPx {
    pub ascent: f32,
    pub descent: f32,
    pub leading: f32,
    pub underline_offset: f32,
    pub strikeout_offset: f32,
    pub stroke_size: f32,
}