textflow-rs 0.2.1

Bounded no_std Unicode text layout, bidi shaping, line breaking, and caret positioning for Rust
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
use super::{
    FontFeature, GlyphBuffer, GlyphMask, LookupRequest, LookupStatus, ScriptProvider, ShapeError,
    ShapeRequest, TextRange,
};
use crate::unicode::{graphemes, Script};

const ALL: GlyphMask = GlyphMask::ALL;

fn enabled(request: &ShapeRequest<'_>, tag: [u8; 4], default: bool) -> bool {
    request
        .features
        .iter()
        .filter(|feature| feature.tag == tag && overlaps(feature, request))
        .fold(default, |_, feature| feature.value != 0)
}

fn overlaps(feature: &FontFeature, request: &ShapeRequest<'_>) -> bool {
    feature.range.end > request.range.start as u32 && feature.range.start < request.range.end as u32
}

fn substitute(
    request: &ShapeRequest<'_>,
    font: &dyn super::ShapingData,
    glyphs: &mut GlyphBuffer<'_>,
    tag: [u8; 4],
    mask: GlyphMask,
    default: bool,
) -> Result<LookupStatus, ShapeError> {
    if !enabled(request, tag, default) {
        return Ok(LookupStatus::NotFound);
    }
    font.substitute(LookupRequest::new(request, tag, mask), glyphs)
}

fn position(
    request: &ShapeRequest<'_>,
    font: &dyn super::ShapingData,
    glyphs: &mut GlyphBuffer<'_>,
    tag: [u8; 4],
    default: bool,
) -> Result<LookupStatus, ShapeError> {
    if !enabled(request, tag, default) {
        return Ok(LookupStatus::NotFound);
    }
    font.position(LookupRequest::new(request, tag, ALL), glyphs)
}

fn normalize_clusters(request: &ShapeRequest<'_>, glyphs: &mut GlyphBuffer<'_>) {
    let text = &request.text[request.range.clone()];
    for cluster in graphemes(text) {
        let range = TextRange::new(
            (request.range.start + cluster.range.start) as u32,
            (request.range.start + cluster.range.end) as u32,
        );
        let mut matched = 0;
        for glyph in glyphs.glyphs_mut() {
            if glyph.cluster.start >= range.start && glyph.cluster.start < range.end {
                glyph.cluster = range;
                matched += 1;
            }
        }
        if matched > 1 {
            for glyph in glyphs.glyphs_mut() {
                if glyph.cluster == range {
                    glyph.set_unsafe_to_break(true);
                }
            }
        }
    }
}

#[cfg(feature = "script-arabic")]
/// Built-in Arabic script provider.
pub const ARABIC: Arabic = Arabic;

#[cfg(feature = "script-arabic")]
/// Applies Arabic joining forms, ligatures, cursive attachment, and mark positioning.
pub struct Arabic;

#[cfg(feature = "script-arabic")]
const ISOL: GlyphMask = GlyphMask::new(1 << 0);
#[cfg(feature = "script-arabic")]
const INIT: GlyphMask = GlyphMask::new(1 << 1);
#[cfg(feature = "script-arabic")]
const MEDI: GlyphMask = GlyphMask::new(1 << 2);
#[cfg(feature = "script-arabic")]
const FINA: GlyphMask = GlyphMask::new(1 << 3);

#[cfg(feature = "script-arabic")]
#[derive(Clone, Copy, Eq, PartialEq)]
enum Joining {
    None,
    Right,
    Dual,
    Transparent,
}

#[cfg(feature = "script-arabic")]
impl Joining {
    const fn joins_previous(self) -> bool {
        matches!(self, Self::Right | Self::Dual)
    }

    const fn joins_next(self) -> bool {
        matches!(self, Self::Dual)
    }
}

