Skip to main content

strata_layout/typography/
shaper.rs

1//! OpenType text shaper: GSUB ligatures, GPOS pair kerning, and glyph placement.
2//!
3//! Evaluates code ligatures (e.g., `===`, `!=`, `=>`), typographic ligatures (`fi`, `fl`),
4//! optical pair kerning adjustments, and subpixel glyph advance positioning.
5
6use super::font_metrics::FontMetrics;
7use strata_primitives::geom::LayoutUnit;
8
9/// Single positioned glyph resulting from text shaping.
10#[derive(Debug, Clone, Copy, PartialEq)]
11pub struct ShapedGlyph {
12    /// Glyph identifier (index in font face or unicode scalar).
13    pub glyph_id: u32,
14    /// UTF-8 byte offset in original text corresponding to this glyph cluster.
15    pub cluster: u32,
16    /// Number of UTF-8 bytes consumed in original source text by this cluster.
17    pub source_bytes: u16,
18    /// Horizontal advance width to the next glyph origin.
19    pub x_advance: LayoutUnit,
20    /// Vertical advance (0 in horizontal writing mode).
21    pub y_advance: LayoutUnit,
22    /// Horizontal subpixel offset relative to glyph origin.
23    pub x_offset: LayoutUnit,
24    /// Vertical subpixel offset relative to baseline.
25    pub y_offset: LayoutUnit,
26    /// Whether this glyph was produced by a multi-character ligature substitution.
27    pub is_ligature: bool,
28    /// Whether this glyph represents a space or non-breaking whitespace.
29    pub is_space: bool,
30    /// Whether this glyph represents a nonspacing combining mark (zero advance, anchors to base).
31    pub is_mark: bool,
32}
33
34/// Classification of OpenType ligature rules.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum LigatureKind {
37    /// Standard typographic ligatures (`liga`).
38    Standard,
39    /// Contextual programming ligatures (`calt`).
40    Contextual,
41    /// Discretionary ligatures (`dlig`).
42    Discretionary,
43    /// Complex Indic script conjuncts.
44    Indic,
45}
46
47/// OpenType GSUB/GPOS feature tags configuration.
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub struct OpenTypeFeatures {
50    /// Standard ligatures (`liga`, `clig`).
51    pub ligatures: bool,
52    /// Contextual alternates and programming code ligatures (`calt`).
53    pub contextual: bool,
54    /// Discretionary typographic ligatures (`dlig`, e.g. `st`, `ct`).
55    pub discretionary: bool,
56    /// Small capitals (`smcp`).
57    pub small_caps: bool,
58}
59
60impl Default for OpenTypeFeatures {
61    fn default() -> Self {
62        Self {
63            ligatures: true,
64            contextual: true,
65            discretionary: false,
66            small_caps: false,
67        }
68    }
69}
70
71/// Maps ASCII lowercase characters to Unicode small-cap equivalents for `smcp` OpenType feature.
72pub fn apply_small_caps(text: &str) -> String {
73    text.chars()
74        .map(|c| match c {
75            'a' => '\u{1D00}',
76            'b' => '\u{1D04}',
77            'c' => '\u{1D05}',
78            'd' => '\u{1D07}',
79            'e' => '\u{1D08}',
80            'f' => '\u{A730}',
81            'g' => '\u{0262}',
82            'h' => '\u{029C}',
83            'i' => '\u{026A}',
84            'j' => '\u{1D0A}',
85            'k' => '\u{1D0B}',
86            'l' => '\u{029F}',
87            'm' => '\u{1D0D}',
88            'n' => '\u{0274}',
89            'o' => '\u{1D0F}',
90            'p' => '\u{1D18}',
91            'q' => '\u{01EB}',
92            'r' => '\u{0280}',
93            's' => '\u{A731}',
94            't' => '\u{1D1B}',
95            'u' => '\u{1D1C}',
96            'v' => '\u{1D20}',
97            'w' => '\u{1D21}',
98            'x' => 'x',
99            'y' => '\u{028F}',
100            'z' => '\u{1D22}',
101            _ => c,
102        })
103        .collect()
104}
105
106/// Known ligature definition with replacement glyph token.
107struct LigatureRule {
108    pattern: &'static str,
109    glyph_id: u32,
110    advance_factor: f32,
111    kind: LigatureKind,
112}
113
114static KNOWN_LIGATURES: &[LigatureRule] = &[
115    // 4-character ligatures
116    LigatureRule {
117        pattern: "<!--",
118        glyph_id: 0xF001,
119        advance_factor: 2.4,
120        kind: LigatureKind::Contextual,
121    },
122    // 3-character code ligatures
123    LigatureRule {
124        pattern: "===",
125        glyph_id: 0xF002,
126        advance_factor: 1.8,
127        kind: LigatureKind::Contextual,
128    },
129    LigatureRule {
130        pattern: "!==",
131        glyph_id: 0xF003,
132        advance_factor: 1.8,
133        kind: LigatureKind::Contextual,
134    },
135    LigatureRule {
136        pattern: "-->",
137        glyph_id: 0xF004,
138        advance_factor: 1.8,
139        kind: LigatureKind::Contextual,
140    },
141    LigatureRule {
142        pattern: "...",
143        glyph_id: 0xF005,
144        advance_factor: 1.2,
145        kind: LigatureKind::Contextual,
146    },
147    LigatureRule {
148        pattern: "ffi",
149        glyph_id: 0xFB03,
150        advance_factor: 1.4,
151        kind: LigatureKind::Standard,
152    },
153    LigatureRule {
154        pattern: "ffl",
155        glyph_id: 0xFB04,
156        advance_factor: 1.4,
157        kind: LigatureKind::Standard,
158    },
159    // 2-character code & typographic ligatures
160    LigatureRule {
161        pattern: "==",
162        glyph_id: 0xF006,
163        advance_factor: 1.3,
164        kind: LigatureKind::Contextual,
165    },
166    LigatureRule {
167        pattern: "!=",
168        glyph_id: 0xF007,
169        advance_factor: 1.3,
170        kind: LigatureKind::Contextual,
171    },
172    LigatureRule {
173        pattern: "<=",
174        glyph_id: 0xF008,
175        advance_factor: 1.3,
176        kind: LigatureKind::Contextual,
177    },
178    LigatureRule {
179        pattern: ">=",
180        glyph_id: 0xF009,
181        advance_factor: 1.3,
182        kind: LigatureKind::Contextual,
183    },
184    LigatureRule {
185        pattern: "=>",
186        glyph_id: 0xF00A,
187        advance_factor: 1.3,
188        kind: LigatureKind::Contextual,
189    },
190    LigatureRule {
191        pattern: "->",
192        glyph_id: 0xF00B,
193        advance_factor: 1.3,
194        kind: LigatureKind::Contextual,
195    },
196    LigatureRule {
197        pattern: "<-",
198        glyph_id: 0xF00C,
199        advance_factor: 1.3,
200        kind: LigatureKind::Contextual,
201    },
202    LigatureRule {
203        pattern: "::",
204        glyph_id: 0xF00D,
205        advance_factor: 1.0,
206        kind: LigatureKind::Contextual,
207    },
208    LigatureRule {
209        pattern: "fi",
210        glyph_id: 0xFB01,
211        advance_factor: 0.95,
212        kind: LigatureKind::Standard,
213    },
214    LigatureRule {
215        pattern: "fl",
216        glyph_id: 0xFB02,
217        advance_factor: 0.95,
218        kind: LigatureKind::Standard,
219    },
220    LigatureRule {
221        pattern: "ff",
222        glyph_id: 0xFB00,
223        advance_factor: 0.95,
224        kind: LigatureKind::Standard,
225    },
226    // Discretionary ligatures (dlig)
227    LigatureRule {
228        pattern: "st",
229        glyph_id: 0xFB06,
230        advance_factor: 1.0,
231        kind: LigatureKind::Discretionary,
232    },
233    LigatureRule {
234        pattern: "ct",
235        glyph_id: 0xF020,
236        advance_factor: 1.0,
237        kind: LigatureKind::Discretionary,
238    },
239    LigatureRule {
240        pattern: "sp",
241        glyph_id: 0xF021,
242        advance_factor: 1.0,
243        kind: LigatureKind::Discretionary,
244    },
245    LigatureRule {
246        pattern: "th",
247        glyph_id: 0xF022,
248        advance_factor: 1.0,
249        kind: LigatureKind::Discretionary,
250    },
251    // Extended code operator ligatures
252    LigatureRule {
253        pattern: "||=",
254        glyph_id: 0xF010,
255        advance_factor: 1.8,
256        kind: LigatureKind::Contextual,
257    },
258    LigatureRule {
259        pattern: "&&=",
260        glyph_id: 0xF011,
261        advance_factor: 1.8,
262        kind: LigatureKind::Contextual,
263    },
264    LigatureRule {
265        pattern: "??=",
266        glyph_id: 0xF012,
267        advance_factor: 1.8,
268        kind: LigatureKind::Contextual,
269    },
270    LigatureRule {
271        pattern: ":=",
272        glyph_id: 0xF013,
273        advance_factor: 1.2,
274        kind: LigatureKind::Contextual,
275    },
276    LigatureRule {
277        pattern: "+=",
278        glyph_id: 0xF014,
279        advance_factor: 1.2,
280        kind: LigatureKind::Contextual,
281    },
282    LigatureRule {
283        pattern: "-=",
284        glyph_id: 0xF015,
285        advance_factor: 1.2,
286        kind: LigatureKind::Contextual,
287    },
288    LigatureRule {
289        pattern: "*=",
290        glyph_id: 0xF016,
291        advance_factor: 1.2,
292        kind: LigatureKind::Contextual,
293    },
294    LigatureRule {
295        pattern: "/=",
296        glyph_id: 0xF017,
297        advance_factor: 1.2,
298        kind: LigatureKind::Contextual,
299    },
300    // Indic complex script conjuncts (consonant + virama + consonant)
301    LigatureRule {
302        pattern: "\u{0915}\u{094D}\u{0937}", // ksha (क्ष)
303        glyph_id: 0xF050,
304        advance_factor: 1.1,
305        kind: LigatureKind::Indic,
306    },
307    LigatureRule {
308        pattern: "\u{0924}\u{094D}\u{0930}", // tra (त्र)
309        glyph_id: 0xF051,
310        advance_factor: 1.0,
311        kind: LigatureKind::Indic,
312    },
313    LigatureRule {
314        pattern: "\u{091C}\u{094D}\u{091E}", // gya (ज्ञ)
315        glyph_id: 0xF052,
316        advance_factor: 1.1,
317        kind: LigatureKind::Indic,
318    },
319    LigatureRule {
320        pattern: "\u{0936}\u{094D}\u{0930}", // shra (श्र)
321        glyph_id: 0xF053,
322        advance_factor: 1.1,
323        kind: LigatureKind::Indic,
324    },
325    LigatureRule {
326        pattern: "\u{0924}\u{094D}\u{0924}", // tta (त्त)
327        glyph_id: 0xF054,
328        advance_factor: 1.0,
329        kind: LigatureKind::Indic,
330    },
331    LigatureRule {
332        pattern: "\u{0926}\u{094D}\u{0935}", // dva (द्व)
333        glyph_id: 0xF055,
334        advance_factor: 1.0,
335        kind: LigatureKind::Indic,
336    },
337    LigatureRule {
338        pattern: "\u{0926}\u{094D}\u{0927}", // ddha (द्ध)
339        glyph_id: 0xF056,
340        advance_factor: 1.0,
341        kind: LigatureKind::Indic,
342    },
343    LigatureRule {
344        pattern: "\u{0938}\u{094D}\u{0924}\u{094D}\u{0930}", // stra (स्त्र)
345        glyph_id: 0xF057,
346        advance_factor: 1.2,
347        kind: LigatureKind::Indic,
348    },
349    LigatureRule {
350        pattern: "\u{0915}\u{094D}\u{0930}", // kra (क्र)
351        glyph_id: 0xF058,
352        advance_factor: 1.0,
353        kind: LigatureKind::Indic,
354    },
355    LigatureRule {
356        pattern: "\u{092A}\u{094D}\u{0930}", // pra (प्र)
357        glyph_id: 0xF059,
358        advance_factor: 1.0,
359        kind: LigatureKind::Indic,
360    },
361    LigatureRule {
362        pattern: "\u{0926}\u{094D}\u{092F}", // dya (द्य)
363        glyph_id: 0xF05A,
364        advance_factor: 1.0,
365        kind: LigatureKind::Indic,
366    },
367    LigatureRule {
368        pattern: "\u{0937}\u{094D}\u{091F}", // shta (ष्ट)
369        glyph_id: 0xF05B,
370        advance_factor: 1.0,
371        kind: LigatureKind::Indic,
372    },
373    LigatureRule {
374        pattern: "\u{0937}\u{094D}\u{0920}", // shtha (ष्ठ)
375        glyph_id: 0xF05C,
376        advance_factor: 1.0,
377        kind: LigatureKind::Indic,
378    },
379];
380
381/// Known optical pair kerning adjustment rules (fractions of em).
382struct KerningPair {
383    first: char,
384    second: char,
385    delta_em: f32,
386}
387
388static KNOWN_KERNING_PAIRS: &[KerningPair] = &[
389    KerningPair {
390        first: 'A',
391        second: 'V',
392        delta_em: -0.085,
393    },
394    KerningPair {
395        first: 'V',
396        second: 'A',
397        delta_em: -0.085,
398    },
399    KerningPair {
400        first: 'A',
401        second: 'W',
402        delta_em: -0.070,
403    },
404    KerningPair {
405        first: 'W',
406        second: 'A',
407        delta_em: -0.070,
408    },
409    KerningPair {
410        first: 'A',
411        second: 'T',
412        delta_em: -0.075,
413    },
414    KerningPair {
415        first: 'T',
416        second: 'A',
417        delta_em: -0.075,
418    },
419    KerningPair {
420        first: 'T',
421        second: 'o',
422        delta_em: -0.070,
423    },
424    KerningPair {
425        first: 'T',
426        second: 'e',
427        delta_em: -0.065,
428    },
429    KerningPair {
430        first: 'W',
431        second: 'e',
432        delta_em: -0.045,
433    },
434    KerningPair {
435        first: 'P',
436        second: 'a',
437        delta_em: -0.055,
438    },
439    KerningPair {
440        first: 'P',
441        second: 'o',
442        delta_em: -0.050,
443    },
444    KerningPair {
445        first: 'Y',
446        second: 'o',
447        delta_em: -0.080,
448    },
449    KerningPair {
450        first: 'Y',
451        second: 'a',
452        delta_em: -0.075,
453    },
454    KerningPair {
455        first: 'F',
456        second: 'a',
457        delta_em: -0.060,
458    },
459    KerningPair {
460        first: 'L',
461        second: 'T',
462        delta_em: -0.065,
463    },
464    KerningPair {
465        first: 'L',
466        second: 'V',
467        delta_em: -0.070,
468    },
469    KerningPair {
470        first: 'r',
471        second: 'c',
472        delta_em: -0.025,
473    },
474    KerningPair {
475        first: 'f',
476        second: 'i',
477        delta_em: -0.020,
478    },
479];
480
481/// Pure-Rust OpenType text shaping engine.
482#[derive(Debug, Clone, Copy, Default)]
483pub struct TextShaper;
484
485impl TextShaper {
486    pub fn new() -> Self {
487        Self
488    }
489
490    /// Shapes text using authentic OpenType glyph advances, kerning, and configured feature tags from an OpenTypeFont.
491    pub fn shape_with_font_and_features(
492        &self,
493        text: &str,
494        font: &super::opentype::OpenTypeFont,
495        font_size: f32,
496        features: OpenTypeFeatures,
497    ) -> Vec<ShapedGlyph> {
498        if text.is_empty() {
499            return Vec::new();
500        }
501
502        let metrics = font.font_metrics(font_size);
503
504        // Complex script pass: Contextual Arabic cursive joining & multi-glyph ligatures
505        if text.chars().any(|c| {
506            ('\u{0600}'..='\u{06FF}').contains(&c) || ('\u{0750}'..='\u{077F}').contains(&c)
507        }) {
508            let mut arabic_glyphs = self.shape_arabic_run(text, &metrics);
509            for g in &mut arabic_glyphs {
510                if let Some(ch) = char::from_u32(g.glyph_id) {
511                    let gid = font.glyph_id(ch);
512                    if gid > 0 {
513                        g.glyph_id = gid as u32;
514                        let adv = font.glyph_advance(gid, font_size);
515                        if adv > 0.0 && !g.is_mark {
516                            g.x_advance = LayoutUnit::from_f32(adv);
517                        }
518                    }
519                }
520            }
521            return arabic_glyphs;
522        }
523
524        // Complex script pass: Indic Universal Shaping Engine (USE) conjuncts & pre-base vowel reordering
525        if text.chars().any(is_indic_char) {
526            let mut indic_glyphs = self.shape_indic_run(text, &metrics);
527            for g in &mut indic_glyphs {
528                if let Some(ch) = char::from_u32(g.glyph_id) {
529                    let gid = font.glyph_id(ch);
530                    if gid > 0 {
531                        g.glyph_id = gid as u32;
532                        let adv = font.glyph_advance(gid, font_size);
533                        if adv > 0.0 && !g.is_mark {
534                            g.x_advance = LayoutUnit::from_f32(adv);
535                        }
536                    }
537                }
538            }
539            return indic_glyphs;
540        }
541
542        let transformed_text: std::borrow::Cow<'_, str> = if features.small_caps {
543            std::borrow::Cow::Owned(apply_small_caps(text))
544        } else {
545            std::borrow::Cow::Borrowed(text)
546        };
547        let input_text = transformed_text.as_ref();
548
549        let bytes = input_text.as_bytes();
550        let mut glyphs = Vec::with_capacity(input_text.len());
551        let mut byte_idx = 0;
552
553        while byte_idx < bytes.len() {
554            let slice = &input_text[byte_idx..];
555
556            // 1. Check for multi-character ligatures based on active OpenType features
557            let mut matched_ligature = None;
558            for lig in KNOWN_LIGATURES {
559                let is_active = match lig.kind {
560                    LigatureKind::Standard => features.ligatures,
561                    LigatureKind::Contextual => features.contextual,
562                    LigatureKind::Discretionary => features.discretionary,
563                    LigatureKind::Indic => true,
564                };
565                if is_active && slice.starts_with(lig.pattern) {
566                    matched_ligature = Some(lig);
567                    break;
568                }
569            }
570
571            if let Some(lig) = matched_ligature {
572                let advance = if let Some(first_ch) = char::from_u32(lig.glyph_id) {
573                    let gid = font.glyph_id(first_ch);
574                    if gid > 0 {
575                        font.glyph_advance(gid, font_size)
576                    } else {
577                        font_size * lig.advance_factor
578                    }
579                } else {
580                    font_size * lig.advance_factor
581                };
582
583                glyphs.push(ShapedGlyph {
584                    glyph_id: lig.glyph_id,
585                    cluster: byte_idx as u32,
586                    source_bytes: lig.pattern.len() as u16,
587                    x_advance: LayoutUnit::from_f32(advance),
588                    y_advance: LayoutUnit::ZERO,
589                    x_offset: LayoutUnit::ZERO,
590                    y_offset: LayoutUnit::ZERO,
591                    is_ligature: true,
592                    is_space: false,
593                    is_mark: false,
594                });
595                byte_idx += lig.pattern.len();
596                continue;
597            }
598
599            let ch = match slice.chars().next() {
600                Some(c) => c,
601                None => break,
602            };
603            let char_len = ch.len_utf8();
604
605            if is_combining_mark(ch) {
606                let y_offset = compute_mark_offset(ch, font_size);
607                glyphs.push(ShapedGlyph {
608                    glyph_id: ch as u32,
609                    cluster: byte_idx as u32,
610                    source_bytes: char_len as u16,
611                    x_advance: LayoutUnit::ZERO,
612                    y_advance: LayoutUnit::ZERO,
613                    x_offset: LayoutUnit::ZERO,
614                    y_offset,
615                    is_ligature: false,
616                    is_space: false,
617                    is_mark: true,
618                });
619                byte_idx += char_len;
620                continue;
621            }
622
623            let gid = font.glyph_id(ch);
624            let advance = font.glyph_advance(gid, font_size);
625            let is_space = ch == ' ' || ch == '\t' || ch == '\u{00A0}';
626
627            glyphs.push(ShapedGlyph {
628                glyph_id: gid as u32,
629                cluster: byte_idx as u32,
630                source_bytes: char_len as u16,
631                x_advance: LayoutUnit::from_f32(advance),
632                y_advance: LayoutUnit::ZERO,
633                x_offset: LayoutUnit::ZERO,
634                y_offset: LayoutUnit::ZERO,
635                is_ligature: false,
636                is_space,
637                is_mark: false,
638            });
639
640            byte_idx += char_len;
641        }
642
643        if glyphs.len() > 1 {
644            for i in 0..glyphs.len() - 1 {
645                let g1 = glyphs[i].glyph_id as u16;
646                let g2 = glyphs[i + 1].glyph_id as u16;
647                let kern_delta = font.pair_kerning(g1, g2, font_size);
648                if kern_delta != 0.0 {
649                    glyphs[i].x_advance = glyphs[i].x_advance + LayoutUnit::from_f32(kern_delta);
650                }
651            }
652        }
653
654        glyphs
655    }
656
657    /// Shapes text using authentic OpenType glyph advances and kerning from an OpenTypeFont using default features.
658    #[inline]
659    pub fn shape_with_font(
660        &self,
661        text: &str,
662        font: &super::opentype::OpenTypeFont,
663        font_size: f32,
664    ) -> Vec<ShapedGlyph> {
665        self.shape_with_font_and_features(text, font, font_size, OpenTypeFeatures::default())
666    }
667
668    /// Shapes a text run into positioned glyphs, applying ligatures and pair kerning.
669    pub fn shape(&self, text: &str, metrics: &FontMetrics, is_monospace: bool) -> Vec<ShapedGlyph> {
670        if text.is_empty() {
671            return Vec::new();
672        }
673
674        // Complex script pass: Contextual Arabic cursive shaping & multi-glyph ligatures
675        if !is_monospace
676            && text.chars().any(|c| {
677                ('\u{0600}'..='\u{06FF}').contains(&c) || ('\u{0750}'..='\u{077F}').contains(&c)
678            })
679        {
680            return self.shape_arabic_run(text, metrics);
681        }
682
683        // Complex script pass: Indic Universal Shaping Engine (USE) conjuncts & pre-base vowel reordering
684        if !is_monospace && text.chars().any(is_indic_char) {
685            return self.shape_indic_run(text, metrics);
686        }
687
688        let mut glyphs = Vec::with_capacity(text.len());
689        let bytes = text.as_bytes();
690        let mut byte_idx = 0;
691
692        while byte_idx < bytes.len() {
693            let slice = &text[byte_idx..];
694
695            // 1. Check for multi-character ligatures if not monospace
696            let mut matched_ligature = None;
697            if !is_monospace {
698                for lig in KNOWN_LIGATURES {
699                    if slice.starts_with(lig.pattern) {
700                        matched_ligature = Some(lig);
701                        break;
702                    }
703                }
704            }
705
706            if let Some(lig) = matched_ligature {
707                let x_advance = LayoutUnit::from_f32(metrics.font_size * lig.advance_factor);
708                glyphs.push(ShapedGlyph {
709                    glyph_id: lig.glyph_id,
710                    cluster: byte_idx as u32,
711                    source_bytes: lig.pattern.len() as u16,
712                    x_advance,
713                    y_advance: LayoutUnit::ZERO,
714                    x_offset: LayoutUnit::ZERO,
715                    y_offset: LayoutUnit::ZERO,
716                    is_ligature: true,
717                    is_space: false,
718                    is_mark: false,
719                });
720                byte_idx += lig.pattern.len();
721                continue;
722            }
723
724            // 2. Extract next Unicode character
725            let ch = match slice.chars().next() {
726                Some(c) => c,
727                None => break,
728            };
729            let char_len = ch.len_utf8();
730
731            // 3. Handle nonspacing combining marks (diacritics, vowels, tone marks)
732            if is_combining_mark(ch) {
733                let y_offset = compute_mark_offset(ch, metrics.font_size);
734                glyphs.push(ShapedGlyph {
735                    glyph_id: ch as u32,
736                    cluster: byte_idx as u32,
737                    source_bytes: char_len as u16,
738                    x_advance: LayoutUnit::ZERO,
739                    y_advance: LayoutUnit::ZERO,
740                    x_offset: LayoutUnit::ZERO,
741                    y_offset,
742                    is_ligature: false,
743                    is_space: false,
744                    is_mark: true,
745                });
746                byte_idx += char_len;
747                continue;
748            }
749
750            // 4. Determine base glyph advance
751            let base_advance = if is_monospace {
752                metrics.font_size * 0.60
753            } else {
754                Self::character_advance(ch, metrics.font_size)
755            };
756
757            let is_space = ch == ' ' || ch == '\t' || ch == '\u{00A0}';
758            let glyph_id = ch as u32;
759
760            glyphs.push(ShapedGlyph {
761                glyph_id,
762                cluster: byte_idx as u32,
763                source_bytes: char_len as u16,
764                x_advance: LayoutUnit::from_f32(base_advance),
765                y_advance: LayoutUnit::ZERO,
766                x_offset: LayoutUnit::ZERO,
767                y_offset: LayoutUnit::ZERO,
768                is_ligature: false,
769                is_space,
770                is_mark: false,
771            });
772
773            byte_idx += char_len;
774        }
775
776        // 5. Apply GPOS optical pair kerning if proportional
777        if !is_monospace && glyphs.len() > 1 {
778            for i in 0..glyphs.len() - 1 {
779                let id1 = glyphs[i].glyph_id;
780                let id2 = glyphs[i + 1].glyph_id;
781
782                if let (Some(c1), Some(c2)) = (char::from_u32(id1), char::from_u32(id2)) {
783                    if let Some(delta) = Self::lookup_kerning(c1, c2) {
784                        let adjustment = LayoutUnit::from_f32(metrics.font_size * delta);
785                        glyphs[i].x_advance = glyphs[i].x_advance + adjustment;
786                    }
787                }
788            }
789        }
790
791        glyphs
792    }
793
794    /// Shapes an Arabic script text run with contextual cursive joining and Lam-Alef ligatures.
795    fn shape_arabic_run(&self, text: &str, metrics: &FontMetrics) -> Vec<ShapedGlyph> {
796        let chars: Vec<(usize, char)> = text.char_indices().collect();
797        let n = chars.len();
798        let mut glyphs = Vec::with_capacity(n);
799        let mut i = 0;
800
801        while i < n {
802            let (byte_idx, c) = chars[i];
803            let c_len = c.len_utf8();
804
805            // Multi-glyph Arabic ligatures (e.g. Allah, Akbar, Bismillah, Muhammad)
806            let slice = &text[byte_idx..];
807            let mut matched_multi_lig = None;
808            for lig in ARABIC_MULTI_LIGATURES {
809                if slice.starts_with(lig.pattern) {
810                    matched_multi_lig = Some(lig);
811                    break;
812                }
813            }
814            if let Some(lig) = matched_multi_lig {
815                let advance = LayoutUnit::from_f32(metrics.font_size * lig.advance_factor);
816                glyphs.push(ShapedGlyph {
817                    glyph_id: lig.glyph_id,
818                    cluster: byte_idx as u32,
819                    source_bytes: lig.pattern.len() as u16,
820                    x_advance: advance,
821                    y_advance: LayoutUnit::ZERO,
822                    x_offset: LayoutUnit::ZERO,
823                    y_offset: LayoutUnit::ZERO,
824                    is_ligature: true,
825                    is_space: false,
826                    is_mark: false,
827                });
828                let pat_chars = lig.pattern.chars().count();
829                i += pat_chars;
830                continue;
831            }
832
833            // Nonspacing combining vowels (Harakat/Tashkeel) stack with zero advance
834            if is_combining_mark(c) {
835                let y_offset = compute_mark_offset(c, metrics.font_size);
836                glyphs.push(ShapedGlyph {
837                    glyph_id: c as u32,
838                    cluster: byte_idx as u32,
839                    source_bytes: c_len as u16,
840                    x_advance: LayoutUnit::ZERO,
841                    y_advance: LayoutUnit::ZERO,
842                    x_offset: LayoutUnit::ZERO,
843                    y_offset,
844                    is_ligature: false,
845                    is_space: false,
846                    is_mark: true,
847                });
848                i += 1;
849                continue;
850            }
851
852            let join_type = arabic_joining_type(c);
853            if join_type == ArabicJoiningType::NonJoining {
854                let base_advance = Self::character_advance(c, metrics.font_size);
855                let is_space = c == ' ' || c == '\t' || c == '\u{00A0}';
856                glyphs.push(ShapedGlyph {
857                    glyph_id: c as u32,
858                    cluster: byte_idx as u32,
859                    source_bytes: c_len as u16,
860                    x_advance: LayoutUnit::from_f32(base_advance),
861                    y_advance: LayoutUnit::ZERO,
862                    x_offset: LayoutUnit::ZERO,
863                    y_offset: LayoutUnit::ZERO,
864                    is_ligature: false,
865                    is_space,
866                    is_mark: false,
867                });
868                i += 1;
869                continue;
870            }
871
872            // Inspect preceding non-transparent character
873            let mut prev_joins = false;
874            let mut p = i;
875            while p > 0 {
876                p -= 1;
877                let prev_c = chars[p].1;
878                let prev_jt = arabic_joining_type(prev_c);
879                if prev_jt != ArabicJoiningType::Transparent {
880                    if prev_jt == ArabicJoiningType::Dual || prev_jt == ArabicJoiningType::Left {
881                        prev_joins = true;
882                    }
883                    break;
884                }
885            }
886
887            // Check for Lam-Alef mandatory ligature
888            if c == '\u{0644}' {
889                let mut next_idx = None;
890                let mut k = i + 1;
891                while k < n {
892                    let next_c = chars[k].1;
893                    let next_jt = arabic_joining_type(next_c);
894                    if next_jt != ArabicJoiningType::Transparent {
895                        next_idx = Some((k, next_c));
896                        break;
897                    }
898                    k += 1;
899                }
900
901                if let Some((k, next_c)) = next_idx {
902                    if let Some(lig_glyph) = check_lam_alef_ligature(c, next_c, prev_joins) {
903                        let total_bytes = (chars[k].0 + next_c.len_utf8()) - byte_idx;
904                        let advance = LayoutUnit::from_f32(metrics.font_size * 0.75);
905                        glyphs.push(ShapedGlyph {
906                            glyph_id: lig_glyph,
907                            cluster: byte_idx as u32,
908                            source_bytes: total_bytes as u16,
909                            x_advance: advance,
910                            y_advance: LayoutUnit::ZERO,
911                            x_offset: LayoutUnit::ZERO,
912                            y_offset: LayoutUnit::ZERO,
913                            is_ligature: true,
914                            is_space: false,
915                            is_mark: false,
916                        });
917                        i = k + 1;
918                        continue;
919                    }
920                }
921            }
922
923            // Inspect succeeding non-transparent character
924            let mut next_joins = false;
925            let mut k = i + 1;
926            while k < n {
927                let next_c = chars[k].1;
928                let next_jt = arabic_joining_type(next_c);
929                if next_jt != ArabicJoiningType::Transparent {
930                    if next_jt == ArabicJoiningType::Dual || next_jt == ArabicJoiningType::Right {
931                        next_joins = true;
932                    }
933                    break;
934                }
935                k += 1;
936            }
937
938            let form = match (prev_joins, next_joins) {
939                (true, true) if join_type == ArabicJoiningType::Dual => ArabicForm::Medial,
940                (true, _) => ArabicForm::Final,
941                (_, true) if join_type == ArabicJoiningType::Dual => ArabicForm::Initial,
942                _ => ArabicForm::Isolated,
943            };
944
945            let glyph_id = map_arabic_form(c, form);
946            let advance = LayoutUnit::from_f32(Self::character_advance(c, metrics.font_size));
947
948            glyphs.push(ShapedGlyph {
949                glyph_id,
950                cluster: byte_idx as u32,
951                source_bytes: c_len as u16,
952                x_advance: advance,
953                y_advance: LayoutUnit::ZERO,
954                x_offset: LayoutUnit::ZERO,
955                y_offset: LayoutUnit::ZERO,
956                is_ligature: false,
957                is_space: false,
958                is_mark: false,
959            });
960
961            i += 1;
962        }
963
964        glyphs
965    }
966
967    /// Shapes an Indic script text run according to Universal Shaping Engine (USE) rules:
968    /// akhand conjuncts, half-forms, Reph handling, and pre-base vowel reordering.
969    fn shape_indic_run(&self, text: &str, metrics: &FontMetrics) -> Vec<ShapedGlyph> {
970        let chars: Vec<(usize, char)> = text.char_indices().collect();
971        let n = chars.len();
972        let mut glyphs = Vec::with_capacity(n);
973        let mut i = 0;
974
975        while i < n {
976            let (byte_idx, c) = chars[i];
977
978            // 1. Check for known Indic conjunct ligatures starting at current position (e.g. क्ष, त्र, ज्ञ, श्र, त्त, द्व, etc.)
979            let slice = &text[byte_idx..];
980            let mut matched_conjunct = None;
981            for lig in KNOWN_LIGATURES {
982                if lig.kind == LigatureKind::Indic && slice.starts_with(lig.pattern) {
983                    matched_conjunct = Some(lig);
984                    break;
985                }
986            }
987
988            if let Some(lig) = matched_conjunct {
989                let lig_char_count = lig.pattern.chars().count();
990                let next_idx = i + lig_char_count;
991
992                // Check if followed by a pre-base vowel sign that must reorder before this conjunct
993                if next_idx < n && is_indic_pre_base_vowel(chars[next_idx].1) {
994                    let (v_byte_idx, v_c) = chars[next_idx];
995                    let v_len = v_c.len_utf8();
996                    // Reorder pre-base vowel: emit pre-base vowel first
997                    glyphs.push(ShapedGlyph {
998                        glyph_id: v_c as u32,
999                        cluster: v_byte_idx as u32,
1000                        source_bytes: v_len as u16,
1001                        x_advance: LayoutUnit::from_f32(metrics.font_size * 0.25),
1002                        y_advance: LayoutUnit::ZERO,
1003                        x_offset: LayoutUnit::ZERO,
1004                        y_offset: LayoutUnit::ZERO,
1005                        is_ligature: false,
1006                        is_space: false,
1007                        is_mark: true,
1008                    });
1009
1010                    // Then emit the conjunct
1011                    glyphs.push(ShapedGlyph {
1012                        glyph_id: lig.glyph_id,
1013                        cluster: byte_idx as u32,
1014                        source_bytes: lig.pattern.len() as u16,
1015                        x_advance: LayoutUnit::from_f32(metrics.font_size * lig.advance_factor),
1016                        y_advance: LayoutUnit::ZERO,
1017                        x_offset: LayoutUnit::ZERO,
1018                        y_offset: LayoutUnit::ZERO,
1019                        is_ligature: true,
1020                        is_space: false,
1021                        is_mark: false,
1022                    });
1023
1024                    i = next_idx + 1;
1025                    continue;
1026                } else {
1027                    glyphs.push(ShapedGlyph {
1028                        glyph_id: lig.glyph_id,
1029                        cluster: byte_idx as u32,
1030                        source_bytes: lig.pattern.len() as u16,
1031                        x_advance: LayoutUnit::from_f32(metrics.font_size * lig.advance_factor),
1032                        y_advance: LayoutUnit::ZERO,
1033                        x_offset: LayoutUnit::ZERO,
1034                        y_offset: LayoutUnit::ZERO,
1035                        is_ligature: true,
1036                        is_space: false,
1037                        is_mark: false,
1038                    });
1039                    i = next_idx;
1040                    continue;
1041                }
1042            }
1043
1044            // 2. Check for Reph: Ra + Virama followed by a base consonant
1045            // In Devanagari: 'र' (U+0930) + Virama (U+094D) + Consonant
1046            if (c == '\u{0930}' || c == '\u{09B0}' || c == '\u{0A30}' || c == '\u{0AB0}')
1047                && i + 1 < n
1048                && is_indic_virama(chars[i + 1].1)
1049                && i + 2 < n
1050                && is_indic_consonant(chars[i + 2].1)
1051            {
1052                let base_consonant_idx = i + 2;
1053                let (base_byte_idx, base_c) = chars[base_consonant_idx];
1054                let base_len = base_c.len_utf8();
1055                let next_after_base = base_consonant_idx + 1;
1056
1057                // Check if base consonant is followed by a pre-base vowel sign
1058                if next_after_base < n && is_indic_pre_base_vowel(chars[next_after_base].1) {
1059                    let (v_byte, v_c) = chars[next_after_base];
1060                    // Emit pre-base vowel
1061                    glyphs.push(ShapedGlyph {
1062                        glyph_id: v_c as u32,
1063                        cluster: v_byte as u32,
1064                        source_bytes: v_c.len_utf8() as u16,
1065                        x_advance: LayoutUnit::from_f32(metrics.font_size * 0.25),
1066                        y_advance: LayoutUnit::ZERO,
1067                        x_offset: LayoutUnit::ZERO,
1068                        y_offset: LayoutUnit::ZERO,
1069                        is_ligature: false,
1070                        is_space: false,
1071                        is_mark: true,
1072                    });
1073                }
1074
1075                // Emit base consonant
1076                let base_advance = Self::character_advance(base_c, metrics.font_size);
1077                glyphs.push(ShapedGlyph {
1078                    glyph_id: base_c as u32,
1079                    cluster: base_byte_idx as u32,
1080                    source_bytes: base_len as u16,
1081                    x_advance: LayoutUnit::from_f32(base_advance),
1082                    y_advance: LayoutUnit::ZERO,
1083                    x_offset: LayoutUnit::ZERO,
1084                    y_offset: LayoutUnit::ZERO,
1085                    is_ligature: false,
1086                    is_space: false,
1087                    is_mark: false,
1088                });
1089
1090                // Emit Reph mark above base consonant
1091                glyphs.push(ShapedGlyph {
1092                    glyph_id: 0x094D, // Virama / Reph mark
1093                    cluster: byte_idx as u32,
1094                    source_bytes: (chars[i + 1].0 + chars[i + 1].1.len_utf8() - byte_idx) as u16,
1095                    x_advance: LayoutUnit::ZERO,
1096                    y_advance: LayoutUnit::ZERO,
1097                    x_offset: LayoutUnit::ZERO,
1098                    y_offset: LayoutUnit::from_f32(metrics.font_size * 0.40),
1099                    is_ligature: true,
1100                    is_space: false,
1101                    is_mark: true,
1102                });
1103
1104                if next_after_base < n && is_indic_pre_base_vowel(chars[next_after_base].1) {
1105                    i = next_after_base + 1;
1106                } else {
1107                    i = base_consonant_idx + 1;
1108                }
1109                continue;
1110            }
1111
1112            // 3. Check for standard Consonant + Pre-Base Vowel Sign Reordering
1113            if is_indic_consonant(c) {
1114                // Look ahead for pre-base vowel sign
1115                let mut pre_base_idx = None;
1116                if i + 1 < n && is_indic_pre_base_vowel(chars[i + 1].1) {
1117                    pre_base_idx = Some(i + 1);
1118                } else if i + 2 < n
1119                    && is_indic_virama(chars[i + 1].1)
1120                    && is_indic_consonant(chars[i + 2].1)
1121                {
1122                    // Consonant + Virama + Consonant (half form + base)
1123                    if i + 3 < n && is_indic_pre_base_vowel(chars[i + 3].1) {
1124                        pre_base_idx = Some(i + 3);
1125                    }
1126                }
1127
1128                if let Some(pb_idx) = pre_base_idx {
1129                    let (pb_byte, pb_c) = chars[pb_idx];
1130                    // USE rule: Pre-base vowel sign is reordered to precede the consonant cluster visually
1131                    glyphs.push(ShapedGlyph {
1132                        glyph_id: pb_c as u32,
1133                        cluster: pb_byte as u32,
1134                        source_bytes: pb_c.len_utf8() as u16,
1135                        x_advance: LayoutUnit::from_f32(metrics.font_size * 0.25),
1136                        y_advance: LayoutUnit::ZERO,
1137                        x_offset: LayoutUnit::ZERO,
1138                        y_offset: LayoutUnit::ZERO,
1139                        is_ligature: false,
1140                        is_space: false,
1141                        is_mark: true,
1142                    });
1143
1144                    // Emit consonant cluster up to pb_idx
1145                    for &(k_byte, k_c) in &chars[i..pb_idx] {
1146                        let is_v = is_indic_virama(k_c);
1147                        let adv = if is_v {
1148                            LayoutUnit::ZERO
1149                        } else {
1150                            LayoutUnit::from_f32(Self::character_advance(k_c, metrics.font_size))
1151                        };
1152                        glyphs.push(ShapedGlyph {
1153                            glyph_id: k_c as u32,
1154                            cluster: k_byte as u32,
1155                            source_bytes: k_c.len_utf8() as u16,
1156                            x_advance: adv,
1157                            y_advance: LayoutUnit::ZERO,
1158                            x_offset: LayoutUnit::ZERO,
1159                            y_offset: LayoutUnit::ZERO,
1160                            is_ligature: false,
1161                            is_space: false,
1162                            is_mark: is_v,
1163                        });
1164                    }
1165
1166                    i = pb_idx + 1;
1167                    continue;
1168                }
1169            }
1170
1171            // 4. Combining marks and generic characters
1172            let c_len = c.len_utf8();
1173            if is_combining_mark(c) {
1174                let y_offset = compute_mark_offset(c, metrics.font_size);
1175                glyphs.push(ShapedGlyph {
1176                    glyph_id: c as u32,
1177                    cluster: byte_idx as u32,
1178                    source_bytes: c_len as u16,
1179                    x_advance: LayoutUnit::ZERO,
1180                    y_advance: LayoutUnit::ZERO,
1181                    x_offset: LayoutUnit::ZERO,
1182                    y_offset,
1183                    is_ligature: false,
1184                    is_space: false,
1185                    is_mark: true,
1186                });
1187                i += 1;
1188                continue;
1189            }
1190
1191            let base_advance = Self::character_advance(c, metrics.font_size);
1192            let is_space = c == ' ' || c == '\t' || c == '\u{00A0}';
1193            glyphs.push(ShapedGlyph {
1194                glyph_id: c as u32,
1195                cluster: byte_idx as u32,
1196                source_bytes: c_len as u16,
1197                x_advance: LayoutUnit::from_f32(base_advance),
1198                y_advance: LayoutUnit::ZERO,
1199                x_offset: LayoutUnit::ZERO,
1200                y_offset: LayoutUnit::ZERO,
1201                is_ligature: false,
1202                is_space,
1203                is_mark: false,
1204            });
1205            i += 1;
1206        }
1207
1208        glyphs
1209    }
1210
1211    /// Looks up optical kerning adjustment between two characters in fraction of em.
1212    fn lookup_kerning(c1: char, c2: char) -> Option<f32> {
1213        for kp in KNOWN_KERNING_PAIRS {
1214            if kp.first == c1 && kp.second == c2 {
1215                return Some(kp.delta_em);
1216            }
1217        }
1218        None
1219    }
1220
1221    /// Proportional character advance width for typical modern sans-serif typography.
1222    fn character_advance(ch: char, font_size: f32) -> f32 {
1223        let em = font_size;
1224
1225        // CJK Unified Ideographs, Hiragana, Katakana, Hangul: full-width em
1226        if ('\u{4E00}'..='\u{9FFF}').contains(&ch)
1227            || ('\u{3040}'..='\u{30FF}').contains(&ch)
1228            || ('\u{AC00}'..='\u{D7AF}').contains(&ch)
1229        {
1230            return em * 1.0;
1231        }
1232
1233        // Arabic characters (~0.45 - 0.70 em)
1234        if ('\u{0600}'..='\u{06FF}').contains(&ch) || ('\u{0750}'..='\u{077F}').contains(&ch) {
1235            return em * 0.52;
1236        }
1237
1238        // Hebrew characters (~0.50 - 0.65 em)
1239        if ('\u{0590}'..='\u{05FF}').contains(&ch) {
1240            return em * 0.54;
1241        }
1242
1243        match ch {
1244            // Very narrow characters
1245            'i' | 'l' | 'j' => em * 0.25,
1246            '\'' | '`' | '\u{200B}' => em * 0.22,
1247            '.' | ',' | ';' | ':' | '!' | '|' => em * 0.26,
1248            ' ' | '\u{00A0}' => em * 0.26,
1249
1250            // Moderately narrow characters
1251            'f' | 't' => em * 0.35,
1252            'r' => em * 0.41,
1253            'c' | 's' | 'z' => em * 0.48,
1254            'v' | 'y' => em * 0.50,
1255            'k' | 'x' => em * 0.52,
1256
1257            // Average proportional lowercase
1258            'a' | 'e' => em * 0.56,
1259            'g' => em * 0.55,
1260            'o' => em * 0.60,
1261            'b' | 'd' | 'h' | 'n' | 'p' | 'q' | 'u' => em * 0.61,
1262
1263            // Wide lowercase
1264            'w' => em * 0.78,
1265            'm' => em * 0.93,
1266
1267            // Uppercase characters
1268            'I' | 'J' => em * 0.28,
1269            'E' | 'F' | 'K' | 'L' | 'Y' | 'Z' => em * 0.54,
1270            'S' | 'T' | 'X' => em * 0.56,
1271            'P' | 'V' => em * 0.60,
1272            'R' => em * 0.62,
1273            'A' | 'B' | 'C' => em * 0.64,
1274            'D' | 'G' | 'U' => em * 0.73,
1275            'H' | 'N' => em * 0.75,
1276            'O' | 'Q' => em * 0.78,
1277            'M' | 'W' => em * 0.92,
1278
1279            // Digits (tabular modern font metrics)
1280            '0'..='9' => em * 0.57,
1281
1282            // Punctuation and symbols
1283            '(' | ')' | '[' | ']' => em * 0.30,
1284            '{' | '}' => em * 0.35,
1285            '-' | '*' | '?' => em * 0.33,
1286            '"' => em * 0.40,
1287            '@' | '%' => em * 0.85,
1288            '—' | '–' => em * 0.70,
1289
1290            // Default fallback proportional advance
1291            _ => em * 0.55,
1292        }
1293    }
1294}
1295
1296/// Identifies nonspacing combining marks (diacritics, vowels, tone marks) that stack vertically.
1297pub fn is_combining_mark(c: char) -> bool {
1298    matches!(
1299        c,
1300        '\u{0300}'..='\u{036F}'
1301            | '\u{0483}'..='\u{0489}'
1302            | '\u{0591}'..='\u{05BD}'
1303            | '\u{05BF}'
1304            | '\u{05C1}'..='\u{05C2}'
1305            | '\u{05C4}'..='\u{05C5}'
1306            | '\u{05C7}'
1307            | '\u{0610}'..='\u{061A}'
1308            | '\u{064B}'..='\u{065F}'
1309            | '\u{0670}'
1310            | '\u{06D6}'..='\u{06DC}'
1311            | '\u{06DF}'..='\u{06E4}'
1312            | '\u{06E7}'..='\u{06E8}'
1313            | '\u{06EA}'..='\u{06ED}'
1314            | '\u{0901}'..='\u{0903}'
1315            | '\u{093A}'
1316            | '\u{093C}'
1317            | '\u{0941}'..='\u{0948}'
1318            | '\u{094D}'
1319            | '\u{0951}'..='\u{0954}'
1320            | '\u{0962}'..='\u{0963}'
1321            | '\u{0E31}'
1322            | '\u{0E34}'..='\u{0E3A}'
1323            | '\u{0E47}'..='\u{0E4E}'
1324    )
1325}
1326
1327/// Computes the vertical subpixel offset for combining marks relative to the baseline.
1328pub fn compute_mark_offset(c: char, font_size: f32) -> LayoutUnit {
1329    let is_above = matches!(
1330        c,
1331        '\u{0300}'..='\u{0314}'
1332            | '\u{0340}'..='\u{0344}'
1333            | '\u{064E}'
1334            | '\u{064F}'
1335            | '\u{0651}'
1336            | '\u{0652}'
1337            | '\u{0653}'..='\u{0658}'
1338            | '\u{0670}'
1339            | '\u{0E48}'..='\u{0E4B}'
1340            | '\u{0E31}'
1341            | '\u{0E34}'..='\u{0E37}'
1342            | '\u{0E47}'
1343            | '\u{0E4C}'..='\u{0E4E}'
1344            | '\u{0901}'..='\u{0902}'
1345    );
1346
1347    let is_below = matches!(
1348        c,
1349        '\u{0315}'..='\u{0333}'
1350            | '\u{05B0}'..='\u{05BC}'
1351            | '\u{0650}'
1352            | '\u{064D}'
1353            | '\u{0E38}'..='\u{0E39}'
1354            | '\u{0941}'..='\u{0944}'
1355    );
1356
1357    if is_above {
1358        LayoutUnit::from_f32(font_size * 0.35)
1359    } else if is_below {
1360        LayoutUnit::from_f32(-font_size * 0.25)
1361    } else {
1362        LayoutUnit::ZERO
1363    }
1364}
1365
1366struct ArabicMultiLigature {
1367    pattern: &'static str,
1368    glyph_id: u32,
1369    advance_factor: f32,
1370}
1371
1372static ARABIC_MULTI_LIGATURES: &[ArabicMultiLigature] = &[
1373    // Bismillah ar-Rahman ar-Rahim: ﷽
1374    ArabicMultiLigature {
1375        pattern: "\u{0628}\u{0633}\u{0645}\u{0020}\u{0627}\u{0644}\u{0644}\u{0647}\u{0020}\u{0627}\u{0644}\u{0631}\u{062D}\u{0645}\u{0646}\u{0020}\u{0627}\u{0644}\u{0631}\u{062D}\u{064A}\u{0645}",
1376        glyph_id: 0xFDFD,
1377        advance_factor: 2.5,
1378    },
1379    // Sallallahu Alayhi Wasallam: ﷺ
1380    ArabicMultiLigature {
1381        pattern: "\u{0635}\u{0644}\u{0649}\u{0020}\u{0627}\u{0644}\u{0644}\u{0647}\u{0020}\u{0639}\u{0644}\u{064A}\u{0647}\u{0020}\u{0648}\u{0633}\u{0644}\u{0645}",
1382        glyph_id: 0xFDFA,
1383        advance_factor: 1.8,
1384    },
1385    // Jalla Jalalouhou: ﷻ
1386    ArabicMultiLigature {
1387        pattern: "\u{062C}\u{0644}\u{0020}\u{062C}\u{0644}\u{0627}\u{0644}\u{0647}",
1388        glyph_id: 0xFDFB,
1389        advance_factor: 1.5,
1390    },
1391    // Allah with Tashkeel: اَللّٰه or اللّٰه or الله
1392    ArabicMultiLigature {
1393        pattern: "\u{0627}\u{0644}\u{0644}\u{0651}\u{0670}\u{0647}",
1394        glyph_id: 0xFDF2,
1395        advance_factor: 1.2,
1396    },
1397    ArabicMultiLigature {
1398        pattern: "\u{0627}\u{0644}\u{0644}\u{0647}", // Allah (الله)
1399        glyph_id: 0xFDF2,
1400        advance_factor: 1.2,
1401    },
1402    ArabicMultiLigature {
1403        pattern: "\u{0644}\u{0644}\u{0647}", // Lillah (لله)
1404        glyph_id: 0xFDF2,
1405        advance_factor: 1.0,
1406    },
1407    // Akbar: أكبر
1408    ArabicMultiLigature {
1409        pattern: "\u{0623}\u{0643}\u{0628}\u{0631}",
1410        glyph_id: 0xFDF3,
1411        advance_factor: 1.2,
1412    },
1413    ArabicMultiLigature {
1414        pattern: "\u{0627}\u{0643}\u{0628}\u{0631}",
1415        glyph_id: 0xFDF3,
1416        advance_factor: 1.2,
1417    },
1418    // Muhammad: محمد
1419    ArabicMultiLigature {
1420        pattern: "\u{0645}\u{062D}\u{0645}\u{062F}",
1421        glyph_id: 0xFDF4,
1422        advance_factor: 1.2,
1423    },
1424    // Rasul: رسول
1425    ArabicMultiLigature {
1426        pattern: "\u{0631}\u{0633}\u{0648}\u{0644}",
1427        glyph_id: 0xFDF6,
1428        advance_factor: 1.1,
1429    },
1430    // Alayhi: عليه
1431    ArabicMultiLigature {
1432        pattern: "\u{0639}\u{0644}\u{064A}\u{0647}",
1433        glyph_id: 0xFDF7,
1434        advance_factor: 1.0,
1435    },
1436    // Wasallam: وسلم
1437    ArabicMultiLigature {
1438        pattern: "\u{0648}\u{0633}\u{0644}\u{0645}",
1439        glyph_id: 0xFDF8,
1440        advance_factor: 1.0,
1441    },
1442    // Salla: صلى
1443    ArabicMultiLigature {
1444        pattern: "\u{0635}\u{0644}\u{0649}",
1445        glyph_id: 0xFDF9,
1446        advance_factor: 0.9,
1447    },
1448];
1449
1450/// Returns true if a character belongs to an Indic script block.
1451pub fn is_indic_char(c: char) -> bool {
1452    matches!(
1453        c,
1454        '\u{0900}'..='\u{097F}' // Devanagari
1455        | '\u{0980}'..='\u{09FF}' // Bengali
1456        | '\u{0A00}'..='\u{0A7F}' // Gurmukhi
1457        | '\u{0A80}'..='\u{0AFF}' // Gujarati
1458        | '\u{0B00}'..='\u{0B7F}' // Oriya
1459        | '\u{0B80}'..='\u{0BFF}' // Tamil
1460        | '\u{0C00}'..='\u{0C7F}' // Telugu
1461        | '\u{0C80}'..='\u{0CFF}' // Kannada
1462        | '\u{0D00}'..='\u{0D7F}' // Malayalam
1463    )
1464}
1465
1466/// Returns true if a character is an Indic Virama (Halant) explicit vowel suppressor.
1467pub fn is_indic_virama(c: char) -> bool {
1468    matches!(
1469        c,
1470        '\u{094D}' // Devanagari Virama
1471        | '\u{09CD}' // Bengali Virama
1472        | '\u{0A4D}' // Gurmukhi Virama
1473        | '\u{0ACD}' // Gujarati Virama
1474        | '\u{0B4D}' // Oriya Virama
1475        | '\u{0BCD}' // Tamil Virama
1476        | '\u{0C4D}' // Telugu Virama
1477        | '\u{0CCD}' // Kannada Virama
1478        | '\u{0D4D}' // Malayalam Virama
1479    )
1480}
1481
1482/// Returns true if an Indic vowel sign is pre-base and must reorder before the consonant cluster under USE rules.
1483pub fn is_indic_pre_base_vowel(c: char) -> bool {
1484    matches!(
1485        c,
1486        '\u{093F}' // Devanagari Vowel Sign I (ि)
1487        | '\u{09BF}' // Bengali Vowel Sign I (ি)
1488        | '\u{09C7}' // Bengali Vowel Sign E (ে)
1489        | '\u{09C8}' // Bengali Vowel Sign AI (ৈ)
1490        | '\u{0A3F}' // Gurmukhi Vowel Sign I (ਿ)
1491        | '\u{0ABF}' // Gujarati Vowel Sign I (િ)
1492        | '\u{0B3F}' // Oriya Vowel Sign I (ି)
1493        | '\u{0BC6}' // Tamil Vowel Sign E (ெ)
1494        | '\u{0BC7}' // Tamil Vowel Sign EE (ே)
1495        | '\u{0BC8}' // Tamil Vowel Sign AI (ை)
1496        | '\u{0D3F}' // Malayalam Vowel Sign I (ി)
1497        | '\u{0D46}' // Malayalam Vowel Sign E (െ)
1498        | '\u{0D47}' // Malayalam Vowel Sign EE (ே)
1499        | '\u{0D48}' // Malayalam Vowel Sign AI (ൈ)
1500    )
1501}
1502
1503/// Returns true if a character is an Indic base consonant.
1504pub fn is_indic_consonant(c: char) -> bool {
1505    matches!(
1506        c,
1507        '\u{0915}'..='\u{0939}' | '\u{0958}'..='\u{095F}' // Devanagari
1508        | '\u{0995}'..='\u{09B9}' | '\u{09DC}'..='\u{09DF}' // Bengali
1509        | '\u{0A15}'..='\u{0A39}' // Gurmukhi
1510        | '\u{0A95}'..='\u{0AB9}' // Gujarati
1511        | '\u{0B15}'..='\u{0B39}' // Oriya
1512        | '\u{0B95}'..='\u{0BB9}' // Tamil
1513        | '\u{0C15}'..='\u{0C39}' // Telugu
1514        | '\u{0C95}'..='\u{0CB9}' // Kannada
1515        | '\u{0D15}'..='\u{0D39}' // Malayalam
1516    )
1517}
1518
1519/// Unicode Arabic joining types according to Unicode Standard Section 9.2.
1520#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1521pub enum ArabicJoiningType {
1522    Dual,
1523    Right,
1524    Left,
1525    NonJoining,
1526    Transparent,
1527}
1528
1529/// Contextual glyph form variants for Arabic script.
1530#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1531pub enum ArabicForm {
1532    Isolated,
1533    Initial,
1534    Medial,
1535    Final,
1536}
1537
1538fn arabic_joining_type(c: char) -> ArabicJoiningType {
1539    if is_combining_mark(c) {
1540        return ArabicJoiningType::Transparent;
1541    }
1542    match c {
1543        '\u{0621}' => ArabicJoiningType::NonJoining,
1544        '\u{0622}'
1545        | '\u{0623}'
1546        | '\u{0624}'
1547        | '\u{0625}'
1548        | '\u{0627}'
1549        | '\u{0629}'
1550        | '\u{062F}'
1551        | '\u{0630}'
1552        | '\u{0631}'
1553        | '\u{0632}'
1554        | '\u{0648}'
1555        | '\u{0649}'
1556        | '\u{0671}'..='\u{0673}'
1557        | '\u{0675}'..='\u{0677}'
1558        | '\u{0688}'..='\u{0699}'
1559        | '\u{06C0}'..='\u{06CB}'
1560        | '\u{06CD}'..='\u{06CF}' => ArabicJoiningType::Right,
1561        '\u{0640}' => ArabicJoiningType::Dual,
1562        '\u{0626}'
1563        | '\u{0628}'
1564        | '\u{062A}'
1565        | '\u{062B}'
1566        | '\u{062C}'
1567        | '\u{062D}'
1568        | '\u{062E}'
1569        | '\u{0633}'
1570        | '\u{0634}'
1571        | '\u{0635}'
1572        | '\u{0636}'
1573        | '\u{0637}'
1574        | '\u{0638}'
1575        | '\u{0639}'
1576        | '\u{063A}'
1577        | '\u{0641}'
1578        | '\u{0642}'
1579        | '\u{0643}'
1580        | '\u{0644}'
1581        | '\u{0645}'
1582        | '\u{0646}'
1583        | '\u{0647}'
1584        | '\u{064A}'
1585        | '\u{0678}'..='\u{0687}'
1586        | '\u{069A}'..='\u{06BF}'
1587        | '\u{06CC}'
1588        | '\u{06D0}'..='\u{06D3}' => ArabicJoiningType::Dual,
1589        _ => ArabicJoiningType::NonJoining,
1590    }
1591}
1592
1593fn map_arabic_form(c: char, form: ArabicForm) -> u32 {
1594    match c {
1595        '\u{0627}' => match form {
1596            ArabicForm::Final => 0xFE8E,
1597            _ => 0xFE8D,
1598        },
1599        '\u{0622}' => match form {
1600            ArabicForm::Final => 0xFE82,
1601            _ => 0xFE81,
1602        },
1603        '\u{0623}' => match form {
1604            ArabicForm::Final => 0xFE84,
1605            _ => 0xFE83,
1606        },
1607        '\u{0624}' => match form {
1608            ArabicForm::Final => 0xFE86,
1609            _ => 0xFE85,
1610        },
1611        '\u{0625}' => match form {
1612            ArabicForm::Final => 0xFE88,
1613            _ => 0xFE87,
1614        },
1615        '\u{0626}' => match form {
1616            ArabicForm::Isolated => 0xFE89,
1617            ArabicForm::Final => 0xFE8A,
1618            ArabicForm::Initial => 0xFE8B,
1619            ArabicForm::Medial => 0xFE8C,
1620        },
1621        '\u{0628}' => match form {
1622            ArabicForm::Isolated => 0xFE8F,
1623            ArabicForm::Final => 0xFE90,
1624            ArabicForm::Initial => 0xFE91,
1625            ArabicForm::Medial => 0xFE92,
1626        },
1627        '\u{0629}' => match form {
1628            ArabicForm::Final => 0xFE94,
1629            _ => 0xFE93,
1630        },
1631        '\u{062A}' => match form {
1632            ArabicForm::Isolated => 0xFE95,
1633            ArabicForm::Final => 0xFE96,
1634            ArabicForm::Initial => 0xFE97,
1635            ArabicForm::Medial => 0xFE98,
1636        },
1637        '\u{062B}' => match form {
1638            ArabicForm::Isolated => 0xFE99,
1639            ArabicForm::Final => 0xFE9A,
1640            ArabicForm::Initial => 0xFE9B,
1641            ArabicForm::Medial => 0xFE9C,
1642        },
1643        '\u{062C}' => match form {
1644            ArabicForm::Isolated => 0xFE9D,
1645            ArabicForm::Final => 0xFE9E,
1646            ArabicForm::Initial => 0xFE9F,
1647            ArabicForm::Medial => 0xFEA0,
1648        },
1649        '\u{062D}' => match form {
1650            ArabicForm::Isolated => 0xFEA1,
1651            ArabicForm::Final => 0xFEA2,
1652            ArabicForm::Initial => 0xFEA3,
1653            ArabicForm::Medial => 0xFEA4,
1654        },
1655        '\u{062E}' => match form {
1656            ArabicForm::Isolated => 0xFEA5,
1657            ArabicForm::Final => 0xFEA6,
1658            ArabicForm::Initial => 0xFEA7,
1659            ArabicForm::Medial => 0xFEA8,
1660        },
1661        '\u{062F}' => match form {
1662            ArabicForm::Final => 0xFEAA,
1663            _ => 0xFEA9,
1664        },
1665        '\u{0630}' => match form {
1666            ArabicForm::Final => 0xFEAC,
1667            _ => 0xFEAB,
1668        },
1669        '\u{0631}' => match form {
1670            ArabicForm::Final => 0xFEAE,
1671            _ => 0xFEAD,
1672        },
1673        '\u{0632}' => match form {
1674            ArabicForm::Final => 0xFEB0,
1675            _ => 0xFEAF,
1676        },
1677        '\u{0633}' => match form {
1678            ArabicForm::Isolated => 0xFEB1,
1679            ArabicForm::Final => 0xFEB2,
1680            ArabicForm::Initial => 0xFEB3,
1681            ArabicForm::Medial => 0xFEB4,
1682        },
1683        '\u{0634}' => match form {
1684            ArabicForm::Isolated => 0xFEB5,
1685            ArabicForm::Final => 0xFEB6,
1686            ArabicForm::Initial => 0xFEB7,
1687            ArabicForm::Medial => 0xFEB8,
1688        },
1689        '\u{0635}' => match form {
1690            ArabicForm::Isolated => 0xFEB9,
1691            ArabicForm::Final => 0xFEBA,
1692            ArabicForm::Initial => 0xFEBB,
1693            ArabicForm::Medial => 0xFEBC,
1694        },
1695        '\u{0636}' => match form {
1696            ArabicForm::Isolated => 0xFEBD,
1697            ArabicForm::Final => 0xFEBE,
1698            ArabicForm::Initial => 0xFEBF,
1699            ArabicForm::Medial => 0xFEC0,
1700        },
1701        '\u{0637}' => match form {
1702            ArabicForm::Isolated => 0xFEC1,
1703            ArabicForm::Final => 0xFEC2,
1704            ArabicForm::Initial => 0xFEC3,
1705            ArabicForm::Medial => 0xFEC4,
1706        },
1707        '\u{0638}' => match form {
1708            ArabicForm::Isolated => 0xFEC5,
1709            ArabicForm::Final => 0xFEC6,
1710            ArabicForm::Initial => 0xFEC7,
1711            ArabicForm::Medial => 0xFEC8,
1712        },
1713        '\u{0639}' => match form {
1714            ArabicForm::Isolated => 0xFEC9,
1715            ArabicForm::Final => 0xFECA,
1716            ArabicForm::Initial => 0xFECB,
1717            ArabicForm::Medial => 0xFECC,
1718        },
1719        '\u{063A}' => match form {
1720            ArabicForm::Isolated => 0xFECD,
1721            ArabicForm::Final => 0xFECE,
1722            ArabicForm::Initial => 0xFECF,
1723            ArabicForm::Medial => 0xFED0,
1724        },
1725        '\u{0641}' => match form {
1726            ArabicForm::Isolated => 0xFED1,
1727            ArabicForm::Final => 0xFED2,
1728            ArabicForm::Initial => 0xFED3,
1729            ArabicForm::Medial => 0xFED4,
1730        },
1731        '\u{0642}' => match form {
1732            ArabicForm::Isolated => 0xFED5,
1733            ArabicForm::Final => 0xFED6,
1734            ArabicForm::Initial => 0xFED7,
1735            ArabicForm::Medial => 0xFED8,
1736        },
1737        '\u{0643}' => match form {
1738            ArabicForm::Isolated => 0xFED9,
1739            ArabicForm::Final => 0xFEDA,
1740            ArabicForm::Initial => 0xFEDB,
1741            ArabicForm::Medial => 0xFEDC,
1742        },
1743        '\u{0644}' => match form {
1744            ArabicForm::Isolated => 0xFEDD,
1745            ArabicForm::Final => 0xFEDE,
1746            ArabicForm::Initial => 0xFEDF,
1747            ArabicForm::Medial => 0xFEE0,
1748        },
1749        '\u{0645}' => match form {
1750            ArabicForm::Isolated => 0xFEE1,
1751            ArabicForm::Final => 0xFEE2,
1752            ArabicForm::Initial => 0xFEE3,
1753            ArabicForm::Medial => 0xFEE4,
1754        },
1755        '\u{0646}' => match form {
1756            ArabicForm::Isolated => 0xFEE5,
1757            ArabicForm::Final => 0xFEE6,
1758            ArabicForm::Initial => 0xFEE7,
1759            ArabicForm::Medial => 0xFEE8,
1760        },
1761        '\u{0647}' => match form {
1762            ArabicForm::Isolated => 0xFEE9,
1763            ArabicForm::Final => 0xFEEA,
1764            ArabicForm::Initial => 0xFEEB,
1765            ArabicForm::Medial => 0xFEEC,
1766        },
1767        '\u{0648}' => match form {
1768            ArabicForm::Final => 0xFEEE,
1769            _ => 0xFEED,
1770        },
1771        '\u{0649}' => match form {
1772            ArabicForm::Final => 0xFEF0,
1773            _ => 0xFEEF,
1774        },
1775        '\u{064A}' => match form {
1776            ArabicForm::Isolated => 0xFEF1,
1777            ArabicForm::Final => 0xFEF2,
1778            ArabicForm::Initial => 0xFEF3,
1779            ArabicForm::Medial => 0xFEF4,
1780        },
1781        _ => c as u32,
1782    }
1783}
1784
1785fn check_lam_alef_ligature(c_lam: char, c_alef: char, joins_before: bool) -> Option<u32> {
1786    if c_lam != '\u{0644}' {
1787        return None;
1788    }
1789    match c_alef {
1790        '\u{0622}' => Some(if joins_before { 0xFEF6 } else { 0xFEF5 }),
1791        '\u{0623}' => Some(if joins_before { 0xFEF8 } else { 0xFEF7 }),
1792        '\u{0625}' => Some(if joins_before { 0xFEFA } else { 0xFEF9 }),
1793        '\u{0627}' => Some(if joins_before { 0xFEFC } else { 0xFEFB }),
1794        _ => None,
1795    }
1796}