1// A font face read from TrueType data: where its tables are, its metrics,2// characters to glyphs, advances and outlines. Its bytes are kept as3// given, read in place.45import std::vector;6import std::option;7import std::math;89import std::string;10import std::fs;1112import reader;13import outline;14import shaping::opentype;15import unicode::tables;16import unicode::properties;17import text;1819// A face's bytes: static ones, as the bundled fonts', the program's, a20// file's read whole, or one mapped (the system's fallback faces), whose21// pages are read only as they are touched.22exp type FaceBytes = enum {23 Static: &[u8],24 Owned: Vector<u8>,25 Read: *[u8],26 Mapped: KeptMappedFile,27};2829exp fn view(self b: &FaceBytes) -> &[u8] {30 match (b) {31 ::Static |&s| {32 return &s;33 }34 ::Owned |&v| {35 return &v.view();36 }37 ::Read |&r| {38 return &r[..];39 }40 ::Mapped |&m| {41 return &m.view();42 }43 }44}4546// Where a face's outlines are: TrueType's `glyf` with its `loca`, or a47// `CFF ` or `CFF2` table pkg::alloy::text_fonts read and draws.48exp type GlyphTable = enum {49 TrueType: TrueTypeGlyphs,50 Cff: *Outlines,51 Nothing, // no outlines (or none read)52};5354// Outlines another package draws (text_fonts' CFF and CFF2).55exp interface Outlines {56 // the glyph's outline at the face's position on its axes57 fn draw(self: &, face: &Face, glyph: u32, out: &var Outline);58}5960// What pkg::alloy::text_fonts installs on the fonts (`install_formats`),61// kept by each face read after: CFF and CFF2 outlines, variable faces and62// color glyphs, beyond TrueType's outlines.63exp type FontFormats = struct {64 // reads what TrueType's reading leaves of the face from its tables:65 // false when it does not read66 exp read: (&var Face, &FaceTables) -> bool,67 // the face at the user values on its axes, one an axis in `fvar`'s68 // order (its default for those not given)69 exp at: (&Face, &[f32]) -> Face,70 exp named_instances: (&Face) -> Vector<NamedInstance>,71 // the glyph's advance at the face's position, from `hmtx`'s72 exp advance: (&Face, u32, f32) -> f32,73 // a variation index device table's delta there (`device_delta`)74 exp device_delta: (&Face, u64, u32) -> f32,75 // the points moved by the glyph's `gvar` deltas there76 exp vary_points: (&Face, u32, &var Vector<Moved>, &[u32]),77 // whether the face draws the glyph in color78 exp is_color: (&Face, u32) -> bool,79 // a color glyph's pixels at the size in pixels, moved right by the80 // shift, the text's color where its palette takes it81 exp color_glyph: (&Face, u32, f32, f32, &TextColor) -> Option<ColorMask>,82};8384// An axis of `fvar`, in its user values.85exp type Axis = struct {86 exp tag: u32,87 exp minimum: f32,88 exp default: f32,89 exp maximum: f32,90 exp hidden: bool,91};9293// A named instance of `fvar`: its subfamily's name and user values.94exp type NamedInstance = struct {95 exp name: u32, // in `name`96 exp values: Vector<f32>,97};9899exp type TrueTypeGlyphs = struct {100 exp glyf: u64,101 exp loca: u64,102 exp long_loca: bool,103};104105// The `cmap` subtable a face maps characters by, at its offset.106exp type CharacterMap = enum {107 Segments: u64, // format 4, the Basic Multilingual Plane108 Groups: u64, // format 12, every plane109 SameGlyphs: u64, // format 13, ranges of characters showing one glyph110};111112exp type Face = struct {113 exp bytes: FaceBytes,114 exp units_per_em: f32 = 1000.0,115 exp ascender: f32 = 0.0, // font units, up116 exp descender: f32 = 0.0, // negative117 exp line_gap: f32 = 0.0,118 exp glyph_count: u32 = 0,119 exp weight: u32 = 400, // OS/2's usWeightClass, 400 regular, 700 bold120 // synthetic bold: how much thicker its outlines and wider its advances121 // are, in font units (HarfBuzz's, after FreeType's em / 24)122 exp embolden: f32 = 0.0,123 exp underline_position: f32 = 0.0,124 exp underline_thickness: f32 = 0.0,125 exp strikeout_position: f32 = 0.0,126 exp strikeout_thickness: f32 = 0.0,127 exp metric_count: u32 = 0,128 exp cmap: CharacterMap,129 exp sequences: Option<u64> = ::None, // cmap's variation sequences, format 14130 exp glyphs: GlyphTable,131 // where its tables sit132 exp hmtx: u64,133 exp kern: Option<u64>,134 exp gsub: Option<u64>,135 exp gpos: Option<u64>,136 exp gdef: Option<u64>,137 exp gsub_sets: LookupSets = LookupSets::none(),138 exp gpos_sets: LookupSets = LookupSets::none(),139 // a variable face's axes, where on them it is (normalized, none at140 // the default) and the tables varying it141 exp axes: Vector<Axis> = Vector<Axis>::empty(),142 exp values: Vector<f32> = Vector<f32>::empty(), // in the axes' user values, none for the default143 exp coords: Vector<f32> = Vector<f32>::empty(),144 exp variations: VariationTables = VariationTables {},145 // the feature variations GSUB and GPOS make there146 exp gsub_variation: Option<u64> = ::None,147 exp gpos_variation: Option<u64> = ::None,148 // the scalars there of the regions of HVAR's, GDEF's and CFF2's149 // variation stores, none at the default150 exp hvar_scalars: Vector<f32> = Vector<f32>::empty(),151 exp gdef_scalars: Vector<f32> = Vector<f32>::empty(),152 exp cff_scalars: Vector<f32> = Vector<f32>::empty(),153 // which printable ASCII characters it has glyphs for, a bit each154 exp ascii: [u64 : 2] = [0, 0],155 exp name: u64 = 0, // its `name` table, 0 for none156 exp colors: ColorTables = ColorTables {},157 // the formats text_fonts installed when it was read158 exp formats: Option<FontFormats> = ::None,159};160161// Where a face's color glyphs' tables sit (text_fonts' color.alloy and162// bitmaps.alloy).163exp type ColorTables = struct {164 exp colr: Option<u64> = ::None,165 exp cpal: Option<u64> = ::None,166 exp cblc: Option<u64> = ::None,167 exp cbdt: Option<u64> = ::None,168 exp sbix: Option<u64> = ::None,169};170171// Whether the face has color glyphs.172exp fn any(self t: &ColorTables) -> bool => t.colr is ::Some173 || t.cbdt is ::Some174 || t.sbix is ::Some;175176// Where a variable face's tables sit.177exp type VariationTables = struct {178 exp fvar: Option<u64> = ::None,179 exp avar: Option<u64> = ::None,180 exp gvar: Option<u64> = ::None,181 exp hvar: Option<u64> = ::None,182 exp mvar: Option<u64> = ::None,183};184185// The face, or None when the data is no font this reads; a186// collection's face by index. TrueType's outlines are read here, the187// rest by the formats text_fonts installs, without which a CFF face188// has no outlines and a variable one is at its default.189exp fn Face::read(bytes: FaceBytes, index: u32, formats: Option<FontFormats>) -> Option<Face> {190 const tables = if (directory(&bytes.view(), index) is ::Some |t|) t else {191 return ::None;192 };193 const cmap = if (character_map(&bytes.view(), tables.cmap) is ::Some |c|) c else {194 return ::None;195 };196 var glyphs = GlyphTable::Nothing;197 if (tables.glyf != 0 && tables.loca != 0) {198 glyphs = GlyphTable::TrueType(TrueTypeGlyphs {199 .glyf = tables.glyf,200 .loca = tables.loca,201 .long_loca = i16_at(&bytes.view(), tables.head + 50) == 1202 });203 }204 const sequences = sequences_table(&bytes.view(), tables.cmap);205 var face = Face {206 .bytes = move bytes,207 .cmap = cmap,208 .sequences = sequences,209 .glyphs = move glyphs,210 .hmtx = tables.hmtx,211 .kern = present(tables.kern),212 .gsub = present(tables.gsub),213 .gpos = present(tables.gpos),214 .gdef = present(tables.gdef),215 .formats = formats216 };217 face.read_metrics(&tables);218 const d = &face.bytes.view();219 face.gsub_sets = LookupSets::of(&d, face.gsub, face.glyph_count, LookupTable::Substitution);220 face.gpos_sets = LookupSets::of(&d, face.gpos, face.glyph_count, LookupTable::Positioning);221 face.name = tables.name;222 for ([0x20..0x7F to u32]) |c| {223 if (face.glyph_of(c) != 0) {224 face.ascii[(c / 64) to u64] |= 1 to u64 << (c % 64) to u64;225 }226 }227 if (formats is ::Some |f| && !(f.read)(&var face, &tables)) {228 return ::None;229 }230 return ::Some(move face);231}232233// Whether the face has axes to vary along.234exp fn variable(self face: &Face) -> bool => face.axes.length() > 0;235236// The index of the face's axis of the tag, if it has one.237exp fn axis(self face: &Face, name: &[u8]) -> Option<u64> {238 const t = tag(&name);239 for (face.axes.view(), [..face.axes.length()]) |&a, k| {240 if (a.tag == t) {241 return ::Some(k);242 }243 }244 return ::None;245}246247// An instance of the face, the same until changed: reading its bytes248// and sharing its lookup sets, which must outlive it.249exp fn shared(self face: &Face) -> Face {250 const d = &face.data();251 return Face {252 .bytes = FaceBytes::Static(&d),253 .units_per_em = face.units_per_em,254 .ascender = face.ascender,255 .descender = face.descender,256 .line_gap = face.line_gap,257 .glyph_count = face.glyph_count,258 .weight = face.weight,259 .underline_position = face.underline_position,260 .underline_thickness = face.underline_thickness,261 .strikeout_position = face.strikeout_position,262 .strikeout_thickness = face.strikeout_thickness,263 .metric_count = face.metric_count,264 .cmap = face.cmap,265 .sequences = face.sequences,266 .glyphs = copy face.glyphs,267 .hmtx = face.hmtx,268 .kern = face.kern,269 .gsub = face.gsub,270 .gpos = face.gpos,271 .gdef = face.gdef,272 .gsub_sets = face.gsub_sets.shared(),273 .gpos_sets = face.gpos_sets.shared(),274 .axes = copy face.axes,275 .variations = face.variations,276 .ascii = face.ascii,277 .name = face.name,278 .colors = face.colors,279 .formats = face.formats280 };281}282283// A variation index device table's delta at the face's position, rounded284// to whole units as HarfBuzz rounds it; 0 for any other device table.285exp fn device_delta(self face: &Face, base: u64, offset: u32) -> f32 {286 if (offset == 0 || face.gdef_scalars.length() == 0) {287 return 0.0;288 }289 if (face.formats is ::Some |f|) {290 return (f.device_delta)(&face, base, offset);291 }292 return 0.0;293}294295// Where a face's tables sit, 0 for those it lacks.296exp type FaceTables = struct {297 exp head: u64 = 0,298 exp hhea: u64 = 0,299 exp maxp: u64 = 0,300 exp os2: u64 = 0,301 exp post: u64 = 0,302 exp cmap: u64 = 0,303 exp glyf: u64 = 0,304 exp loca: u64 = 0,305 exp cff: u64 = 0,306 exp cff2: u64 = 0,307 exp hmtx: u64 = 0,308 exp kern: u64 = 0,309 exp gsub: u64 = 0,310 exp gpos: u64 = 0,311 exp gdef: u64 = 0,312 exp fvar: u64 = 0,313 exp avar: u64 = 0,314 exp gvar: u64 = 0,315 exp hvar: u64 = 0,316 exp mvar: u64 = 0,317 exp name: u64 = 0,318 exp colr: u64 = 0,319 exp cpal: u64 = 0,320 exp cblc: u64 = 0,321 exp cbdt: u64 = 0,322 exp sbix: u64 = 0,323};324325fn present(offset: u64) -> Option<u64> => if (offset == 0) ::None else ::Some(offset);326327// The face's tables, None when it is no OpenType face, lacks one it328// needs, has one past its data's end or is past a collection's faces (or329// a single face's).330fn directory(d: &[u8], index: u32) -> Option<FaceTables> {331 var start: u64 = 0;332 if (u32_at(&d, 0) == tag(&"ttcf")) {333 if (index >= u32_at(&d, 8)) {334 return ::None;335 }336 start = u32_at(&d, 12 + index to u64 * 4) to u64;337 } else if (index > 0) {338 return ::None;339 }340 const version = u32_at(&d, start);341 if (version != 0x00010000 && version != tag(&"true") && version != tag(&"OTTO")) {342 return ::None;343 }344 var tables = FaceTables {};345 const count = u16_at(&d, start + 4) to u64;346 for ([..count]) |k| {347 const record = start + 12 + k * 16;348 const offset = u32_at(&d, record + 8) to u64;349 if (offset + u32_at(&d, record + 12) to u64 > d.length()) {350 return ::None;351 }352 match (tag_at(&d, record)) {353 "head" {354 tables.head = offset;355 }356 "hhea" {357 tables.hhea = offset;358 }359 "maxp" {360 tables.maxp = offset;361 }362 "OS/2" {363 tables.os2 = offset;364 }365 "post" {366 tables.post = offset;367 }368 "cmap" {369 tables.cmap = offset;370 }371 "glyf" {372 tables.glyf = offset;373 }374 "loca" {375 tables.loca = offset;376 }377 "CFF " {378 tables.cff = offset;379 }380 "CFF2" {381 tables.cff2 = offset;382 }383 "hmtx" {384 tables.hmtx = offset;385 }386 "kern" {387 tables.kern = offset;388 }389 "GSUB" {390 tables.gsub = offset;391 }392 "GPOS" {393 tables.gpos = offset;394 }395 "GDEF" {396 tables.gdef = offset;397 }398 "fvar" {399 tables.fvar = offset;400 }401 "avar" {402 tables.avar = offset;403 }404 "gvar" {405 tables.gvar = offset;406 }407 "HVAR" {408 tables.hvar = offset;409 }410 "MVAR" {411 tables.mvar = offset;412 }413 "name" {414 tables.name = offset;415 }416 "COLR" {417 tables.colr = offset;418 }419 "CPAL" {420 tables.cpal = offset;421 }422 "CBLC" {423 tables.cblc = offset;424 }425 "CBDT" {426 tables.cbdt = offset;427 }428 "sbix" {429 tables.sbix = offset;430 }431 }432 }433 // a face without outlines or metrics still shapes, as HarfBuzz's434 if (tables.head == 0 || tables.maxp == 0 || tables.cmap == 0) {435 return ::None;436 }437 return ::Some(tables);438}439440fn read_metrics(self face: &var Face, tables: &FaceTables) {441 const d = &face.bytes.view();442 const head = tables.head;443 const hhea = tables.hhea;444 face.units_per_em = u16_at(&d, head + 18) to f32;445 if (hhea != 0 && tables.hmtx != 0) {446 face.ascender = i16_at(&d, hhea + 4) to f32;447 face.descender = i16_at(&d, hhea + 6) to f32;448 face.line_gap = i16_at(&d, hhea + 8) to f32;449 face.metric_count = u16_at(&d, hhea + 34);450 }451 face.glyph_count = u16_at(&d, tables.maxp + 4);452 const os2 = tables.os2;453 if (os2 != 0) {454 face.weight = u16_at(&d, os2 + 4);455 face.strikeout_thickness = i16_at(&d, os2 + 26) to f32;456 face.strikeout_position = i16_at(&d, os2 + 28) to f32;457 if ((u16_at(&d, os2 + 62) & 0x80) != 0) {458 // USE_TYPO_METRICS459 face.ascender = i16_at(&d, os2 + 68) to f32;460 face.descender = i16_at(&d, os2 + 70) to f32;461 face.line_gap = i16_at(&d, os2 + 72) to f32;462 }463 }464 if (tables.post != 0) {465 face.underline_position = i16_at(&d, tables.post + 8) to f32;466 face.underline_thickness = i16_at(&d, tables.post + 10) to f32;467 }468 if (face.underline_thickness == 0.0) {469 face.underline_thickness = face.units_per_em / 14.0;470 face.underline_position = -face.units_per_em / 10.0;471 }472 if (face.strikeout_thickness == 0.0) {473 face.strikeout_thickness = face.underline_thickness;474 face.strikeout_position = face.units_per_em / 4.0;475 }476}477478// `cmap`'s Unicode platform, and the Windows platform with its Unicode479// encodings, of the Basic Multilingual Plane and of every plane480const PLATFORM_UNICODE: u32 = 0;481const PLATFORM_WINDOWS: u32 = 3;482const WINDOWS_BMP: u32 = 1;483const WINDOWS_FULL: u32 = 10;484// the subtable formats read, CharacterMap's485const FORMAT_SEGMENTS: u32 = 4;486const FORMAT_GROUPS: u32 = 12;487const FORMAT_SAME_GLYPHS: u32 = 13;488489// A Unicode subtable of the `cmap` table: the full repertoire's first,490// then the Basic Multilingual Plane's.491fn character_map(d: &[u8], cmap: u64) -> Option<CharacterMap> {492 var segments: Option<u64> = ::None;493 const tables = u16_at(&d, cmap + 2) to u64;494 for ([..tables]) |k| {495 const record = cmap + 4 + k * 8;496 const platform = u16_at(&d, record);497 const encoding = u16_at(&d, record + 2);498 const offset = cmap + u32_at(&d, record + 4) to u64;499 const unicode = platform == PLATFORM_UNICODE;500 match (u16_at(&d, offset)) {501 FORMAT_GROUPS {502 if (unicode || (platform == PLATFORM_WINDOWS && encoding == WINDOWS_FULL)) {503 return ::Some(CharacterMap::Groups(offset));504 }505 }506 FORMAT_SAME_GLYPHS {507 if (unicode || (platform == PLATFORM_WINDOWS && encoding == WINDOWS_FULL)) {508 return ::Some(CharacterMap::SameGlyphs(offset));509 }510 }511 FORMAT_SEGMENTS {512 if (513 (unicode || (platform == PLATFORM_WINDOWS && encoding == WINDOWS_BMP))514 && segments is ::None515 ) {516 segments = ::Some(offset);517 }518 }519 }520 }521 if (segments is ::Some |offset|) {522 return ::Some(CharacterMap::Segments(offset));523 }524 return ::None;525}526527// cmap's variation sequences subtable (format 14), if it has one.528fn sequences_table(d: &[u8], cmap: u64) -> Option<u64> {529 const tables = u16_at(&d, cmap + 2) to u64;530 for ([..tables]) |k| {531 const record = cmap + 4 + k * 8;532 const offset = cmap + u32_at(&d, record + 4) to u64;533 if (534 u16_at(&d, record) == PLATFORM_UNICODE535 && u16_at(&d, record + 2) == 5536 && u16_at(&d, offset) == 14537 ) {538 return ::Some(offset);539 }540 }541 return ::None;542}543544fn u24_at(545 d: &[u8],546 at: u64547) -> u32 => (d[at] to u32 << 16) | (d[at + 1] to u32 << 8) | d[at + 2] to u32;548549// The glyph for the character followed by the variation selector, if550// the face maps the sequence: its own, or the character's where the551// sequence takes the default glyph.552exp fn variation_glyph(self face: &Face, c: u32, selector: u32) -> Option<u32> {553 const table = if (face.sequences is ::Some |t|) t else {554 return ::None;555 };556 const d = &face.data();557 var low: u64 = 0;558 var high = u32_at(&d, table + 6) to u64;559 while (low < high) {560 const middle = (low + high) / 2;561 const record = table + 10 + middle * 11;562 const found = u24_at(&d, record);563 if (found < selector) {564 low = middle + 1;565 } else if (found > selector) {566 high = middle;567 } else {568 const defaults = u32_at(&d, record + 3) to u64;569 if (defaults != 0) {570 const ranges = u32_at(&d, table + defaults) to u64;571 var lo: u64 = 0;572 var hi = ranges;573 while (lo < hi) {574 const m = (lo + hi) / 2;575 const range = table + defaults + 4 + m * 4;576 const start = u24_at(&d, range);577 if (c < start) {578 hi = m;579 } else if (c > start + d[range + 3] to u32) {580 lo = m + 1;581 } else {582 const glyph = face.glyph_of(c);583 return if (glyph == 0) ::None else ::Some(glyph);584 }585 }586 }587 const others = u32_at(&d, record + 7) to u64;588 if (others != 0) {589 var lo: u64 = 0;590 var hi = u32_at(&d, table + others) to u64;591 while (lo < hi) {592 const m = (lo + hi) / 2;593 const mapping = table + others + 4 + m * 5;594 const unicode = u24_at(&d, mapping);595 if (unicode < c) {596 lo = m + 1;597 } else if (unicode > c) {598 hi = m;599 } else {600 return ::Some(u16_at(&d, mapping + 3));601 }602 }603 }604 return ::None;605 }606 }607 return ::None;608}609610exp fn data(self face: &Face) -> &[u8] {611 return &face.bytes.view();612}613614// Whether the face has every printable ASCII character.615exp fn covers_ascii(self face: &Face) -> bool => face.ascii[0] == 0xFFFFFFFF00000000616 && face.ascii[1] == 0x7FFFFFFFFFFFFFFF;617618// Whether the face has glyphs for every character of the text from start619// to end but those default ignorable, which shaping may leave out.620exp fn covers(self face: &Face, text: &[u8], start: u64, end: u64) -> bool {621 var at = start;622 while (at < end) {623 const b = text[at];624 if (b < 0x80) {625 if (b >= 0x20 && (face.ascii[(b / 64) to u64] & (1 to u64 << (b % 64) to u64)) == 0) {626 return false;627 }628 at += 1;629 continue;630 }631 const d = decode(&text, at);632 if (face.glyph_of(d.c) == 0 && (properties(d.c) & IGNORABLE) == 0) {633 return false;634 }635 at += d.length;636 }637 return true;638}639640// The face's PostScript name (`name` ID 6), empty when it has none.641exp fn postscript_name(self face: &Face) -> String => name_in(&face.data(), face.name);642643// The PostScript name of a font's face by its index in a collection,644// read from its `name` table alone; None past the collection's faces.645exp fn postscript_name_at(d: &[u8], index: u32) -> Option<String> {646 const tables = if (directory(&d, index) is ::Some |t|) t else {647 return ::None;648 };649 return ::Some(name_in(&d, tables.name));650}651652fn name_in(d: &[u8], name: u64) -> String {653 var out = String::empty();654 if (name == 0) {655 return move out;656 }657 const count = u16_at(&d, name + 2) to u64;658 const strings = name + u16_at(&d, name + 4) to u64;659 for ([..count]) |k| {660 const record = name + 6 + k * 12;661 if (u16_at(&d, record + 6) != 6) {662 continue;663 }664 const platform = u16_at(&d, record);665 const length = u16_at(&d, record + 8) to u64;666 const at = strings + u16_at(&d, record + 10) to u64;667 if (at + length > d.length()) {668 continue;669 }670 // Windows' UTF-16 (ASCII alone in a PostScript name), or Mac Roman671 if (platform == 3 || platform == 0) {672 for ([..length / 2]) |i| {673 out.push(d[at + i * 2 + 1]);674 }675 } else {676 out.append(&d[at..at + length]);677 }678 return move out;679 }680 return move out;681}682683// The glyph for the character, 0 (.notdef) when the face has none.684exp fn glyph_of(self face: &Face, c: u32) -> u32 {685 return match (face.cmap) {686 ::Groups |at| glyph_in_groups(&face.data(), at, c, true);687 ::SameGlyphs |at| glyph_in_groups(&face.data(), at, c, false);688 ::Segments |at| glyph_in_segments(&face.data(), at, c);689 };690}691692// The glyph of a format 12 subtable's groups (`counting`, a glyph a693// character from the group's first) or a format 13 one's (one glyph a694// group).695fn glyph_in_groups(d: &[u8], t: u64, c: u32, counting: bool) -> u32 {696 var low: u64 = 0;697 var high = u32_at(&d, t + 12) to u64;698 while (low < high) {699 const middle = (low + high) / 2;700 const group = t + 16 + middle * 12;701 const first = u32_at(&d, group);702 const last = u32_at(&d, group + 4);703 if (c < first) {704 high = middle;705 } else if (c > last) {706 low = middle + 1;707 } else {708 return u32_at(&d, group + 8) + (if (counting) c - first else 0);709 }710 }711 return 0;712}713714fn glyph_in_segments(d: &[u8], t: u64, c: u32) -> u32 {715 if (c > 0xFFFF) {716 return 0;717 }718 const segments = (u16_at(&d, t + 6) / 2) to u64;719 const ends = t + 14;720 const starts = ends + segments * 2 + 2;721 const deltas = starts + segments * 2;722 const ranges = deltas + segments * 2;723 var low: u64 = 0;724 var high = segments;725 while (low < high) {726 const middle = (low + high) / 2;727 if (u16_at(&d, ends + middle * 2) < c) {728 low = middle + 1;729 } else {730 high = middle;731 }732 }733 if (low >= segments) {734 return 0;735 }736 const start = u16_at(&d, starts + low * 2);737 if (c < start) {738 return 0;739 }740 const delta = u16_at(&d, deltas + low * 2);741 const range = u16_at(&d, ranges + low * 2) to u64;742 if (range == 0) {743 return (c + delta) & 0xFFFF;744 }745 const at = ranges + low * 2 + range + (c - start) to u64 * 2;746 const g = u16_at(&d, at);747 return if (g == 0) 0 else (g + delta) & 0xFFFF;748}749750// The glyph's horizontal advance, in font units: `hmtx`'s, moved at a751// variable face's position (text_fonts').752exp fn advance(self face: &Face, glyph: u32) -> f32 {753 var advance = face.hmtx_advance(glyph);754 if (face.coords.length() > 0 && face.metric_count > 0 && face.formats is ::Some |f|) {755 advance = (f.advance)(&face, glyph, advance);756 }757 if (face.embolden != 0.0 && advance != 0.0) {758 advance += face.embolden;759 }760 return advance;761}762763// The glyph's advance in `hmtx`, whatever the face's position.764exp fn hmtx_advance(self face: &Face, glyph: u32) -> f32 {765 if (face.metric_count == 0) {766 return (face.units_per_em to u32 / 2) to f32; // as HarfBuzz, with no hmtx767 }768 const k = if (glyph < face.metric_count) glyph else face.metric_count - 1;769 return u16_at(&face.data(), face.hmtx + k to u64 * 4) to f32;770}771772// The glyph's left side bearing in `hmtx`.773exp fn left_side_bearing(self face: &Face, glyph: u32) -> f32 {774 const d = &face.data();775 if (glyph < face.metric_count) {776 return i16_at(&d, face.hmtx + glyph to u64 * 4 + 2) to f32;777 }778 return i16_at(779 &d,780 face.hmtx + face.metric_count to u64 * 4 + (glyph - face.metric_count) to u64 * 2781 ) to f32;782}783784// How many components a composite glyph's data lists.785exp fn component_count(g: &[u8]) -> u64 {786 var p: u64 = 10;787 var count: u64 = 0;788 while (p + 4 <= g.length()) {789 const flags = u16_at(&g, p);790 count += 1;791 p += 4 + (if ((flags & 0x1) != 0) 4 else 2);792 if ((flags & 0x8) != 0) {793 p += 2;794 } else if ((flags & 0x40) != 0) {795 p += 4;796 } else if ((flags & 0x80) != 0) {797 p += 8;798 }799 if ((flags & 0x20) == 0) {800 break;801 }802 }803 return count;804}805806// The legacy `kern` table's adjustment between the two glyphs, in font807// units: the sum of its horizontal subtables' of formats 0 (pairs) and 2808// (classes), as HarfBuzz reads them; cross-stream ones left out.809exp fn kerning(self face: &Face, left: u32, right: u32) -> f32 {810 const kern = if (face.kern is ::Some |k|) k else {811 return 0.0;812 };813 const d = &face.data();814 // Microsoft's version 0, or Apple's 1 with longer headers815 const apple = u16_at(&d, kern) == 1;816 var total: f32 = 0.0;817 var at = kern + (if (apple) 8 else 4 to u64);818 const tables = if (apple) u32_at(&d, kern + 4) to u64 else u16_at(&d, kern + 2) to u64;819 for ([..tables]) {820 var length: u64 = 0;821 var format: u32 = 0;822 var usable = false;823 var replaces = false;824 if (apple) {825 length = u32_at(&d, at) to u64;826 const coverage = u16_at(&d, at + 4);827 format = coverage & 0xFF;828 usable = (coverage & 0xE000) == 0; // horizontal, along the line, not varied829 } else {830 length = u16_at(&d, at + 2) to u64;831 const coverage = u16_at(&d, at + 4);832 format = coverage >> 8;833 usable = (coverage & 0x05) == 0x01;834 replaces = (coverage & 0x08) != 0;835 }836 if (usable) {837 // the format's data after the header, in the same layout838 const header: u64 = if (apple) 8 else 6;839 const value = match (format) {840 0 pair_kerning(&d, at + header, left, right);841 2 class_kerning(&d, at, header, left, right);842 else 0.0;843 };844 total = if (replaces) value else total + value;845 }846 if (length == 0) {847 break;848 }849 at += length;850 }851 return total;852}853854// A format 0 subtable's pair, by binary search, its data at `at`.855fn pair_kerning(d: &[u8], at: u64, left: u32, right: u32) -> f32 {856 const pairs = u16_at(&d, at) to u64;857 const key = (left << 16) | right;858 var low: u64 = 0;859 var high = pairs;860 while (low < high) {861 const middle = (low + high) / 2;862 const pair = at + 8 + middle * 6;863 const found = u32_at(&d, pair);864 if (found < key) {865 low = middle + 1;866 } else if (found > key) {867 high = middle;868 } else {869 return i16_at(&d, pair + 4) to f32;870 }871 }872 return 0.0;873}874875// A format 2 subtable's value: the glyphs' classes are offsets into its876// array, from the subtable's start; its data after a header of `header`877// bytes.878fn class_kerning(d: &[u8], at: u64, header: u64, left: u32, right: u32) -> f32 {879 const l = kerning_class(&d, at + u16_at(&d, at + header + 2) to u64, left);880 const r = kerning_class(&d, at + u16_at(&d, at + header + 4) to u64, right);881 const array = u16_at(&d, at + header + 6) to u64;882 const value = at + l + r;883 if (l + r < array || value + 2 > d.length()) {884 return 0.0;885 }886 return i16_at(&d, value) to f32;887}888889fn kerning_class(d: &[u8], table: u64, glyph: u32) -> u64 {890 const first = u16_at(&d, table);891 const count = u16_at(&d, table + 2);892 if (glyph < first || glyph - first >= count) {893 return 0;894 }895 return u16_at(&d, table + 4 + (glyph - first) to u64 * 2) to u64;896}897898// The glyph's outline data in `glyf`: none for a glyph past the face's899// or without an outline.900exp fn glyph_data(self face: &Face, table: &TrueTypeGlyphs, glyph: u32) -> &[u8] {901 const d = &face.data();902 if (glyph >= face.glyph_count) {903 return &d[..0];904 }905 const start = table.glyf + location(&d, &table, glyph to u64);906 const end = min(table.glyf + location(&d, &table, glyph to u64 + 1), d.length());907 if (end <= start) {908 return &d[..0];909 }910 return &d[start..end];911}912913// Where `loca` puts the glyph's data in `glyf`.914fn location(d: &[u8], table: &TrueTypeGlyphs, glyph: u64) -> u64 {915 if (table.long_loca) {916 return u32_at(&d, table.loca + glyph * 4) to u64;917 }918 return u16_at(&d, table.loca + glyph * 2) to u64 * 2;919}