#[cfg(feature = "script-arabic")]
fn joining(character: char) -> Joining {
    let scalar = character as u32;
    if matches!(
        scalar,
        0x0610..=0x061A | 0x064B..=0x065F | 0x0670 | 0x06D6..=0x06ED | 0x08D3..=0x08FF
    ) {
        return Joining::Transparent;
    }
    if matches!(
        scalar,
        0x0622..=0x0625
            | 0x0627
            | 0x0629
            | 0x062F..=0x0632
            | 0x0648
            | 0x0671..=0x0673
            | 0x0675..=0x0677
            | 0x0688..=0x0699
            | 0x06C0
            | 0x06C3..=0x06CB
            | 0x06CD
            | 0x06CF
            | 0x06D2..=0x06D3
    ) {
        return Joining::Right;
    }
    if matches!(
        scalar,
        0x0626
            | 0x0628
            | 0x062A..=0x062E
            | 0x0633..=0x063A
            | 0x0641..=0x0647
            | 0x0649..=0x064A
            | 0x066E..=0x066F
            | 0x0678..=0x0687
            | 0x069A..=0x06BF
            | 0x06CC
            | 0x06CE
            | 0x06D0..=0x06D1
            | 0x06FA..=0x06FC
    ) {
        return Joining::Dual;
    }
    Joining::None
}

#[cfg(feature = "script-arabic")]
fn character_at(
    request: &ShapeRequest<'_>,
    glyphs: &GlyphBuffer<'_>,
    index: usize,
) -> Option<char> {
    let start = usize::try_from(glyphs.get(index)?.cluster.start).ok()?;
    request.text.get(start..)?.chars().next()
}

#[cfg(feature = "script-arabic")]
fn neighbor(
    request: &ShapeRequest<'_>,
    glyphs: &GlyphBuffer<'_>,
    index: usize,
    previous: bool,
) -> Option<Joining> {
    if previous {
        for slot in (0..index).rev() {
            let class = joining(character_at(request, glyphs, slot)?);
            if class != Joining::Transparent {
                return Some(class);
            }
        }
    } else {
        for slot in index + 1..glyphs.len() {
            let class = joining(character_at(request, glyphs, slot)?);
            if class != Joining::Transparent {
                return Some(class);
            }
        }
    }
    None
}

#[cfg(feature = "script-arabic")]
fn assign_joining_masks(
    request: &ShapeRequest<'_>,
    glyphs: &mut GlyphBuffer<'_>,
) -> Result<bool, ShapeError> {
    let mut joined = false;
    for index in 0..glyphs.len() {
        let current =
            joining(character_at(request, glyphs, index).ok_or(ShapeError::InvalidGlyphRange)?);
        if current == Joining::Transparent {
            glyphs.set_mask(index, GlyphMask::NONE)?;
            continue;
        }
        let previous = neighbor(request, glyphs, index, true)
            .is_some_and(|class| class.joins_next() && current.joins_previous());
        let next = neighbor(request, glyphs, index, false)
            .is_some_and(|class| current.joins_next() && class.joins_previous());
        let mask = match (previous, next) {
            (false, false) => ISOL,
            (false, true) => INIT,
            (true, true) => MEDI,
            (true, false) => FINA,
        };
        joined |= previous || next;
        if previous || next {
            glyphs
                .get_mut(index)
                .expect("valid joining slot")
                .set_unsafe_to_break(true);
        }
        glyphs.set_mask(index, mask)?;
    }
    Ok(joined)
}

#[cfg(feature = "script-arabic")]
impl ScriptProvider for Arabic {
    fn script(&self) -> Script {
        Script::Arabic
    }

    fn substitute(
        &self,
        request: &ShapeRequest<'_>,
        font: &dyn super::ShapingData,
        glyphs: &mut GlyphBuffer<'_>,
    ) -> Result<(), ShapeError> {
        normalize_clusters(request, glyphs);
        let joined = assign_joining_masks(request, glyphs)?;
        substitute(request, font, glyphs, *b"ccmp", ALL, true)?;
        substitute(request, font, glyphs, *b"locl", ALL, true)?;
        let mut forms = 0;
        for (tag, mask) in [
            (*b"isol", ISOL),
            (*b"fina", FINA),
            (*b"medi", MEDI),
            (*b"init", INIT),
        ] {
            forms += usize::from(
                substitute(request, font, glyphs, tag, mask, true)? == LookupStatus::Applied,
            );
        }
        if joined && forms == 0 {
            return Err(ShapeError::ShapingUnavailable);
        }
        for tag in [*b"rlig", *b"calt", *b"liga"] {
            substitute(request, font, glyphs, tag, ALL, true)?;
        }
        Ok(())
    }

