1// What shaping a run applies, compiled once for a face, script,2// language, direction and set of features (HarfBuzz's shape plan and3// feature map, hb-ot-map.cc and hb-ot-shape.cc): the script's shaper,4// the language system its features are read from, each feature's mask,5// and the lookups of GSUB and GPOS in stages, each stage ending in what6// the shaper does between them.78import std::vector;9import std::option;10import std::string;11import std::sort;1213import text;14import font::reader;15import font::face;16import unicode::tables;17import opentype;18import tags;19import shapers;2021// How a feature is applied.22exp type FeatureFlags = struct {23 exp global: bool = false, // to every glyph, through the global mask bit24 exp has_fallback: bool = false, // given a mask even when the face lacks it25 exp manual_zwnj: bool = false, // ZWNJ not skipped when matching context26 exp manual_zwj: bool = false, // ZWJ not skipped when matching input27 exp global_search: bool = false, // looked for outside the language system too28 exp random: bool = false, // alternates picked at random29 exp per_syllable: bool = false, // matching kept within a syllable30};3132const MANUAL_JOINERS = FeatureFlags { .global = true, .manual_zwnj = true, .manual_zwj = true };3334// What the shaper does between two stages of lookups.35exp type Pause = enum {36 Nothing,37 ClearSubstitutionFlags,38 ArabicStretch, // records `stch`'s glyphs39 ArabicFallback, // presentation forms where the face lacks the features40 IndicSyllables,41 IndicInitialReordering,42 IndicFinalReordering,43 KhmerSyllables,44 KhmerReordering,45 MyanmarSyllables,46 MyanmarReordering,47 UseSyllables,48 UseRepha, // records `rphf`'s glyphs49 UsePreBase, // records `pref`'s glyphs50 UseReordering,51};5253// A feature as the shaper asks for it.54type FeatureInfo = struct {55 tag: u32,56 sequence: u32,57 max_value: u32,58 flags: FeatureFlags,59 default_value: u32,60 stage: [u32 : 2],61};6263// A feature of the plan: where its lookups are in each table (0xFFFF for64// none), its stage in each, and its bits in a glyph's mask.65exp type FeatureMap = struct {66 exp tag: u32,67 exp index: [u32 : 2],68 exp stage: [u32 : 2],69 exp shift: u32,70 exp mask: u32,71 exp one_mask: u32, // its value 172 exp auto_zwnj: bool,73 exp auto_zwj: bool,74 exp random: bool,75 exp per_syllable: bool,76 exp needs_fallback: bool,77};7879// A lookup of the plan and the glyphs it applies to.80exp type LookupMap = struct {81 exp index: u32,82 exp mask: u32,83 exp auto_zwnj: bool = true,84 exp auto_zwj: bool = true,85 exp random: bool = false,86 exp per_syllable: bool = false,87 exp feature: u32 = 0,88};8990// A stage: the lookups before `end`, then the pause.91exp type Stage = struct {92 exp end: u64,93 exp pause: Pause,94};9596exp const NO_FEATURE: u32 = 0xFFFF;97exp const GLOBAL_BIT: u32 = 0x80000000;9899exp type Plan = struct {100 // its key101 exp face: u32,102 exp script: Script,103 exp language: String,104 exp rtl: bool,105 exp settings: Vector<Feature>,106 // what it is107 exp shaper: Shaper,108 exp chosen: [u32 : 2], // the script tags chosen in GSUB and GPOS109 exp found: [bool : 2],110 exp global_mask: u32 = GLOBAL_BIT,111 exp features: Vector<FeatureMap>,112 exp substitutions: Vector<LookupMap>,113 exp positionings: Vector<LookupMap>,114 exp substitution_stages: Vector<Stage>,115 exp positioning_stages: Vector<Stage>,116 exp rtlm_mask: u32 = 0,117 exp frac_mask: u32 = 0,118 exp numr_mask: u32 = 0,119 exp dnom_mask: u32 = 0,120 exp has_frac: bool = false,121 exp kern_mask: u32 = 0,122 exp apply_gpos: bool = false,123 exp apply_kern: bool = false,124 exp zero_marks: bool = false,125 exp has_gpos_mark: bool = false,126 exp adjust_mark_positioning: bool = false, // when zeroing marks' advances127 exp fallback_mark_positioning: bool = false,128 exp fallback_glyph_classes: bool = false,129 // a complex script's shaper (pkg::alloy::text_scripts), none for the130 // default one, and the characters' mirrors right to left131 exp complex: Option<*var ComplexShaper> = ::None,132 exp mirror: Option<(u32) -> Option<u32>> = ::None,133};134135// A feature's mask, 0 when the plan has not got it.136exp fn mask_of(self plan: &Plan, feature: u32) -> u32 {137 if (plan.feature(feature) is ::Some |f|) {138 return f.mask;139 }140 return 0;141}142143// The mask setting the feature to 1, 0 when the plan has not got it.144exp fn one_mask(self plan: &Plan, feature: u32) -> u32 {145 if (plan.feature(feature) is ::Some |f|) {146 return f.one_mask;147 }148 return 0;149}150151exp fn feature(self plan: &Plan, feature: u32) -> Option<&FeatureMap> {152 var low: u64 = 0;153 var high = plan.features.length();154 while (low < high) {155 const middle = (low + high) / 2;156 const f = &plan.features.get(middle);157 if (f.tag < feature) {158 low = middle + 1;159 } else if (f.tag > feature) {160 high = middle;161 } else {162 return ::Some(&f);163 }164 }165 return ::None;166}167168// Whether the plan's language system has the feature in a table.169exp fn feature_index(self plan: &Plan, table: u64, feature: u32) -> u32 {170 if (plan.feature(feature) is ::Some |f|) {171 return f.index[table];172 }173 return NO_FEATURE;174}175176// What a plan is being built from: the language systems found, the177// features asked for and the stages so far.178exp type Builder = struct {179 exp face: &Face,180 exp script: Script,181 exp rtl: bool,182 exp shaper: Shaper,183 exp chosen: [u32 : 2] = [0, 0],184 exp found: [bool : 2] = [false, false],185 // each table's language system, if its script is in it186 language: [Option<u64> : 2] = [::None, ::None],187 features: Vector<FeatureInfo> = Vector<FeatureInfo>::empty(),188 // each stage's index and pause, GSUB's then GPOS's189 substitution_pauses: Vector<Stage> = Vector<Stage>::empty(),190 positioning_pauses: Vector<Stage> = Vector<Stage>::empty(),191 current: [u32 : 2] = [0, 0],192 simple: bool = true,193};194195fn table_of(face: &Face, table: u64) -> Option<u64> => if (table == 0) face.gsub else face.gpos;196197exp fn Builder::of(198 face: &Face,199 script: Script,200 language: &[u8],201 rtl: bool,202 scripts: &Option<ScriptHooks>203) -> Builder {204 var b = Builder { .face = &face, .script = script, .rtl = rtl, .shaper = Shaper::Default };205 const d = &face.data();206 const script_tags = script_tags(script);207 // the language's systems, which text_scripts knows; the default's208 // without it209 var language_tags = Tags {};210 if (scripts is ::Some |&h|) {211 language_tags = (h.languages)(&language);212 }213 for ([..2 to u64]) |t| {214 const table = if (table_of(&face, t) is ::Some |x|) x else {215 continue;216 };217 // the script's tags in order, then DFLT, dflt and latn218 var found: Option<u64> = ::None;219 for (script_tags.view()) |tag| {220 if (find_script(&d, table, tag) is ::Some |s|) {221 found = ::Some(s);222 b.chosen[t] = tag;223 b.found[t] = true;224 break;225 }226 }227 if (found is ::None) {228 for ([tag(&"DFLT"), tag(&"dflt"), tag(&"latn")]) |fallback| {229 if (find_script(&d, table, fallback) is ::Some |s|) {230 found = ::Some(s);231 b.chosen[t] = fallback;232 break;233 }234 }235 }236 const s = if (found is ::Some |s|) s else {237 continue;238 };239 for (language_tags.view()) |tag| {240 if (find_language(&d, s, tag) is ::Some |l|) {241 b.language[t] = ::Some(l);242 break;243 }244 }245 if (b.language[t] is ::None) {246 if (find_language(&d, s, tag(&"dflt")) is ::Some |l|) {247 b.language[t] = ::Some(l);248 } else {249 b.language[t] = default_language(&d, s);250 }251 }252 }253 return move b;254}255256exp fn add_feature(self b: &var Builder, tag: u32, flags: FeatureFlags, value: u32) {257 if (tag == 0) {258 return;259 }260 b.features.push(FeatureInfo {261 .tag = tag,262 .sequence = b.features.length() to u32 + 1,263 .max_value = value,264 .flags = flags,265 .default_value = if (flags.global) value else 0,266 .stage = b.current267 });268}269270// Adds the feature, on for every glyph.271exp fn enable_feature(self b: &var Builder, tag: u32, flags: FeatureFlags) {272 var global = flags;273 global.global = true;274 b.add_feature(tag, global, 1);275}276277exp fn enable(self b: &var Builder, name: &[u8]) {278 b.enable_feature(tag(&name), FeatureFlags {});279}280281// Ends the GSUB stage with the pause.282exp fn add_gsub_pause(self b: &var Builder, pause: Pause) {283 b.substitution_pauses.push(Stage { .end = b.current[0] to u64, .pause = pause });284 b.current[0] += 1;285}286287exp fn add_gpos_pause(self b: &var Builder, pause: Pause) {288 b.positioning_pauses.push(Stage { .end = b.current[1] to u64, .pause = pause });289 b.current[1] += 1;290}291292// Whether either table's language system has the feature.293exp fn has_feature(self b: &Builder, tag: u32) -> bool {294 const d = &b.face.data();295 for ([..2 to u64]) |t| {296 if (b.language[t] is ::Some |l| && table_of(&b.face, t) is ::Some |table|) {297 const count = u16_at(&d, l + 4) to u64;298 for ([..count]) |k| {299 if (feature_tag(&d, table, u16_at(&d, l + 6 + k * 2)) == tag) {300 return true;301 }302 }303 }304 }305 return false;306}307308const COMMON: [&[u8] : 7] = [&"abvm", &"blwm", &"ccmp", &"locl", &"mark", &"mkmk", &"rlig"];309const HORIZONTAL: [&[u8] : 7] = [&"calt", &"clig", &"curs", &"dist", &"kern", &"liga", &"rclt"];310311// The plan for the run, its features those HarfBuzz turns on with the312// shaper's and the settings', its shaper a complex one where313// text_scripts gives one.314exp fn Plan::compile(315 face_index: u32,316 face: &Face,317 script: Script,318 language: &[u8],319 rtl: bool,320 settings: &[Feature],321 scripts: &Option<ScriptHooks>322) -> Plan {323 var b = Builder::of(&face, script, &language, rtl, &scripts);324 var complex: Option<*var ComplexShaper> = ::None;325 if (scripts is ::Some |&h|) {326 complex = (h.shaper)(script, b.chosen[0]);327 }328 if (complex is ::Some |&c|) {329 b.shaper = c.kind();330 }331 b.enable(&"rvrn");332 b.add_gsub_pause(Pause::Nothing);333 if (rtl) {334 b.enable(&"rtla");335 b.add_feature(tag(&"rtlm"), FeatureFlags {}, 1);336 } else {337 b.enable(&"ltra");338 b.enable(&"ltrm");339 }340 b.add_feature(tag(&"frac"), FeatureFlags {}, 1);341 b.add_feature(tag(&"numr"), FeatureFlags {}, 1);342 b.add_feature(tag(&"dnom"), FeatureFlags {}, 1);343 b.add_feature(tag(&"rand"), FeatureFlags { .global = true, .random = true }, 255);344 b.enable(&"Harf");345 b.enable(&"HARF");346 if (complex is ::Some |&c| && c.collect_features(&var b)) {347 b.simple = false;348 }349 b.enable(&"Buzz");350 b.enable(&"BUZZ");351 for (COMMON) |&name| {352 const flags = if (name == "mark" || name == "mkmk") MANUAL_JOINERS else FeatureFlags {353 .global = true354 };355 b.add_feature(tag(&name), flags, 1);356 }357 for (HORIZONTAL) |&name| {358 b.add_feature(359 tag(&name),360 FeatureFlags { .global = true, .has_fallback = name == "kern" },361 1362 );363 }364 if (settings.length() > 0) {365 b.simple = false;366 }367 for (settings) |&s| {368 b.add_feature(s.tag, FeatureFlags { .global = true }, if (s.on) 1 else 0);369 }370 if (complex is ::Some |&c|) {371 c.override_features(&var b);372 }373 var plan = b.compile();374 plan.face = face_index;375 plan.language = String::from(&language);376 plan.settings = Vector<Feature>::from(&settings);377 if (complex is ::Some |&var c|) {378 c.prepare(&plan, &face);379 }380 plan.complex = move complex;381 if (scripts is ::Some |&h|) {382 plan.mirror = ::Some(h.mirror);383 }384 return move plan;385}386387fn compile(self b: &var Builder) -> Plan {388 const d = &b.face.data();389 var plan = Plan {390 .face = 0,391 .script = b.script,392 .language = String::empty(),393 .rtl = b.rtl,394 .settings = Vector<Feature>::empty(),395 .shaper = b.shaper,396 .chosen = b.chosen,397 .found = b.found,398 .features = Vector<FeatureMap>::empty(),399 .substitutions = Vector<LookupMap>::empty(),400 .positionings = Vector<LookupMap>::empty(),401 .substitution_stages = Vector<Stage>::empty(),402 .positioning_stages = Vector<Stage>::empty()403 };404 // the required features, applied in stage 0 unless another feature405 // with their tag is in a later one406 var required: [u32 : 2] = [NO_FEATURE, NO_FEATURE];407 var required_tag: [u32 : 2] = [0, 0];408 var required_stage: [u32 : 2] = [0, 0];409 for ([..2 to u64]) |t| {410 if (b.language[t] is ::Some |l| && table_of(&b.face, t) is ::Some |table|) {411 const index = u16_at(&d, l + 2);412 if (index != 0xFFFF) {413 required[t] = index;414 required_tag[t] = feature_tag(&d, table, index);415 }416 }417 }418 // the features by tag, those asked for twice merged419 sort_by(420 &var b.features.items(),421 (x, y) => x.tag < y.tag || (x.tag == y.tag && x.sequence < y.sequence)422 );423 var merged = Vector<FeatureInfo>::empty();424 for (b.features.view()) |&f| {425 if (merged.length() > 0 && merged.last().tag == f.tag) {426 var m = &var merged.get_var(merged.length() - 1);427 if (f.flags.global) {428 m.flags.global = true;429 m.max_value = f.max_value;430 m.default_value = f.default_value;431 } else {432 m.flags.global = false;433 m.max_value = if (m.max_value > f.max_value) m.max_value else f.max_value;434 }435 m.flags.has_fallback = m.flags.has_fallback || f.flags.has_fallback;436 m.stage[0] = if (m.stage[0] < f.stage[0]) m.stage[0] else f.stage[0];437 m.stage[1] = if (m.stage[1] < f.stage[1]) m.stage[1] else f.stage[1];438 } else {439 merged.push(f);440 }441 }442 // each feature's bits, past the three of HarfBuzz's glyph flags; the443 // global bit for those on everywhere with value 1444 var next_bit: u32 = 4;445 for (merged.view()) |&info| {446 const global_one = info.flags.global && info.max_value == 1;447 const bits = if (global_one) 0 else min_u32(8, bit_storage(info.max_value));448 if (info.max_value == 0 || next_bit + bits >= 31) {449 continue;450 }451 var found = false;452 var index: [u32 : 2] = [NO_FEATURE, NO_FEATURE];453 for ([..2 to u64]) |t| {454 if (required_tag[t] == info.tag) {455 required_stage[t] = info.stage[t];456 }457 if (b.language_feature(t, info.tag) is ::Some |k|) {458 index[t] = k;459 found = true;460 }461 }462 if (!found && info.flags.global_search) {463 for ([..2 to u64]) |t| {464 if (table_of(&b.face, t) is ::Some |table|) {465 for ([..feature_count(&d, table)]) |k| {466 if (feature_tag(&d, table, k) == info.tag) {467 index[t] = k;468 found = true;469 break;470 }471 }472 }473 }474 }475 if (!found && !info.flags.has_fallback) {476 continue;477 }478 var map = FeatureMap {479 .tag = info.tag,480 .index = index,481 .stage = info.stage,482 .shift = 31,483 .mask = GLOBAL_BIT,484 .one_mask = GLOBAL_BIT,485 .auto_zwnj = !info.flags.manual_zwnj,486 .auto_zwj = !info.flags.manual_zwj,487 .random = info.flags.random,488 .per_syllable = info.flags.per_syllable,489 .needs_fallback = !found490 };491 if (!global_one) {492 map.shift = next_bit;493 map.mask = (494 (1 to u64 << (next_bit + bits) to u64) - (1 to u64 << next_bit to u64)495 ) to u32;496 map.one_mask = (1 << next_bit) & map.mask;497 next_bit += bits;498 plan.global_mask |= (info.default_value << map.shift) & map.mask;499 }500 plan.features.push(map);501 }502 b.add_gsub_pause(Pause::Nothing);503 b.add_gpos_pause(Pause::Nothing);504 // each stage's lookups, sorted, those of several features merged505 for ([..2 to u64]) |t| {506 const table = table_of(&b.face, t);507 const variation = if (t == 0) b.face.gsub_variation else b.face.gpos_variation;508 const pauses = if (t == 0) &b.substitution_pauses.view() else &b.positioning_pauses.view();509 var lookups = Vector<LookupMap>::empty();510 var stages = Vector<Stage>::empty();511 var pause_index: u64 = 0;512 var last: u64 = 0;513 for ([..b.current[t]]) |stage| {514 if (required[t] != NO_FEATURE && required_stage[t] == stage && table is ::Some |x|) {515 add_lookups(&d, x, variation, required[t], &var lookups, LookupMap {516 .index = 0,517 .mask = GLOBAL_BIT518 });519 }520 for (plan.features.view()) |&f| {521 if (f.stage[t] == stage && f.index[t] != NO_FEATURE && table is ::Some |x|) {522 add_lookups(&d, x, variation, f.index[t], &var lookups, LookupMap {523 .index = 0,524 .mask = f.mask,525 .auto_zwnj = f.auto_zwnj,526 .auto_zwj = f.auto_zwj,527 .random = f.random,528 .per_syllable = f.per_syllable,529 .feature = f.tag530 });531 }532 }533 if (last + 1 < lookups.length()) {534 sort_by(&var lookups.items()[last..], (x, y) => x.index < y.index);535 var j = last;536 for ([last + 1..lookups.length()]) |i| {537 const l = lookups.get(i);538 if (l.index != lookups.get(j).index) {539 j += 1;540 lookups.get_var(j) = l;541 } else {542 var m = &var lookups.get_var(j);543 m.mask |= l.mask;544 m.auto_zwnj = m.auto_zwnj && l.auto_zwnj;545 m.auto_zwj = m.auto_zwj && l.auto_zwj;546 }547 }548 lookups.truncate(j + 1);549 }550 last = lookups.length();551 if (pause_index < pauses.length() && pauses[pause_index].end == stage to u64) {552 stages.push(Stage { .end = last, .pause = pauses[pause_index].pause });553 pause_index += 1;554 }555 }556 if (t == 0) {557 plan.substitutions = move lookups;558 plan.substitution_stages = move stages;559 } else {560 plan.positionings = move lookups;561 plan.positioning_stages = move stages;562 }563 }564 plan.rtlm_mask = plan.one_mask(tag(&"rtlm"));565 plan.frac_mask = plan.one_mask(tag(&"frac"));566 plan.numr_mask = plan.one_mask(tag(&"numr"));567 plan.dnom_mask = plan.one_mask(tag(&"dnom"));568 plan.has_frac = plan.frac_mask != 0 || (plan.numr_mask != 0 && plan.dnom_mask != 0);569 plan.kern_mask = plan.mask_of(tag(&"kern"));570 const has_gpos_kern = plan.feature_index(1, tag(&"kern")) != NO_FEATURE;571 const gpos_tag = b.shaper.gpos_tag();572 const disable_gpos = gpos_tag != 0 && gpos_tag != plan.chosen[1];573 plan.fallback_glyph_classes = !has_glyph_classes(&b.face);574 plan.apply_gpos = !disable_gpos && b.face.gpos is ::Some;575 const fallback_position = b.shaper.fallback_position();576 if ((!has_gpos_kern || !plan.apply_gpos) && b.face.kern is ::Some) {577 plan.apply_kern = fallback_position;578 }579 plan.zero_marks = !(b.shaper.zero_width_marks() is ::Nothing);580 plan.has_gpos_mark = plan.one_mask(tag(&"mark")) != 0;581 plan.adjust_mark_positioning = !plan.apply_gpos;582 plan.fallback_mark_positioning = plan.adjust_mark_positioning && fallback_position;583 return move plan;584}585586// The index of the feature in the table's language system, the first587// listed when it is listed twice.588fn language_feature(self b: &Builder, t: u64, feature: u32) -> Option<u32> {589 const d = &b.face.data();590 if (b.language[t] is ::Some |l| && table_of(&b.face, t) is ::Some |table|) {591 const count = u16_at(&d, l + 4) to u64;592 for ([..count]) |k| {593 const index = u16_at(&d, l + 6 + k * 2);594 if (feature_tag(&d, table, index) == feature) {595 return ::Some(index);596 }597 }598 }599 return ::None;600}601602// Adds the lookups of the table's feature, as `model` says.603fn add_lookups(604 d: &[u8],605 table: u64,606 variation: Option<u64>,607 feature: u32,608 lookups: &var Vector<LookupMap>,609 model: LookupMap610) {611 const feature_list = table + u16_at(&d, table + 6) to u64;612 if (feature >= u16_at(&d, feature_list)) {613 return;614 }615 const at = feature_table(&d, feature_list, variation, feature);616 const count = u16_at(&d, at + 2) to u64;617 const total = lookup_count(&d, table);618 for ([..count]) |k| {619 const index = u16_at(&d, at + 4 + k * 2);620 if (index >= total) {621 continue;622 }623 var l = model;624 l.index = index;625 lookups.push(l);626 }627}628629fn has_glyph_classes(face: &Face) -> bool {630 if (face.gdef is ::Some |gdef|) {631 return u16_at(&face.data(), gdef + 4) != 0;632 }633 return false;634}635636fn bit_storage(value: u32) -> u32 {637 var bits: u32 = 0;638 var v = value;639 while (v != 0) {640 bits += 1;641 v >>= 1;642 }643 return bits;644}645646fn min_u32(a: u32, b: u32) -> u32 => if (a < b) a else b;