1// Shaping a run of text in one face, in one direction, as HarfBuzz's2// OpenType shaper does (hb-ot-shape.cc): characters given their Unicode3// props and grapheme clusters, prepared by their script's shaper,4// mirrored right to left, normalized and mapped to glyphs, then5// substituted and positioned by the plan's lookups in stages, default6// ignorables hidden at the end.78import std::vector;9import std::option;10import std::math;1112import text;13import font::reader;14import font::face;15import unicode::tables;16import unicode::properties;17import opentype;18import buffer;19import plan;20import shapers;21import tags;22import normalize;23import apply;24import gsub;25import gpos;26import fallback;2728// A run's glyphs, in font units, each with the byte offset of the first29// character it shows, in the text's order (right to left too: HarfBuzz30// gives the same glyphs reversed).31exp type Shaped = struct {32 exp infos: Vector<GlyphInfo>,33 exp positions: Vector<GlyphPosition>,34};3536// Shapes the run as hb-shape does without a script or language: the37// script its first character of one names, the default language, the38// direction given, the complex shapers text_scripts gives.39exp fn shape(40 face: &Face,41 text: &[u8],42 start: u64,43 end: u64,44 settings: &[Feature],45 rtl: bool,46 scripts: &Option<ScriptHooks>47) -> Shaped {48 const plan = Plan::compile(49 0,50 &face,51 guess_script(&text, start, end),52 &"",53 rtl,54 &settings,55 &scripts56 );57 return shape_with(&face, &plan, &text, start, end);58}5960// The script of the first character with one of its own, Common61// without.62exp fn guess_script(text: &[u8], start: u64, end: u64) -> Script {63 var at = start;64 while (at < end) {65 const d = decode(&text, at);66 const s = script(d.c);67 if (!(s is ::Common || s is ::Inherited || s is ::Unknown)) {68 return s;69 }70 at += d.length;71 }72 return Script::Common;73}7475// Shapes text[start..end] in the face by the plan.76exp fn shape_with(face: &Face, plan: &Plan, text: &[u8], start: u64, end: u64) -> Shaped {77 var buffer = Buffer {78 .infos = Vector<GlyphInfo>::with_capacity(end - start),79 .rtl = plan.rtl,80 .script = plan.script81 };82 var at = start;83 while (at < end) {84 const d = decode(&text, at);85 buffer.infos.push(GlyphInfo {86 .glyph = d.c,87 .cluster = at to u32,88 .mask = plan.global_mask89 });90 at += d.length;91 }92 // the characters around the run93 var back = start;94 while (back > 0 && buffer.before_count < 5) {95 back -= 1;96 while (back > 0 && (text[back] & 0xC0) == 0x80) {97 back -= 1;98 }99 buffer.before[buffer.before_count] = decode(&text, back).c;100 buffer.before_count += 1;101 }102 var ahead = end;103 while (ahead < text.length() && buffer.after_count < 5) {104 const d = decode(&text, ahead);105 buffer.after[buffer.after_count] = d.c;106 buffer.after_count += 1;107 ahead += d.length;108 }109 set_unicode_props(&var buffer);110 form_clusters(&var buffer);111 const reversed = ensure_native_direction(&var buffer);112 preprocess_text(&plan, &face, &var buffer);113 // substitutions114 rotate_characters(&plan, &face, &var buffer);115 normalize(&plan, &face, &var buffer);116 setup_fraction_masks(&plan, &var buffer);117 setup_masks(&plan, &face, &var buffer);118 if (plan.fallback_mark_positioning) {119 recategorize_marks(&var buffer);120 }121 for (buffer.infos.items()) |&var info| {122 info.glyph = info.mapped;123 info.props = glyph_props(&face, info.glyph);124 info.ligature = 0;125 }126 if (plan.fallback_glyph_classes) {127 synthesize_glyph_classes(&var buffer);128 }129 substitute(&plan, &face, &var buffer);130 // positions131 buffer.positions = Vector<GlyphPosition>::with_capacity(buffer.infos.length());132 for (buffer.infos.view()) |&info| {133 buffer.positions.push(GlyphPosition { .x_advance = face.advance(info.glyph) });134 }135 if (buffer.has_space_fallback) {136 fallback_spaces(&face, &var buffer);137 }138 position(&plan, &face, &var buffer);139 // what is left of the substitutions140 hide_default_ignorables(&face, &var buffer);141 postprocess_glyphs(&plan, &face, &var buffer);142 if (reversed) {143 buffer.reverse_range(0, buffer.infos.length());144 }145 return Shaped { .infos = move buffer.infos, .positions = move buffer.positions };146}147148// Each character's Unicode props, and what continues a grapheme beyond149// marks: emoji modifiers, the second of a pair of regional indicators, a150// ZWJ and the pictograph after it, and a few others.151fn set_unicode_props(buffer: &var Buffer) {152 const count = buffer.infos.length();153 var i: u64 = 0;154 while (i < count) {155 var info = buffer.infos.get(i);156 info.set_unicode(&var buffer);157 const c = info.glyph;158 if (c >= 0x80) {159 const category = info.general();160 const letter_or_space = category is ::LowercaseLetter || category is ::UppercaseLetter161 || category is ::TitlecaseLetter162 || category is ::OtherLetter163 || category is ::SpaceSeparator;164 if (!letter_or_space) {165 if (category is ::ModifierSymbol && c >= 0x1F3FB && c <= 0x1F3FF) {166 info.set_continuation();167 } else if (i > 0 && c >= 0x1F1E6 && c <= 0x1F1FF) {168 const before = &buffer.infos.get(i - 1);169 if (170 before.glyph >= 0x1F1E6171 && before.glyph <= 0x1F1FF172 && !before.is_continuation()173 ) {174 info.set_continuation();175 }176 } else if (info.is_zwj()) {177 info.set_continuation();178 buffer.infos.get_var(i) = info;179 if (180 i + 1 < count181 && (properties(buffer.infos.get(i + 1).glyph) & PICTOGRAPHIC) != 0182 ) {183 i += 1;184 var next = buffer.infos.get(i);185 next.set_unicode(&var buffer);186 next.set_continuation();187 buffer.infos.get_var(i) = next;188 }189 i += 1;190 continue;191 } else if ((c >= 0xFF9E && c <= 0xFF9F) || (c >= 0xE0020 && c <= 0xE007F)) {192 info.set_continuation();193 } else if (c == 0x2044) {194 buffer.has_fraction_slash = true;195 }196 }197 }198 buffer.infos.get_var(i) = info;199 i += 1;200 }201 for (buffer.infos.view()) |&info| {202 buffer.has_continuations = buffer.has_continuations || info.is_continuation();203 }204}205206// Each grapheme (a character and those continuing it) one cluster.207fn form_clusters(buffer: &var Buffer) {208 if (!buffer.has_continuations) {209 return;210 }211 const count = buffer.infos.length();212 var start: u64 = 0;213 while (start < count) {214 var end = start + 1;215 while (end < count && buffer.infos.get(end).is_continuation()) {216 end += 1;217 }218 buffer.merge_clusters(start, end);219 start = end;220 }221}222223// Reverses the graphemes of a run going against its script's direction224// (a left-to-right script set right to left), shaping it in its own:225// whether it did. Numbers alone in a right-to-left script go left to226// right as they are.227fn ensure_native_direction(buffer: &var Buffer) -> bool {228 var native_rtl = is_right_to_left_script(buffer.script);229 if (is_either_direction_script(buffer.script)) {230 return false;231 }232 if (native_rtl && !buffer.rtl) {233 var number = false;234 var letter = false;235 for (buffer.infos.view()) |&info| {236 const category = info.general();237 if (238 category is ::LowercaseLetter || category is ::ModifierLetter239 || category is ::OtherLetter240 || category is ::TitlecaseLetter241 || category is ::UppercaseLetter242 ) {243 letter = true;244 break;245 }246 if (category is ::DecimalNumber || (info.glyph >= 0x1F1E6 && info.glyph <= 0x1F1FF)) {247 number = true;248 }249 }250 if (number && !letter) {251 native_rtl = false;252 }253 }254 if (native_rtl == buffer.rtl) {255 return false;256 }257 // the graphemes in reverse, each kept in order258 const count = buffer.infos.length();259 buffer.reverse_range(0, count);260 var start: u64 = 0;261 while (start < count) {262 // reversed, a grapheme ends at its first character263 var end = start;264 while (end < count && buffer.infos.get(end).is_continuation()) {265 end += 1;266 }267 end = min(end + 1, count);268 buffer.reverse_range(start, end);269 start = end;270 }271 buffer.rtl = !buffer.rtl;272 return true;273}274275// Right to left (as the run is shown, before any reversal for its276// script), each character the face has a mirror's glyph for shows it,277// and the others take `rtlm`.278fn rotate_characters(plan: &Plan, face: &Face, buffer: &var Buffer) {279 if (!plan.rtl) {280 return;281 }282 for (buffer.infos.items()) |&var info| {283 if (284 plan.mirror is ::Some |mirror|285 && mirror(info.glyph) is ::Some |m|286 && face.glyph_of(m) != 0287 ) {288 info.glyph = m;289 } else {290 info.mask |= plan.rtlm_mask;291 }292 }293}294295// Digits around a fraction slash take `numr` before it and `dnom` after296// it, and all of them `frac`.297fn setup_fraction_masks(plan: &Plan, buffer: &var Buffer) {298 if (!buffer.has_fraction_slash || !plan.has_frac) {299 return;300 }301 const before = if (302 buffer.rtl303 ) plan.frac_mask | plan.dnom_mask else plan.numr_mask | plan.frac_mask;304 const after = if (305 buffer.rtl306 ) plan.numr_mask | plan.frac_mask else plan.frac_mask | plan.dnom_mask;307 const count = buffer.infos.length();308 var i: u64 = 0;309 while (i < count) {310 if (buffer.infos.get(i).glyph != 0x2044) {311 i += 1;312 continue;313 }314 var start = i;315 var end = i + 1;316 while (start > 0 && buffer.infos.get(start - 1).general() is ::DecimalNumber) {317 start -= 1;318 }319 while (end < count && buffer.infos.get(end).general() is ::DecimalNumber) {320 end += 1;321 }322 if (start == i || end == i + 1) {323 i += 1;324 continue;325 }326 const infos = &var buffer.infos.items();327 for (infos[start..i]) |&var info| {328 info.mask |= before;329 }330 infos[i].mask |= plan.frac_mask;331 for (infos[i + 1..end]) |&var info| {332 info.mask |= after;333 }334 i = end;335 }336}337338// Glyph classes where GDEF gives none: marks (but default ignorables)339// as marks, the rest as bases.340fn synthesize_glyph_classes(buffer: &var Buffer) {341 for (buffer.infos.items()) |&var info| {342 const mark = info.general() is ::NonspacingMark && !info.is_default_ignorable();343 info.props = if (mark) MARK else BASE_GLYPH;344 }345}346347// The plan's GSUB lookups, stage by stage, each stage's pause after it.348fn substitute(plan: &Plan, face: &Face, buffer: &var Buffer) {349 var c = Apply::of(&face, LookupTable::Substitution);350 c.rtl = buffer.rtl;351 var i: u64 = 0;352 for (plan.substitution_stages.view()) |&stage| {353 while (i < stage.end) {354 const l = &plan.substitutions.get(i);355 c.lookup_mask = l.mask;356 c.auto_zwnj = l.auto_zwnj;357 c.auto_zwj = l.auto_zwj;358 c.random = l.random;359 c.per_syllable = l.per_syllable;360 substitute_lookup(&var c, &var buffer, l.index);361 i += 1;362 }363 run_pause(stage.pause, &plan, &face, &var buffer);364 }365}366367// The plan's GPOS lookups or the face's `kern` table, with marks' advances368// zeroed before or after as the shaper says, then attachments resolved.369fn position(plan: &Plan, face: &Face, buffer: &var Buffer) {370 const adjust_offsets = plan.adjust_mark_positioning && !buffer.rtl;371 const zero = plan.shaper.zero_width_marks();372 if (plan.zero_marks && zero is ::Early) {373 zero_mark_widths(&var buffer, adjust_offsets);374 }375 if (plan.apply_gpos) {376 var c = Apply::of(&face, LookupTable::Positioning);377 c.rtl = buffer.rtl;378 var i: u64 = 0;379 for (plan.positioning_stages.view()) |&stage| {380 while (i < stage.end) {381 const l = &plan.positionings.get(i);382 c.lookup_mask = l.mask;383 c.auto_zwnj = l.auto_zwnj;384 c.auto_zwj = l.auto_zwj;385 c.random = l.random;386 c.per_syllable = l.per_syllable;387 position_lookup(&var c, &var buffer, l.index);388 i += 1;389 }390 }391 }392 if (plan.apply_kern) {393 kern(&plan, &face, &var buffer);394 }395 if (plan.zero_marks && zero is ::Late) {396 zero_mark_widths(&var buffer, adjust_offsets);397 }398 // default ignorables take no room399 if (buffer.has_ignorables) {400 for (buffer.infos.view(), buffer.positions.items()) |&info, &var p| {401 if (info.is_default_ignorable()) {402 p.x_advance = 0.0;403 p.y_advance = 0.0;404 p.x_offset = 0.0;405 }406 }407 }408 resolve_attachments(&var buffer);409 if (plan.fallback_mark_positioning) {410 position_marks(&face, &var buffer, adjust_offsets);411 }412}413414// Marks by GDEF take no room, their offsets moved back by their advance415// when GPOS will not place them.416fn zero_mark_widths(buffer: &var Buffer, adjust_offsets: bool) {417 for (buffer.infos.view(), buffer.positions.items()) |&info, &var p| {418 if (info.is_mark()) {419 if (adjust_offsets) {420 p.x_offset -= p.x_advance;421 p.y_offset -= p.y_advance;422 }423 p.x_advance = 0.0;424 p.y_advance = 0.0;425 }426 }427}428429// The `kern` table's pairs, each kerning shared between its two glyphs,430// marks skipped (HarfBuzz's hb_kern_machine_t).431fn kern(plan: &Plan, face: &Face, buffer: &var Buffer) {432 var c = Apply::of(&face, LookupTable::Positioning);433 c.lookup_mask = plan.kern_mask;434 c.lookup_props = IGNORE_MARKS;435 const m = c.matcher(false);436 const count = buffer.infos.length();437 var i: u64 = 0;438 while (i < count) {439 if ((buffer.infos.get(i).mask & plan.kern_mask) == 0) {440 i += 1;441 continue;442 }443 const j = if (444 m.next_match(&c, &buffer.infos.view(), i, count, &Items::none(), 0) is ::Some |n|445 ) n else {446 i += 1;447 continue;448 };449 const kerning = face.kerning(buffer.infos.get(i).glyph, buffer.infos.get(j).glyph);450 if (kerning != 0.0) {451 const first = floor(kerning / 2.0);452 const second = kerning - first;453 buffer.positions.get_var(i).x_advance += first;454 buffer.positions.get_var(j).x_advance += second;455 buffer.positions.get_var(j).x_offset += second;456 }457 i = j;458 }459}460461// Spaces shown in the face's space glyph, for lack of their own, given462// their widths (HarfBuzz's _hb_ot_shape_fallback_spaces).463fn fallback_spaces(face: &Face, buffer: &var Buffer) {464 const em = face.units_per_em to i64;465 for (buffer.infos.view(), buffer.positions.items()) |&info, &var p| {466 if (!info.is_unicode_space() || info.ligated()) {467 continue;468 }469 const kind = info.space_kind();470 match (kind) {471 1, 2, 3, 4, 5, 6, SPACE_EM_16 {472 p.x_advance = ((em + (kind / 2) to i64) / kind to i64) to f32;473 }474 SPACE_4_EM_18 {475 p.x_advance = (em * 4 / 18) to f32;476 }477 SPACE_FIGURE {478 for ([0x30..0x3A to u32]) |digit| {479 const glyph = face.glyph_of(digit);480 if (glyph != 0) {481 p.x_advance = face.advance(glyph);482 break;483 }484 }485 }486 SPACE_PUNCTUATION {487 var glyph = face.glyph_of('.');488 if (glyph == 0) {489 glyph = face.glyph_of(',');490 }491 if (glyph != 0) {492 p.x_advance = face.advance(glyph);493 }494 }495 SPACE_NARROW {496 p.x_advance = (p.x_advance to i64 / 2) to f32;497 }498 else {}499 }500 }501}502503// Default ignorables show the face's space glyph, with no width, or go504// when it has none, their clusters merged into their neighbors'.505fn hide_default_ignorables(face: &Face, buffer: &var Buffer) {506 if (!buffer.has_ignorables) {507 return;508 }509 const space = face.glyph_of(' ');510 if (space != 0) {511 for (buffer.infos.items()) |&var info| {512 if (info.is_default_ignorable()) {513 info.glyph = space;514 }515 }516 return;517 }518 var j: u64 = 0;519 const count = buffer.infos.length();520 for ([..count]) |i| {521 const info = buffer.infos.get(i);522 if (info.is_default_ignorable()) {523 const cluster = info.cluster;524 if (i + 1 < count && cluster == buffer.infos.get(i + 1).cluster) {525 continue;526 }527 if (j > 0) {528 if (cluster < buffer.infos.get(j - 1).cluster) {529 const old = buffer.infos.get(j - 1).cluster;530 var k = j;531 while (k > 0 && buffer.infos.get(k - 1).cluster == old) {532 buffer.infos.get_var(k - 1).cluster = cluster;533 k -= 1;534 }535 }536 continue;537 }538 if (i + 1 < count) {539 buffer.merge_clusters(i, i + 2);540 }541 continue;542 }543 if (j != i) {544 buffer.infos.get_var(j) = buffer.infos.get(i);545 buffer.positions.get_var(j) = buffer.positions.get(i);546 }547 j += 1;548 }549 buffer.infos.truncate(j);550 buffer.positions.truncate(j);551}