    fn position(
        &self,
        request: &ShapeRequest<'_>,
        font: &dyn super::ShapingData,
        glyphs: &mut GlyphBuffer<'_>,
    ) -> Result<(), ShapeError> {
        position(request, font, glyphs, *b"curs", true)?;
        position(request, font, glyphs, *b"kern", true)?;
        let has_marks = request.text[request.range.clone()]
            .chars()
            .any(|character| joining(character) == Joining::Transparent);
        let mark = position(request, font, glyphs, *b"mark", true)?;
        let mkmk = position(request, font, glyphs, *b"mkmk", true)?;
        if has_marks && mark == LookupStatus::NotFound && mkmk == LookupStatus::NotFound {
            return Err(ShapeError::ShapingUnavailable);
        }
        Ok(())
    }
}

#[cfg(feature = "script-thai")]
/// Built-in Thai script provider.
pub const THAI: Thai = Thai;

#[cfg(feature = "script-thai")]
/// Applies Thai cluster substitutions and mark positioning.
pub struct Thai;

#[cfg(feature = "script-thai")]
fn thai_mark(character: char) -> bool {
    matches!(character as u32, 0x0E31 | 0x0E34..=0x0E3A | 0x0E47..=0x0E4E)
}

#[cfg(feature = "script-thai")]
impl ScriptProvider for Thai {
    fn script(&self) -> Script {
        Script::Thai
    }

    fn substitute(
        &self,
        request: &ShapeRequest<'_>,
        font: &dyn super::ShapingData,
        glyphs: &mut GlyphBuffer<'_>,
    ) -> Result<(), ShapeError> {
        normalize_clusters(request, glyphs);
        for tag in [*b"ccmp", *b"locl", *b"liga"] {
            substitute(request, font, glyphs, tag, ALL, true)?;
        }
        Ok(())
    }

