draw

source of pkg::alloy::text::shaping::apply

1// Applying GSUB's and GPOS's lookups to a buffer, as HarfBuzz's apply2// context does (hb-ot-layout-gsubgpos.hh): each lookup over the glyphs3// its feature's mask selects, skipping those its flags ignore and the4// default ignorables; sequences matched by glyph, class or coverage,5// ligatures formed with the marks between their components kept apart,6// and the lookups a contextual rule names applied at positions within7// its match. The buffer is one array: the glyphs before `at` are those8// already done, HarfBuzz's output buffer, the rest its input.910import std::vector;11import std::option;12import std::math;1314import font::reader;15import font::face;16import unicode::tables;17import opentype;18import buffer;1920// The state of applying a lookup.21exp type Apply = struct {22    exp face: &Face,23    exp data: &[u8], // where the lookups are: the face's, or Arabic's fallback24    exp digests: bool = true, // whether the face's subtable digests apply2526    exp table: LookupTable,27    exp at: u64, // the glyph being looked at28    exp lookup_index: u32 = 0,29    exp lookup_mask: u32 = 1,30    exp lookup_props: u32 = 0,31    exp auto_zwnj: bool = true,32    exp auto_zwj: bool = true,33    exp per_syllable: bool = false,34    exp random: bool = false,35    exp random_state: u32 = 1,36    exp nesting_left: u32 = MAX_NESTING,37    exp rtl: bool = false,38    exp has_glyph_classes: bool = false,39    // mark-to-base and mark-to-ligature's last base found, and up to40    // where it was looked for41    exp last_base: Option<u64> = ::None,42    exp last_base_until: u64 = 0,43    // where the glyphs of the latest match are44    exp positions: Vector<u64> = Vector<u64>::empty(),45};4647exp const MAX_NESTING: u32 = 64;48// the longest sequence a rule may match49exp const MAX_CONTEXT: u64 = 64;5051// lookup flags52exp const RIGHT_TO_LEFT: u32 = 0x1;53exp const IGNORE_FLAGS: u32 = 0x0E;54exp const IGNORE_MARKS: u32 = 0x8;55exp const MARK_FILTERING: u32 = 0x10;56exp const MARK_ATTACHMENT_TYPE: u32 = 0xFF00;5758exp fn Apply::of(face: &Face, table: LookupTable) -> Apply {59    var has_classes = false;60    if (face.gdef is ::Some |gdef|) {61        has_classes = u16_at(&face.data(), gdef + 4) != 0;62    }63    return Apply {64        .face = &face,65        .data = &face.data(),66        .table = table,67        .at = 0,68        .has_glyph_classes = has_classes69    };70}7172// Whether the lookup's flags (`lookup_props`, its mark filtering set in73// the high half) let it see the glyph.74exp fn sees(self c: &Apply, info: &GlyphInfo, lookup_props: u32) -> bool {75    const props = info.props to u32;76    if ((props & lookup_props & IGNORE_FLAGS) != 0) {77        return false;78    }79    if ((props & MARK to u32) != 0) {80        if ((lookup_props & MARK_FILTERING) != 0) {81            return in_mark_set(&c.face, lookup_props >> 16, info.glyph);82        }83        if ((lookup_props & MARK_ATTACHMENT_TYPE) != 0) {84            return (lookup_props & MARK_ATTACHMENT_TYPE) == (props & MARK_ATTACHMENT_TYPE);85        }86    }87    return true;88}8990// The glyph's props from GDEF: its class, and a mark's attachment class91// in the high byte.92exp fn glyph_props(face: &Face, glyph: u32) -> u16 {93    const gdef = if (face.gdef is ::Some |g|) g else {94        return 0;95    };96    const d = &face.data();97    const classes = u16_at(&d, gdef + 4) to u64;98    if (classes == 0) {99        return 0;100    }101    match (class_of(&d, gdef + classes, glyph)) {102        1 {103            return BASE_GLYPH;104        }105        2 {106            return LIGATURE;107        }108        3 {109            const marks = u16_at(&d, gdef + 10) to u64;110            const attachment = if (marks == 0) 0 else class_of(&d, gdef + marks, glyph);111            return MARK | (attachment to u16 << 8);112        }113    }114    return 0;115}116117// Sets the glyph at `at` to `glyph` with its props, keeping what118// substitutions said and adding that one did (HarfBuzz's119// _set_glyph_class): a ligature's or a multiplied glyph's class guessed120// where GDEF gives none.121exp fn set_glyph(122    self c: &Apply,123    buffer: &var Buffer,124    at: u64,125    glyph: u32,126    class_guess: u16,127    ligature: bool,128    component: bool129) {130    var info = &var buffer.infos.get_var(at);131    var props = info.props | SUBSTITUTED;132    if (ligature) {133        // as Uniscribe, the last of ligating and multiplying counts134        props = (props | LIGATED) & ~MULTIPLIED;135    }136    if (component) {137        props |= MULTIPLIED;138    }139    if (c.has_glyph_classes) {140        props = (props & PRESERVED) | glyph_props(&c.face, glyph);141    } else if (class_guess != 0) {142        props = (props & PRESERVED) | class_guess;143    }144    info.props = props;145    info.glyph = glyph;146}147148// Replaces the current glyph, moving on past it.149exp fn replace_glyph(self c: &var Apply, buffer: &var Buffer, glyph: u32) {150    c.set_glyph(&var buffer, c.at, glyph, 0, false, false);151    c.at += 1;152}153154// How a sequence's items name glyphs: by id, by class in a class155// definition table, or by coverage tables at offsets from the subtable.156exp type Naming = enum {157    Glyphs,158    Classes: u64, // the class definition table, 0 for none159    Coverages: u64, // the subtable160};161162// A list of items in a rule: `count` 16-bit values at `at`, none for a163// matcher that matches any glyph.164exp type Items = struct {165    exp naming: Naming,166    exp at: u64,167    exp count: u64,168};169170exp fn Items::none() -> Items => Items { .naming = Naming::Glyphs, .at = 0, .count = 0 };171172exp fn matches(self items: &Items, d: &[u8], k: u64, glyph: u32) -> bool {173    const value = u16_at(&d, items.at + k * 2);174    return match (items.naming) {175        ::Glyphs value == glyph;176        ::Classes |classes| class_of(&d, classes, glyph) == value;177        ::Coverages |base| coverage(&d, base + value to u64, glyph) is ::Some;178    };179}180181// What a skipping iterator matches with (HarfBuzz's matcher_t).182exp type Matcher = struct {183    exp lookup_props: u32,184    exp mask: u32,185    exp ignore_zwnj: bool,186    exp ignore_zwj: bool,187    exp ignore_hidden: bool,188    exp per_syllable: bool,189    exp syllable: u8 = 0,190};191192// The matcher for the input (`context` false) or the context around it.193exp fn matcher(self c: &Apply, context: bool) -> Matcher {194    const positioning = c.table is ::Positioning;195    return Matcher {196        .lookup_props = c.lookup_props,197        .mask = if (context) 0xFFFFFFFF else c.lookup_mask,198        .ignore_zwnj = positioning || (context && c.auto_zwnj),199        .ignore_zwj = context || c.auto_zwj,200        .ignore_hidden = positioning,201        .per_syllable = !positioning && c.per_syllable202    };203}204205// What a glyph is to a matcher.206exp type Seen = enum {207    Match,208    NotMatch,209    Skip,210};211212// Whether the matcher matches, does not match or skips the glyph,213// `matched` what the item to match says of it (None for any glyph).214exp fn see(self m: &Matcher, c: &Apply, info: &GlyphInfo, matched: Option<bool>) -> Seen {215    if (!c.sees(&info, m.lookup_props)) {216        return Seen::Skip;217    }218    const skip_maybe = info.is_default_ignorable()219        && (m.ignore_zwnj || !info.is_zwnj())220        && (m.ignore_zwj || !info.is_zwj())221        && (m.ignore_hidden || !info.is_hidden());222    // 0 no, 1 yes, 2 maybe223    var may_match: u32 = 2;224    if (225        (info.mask & m.mask) == 0226        || (m.per_syllable && m.syllable != 0 && m.syllable != info.syllable)227    ) {228        may_match = 0;229    } else if (matched is ::Some |yes|) {230        may_match = if (yes) 1 else 0;231    }232    if (may_match == 1 || (may_match == 2 && !skip_maybe)) {233        return Seen::Match;234    }235    return if (skip_maybe) Seen::Skip else Seen::NotMatch;236}237238// The next glyph after `from` (before `end`) the matcher matches, the239// item's `k`th value naming it; None at one it does not or at the end.240exp fn next_match(241    self m: &Matcher,242    c: &Apply,243    infos: &[GlyphInfo],244    from: u64,245    end: u64,246    items: &Items,247    k: u64248) -> Option<u64> {249    const d = &c.data;250    var i = from;251    while (i + 1 < end) {252        i += 1;253        const info = &infos[i];254        const matched: Option<bool> = if (items.count > 0) ::Some(255            items.matches(&d, k, info.glyph)256        ) else ::None;257        match (m.see(&c, &info, matched)) {258            ::Match {259                return ::Some(i);260            }261            ::NotMatch {262                return ::None;263            }264            ::Skip {}265        }266    }267    return ::None;268}269270// The glyph before `from` the matcher matches, as next_match.271exp fn previous_match(272    self m: &Matcher,273    c: &Apply,274    infos: &[GlyphInfo],275    from: u64,276    items: &Items,277    k: u64278) -> Option<u64> {279    const d = &c.data;280    var i = from;281    while (i > 0) {282        i -= 1;283        const info = &infos[i];284        const matched: Option<bool> = if (items.count > 0) ::Some(285            items.matches(&d, k, info.glyph)286        ) else ::None;287        match (m.see(&c, &info, matched)) {288            ::Match {289                return ::Some(i);290            }291            ::NotMatch {292                return ::None;293            }294            ::Skip {}295        }296    }297    return ::None;298}299300// Matches the input after the current glyph (the input's first, already301// matched), putting its glyphs' positions in `c.positions`; the end of302// the match and the components the glyphs make, for a ligature, when it303// matches (HarfBuzz's match_input).304exp fn match_input(self c: &var Apply, buffer: &Buffer, input: &Items) -> Option<[u64 : 2]> {305    const infos = &buffer.infos.view();306    const first = &infos[c.at];307    c.positions.clear();308    c.positions.push(c.at);309    if (input.count == 0) {310        return ::Some([c.at + 1, first.component_count() to u64]);311    }312    if (input.count + 1 > MAX_CONTEXT) {313        return ::None;314    }315    var m = c.matcher(false);316    m.syllable = first.syllable;317    const first_id = first.ligature_id();318    const first_component = first.ligature_component();319    var total = first.component_count() to u64;320    // 0 not checked, 1 may not skip, 2 may skip321    var ligature_base: u32 = 0;322    var i = c.at;323    for ([..input.count]) |k| {324        i = if (m.next_match(&c, &infos, i, infos.length(), &input, k) is ::Some |n|) n else {325            return ::None;326        };327        c.positions.push(i);328        const this_id = infos[i].ligature_id();329        const this_component = infos[i].ligature_component();330        if (first_id != 0 && first_component != 0) {331            // after a glyph on a ligature's component, only glyphs on that332            // component, unless the ligature itself is skipped333            if (first_id != this_id || first_component != this_component) {334                if (ligature_base == 0) {335                    var found = false;336                    var j = c.at;337                    while (j > 0 && infos[j - 1].ligature_id() == first_id) {338                        j -= 1;339                        if (infos[j].ligature_component() == 0) {340                            found = true;341                            break;342                        }343                    }344                    // unless the ligature itself is one the lookup's flags skip345                    ligature_base = if (found && !c.sees(&infos[j], m.lookup_props)) 2 else 1;346                }347                if (ligature_base == 1) {348                    return ::None;349                }350            }351        } else if (this_id != 0 && this_component != 0 && this_id != first_id) {352            return ::None;353        }354        total += infos[i].component_count() to u64;355    }356    return ::Some([i + 1, total]);357}358359// Replaces the matched glyphs (`c.positions`, ending before `end`) by the360// ligature glyph, the marks between them taking its id and the component361// they were on (HarfBuzz's ligate_input).362exp fn ligate(self c: &var Apply, buffer: &var Buffer, end: u64, glyph: u32, total: u64) {363    buffer.merge_clusters(c.at, end);364    const count = c.positions.length();365    const infos = &buffer.infos.view();366    var base_ligature = infos[c.positions.get(0)].is_base_glyph();367    var mark_ligature = infos[c.positions.get(0)].is_mark();368    for ([1..count]) |k| {369        if (!infos[c.positions.get(k)].is_mark()) {370            base_ligature = false;371            mark_ligature = false;372            break;373        }374    }375    const is_ligature = !base_ligature && !mark_ligature;376    const class: u16 = if (is_ligature) LIGATURE else 0;377    const id = if (is_ligature) buffer.next_ligature_id() else 0;378    var last_id = buffer.infos.get(c.at).ligature_id();379    var last_count = buffer.infos.get(c.at).component_count();380    var so_far = last_count;381    if (is_ligature) {382        var first = &var buffer.infos.get_var(c.at);383        first.set_ligature_props(id, total to u32);384        if (first.general() is ::NonspacingMark) {385            first.set_general(GeneralCategory::OtherLetter);386        }387    }388    c.set_glyph(&var buffer, c.at, glyph, class, true, false);389    // each later component goes, the marks before it moved onto the390    // ligature's component they were on391    var removed: u64 = 0;392    var i = c.at + 1;393    for ([1..count]) |k| {394        const position = c.positions.get(k) - removed;395        while (i < position) {396            if (is_ligature) {397                var info = &var buffer.infos.get_var(i);398                var component = info.ligature_component();399                if (component == 0) {400                    component = last_count;401                }402                info.set_mark_props(id, so_far - last_count + min(component, last_count));403            }404            i += 1;405        }406        last_id = buffer.infos.get(position).ligature_id();407        last_count = buffer.infos.get(position).component_count();408        so_far += last_count;409        buffer.infos.remove(position);410        removed += 1;411    }412    if (!mark_ligature && last_id != 0) {413        // marks after the last component, on one of its components414        for (buffer.infos.items()[i..]) |&var info| {415            if (info.ligature_id() != last_id) {416                break;417            }418            const component = info.ligature_component();419            if (component == 0) {420                break;421            }422            info.set_mark_props(id, so_far - last_count + min(component, last_count));423        }424    }425    c.at = i;426}427428// Matches the backtrack before the current glyph.429exp fn match_backtrack(self c: &Apply, buffer: &Buffer, backtrack: &Items) -> bool {430    if (backtrack.count == 0) {431        return true;432    }433    const infos = &buffer.infos.view();434    var m = c.matcher(true);435    m.syllable = infos[c.at].syllable;436    var i = c.at;437    for ([..backtrack.count]) |k| {438        i = if (m.previous_match(&c, &infos, i, &backtrack, k) is ::Some |p|) p else {439            return false;440        };441    }442    return true;443}444445// Matches the lookahead from `start` (past the input).446exp fn match_lookahead(self c: &Apply, buffer: &Buffer, lookahead: &Items, start: u64) -> bool {447    if (lookahead.count == 0) {448        return true;449    }450    const infos = &buffer.infos.view();451    var m = c.matcher(true);452    m.syllable = infos[c.at].syllable;453    var i = start - 1;454    for ([..lookahead.count]) |k| {455        i = if (m.next_match(&c, &infos, i, infos.length(), &lookahead, k) is ::Some |n|) n else {456            return false;457        };458    }459    return true;460}461462// The lookups a matched rule names, each at its position in the match,463// later positions moved as each adds or takes glyphs; then on past the464// match (HarfBuzz's apply_lookup). `apply` applies a lookup at `c.at`.465exp fn apply_records(466    self c: &var Apply,467    buffer: &var Buffer,468    records: u64,469    record_count: u64,470    match_end: u64,471    apply: (&var Apply, &var Buffer, u32) -> bool472) {473    const d = &c.data;474    var positions = Vector<u64>::from(&c.positions.view());475    var end = match_end to i64;476    for ([..record_count]) |r| {477        const record = records + r * 4;478        const index = u16_at(&d, record) to u64;479        const lookup = u16_at(&d, record + 2);480        const count = positions.length();481        if (index >= count) {482            continue;483        }484        const length = buffer.infos.length();485        if (positions.get(index) >= length) {486            continue;487        }488        if (c.nesting_left == 0) {489            break;490        }491        c.at = positions.get(index);492        c.nesting_left -= 1;493        const applied = apply(&var c, &var buffer, lookup);494        c.nesting_left += 1;495        if (!applied) {496            continue;497        }498        var delta = buffer.infos.length() to i64 - length to i64;499        if (delta == 0) {500            continue;501        }502        end += delta;503        if (end < positions.get(index) to i64) {504            delta += positions.get(index) to i64 - end;505            end = positions.get(index) to i64;506        }507        // as many positions after this one added, filled with the glyphs508        // following it, or taken509        var next = index + 1;510        if (delta > 0) {511            if (delta to u64 + count > MAX_CONTEXT) {512                break;513            }514            for ([..delta to u64]) |k| {515                positions.insert(next + k, positions.get(next + k - 1) + 1);516            }517            next += delta to u64;518        } else {519            delta = max(delta, next to i64 - count to i64);520            for ([..(-delta) to u64]) {521                positions.remove(next);522            }523        }524        for (positions.items()[next..]) |&var p| {525            p = (p to i64 + delta) to u64;526        }527    }528    c.at = end to u64;529}530531fn in_mark_set(face: &Face, set: u32, glyph: u32) -> bool {532    const d = &face.data();533    const gdef = if (face.gdef is ::Some |g|) g else {534        return false;535    };536    if (u16_at(&d, gdef + 2) < 2) {537        return false;538    }539    const sets = u16_at(&d, gdef + 12) to u64;540    if (sets == 0 || set >= u16_at(&d, gdef + sets + 2)) {541        return false;542    }543    const table = gdef + sets + u32_at(&d, gdef + sets + 4 + set to u64 * 4) to u64;544    return coverage(&d, table, glyph) is ::Some;545}