text_scripts

source of shaping::arabic

1// The Arabic shaper (hb-ot-shaper-arabic.cc), for Arabic, Syriac and,2// through the Universal Shaping Engine, the other joining scripts: each3// character's joining form from its Joining_Type and its neighbors'4// (`isol`, `fina`, `fin2`, `fin3`, `medi`, `med2`, `init`), the features5// in the order the Arabic specification applies them, `stch`'s pieces6// repeated to fill the word they stretch, and the modifier combining7// marks of UTR #53 moved before the other marks.89import std::vector;10import std::option;11import std::math;12import std::sort;1314import pkg::alloy::text::font::reader;15import pkg::alloy::text::font::face;16import pkg::alloy::text::unicode::tables;17import unicode::script_tables;18import pkg::alloy::text::unicode::properties;19import unicode::script_properties;20import pkg::alloy::text::shaping::opentype;21import pkg::alloy::text::shaping::buffer;22import pkg::alloy::text::shaping::plan;23import pkg::alloy::text::shaping::shapers;24import pkg::alloy::text::shaping::apply;25import pkg::alloy::text::shaping::gsub;2627// What joining does to a character, kept in its `category`: the form it28// takes, then (for `stch`) whether a piece of a stretch is fixed or29// repeated.30const ISOL: u8 = 0;31const FINA: u8 = 1;32const FIN2: u8 = 2;33const FIN3: u8 = 3;34const MEDI: u8 = 4;35const MED2: u8 = 5;36const INIT: u8 = 6;37const NONE: u8 = 7;38const STCH_FIXED: u8 = 8;39const STCH_REPEATING: u8 = 9;4041// The forms' features, in the actions' order.42const FORMS: [&[u8] : 7] = [&"isol", &"fina", &"fin2", &"fin3", &"medi", &"med2", &"init"];4344// What the shaper keeps in its plan: each action's mask (NONE's 0),45// whether the face has `stch`, and the fallback's lookups for a face of46// Arabic without the forms' features.47pub type ArabicData = struct {48    pub masks: [u32 : 8],49    pub has_stch: bool,50    pub fallback: Fallback,51};5253// GSUB lookups made from the face's presentation forms, as HarfBuzz54// synthesizes them (hb-ot-shaper-arabic-fallback.hh): the lookups'55// bytes, and each lookup's offset in them with the mask it applies to.56pub type Fallback = struct {57    pub data: Vector<u8>,58    pub lookups: Vector<[u64 : 2]>,59};6061// The joining state machine: for the state and the joining type of the62// next character, the action for the character before, the action for63// this one and the next state (states: 0 not joining, 1 after R or an64// isolated Alaph, 2 after D or L isolated, 3 after D final, 4 after a65// final Alaph, 5 after Alaph's fin2 or fin3, 6 after Dalath or Rish).66// The columns are U, L, R, D, Alaph and Dalath Rish.67const STATES: [[[u8 : 3] : 6] : 7] = [68    [69        [NONE, NONE, 0],70        [NONE, ISOL, 2],71        [NONE, ISOL, 1],72        [NONE, ISOL, 2],73        [NONE, ISOL, 1],74        [NONE, ISOL, 6]75    ],76    [77        [NONE, NONE, 0],78        [NONE, ISOL, 2],79        [NONE, ISOL, 1],80        [NONE, ISOL, 2],81        [NONE, FIN2, 5],82        [NONE, ISOL, 6]83    ],84    [85        [NONE, NONE, 0],86        [NONE, ISOL, 2],87        [INIT, FINA, 1],88        [INIT, FINA, 3],89        [INIT, FINA, 4],90        [INIT, FINA, 6]91    ],92    [93        [NONE, NONE, 0],94        [NONE, ISOL, 2],95        [MEDI, FINA, 1],96        [MEDI, FINA, 3],97        [MEDI, FINA, 4],98        [MEDI, FINA, 6]99    ],100    [101        [NONE, NONE, 0],102        [NONE, ISOL, 2],103        [MED2, ISOL, 1],104        [MED2, ISOL, 2],105        [MED2, FIN2, 5],106        [MED2, ISOL, 6]107    ],108    [109        [NONE, NONE, 0],110        [NONE, ISOL, 2],111        [ISOL, ISOL, 1],112        [ISOL, ISOL, 2],113        [ISOL, FIN2, 5],114        [ISOL, ISOL, 6]115    ],116    [117        [NONE, NONE, 0],118        [NONE, ISOL, 2],119        [NONE, ISOL, 1],120        [NONE, ISOL, 2],121        [NONE, FIN3, 5],122        [NONE, ISOL, 6]123    ]124];125126// The features, with pauses between the forms as the specification127// orders them, and between `rlig` and `calt` for Arabic.128pub fn collect_arabic_features(b: &var Builder) {129    b.enable(&"stch");130    b.add_gsub_pause(Pause::ArabicStretch);131    b.enable_feature(tag(&"ccmp"), FeatureFlags { .manual_zwj = true });132    b.enable_feature(tag(&"locl"), FeatureFlags { .manual_zwj = true });133    b.add_gsub_pause(Pause::Nothing);134    for (FORMS) |&name| {135        const syriac = name[3] == '2' || name[3] == '3';136        b.add_feature(137            tag(&name),138            FeatureFlags { .manual_zwj = true, .has_fallback = b.script is ::Arabic && !syriac },139            1140        );141        b.add_gsub_pause(Pause::Nothing);142    }143    b.add_gsub_pause(Pause::Nothing);144    b.enable_feature(tag(&"rlig"), FeatureFlags { .manual_zwj = true, .has_fallback = true });145    if (b.script is ::Arabic) {146        b.add_gsub_pause(Pause::ArabicFallback);147    }148    b.enable_feature(tag(&"calt"), FeatureFlags { .manual_zwj = true });149    if (!b.has_feature(tag(&"rclt"))) {150        b.add_gsub_pause(Pause::Nothing);151    }152    b.enable_feature(tag(&"liga"), FeatureFlags { .manual_zwj = true });153    b.enable_feature(tag(&"clig"), FeatureFlags { .manual_zwj = true });154    b.enable_feature(tag(&"mset"), FeatureFlags { .manual_zwj = true });155}156157pub fn arabic_data(plan: &Plan, face: &Face) -> ArabicData {158    var data = ArabicData {159        .masks = [0, 0, 0, 0, 0, 0, 0, 0],160        .has_stch = plan.one_mask(tag(&"stch")) != 0,161        .fallback = Fallback { .data = Vector<u8>::empty(), .lookups = Vector<[u64 : 2]>::empty() }162    };163    // the fallback only for Arabic whose face has none of the forms164    var fallback = plan.script is ::Arabic;165    for (FORMS, [..FORMS.length()]) |&name, k| {166        data.masks[k] = plan.one_mask(tag(&name));167        const syriac = name[3] == '2' || name[3] == '3';168        if (!syriac && !needs_fallback(&plan, &name)) {169            fallback = false;170        }171    }172    if (fallback) {173        data.fallback = make_fallback(&plan, &face);174    }175    return move data;176}177178fn needs_fallback(plan: &Plan, name: &[u8]) -> bool {179    if (plan.feature(tag(&name)) is ::Some |f|) {180        return f.needs_fallback;181    }182    return false;183}184185// The fallback's lookups: the forms (init, medi, fina, isol), then the186// ligatures (rlig) of three, of two, and of marks.187fn make_fallback(plan: &Plan, face: &Face) -> Fallback {188    var f = Fallback { .data = Vector<u8>::empty(), .lookups = Vector<[u64 : 2]>::empty() };189    for ([..4 to u64]) |form| {190        const mask = plan.one_mask(tag(&FALLBACK_FORMS[form]));191        if (mask != 0) {192            make_single(&var f, &face, form, mask);193        }194    }195    const rlig = plan.one_mask(tag(&"rlig"));196    if (rlig != 0) {197        make_ligatures(&var f, &face, &ARABIC_LIGATURES3, 3, IGNORE_MARKS, rlig);198        make_ligatures(&var f, &face, &ARABIC_LIGATURES, 2, IGNORE_MARKS, rlig);199        make_ligatures(&var f, &face, &ARABIC_MARK_LIGATURES, 2, 0, rlig);200    }201    return move f;202}203204// The forms in ARABIC_FORMS' order.205const FALLBACK_FORMS: [&[u8] : 4] = [&"init", &"medi", &"fina", &"isol"];206207fn put_u16(out: &var Vector<u8>, value: u64) {208    out.push((value >> 8) to u8);209    out.push((value & 0xFF) to u8);210}211212fn set_u16(out: &var Vector<u8>, at: u64, value: u64) {213    out.get_var(at) = (value >> 8) to u8;214    out.get_var(at + 1) = (value & 0xFF) to u8;215}216217// A single substitution lookup from each character to its form, where218// the face has both.219fn make_single(f: &var Fallback, face: &Face, form: u64, mask: u32) {220    var pairs = Vector<[u32 : 2]>::empty();221    for ([..ARABIC_FORMS.length() / 4]) |k| {222        const s = ARABIC_FORMS[k * 4 + form];223        if (s == 0) {224            continue;225        }226        const from = face.glyph_of(ARABIC_FORMS_FIRST + k to u32);227        const to_glyph = face.glyph_of(s);228        if (from == 0 || to_glyph == 0 || from == to_glyph) {229            continue;230        }231        pairs.push([from, to_glyph]);232    }233    if (pairs.length() == 0) {234        return;235    }236    sort_by(&var pairs.items(), (a, b) => a[0] < b[0]);237    const at = f.data.length() to u64;238    // the lookup, its one subtable (format 2) and its coverage (format 1)239    put_u16(&var f.data, SINGLE_SUBSTITUTION to u64);240    put_u16(&var f.data, IGNORE_MARKS to u64);241    put_u16(&var f.data, 1);242    put_u16(&var f.data, 8);243    const count = pairs.length();244    put_u16(&var f.data, 2);245    put_u16(&var f.data, 6 + count * 2);246    put_u16(&var f.data, count);247    for (pairs.view()) |p| {248        put_u16(&var f.data, p[1] to u64);249    }250    put_u16(&var f.data, 1);251    put_u16(&var f.data, count);252    for (pairs.view()) |p| {253        put_u16(&var f.data, p[0] to u64);254    }255    f.lookups.push([at, mask to u64]);256}257258// A ligature substitution lookup from the table's entries (`size`259// characters, then the ligature), sorted by their first character,260// where the face has every glyph.261fn make_ligatures(f: &var Fallback, face: &Face, table: &[u32], size: u64, flags: u32, mask: u32) {262    const stride = size + 1;263    // each entry's glyphs, the face having them all264    var entries = Vector<[u32 : 4]>::empty();265    for ([..table.length() / stride]) |k| {266        var glyphs: [u32 : 4] = [0, 0, 0, 0];267        var complete = true;268        for ([..stride]) |j| {269            glyphs[j] = face.glyph_of(table[k * stride + j]);270            complete = complete && glyphs[j] != 0;271        }272        if (complete) {273            entries.push(glyphs);274        }275    }276    if (entries.length() == 0) {277        return;278    }279    sort_by(&var entries.items(), (a, b) => a[0] < b[0]);280    // the first glyphs, once each281    var firsts = Vector<u32>::empty();282    for (entries.view()) |e| {283        if (firsts.length() == 0 || firsts.last() != e[0]) {284            firsts.push(e[0]);285        }286    }287    const at = f.data.length() to u64;288    put_u16(&var f.data, LIGATURE_SUBSTITUTION to u64);289    put_u16(&var f.data, flags to u64);290    put_u16(&var f.data, 1);291    put_u16(&var f.data, 8);292    const subtable = f.data.length() to u64;293    put_u16(&var f.data, 1);294    put_u16(&var f.data, 0); // the coverage's offset, written below295    put_u16(&var f.data, firsts.length());296    const sets = f.data.length() to u64;297    for (firsts.view()) {298        put_u16(&var f.data, 0);299    }300    var e: u64 = 0;301    for (firsts.view(), [..firsts.length()]) |first, k| {302        const set = f.data.length() to u64;303        set_u16(&var f.data, sets + k * 2, set - subtable);304        var end = e;305        while (end < entries.length() && entries.get(end)[0] == first) {306            end += 1;307        }308        put_u16(&var f.data, end - e);309        const offsets = f.data.length() to u64;310        for ([e..end]) {311            put_u16(&var f.data, 0);312        }313        for ([e..end]) |j| {314            set_u16(&var f.data, offsets + (j - e) * 2, f.data.length() to u64 - set);315            const glyphs = entries.get(j);316            put_u16(&var f.data, glyphs[size] to u64);317            put_u16(&var f.data, size);318            for ([1..size]) |c| {319                put_u16(&var f.data, glyphs[c] to u64);320            }321        }322        e = end;323    }324    set_u16(&var f.data, subtable + 2, f.data.length() to u64 - subtable);325    put_u16(&var f.data, 1);326    put_u16(&var f.data, firsts.length());327    for (firsts.view()) |first| {328        put_u16(&var f.data, first to u64);329    }330    f.lookups.push([at, mask to u64]);331}332333// After `rlig`: the fallback's lookups, for a face that needs them.334pub fn apply_fallback(data: &ArabicData, face: &Face, buffer: &var Buffer) {335    if (data.fallback.lookups.length() == 0) {336        return;337    }338    var c = Apply::of(&face, LookupTable::Substitution);339    c.data = &data.fallback.data.view();340    c.digests = false;341    c.rtl = buffer.rtl;342    for (data.fallback.lookups.view()) |l| {343        c.lookup_mask = l[1] to u32;344        substitute_made_lookup(&var c, &var buffer, l[0]);345    }346}347348// The character's joining type as the state machine's column, None for349// one joining is transparent to.350fn joining_column(c: u32, category: GeneralCategory) -> Option<u64> {351    const t = joining_type(c);352    const resolved = if (t is ::X) (353        if (354            category is ::NonspacingMark355            || category is ::EnclosingMark356            || category is ::Format357        ) JoiningType::T else JoiningType::U358    ) else t;359    if (resolved is ::T) {360        return ::None;361    }362    return ::Some(resolved to u64);363}364365// Gives each character its form's mask, from the joining of the run366// with the characters around it.367pub fn setup_arabic_masks(data: &ArabicData, buffer: &var Buffer) {368    var state: u64 = 0;369    for (buffer.context_before()) |c| {370        if (joining_column(c, general_category(c)) is ::Some |column|) {371            state = STATES[state][column][2] to u64;372            break;373        }374    }375    var previous: Option<u64> = ::None;376    const count = buffer.infos.length();377    for ([..count]) |i| {378        const info = &buffer.infos.get(i);379        const column = if (joining_column(info.glyph, info.general()) is ::Some |k|) k else {380            buffer.infos.get_var(i).category = NONE;381            continue;382        };383        const entry = STATES[state][column];384        if (entry[0] != NONE && previous is ::Some |p|) {385            buffer.infos.get_var(p).category = entry[0];386        }387        buffer.infos.get_var(i).category = entry[1];388        previous = ::Some(i);389        state = entry[2] to u64;390    }391    for (buffer.context_after()) |c| {392        if (joining_column(c, general_category(c)) is ::Some |column|) {393            const entry = STATES[state][column];394            if (entry[0] != NONE && previous is ::Some |p|) {395                buffer.infos.get_var(p).category = entry[0];396            }397            break;398        }399    }400    if (buffer.script is ::Mongolian && count > 1) {401        // free variation selectors take their base's form402        for ([1..count]) |i| {403            const c = buffer.infos.get(i).glyph;404            if ((c >= 0x180B && c <= 0x180D) || c == 0x180F) {405                buffer.infos.get_var(i).category = buffer.infos.get(i - 1).category;406            }407        }408    }409    for (buffer.infos.items()) |&var info| {410        info.mask |= data.masks[info.category to u64];411    }412}413414// After `stch`: the glyphs it multiplied become the pieces of a stretch,415// fixed and repeated in turn.416pub fn record_stretch(data: &ArabicData, buffer: &var Buffer) {417    if (!data.has_stch) {418        return;419    }420    for (buffer.infos.items()) |&var info| {421        if (info.multiplied()) {422            info.category = if (info.ligature_component() % 2 == 1) STCH_REPEATING else STCH_FIXED;423            buffer.has_stretch = true;424        }425    }426}427428fn is_stretch(info: &GlyphInfo) -> bool => info.category == STCH_FIXED429    || info.category == STCH_REPEATING;430431// The General_Categories a stretch fills the width of (HarfBuzz's432// HB_ARABIC_GENERAL_CATEGORY_IS_WORD).433fn is_word(category: GeneralCategory) -> bool => match (category) {434    ::Unassigned, ::PrivateUse, ::ModifierLetter, ::OtherLetter, ::SpacingMark,435    ::EnclosingMark, ::NonspacingMark, ::DecimalNumber, ::LetterNumber, ::OtherNumber,436    ::CurrencySymbol, ::ModifierSymbol, ::MathSymbol, ::OtherSymbol true;437    else false;438};439440// The most glyphs a stretch may take.441const STRETCH_GLYPHS: u64 = 256;442443// Repeats each stretch's repeated pieces until they fill the width of444// the rest of its word, overlapping them to fit (HarfBuzz's apply_stch).445pub fn apply_stretch(face: &Face, buffer: &var Buffer) {446    if (!buffer.has_stretch) {447        return;448    }449    const rtl = buffer.rtl;450    // the glyphs from the text's last, as HarfBuzz has them here451    buffer.reverse_range(0, buffer.infos.length());452    var infos = Vector<GlyphInfo>::empty();453    var positions = Vector<GlyphPosition>::empty();454    // built backwards, from the last glyph, then reversed455    var i = buffer.infos.length();456    while (i > 0) {457        if (!is_stretch(&buffer.infos.get(i - 1))) {458            infos.push(buffer.infos.get(i - 1));459            positions.push(buffer.positions.get(i - 1));460            i -= 1;461            continue;462        }463        var fixed: i64 = 0;464        var repeating: i64 = 0;465        var fixed_count: u64 = 0;466        var repeating_count: u64 = 0;467        const end = i;468        while (i > 0 && is_stretch(&buffer.infos.get(i - 1))) {469            i -= 1;470            const width = face.advance(buffer.infos.get(i).glyph) to i64;471            if (buffer.infos.get(i).category == STCH_FIXED) {472                fixed += width;473                fixed_count += 1;474            } else {475                repeating += width;476                repeating_count += 1;477            }478        }479        const start = i;480        // the width of the rest of the word before it481        var total: i64 = 0;482        var context = i;483        while (context > 0) {484            const before = &buffer.infos.get(context - 1);485            if (486                is_stretch(&before)487                || !(before.is_default_ignorable() || is_word(before.general()))488            ) {489                break;490            }491            context -= 1;492            total += buffer.positions.get(context).x_advance to i64;493        }494        var copies: i64 = 0;495        var remaining = total - fixed;496        if (remaining > repeating && repeating > 0) {497            copies = remaining / repeating - 1;498        }499        // one more copy, overlapping them a little, when it fits better500        var overlap: i64 = 0;501        const shortfall = remaining - repeating * (copies + 1);502        if (shortfall > 0 && repeating_count > 0) {503            copies += 1;504            const excess = (copies + 1) * repeating - remaining;505            if (excess > 0) {506                overlap = excess / (copies * repeating_count to i64);507                remaining = 0;508            }509        }510        var most: i64 = 0;511        if (repeating_count > 0 && fixed_count + repeating_count < STRETCH_GLYPHS) {512            most = ((STRETCH_GLYPHS - fixed_count - repeating_count) / repeating_count) to i64;513        }514        copies = if (copies < most) copies else most;515        var x_offset = remaining / 2;516        var k = end;517        while (k > start) {518            const info = buffer.infos.get(k - 1);519            const width = face.advance(info.glyph) to i64;520            const repeat = if (info.category == STCH_REPEATING) 1 + copies else 1;521            var p = buffer.positions.get(k - 1);522            p.x_advance = 0.0;523            for ([..repeat to u64]) |n| {524                if (rtl) {525                    x_offset -= width;526                    if (n > 0) {527                        x_offset += overlap;528                    }529                }530                p.x_offset = x_offset to f32;531                infos.push(info);532                positions.push(p);533                if (!rtl) {534                    x_offset += width;535                    if (n > 0) {536                        x_offset -= overlap;537                    }538                }539            }540            k -= 1;541        }542    }543    // pushed from the last, so in the text's order544    buffer.infos = move infos;545    buffer.positions = move positions;546}547548// The modifier combining marks of UTR #53, which go before the other549// marks of their class.550fn is_modifier_mark(c: u32) -> bool => match (c) {551    0x0654, 0x0655, 0x0658, 0x06DC, 0x06E3, 0x06E7, 0x06E8, 0x08CA, 0x08CB, 0x08CD, 0x08CE,552    0x08CF, 0x08D3, 0x08F3 true;553    else false;554};555556const MODIFIER_CLASSES: [u32 : 2] = [220, 230];557558// Moves the modifier marks below (220) and above (230) to the start of559// the marks from start to end, renumbering what they now stand before so560// the classes still rise.561pub fn reorder_arabic_marks(buffer: &var Buffer, from: u64, end: u64) {562    var start = from;563    var i = start;564    for (MODIFIER_CLASSES) |class| {565        while (i < end && buffer.infos.get(i).combining_class() < class) {566            i += 1;567        }568        if (i == end) {569            break;570        }571        if (buffer.infos.get(i).combining_class() > class) {572            continue;573        }574        var j = i;575        while (576            j < end577            && buffer.infos.get(j).combining_class() == class578            && is_modifier_mark(buffer.infos.get(j).glyph)579        ) {580            j += 1;581        }582        if (i == j) {583            continue;584        }585        buffer.merge_clusters(start, j);586        // infos[start..j] rotated so that infos[i..j] come first587        const infos = &var buffer.infos.items();588        reverse(&var infos[start..i]);589        reverse(&var infos[i..j]);590        reverse(&var infos[start..j]);591        const new_start = start + j - i;592        const renumbered: u32 = if (class == 220) 25 else 26;593        while (start < new_start) {594            buffer.infos.get_var(start).set_combining_class(renumbered);595            start += 1;596        }597        i = j;598    }599}600601fn reverse(infos: &var [GlyphInfo]) {602    if (infos.length() < 2) {603        return;604    }605    var a: u64 = 0;606    var b = infos.length() - 1;607    while (a < b) {608        const t = infos[a];609        infos[a] = infos[b];610        infos[b] = t;611        a += 1;612        b -= 1;613    }614}