    fn position(
        &self,
        request: &ShapeRequest<'_>,
        font: &dyn super::ShapingData,
        glyphs: &mut GlyphBuffer<'_>,
    ) -> Result<(), ShapeError> {
        position(request, font, glyphs, *b"kern", true)?;
        let has_marks = request.text[request.range.clone()].chars().any(thai_mark);
        let mark = position(request, font, glyphs, *b"mark", true)?;
        let mkmk = position(request, font, glyphs, *b"mkmk", true)?;
        if has_marks && mark == LookupStatus::NotFound && mkmk == LookupStatus::NotFound {
            return Err(ShapeError::ShapingUnavailable);
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bidi::Direction;
    use crate::shaping::{
        FlowPoint, FontAccessError, FontId, GlyphId, GlyphSource, ShapedGlyph, ShapingData,
    };

    struct Font;

    impl GlyphSource for Font {
        fn id(&self) -> FontId {
            FontId::new(1)
        }
        fn metrics(&self) -> Result<super::super::FontMetrics, FontAccessError> {
            Ok(super::super::FontMetrics::default())
        }
        fn glyph_for(&self, character: char) -> Result<Option<GlyphId>, FontAccessError> {
            Ok(Some(GlyphId::new(character as u16)))
        }
        fn glyph_advance(&self, _glyph: GlyphId) -> Result<FlowPoint, FontAccessError> {
            Ok(FlowPoint { x: 10, y: 0 })
        }
    }

    struct Data;
    impl ShapingData for Data {
        fn substitute(
            &self,
            request: LookupRequest<'_, '_>,
            glyphs: &mut GlyphBuffer<'_>,
        ) -> Result<LookupStatus, ShapeError> {
            for index in 0..glyphs.len() {
                if glyphs.mask(index).is_some_and(|mask| request.selects(mask)) {
                    glyphs.set_glyph(index, GlyphId::new(100 + request.feature()[0] as u16))?;
                }
            }
            Ok(LookupStatus::Applied)
        }
        fn position(
            &self,
            _request: LookupRequest<'_, '_>,
            _glyphs: &mut GlyphBuffer<'_>,
        ) -> Result<LookupStatus, ShapeError> {
            Ok(LookupStatus::Applied)
        }
    }

    struct MissingData;

    impl ShapingData for MissingData {
        fn substitute(
            &self,
            _request: LookupRequest<'_, '_>,
            _glyphs: &mut GlyphBuffer<'_>,
        ) -> Result<LookupStatus, ShapeError> {
            Ok(LookupStatus::NotFound)
        }

        fn position(
            &self,
            _request: LookupRequest<'_, '_>,
            _glyphs: &mut GlyphBuffer<'_>,
        ) -> Result<LookupStatus, ShapeError> {
            Ok(LookupStatus::NotFound)
        }
    }

    #[cfg(feature = "script-arabic")]
    #[test]
    fn arabic_assigns_contextual_forms_without_allocating() {
        let providers: [&dyn ScriptProvider; 1] = [&ARABIC];
        let face = super::super::ScriptTypeface::new(&Font, &Data).with_scripts(&providers);
        let text = "مرحبا";
        let request =
            ShapeRequest::new(text, 0..text.len(), Direction::RightToLeft, Script::Arabic);
        let mut output = [ShapedGlyph::default(); 5];
        let count = super::super::Typeface::shape_into(&face, &request, &mut output).unwrap();
        assert_eq!(count, 5);
        assert!(output
            .iter()
            .all(|glyph| glyph.glyph_id() == GlyphId::new(208)));
        assert!(output.iter().all(|glyph| glyph.unsafe_to_break()));
    }

    #[cfg(feature = "script-arabic")]
    #[test]
    fn arabic_joining_masks_skip_transparent_marks() {
        let text = "بَبب";
        let request =
            ShapeRequest::new(text, 0..text.len(), Direction::RightToLeft, Script::Arabic);
        let mut output = [ShapedGlyph::default(); 4];
        for (slot, (offset, character)) in output.iter_mut().zip(text.char_indices()) {
            *slot = ShapedGlyph::new(
                GlyphId::new(character as u16),
                TextRange::new(offset as u32, (offset + character.len_utf8()) as u32),
            );
        }
        let mut glyphs = GlyphBuffer::new(&mut output, 4).unwrap();

        assert!(assign_joining_masks(&request, &mut glyphs).unwrap());
        assert_eq!(glyphs.mask(0), Some(INIT));
        assert_eq!(glyphs.mask(1), Some(GlyphMask::NONE));
        assert_eq!(glyphs.mask(2), Some(MEDI));
        assert_eq!(glyphs.mask(3), Some(FINA));
    }

    #[cfg(feature = "script-arabic")]
    #[test]
    fn arabic_marks_require_positioning_data() {
        let providers: [&dyn ScriptProvider; 1] = [&ARABIC];
        let face = super::super::ScriptTypeface::new(&Font, &MissingData).with_scripts(&providers);
        let text = "بَ";
        let request =
            ShapeRequest::new(text, 0..text.len(), Direction::RightToLeft, Script::Arabic);
        let mut output = [ShapedGlyph::default(); 2];

        assert_eq!(
            super::super::Typeface::shape_into(&face, &request, &mut output),
            Err(ShapeError::ShapingUnavailable)
        );
    }

    #[cfg(feature = "script-thai")]
    #[test]
    fn thai_keeps_base_and_mark_in_one_cluster() {
        let providers: [&dyn ScriptProvider; 1] = [&THAI];
        let face = super::super::ScriptTypeface::new(&Font, &Data).with_scripts(&providers);
        let text = "กิ";
        let request = ShapeRequest::new(text, 0..text.len(), Direction::LeftToRight, Script::Thai);
        let mut output = [ShapedGlyph::default(); 2];
        let count = super::super::Typeface::shape_into(&face, &request, &mut output).unwrap();
        assert_eq!(count, 2);
        assert!(output
            .iter()
            .all(|glyph| glyph.glyph_id() == GlyphId::new(208)));
        assert_eq!(output[0].cluster, output[1].cluster);
        assert!(output.iter().all(|glyph| glyph.unsafe_to_break()));
    }

    #[cfg(feature = "script-thai")]
    #[test]
    fn thai_marks_require_positioning_data() {
        let providers: [&dyn ScriptProvider; 1] = [&THAI];
        let face = super::super::ScriptTypeface::new(&Font, &MissingData).with_scripts(&providers);
        let text = "กิ";
        let request = ShapeRequest::new(text, 0..text.len(), Direction::LeftToRight, Script::Thai);
        let mut output = [ShapedGlyph::default(); 2];

        assert_eq!(
            super::super::Typeface::shape_into(&face, &request, &mut output),
            Err(ShapeError::ShapingUnavailable)
        );
    }
}