///| Colour emoji from a CBDT/CBLC font (Noto Color Emoji): the picture for an emoji sequence. /// /// stb_truetype (which draws Chandra's text) only knows outlines, and Noto Color Emoji has none: /// each emoji is a PNG in the font's CBDT table, found through its CBLC index. Sequences (skin /// tones, families, flags, keycaps) become one glyph through the font's GSUB ligatures; the font /// has no glyph for U+FE0F, so it is left out before looking up. Checked against HarfBuzz on every /// emoji of Emoji 18.0 with Noto Color Emoji 2.047 and 2.051: the same glyph for each one the /// font has. /// /// This runs where the font file is (the native compositor, or the wasm host); the picker only /// gets the pictures. ///| Chandra's own copy of Noto Color Emoji (the bitmap edition, fetched by /// scripts/fetch-emoji-font.sh), relative to the working directory: the checkout, or /// /usr/local/share/chandra once installed. CHANDRA_EMOJI_FONT names another CBDT font. /// /// Not the system's: distributions ship different editions, and Fedora's (and Google Fonts') /// Noto Color Emoji is COLRv1, vector paint graphs this reader doesn't draw. pub let font_path : String = "assets/fonts/NotoColorEmoji.ttf" ///| What to tell someone whose emoji font is missing or unreadable. pub fn missing_font_message(env_path : String) -> String { if env_path.length() > 0 { "CHANDRA_EMOJI_FONT=" + env_path + " can't be read as a bitmap (CBDT) colour emoji font. " + "Unset it to use Chandra's own Noto Color Emoji." } else { "Chandra's emoji font is missing: " + font_path + " (Noto Color Emoji, bitmap edition). " + "Run `just install` (or `just emoji-font` in a checkout), then press Super+. again." } } ///| A table of the font: offset and length. priv struct Table { off : Int len : Int } ///| One bitmap index range of the CBLC strike. priv struct IndexRange { first : Int last : Int /// Offset of its index subtable in the file. sub : Int } ///| A parsed colour emoji font. pub struct EmojiFont { data : Bytes /// cmap format 12 groups: (first code point, last, first glyph). priv groups : Array[(Int, Int, Int)] /// GSUB ligature lookups, in lookup order: first glyph -> (rest of the glyphs, ligature glyph), /// in the font's order of preference. priv ligatures : Array[Map[Int, Array[(Array[Int], Int)]]] priv ranges : Array[IndexRange] priv cbdt : Int /// The strike's pixels per em. ppem : Int } ///| Why a font can't be used. pub(all) suberror EmojiFontError { EmojiFontError(String) } derive(Show) ///| fn u8(b : Bytes, o : Int) -> Int raise EmojiFontError { if o < 0 || o >= b.length() { raise EmojiFontError("read past the end of the font at " + o.to_string()) } b[o].to_int() } ///| fn u16(b : Bytes, o : Int) -> Int raise EmojiFontError { (u8(b, o) << 8) | u8(b, o + 1) } ///| fn u32(b : Bytes, o : Int) -> Int raise EmojiFontError { (u16(b, o) << 16) | u16(b, o + 2) } ///| fn tag_at(b : Bytes, o : Int) -> String raise EmojiFontError { let sb = StringBuilder::new() for i = 0; i < 4; i = i + 1 { sb.write_char(Int::unsafe_to_char(u8(b, o + i))) } sb.to_string() } ///| Glyphs a coverage table lists, in coverage index order. fn coverage(b : Bytes, o : Int) -> Array[Int] raise EmojiFontError { let out : Array[Int] = [] match u16(b, o) { 1 => { let n = u16(b, o + 2) for i = 0; i < n; i = i + 1 { out.push(u16(b, o + 4 + i * 2)) } } 2 => { let n = u16(b, o + 2) for i = 0; i < n; i = i + 1 { let r = o + 4 + i * 6 for g = u16(b, r); g <= u16(b, r + 2); g = g + 1 { out.push(g) } } } f => raise EmojiFontError("GSUB coverage format " + f.to_string() + " is unknown") } out } ///| A ligature substitution subtable (GSUB lookup type 4) into `into`. fn read_ligatures(b : Bytes, o : Int, into : Map[Int, Array[(Array[Int], Int)]]) -> Unit raise EmojiFontError { if u16(b, o) != 1 { raise EmojiFontError("GSUB ligature subtable format " + u16(b, o).to_string() + " is unknown") } let firsts = coverage(b, o + u16(b, o + 2)) let nsets = u16(b, o + 4) for s = 0; s < nsets && s < firsts.length(); s = s + 1 { let set = o + u16(b, o + 6 + s * 2) let nlig = u16(b, set) let list = match into.get(firsts[s]) { Some(l) => l None => { let l = [] into.set(firsts[s], l) l } } for l = 0; l < nlig; l = l + 1 { let lo = set + u16(b, set + 2 + l * 2) let glyph = u16(b, lo) let ncomp = u16(b, lo + 2) let rest : Array[Int] = [] for c = 1; c < ncomp; c = c + 1 { rest.push(u16(b, lo + 4 + (c - 1) * 2)) } list.push((rest, glyph)) } } } ///| Parse the font in `data`. pub fn EmojiFont::parse(data : Bytes) -> EmojiFont raise EmojiFontError { let b = data let tables : Map[String, Table] = {} let ntables = u16(b, 4) for i = 0; i < ntables; i = i + 1 { let r = 12 + i * 16 tables.set(tag_at(b, r), { off: u32(b, r + 8), len: u32(b, r + 12) }) } fn need(name : String) -> Table raise EmojiFontError { match tables.get(name) { Some(t) => t None => raise EmojiFontError("the font has no " + name + " table (not a bitmap (CBDT) colour emoji font)") } } // cmap: the format 12 subtable (all of Unicode). let cmap = need("cmap").off let mut f12 = -1 for i = 0; i < u16(b, cmap + 2); i = i + 1 { let r = cmap + 4 + i * 8 let sub = cmap + u32(b, r + 4) if u16(b, sub) == 12 { f12 = sub } } if f12 < 0 { raise EmojiFontError("the font's cmap has no format 12 subtable (emoji past U+FFFF)") } let groups : Array[(Int, Int, Int)] = [] for i = 0; i < u32(b, f12 + 12); i = i + 1 { let g = f12 + 16 + i * 12 groups.push((u32(b, g), u32(b, g + 4), u32(b, g + 8))) } // GSUB: every ligature lookup (type 4, or type 7 extensions of it), in order. let ligatures : Array[Map[Int, Array[(Array[Int], Int)]]] = [] match tables.get("GSUB") { Some(t) => { let lookups = t.off + u16(b, t.off + 8) for i = 0; i < u16(b, lookups); i = i + 1 { let lk = lookups + u16(b, lookups + 2 + i * 2) let kind = u16(b, lk) let nsub = u16(b, lk + 4) let m : Map[Int, Array[(Array[Int], Int)]] = {} for s = 0; s < nsub; s = s + 1 { let st = lk + u16(b, lk + 6 + s * 2) if kind == 4 { read_ligatures(b, st, m) } else if kind == 7 && u16(b, st + 2) == 4 { read_ligatures(b, st + u32(b, st + 4), m) } } if m.size() > 0 { ligatures.push(m) } } } None => () } // CBLC: the biggest strike's index ranges. let cblc = need("CBLC").off let cbdt = need("CBDT").off let nsizes = u32(b, cblc + 4) if nsizes == 0 { raise EmojiFontError("the font's CBLC table has no bitmap sizes") } let mut best = cblc + 8 for i = 1; i < nsizes; i = i + 1 { let s = cblc + 8 + i * 48 if u8(b, s + 45) > u8(b, best + 45) { best = s } } let arr = cblc + u32(b, best) let ranges : Array[IndexRange] = [] for i = 0; i < u32(b, best + 8); i = i + 1 { let r = arr + i * 8 ranges.push({ first: u16(b, r), last: u16(b, r + 2), sub: arr + u32(b, r + 4) }) } { data, groups, ligatures, ranges, cbdt, ppem: u8(b, best + 45) } } ///| The glyph for code point `cp`, 0 when the font has none. fn EmojiFont::glyph(self : EmojiFont, cp : Int) -> Int { let mut lo = 0 let mut hi = self.groups.length() - 1 while lo <= hi { let mid = (lo + hi) / 2 let (a, z, g) = self.groups[mid] if cp < a { hi = mid - 1 } else if cp > z { lo = mid + 1 } else { return g + (cp - a) } } 0 } ///| The glyphs `text` shapes to: its code points' glyphs (U+FE0F left out) with the ligatures /// applied. Empty when the font lacks one of its code points. pub fn EmojiFont::shape(self : EmojiFont, text : String) -> Array[Int] { let mut gs : Array[Int] = [] for c in text { if c.to_int() == 0xFE0F { continue } let g = self.glyph(c.to_int()) if g == 0 { return [] } gs.push(g) } for lk in self.ligatures { let out : Array[Int] = [] let mut i = 0 while i < gs.length() { let mut used = 1 let mut put = gs[i] match lk.get(gs[i]) { Some(ligs) => for l in ligs { let (rest, glyph) = l if i + 1 + rest.length() <= gs.length() { let mut ok = true for k, r in rest { if gs[i + 1 + k] != r { ok = false break } } if ok { used = 1 + rest.length() put = glyph break } } } None => () } out.push(put) i = i + used } gs = out } gs } ///| The PNG the font has for glyph `g`, None when it has no bitmap for it. fn EmojiFont::glyph_png(self : EmojiFont, g : Int) -> Bytes? raise EmojiFontError { let b = self.data for r in self.ranges { if g < r.first || g > r.last { continue } let sub = r.sub let index_format = u16(b, sub) let image_format = u16(b, sub + 2) let data_off = self.cbdt + u32(b, sub + 4) let i = g - r.first let (at, len) : (Int, Int) = match index_format { 1 => { let a = u32(b, sub + 8 + i * 4) (data_off + a, u32(b, sub + 8 + (i + 1) * 4) - a) } 2 => { let size = u32(b, sub + 8) (data_off + i * size, size) } 3 => { let a = u16(b, sub + 8 + i * 2) (data_off + a, u16(b, sub + 8 + (i + 1) * 2) - a) } 4 => { let n = u32(b, sub + 8) let mut found = (-1, 0) for k = 0; k < n; k = k + 1 { let e = sub + 12 + k * 4 if u16(b, e) == g { let a = u16(b, e + 2) found = (data_off + a, u16(b, e + 6) - a) break } } found } 5 => { let size = u32(b, sub + 8) let n = u32(b, sub + 20) let mut found = (-1, 0) for k = 0; k < n; k = k + 1 { if u16(b, sub + 24 + k * 2) == g { found = (data_off + k * size, size) break } } found } f => raise EmojiFontError("CBLC index format " + f.to_string() + " is unknown") } if at < 0 || len <= 0 { return None } let png_at = match image_format { 17 => at + 9 // small metrics (5) + data length (4) 18 => at + 12 // big metrics (8) + data length (4) 19 => at + 4 f => raise EmojiFontError("CBDT image format " + f.to_string() + " is not PNG") } let png_len = u32(b, png_at - 4) if png_at + png_len > b.length() { raise EmojiFontError("a CBDT image runs past the end of the font") } return Some(b[png_at:png_at + png_len].to_bytes()) } None } ///| Whether the font has one picture for all of `text`. pub fn EmojiFont::has(self : EmojiFont, text : String) -> Bool raise EmojiFontError { let gs = self.shape(text) gs.length() == 1 && self.glyph_png(gs[0]) is Some(_) } ///| The picture for `text`, `px` x `px` (the bitmap scaled to fit and centred), straight RGBA. /// None when the font has no single picture for it. pub fn EmojiFont::picture(self : EmojiFont, text : String, px : Int) -> @renderer.Pixmap? raise EmojiFontError { let gs = self.shape(text) if gs.length() != 1 || px <= 0 { return None } match self.glyph_png(gs[0]) { None => None Some(png) => match @renderer.decode_png(png) { None => raise EmojiFontError("the font's picture for " + text + " is not a PNG Chandra can read") Some(p) => Some(fit_square(p, px)) } } } ///| `p` scaled (area average, alpha weighted) to fit a `px` x `px` square, centred. pub fn fit_square(p : @renderer.Pixmap, px : Int) -> @renderer.Pixmap { let out = @renderer.Pixmap::new(px, px) let side = if p.width > p.height { p.width } else { p.height } let dw = (p.width * px + side / 2) / side let dh = (p.height * px + side / 2) / side let ox = (px - dw) / 2 let oy = (px - dh) / 2 for y = 0; y < dh; y = y + 1 { let sy0 = y * p.height / dh let sy1 = ((y + 1) * p.height / dh).max(sy0 + 1) for x = 0; x < dw; x = x + 1 { let sx0 = x * p.width / dw let sx1 = ((x + 1) * p.width / dw).max(sx0 + 1) let mut r = 0 let mut g = 0 let mut bl = 0 let mut a = 0 let mut n = 0 for sy = sy0; sy < sy1; sy = sy + 1 { for sx = sx0; sx < sx1; sx = sx + 1 { let o = (sy * p.width + sx) * 4 let al = p.data[o + 3].to_int() r = r + p.data[o].to_int() * al g = g + p.data[o + 1].to_int() * al bl = bl + p.data[o + 2].to_int() * al a = a + al n = n + 1 } } let o = ((oy + y) * px + ox + x) * 4 if a > 0 { out.data[o] = (r / a).to_byte() out.data[o + 1] = (g / a).to_byte() out.data[o + 2] = (bl / a).to_byte() out.data[o + 3] = (a / n).to_byte() } } } out } ///| The colour emoji font as the renderer uses it: opened on first use, pictures made once per /// emoji and size. The native compositor's renderer and the wasm host each keep one. pub struct EmojiSource { priv mut state : Result[(String, EmojiFont), String]? priv images : Map[String, UInt] } ///| pub fn EmojiSource::new() -> EmojiSource { { state: None, images: {} } } ///| Open the font: CHANDRA_EMOJI_FONT when set, else the first of `font_paths` that parses. /// The path, or what to tell the user. Logged once. pub fn EmojiSource::font(self : EmojiSource) -> Result[String, String] { let st = match self.state { Some(s) => s None => { let env = @sys.getenv("CHANDRA_EMOJI_FONT") let p = if env.length() > 0 { env } else { font_path } let data = @sys.read_file_bytes(p) let found : Result[(String, EmojiFont), String] = if data.length() == 0 { Err(missing_font_message(env)) } else { match (try Ok(EmojiFont::parse(data)) catch { e => Err(e) }) { Ok(f) => Ok((p, f)) Err(EmojiFontError(why)) => Err(p + ": " + why + ". " + missing_font_message(env)) } } match found { Ok((p, f)) => @sys.log("emoji: " + p + " (" + f.ppem.to_string() + " px pictures)") Err(m) => @sys.log("emoji: " + m) } self.state = Some(found) found } } match st { Ok((p, _)) => Ok(p) Err(m) => Err(m) } } ///| For each of `texts`, whether the font has one picture for it (all false without a font). pub fn EmojiSource::has(self : EmojiSource, texts : Array[String]) -> Array[Bool] { ignore(self.font()) match self.state { Some(Ok((_, f))) => texts.map(t => try f.has(t) catch { EmojiFontError(why) => { // A damaged font: say so for each emoji it can't index. @sys.log("emoji: can't look up " + t + " in the font: " + why) false } }) _ => texts.map(_ => false) } } ///| The picture for `text` at `px`, registered with `put` (the renderer's image store): its /// handle, 0 when the font has none. A picture that can't be decoded is logged and gives 0. pub fn EmojiSource::image(self : EmojiSource, text : String, px : Int, put : (@renderer.Pixmap) -> UInt) -> UInt { let key = px.to_string() + " " + text match self.images.get(key) { Some(h) => return h None => () } ignore(self.font()) let h = match self.state { Some(Ok((_, f))) => match (try Ok(f.picture(text, px)) catch { e => Err(e) }) { Ok(Some(p)) => put(p) Ok(None) => 0U Err(EmojiFontError(why)) => { @sys.log("emoji: no picture for " + text + ": " + why) 0U } } _ => 0U } self.images.set(key, h) h }