Merge #616 (TerryTel93): emoji pack from the SD card, rebased on main

Follow-ups in the merge, from the review:
- emojiRememberRecent copies the picked text first: a Recent cell points into
  s_emoji_recent, and the shift overwrote it before the copy into slot 0.
- The text menu's Emoji opens the emoji set (it passed k_emoji_items, which
  marked the sheet as special characters, so nothing was remembered).
- Without a pack the picker is the plain grid it always was: no tabs, no
  Recent, and hearts never show as a "More" tab (they sit under Smileys).
- Removed wada_shape_flag_codepoint, which nothing called.
- emoji_data.c regenerated with the merged add-emoji.py (the eight bot emoji
  from beta_102 kept); the EmojiGlyph typedef stays on one line.
- .lang rows for the tab names in all 15 languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kaj SchittecatandClaude Opus 5.5 committed 2026-11-11 11:36:20 +01:00
commit 919af1cc47
29 files changed
+2560 -154

No files matched your search

+41 -69
View File
@@ -8,18 +8,13 @@
# python3 scripts/build/add-emoji.py
#
# Source art: googlefonts/noto-emoji png/128 (OFL). RGB565+alpha, swap=0.
import os, re, sys, urllib.request
import os, re, sys
from PIL import Image
from emoji_common import PX, ROOT, fetch, fetch_flag, to_rgb565a8
PX = 16
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.abspath(os.path.join(HERE, "..", ".."))
OUTDIR = os.path.join(ROOT, "src", "ui-touch")
OUTC = os.path.join(OUTDIR, "emoji_data.c")
OUTH = os.path.join(OUTDIR, "emoji_data.h")
CACHE = os.path.join(ROOT, "data", "emoji-cache")
BASE = "https://raw.githubusercontent.com/googlefonts/noto-emoji/main/2D/png/128/emoji_u{}.png"
os.makedirs(CACHE, exist_ok=True)
# Single-codepoint emoji: (codepoint, noto-filename-stem)
SINGLE = [
@@ -54,13 +49,13 @@ SINGLE = [
(0x1F6A8, "1f6a8"), # police car light
]
# ZWJ sequences baked as ONE combined image, keyed on the lead codepoint, with the
# trailing visible symbol(s) mapped to the zero-width glyph so the whole UTF-8
# sequence renders as the single combined emoji. The bare lead cp (a plain waving
# white flag U+1F3F3) is not offered anywhere in the UI, so reusing it as the key
# is safe. (noto-emoji drops the FE0F variation selectors from png filenames.)
# trailing visible symbol(s) mapped to the zero-width glyph. Keep the full codepoint
# sequence too, so picker cells can resolve the composite image without relying on
# platform text shaping. (Noto drops FE0F selectors from png filenames.)
SEQ = [
# (key_cp, noto-stem, [extra cps -> zero])
(0x1F3F3, "1f3f3_200d_26a7", [0x26A7]), # transgender flag ðŸ³ï¸â€âš§ï¸
# (key_cp, noto-stem, [extra cps -> zero], full codepoint sequence)
(0x1F3F3, "1f3f3_200d_26a7", [0x26A7],
[0x1F3F3, 0xFE0F, 0x200D, 0x26A7, 0xFE0F]), # transgender flag
]
@@ -76,75 +71,23 @@ FLAGS = [
]
def fetch(stem):
fn = os.path.join(CACHE, "u_{}.png".format(stem))
if os.path.exists(fn) and os.path.getsize(fn) > 0:
return fn
for url in (BASE.format(stem), BASE.format(stem + "_fe0f")):
try:
req = urllib.request.Request(url, headers={"User-Agent": "emoji-gen"})
data = urllib.request.urlopen(req, timeout=20).read()
with open(fn, "wb") as f:
f.write(data)
return fn
except Exception:
continue
return None
def fetch_flag(iso):
fn = os.path.join(CACHE, "flag_{}.png".format(iso))
if os.path.exists(fn) and os.path.getsize(fn) > 0:
return fn
url = ("https://raw.githubusercontent.com/googlefonts/noto-emoji/main"
"/third_party/region-flags/png/{}.png".format(iso))
try:
req = urllib.request.Request(url, headers={"User-Agent": "emoji-gen"})
data = urllib.request.urlopen(req, timeout=20).read()
with open(fn, "wb") as f:
f.write(data)
return fn
except Exception:
return None
def to_rgb565a8(img):
# IDENTICAL to gen-emoji-font.py: autocrop transparent margin, bottom-align to
# the text baseline, emit [lo, hi, alpha] per pixel (LV_COLOR_16_SWAP=0).
PAD_BOTTOM = 0
img = img.convert("RGBA")
bbox = img.split()[3].getbbox()
if bbox:
img = img.crop(bbox)
w, h = img.size
avail_h = PX - PAD_BOTTOM
scale = min(PX / w, avail_h / h)
nw, nh = max(1, round(w * scale)), max(1, round(h * scale))
content = img.resize((nw, nh), Image.LANCZOS)
canvas = Image.new("RGBA", (PX, PX), (0, 0, 0, 0))
canvas.paste(content, ((PX - nw) // 2, PX - PAD_BOTTOM - nh))
out = bytearray()
for (r, g, b, a) in canvas.getdata():
v = ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3)
out += bytes((v & 0xFF, (v >> 8) & 0xFF, a))
return out
# ---- bake the new glyphs ----
new_defs = [] # (cp, ename, bytes)
new_entries = [] # (cp, ref)
sequence_entries = [] # (UTF-8 bytes, composite glyph key)
for cp, stem in SINGLE:
fn = fetch(stem)
if not fn:
sys.exit("FAILED to fetch U+{:X} ({})".format(cp, stem))
new_defs.append((cp, "e_{:x}".format(cp), to_rgb565a8(Image.open(fn))))
new_entries.append((cp, "d_{:x}".format(cp)))
for key_cp, stem, zeros in SEQ:
for key_cp, stem, zeros, sequence in SEQ:
fn = fetch(stem)
if not fn:
sys.exit("FAILED to fetch combined {} for U+{:X}".format(stem, key_cp))
new_defs.append((key_cp, "e_{:x}".format(key_cp), to_rgb565a8(Image.open(fn))))
new_entries.append((key_cp, "d_{:x}".format(key_cp)))
sequence_entries.append(("".join(chr(cp) for cp in sequence).encode("utf-8"), key_cp))
for z in zeros:
new_entries.append((z, "d_zero"))
@@ -161,7 +104,13 @@ src = open(OUTC).read()
TYPE_MARK = "\ntypedef struct { uint32_t cp;"
FUNC_MARK = "const lv_img_dsc_t* emojiGlyphLookup(uint32_t cp) {"
head = src[:src.index(TYPE_MARK)] # header + includes + all glyph defs
func = src[src.index(FUNC_MARK):] # the binary-search getter (verbatim)
head = re.sub(r"(?m)^#include <string.h>\n", "", head)
head = head.replace(
'#include "emoji_data.h"', '#include "emoji_data.h"\n#include <string.h>', 1
)
func_start = src.index(FUNC_MARK)
func_end = src.find("\nconst lv_img_dsc_t* emojiGlyphSequenceLookup", func_start)
func = src[func_start:func_end if func_end >= 0 else len(src)] # binary-search getter
# Idempotency: on a RE-RUN, `head` still holds the e_/d_ glyph defs spliced in by a
# PRIOR run (they live before the typedef), so blindly re-appending new_defs would
@@ -199,15 +148,38 @@ out.append("static const EmojiGlyph kGlyphs[] = {")
for cp, ref in entries:
out.append(" {{ 0x{:X}u, &{} }},".format(cp, ref))
out.append("};")
out.append(
"typedef struct { const char* utf8; const lv_img_dsc_t* dsc; } EmojiSequence;"
)
out.append("static const EmojiSequence kSequences[] = {")
for utf8, key_cp in sequence_entries:
literal = "".join("\\x{:02X}".format(b) for b in utf8)
out.append(' {{ "{}", &d_{:x} }},'.format(literal, key_cp))
out.append("};")
out.append("const uint16_t kEmojiGlyphCount = {};".format(count))
out.append("")
out.append(func.rstrip("\n"))
out.append("")
out.append("const lv_img_dsc_t* emojiGlyphSequenceLookup(const char* utf8) {")
out.append(" if (!utf8) return 0;")
out.append(" for (size_t i = 0; i < sizeof(kSequences) / sizeof(kSequences[0]); ++i)")
out.append(" if (strcmp(utf8, kSequences[i].utf8) == 0) return kSequences[i].dsc;")
out.append(" return 0;")
out.append("}")
out.append("")
open(OUTC, "w").write("\n".join(out))
# ---- header comment count ----
h = open(OUTH).read()
h = re.sub(r"// \d+ Noto colour emoji", "// {} Noto colour emoji".format(count), h, count=1)
if "emojiGlyphSequenceLookup" not in h:
h = h.replace(
"const lv_img_dsc_t* emojiGlyphLookup(uint32_t cp);",
"const lv_img_dsc_t* emojiGlyphLookup(uint32_t cp);\n"
"// Returns a baked composite image for an exact UTF-8 emoji sequence, or NULL.\n"
"const lv_img_dsc_t* emojiGlyphSequenceLookup(const char* utf8);",
1,
)
open(OUTH, "w").write(h)
print("added {} glyphs -> {} total ({} lookup rows incl zero-width)".format(
+116
View File
@@ -0,0 +1,116 @@
#!/usr/bin/env python3
# Mirror of the validation in src/ui-touch/EmojiPack.cpp parseLoaded(), so a pack
# can be cleared (or blamed) on the host instead of on the device.
#
# python3 scripts/build/check-emoji-pack.py emoji.pack
import struct, sys
BLOB, HEADER, IDX_ENTRY, ZERO = 768, 32, 12, 0xFFFFFFFF
MAX_FILE, MAX_INDEX, MAX_ITEMS, MAX_ITEM_LEN = 2 * 1024 * 1024, 8192, 4096, 32
fails = []
def check(cond, msg):
if not cond:
fails.append(msg)
return cond
def utf8_ok(b):
try:
s = b.decode("utf-8")
except UnicodeDecodeError:
return False
return all(not (0xD800 <= ord(c) <= 0xDFFF) for c in s)
def main(path):
data = open(path, "rb").read()
print("file: {} ({} bytes)".format(path, len(data)))
if not check(HEADER <= len(data) <= MAX_FILE, "size out of range"):
return
if not check(data[:4] == b"WMEP", "bad magic"):
return
ver, px, glyphs, idxn, ioff, ilen, boff, blen = struct.unpack(
"<HHIIIIII", data[4:HEADER]
)
print(
" version={} px={} glyphs={} index={} items@{}+{} blobs@{}+{}".format(
ver, px, glyphs, idxn, ioff, ilen, boff, blen
)
)
check(ver == 1, "version != 1")
check(px == 16, "px != 16")
check(0 < glyphs <= MAX_FILE // BLOB, "glyph count out of range")
check(
0 < idxn <= MAX_INDEX,
"index count out of range ({} > {})".format(idxn, MAX_INDEX),
)
check(
blen % BLOB == 0 and blen // BLOB == glyphs,
"blob length disagrees with glyph count",
)
check(HEADER + idxn * IDX_ENTRY <= len(data), "index runs past EOF")
check(HEADER <= ioff and ioff + ilen <= len(data), "items section out of bounds")
check(HEADER <= boff and boff + blen <= len(data), "blob section out of bounds")
if fails:
return
prev, zeros = -1, 0
for i in range(idxn):
cp, off = struct.unpack(
"<II", data[HEADER + i * IDX_ENTRY : HEADER + i * IDX_ENTRY + 8]
)
if not check(cp <= 0x10FFFF, "index[{}] codepoint out of range".format(i)):
return
if not check(
cp > prev, "index[{}] not strictly increasing (U+{:04X})".format(i, cp)
):
return
prev = cp
if off == ZERO:
zeros += 1
elif not check(
off % BLOB == 0 and off <= blen - BLOB,
"index[{}] blob offset {} invalid".format(i, off),
):
return
print(" index ok: {} rows, {} zero-width".format(idxn, zeros))
check(ilen >= 2, "items section too short")
n = struct.unpack("<H", data[ioff : ioff + 2])[0]
check(n <= MAX_ITEMS, "item count out of range ({} > {})".format(n, MAX_ITEMS))
if fails:
return
pos = 2
for i in range(n):
if not check(pos + 2 <= ilen, "item[{}] header past section".format(i)):
return
ln = data[ioff + pos + 1]
pos += 2
if not check(
0 < ln <= MAX_ITEM_LEN and pos + ln <= ilen,
"item[{}] length {} invalid".format(i, ln),
):
return
if not check(
utf8_ok(data[ioff + pos : ioff + pos + ln]), "item[{}] bad UTF-8".format(i)
):
return
pos += ln
print(" items ok: {}".format(n))
print(
" PSRAM needed: ~{} KB".format(
(len(data) + idxn * 4 + idxn * 12 + n * 5) // 1024
)
)
if __name__ == "__main__":
main(sys.argv[1] if len(sys.argv) > 1 else "emoji.pack")
print(
"FAILED: " + "; ".join(fails)
if fails
else "PASS - the device would accept this pack"
)
+38
View File
@@ -0,0 +1,38 @@
# Manifest for scripts/build/gen-emoji-pack.py — the optional SD-card emoji pack.
#
# For the whole upstream set, run:
# python3 scripts/build/gen-emoji-pack.py --all
# which takes every eligible single-codepoint Noto emoji and all country/region
# flag pairs from Unicode's emoji list.
#
# This manifest is for hand-picking instead:
#
# <category> <codepoints> <source>
#
# category faces gestures hearts symbols objects animals activity special food places flags extra
# Picker entries are slotted into the matching built-in group;
# "extra" lands after every other group.
# codepoints '+'-joined hex. Multiple codepoints = one picker item. Regional
# country pairs and supported UK subdivision flags use unique keys;
# other sequences use the lead codepoint. Include FE0F selectors if
# the emoji uses them, or the sequence you type won't match.
# source A noto-emoji png/128 filename stem (FE0F selectors omitted, that's
# how Noto names the files), or "flag:XX" for an ISO-3166 alpha-2
# country or a supported subdivision code such as "flag:gbeng".
#
# A codepoint already baked into the firmware is a no-op — the baked art wins —
# and the generator warns about it. 512 KB hard limit, ~768 bytes per glyph.
faces 1f978 1f978 # disguised face
gestures 1f90c 1f90c # pinched fingers
animals 1f98a 1f98a # fox
animals 1f9a5 1f9a5 # sloth
objects 1f52d 1f52d # telescope
objects 1f9ed 1f9ed # compass
objects 1f6e0+fe0f 1f6e0 # hammer and wrench
activity 1f3d5+fe0f 1f3d5 # camping
activity 1f3d4+fe0f 1f3d4 # snow-capped mountain
activity 26f7+fe0f 26f7 # skier
extra 1f6f0+fe0f 1f6f0 # satellite
flags 1f1e9+1f1ea flag:DE # Germany
flags 1f1eb+1f1f7 flag:FR # France
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env python3
# Shared Noto colour-emoji fetch + RGB565A8 conversion.
#
# Used by add-emoji.py (bakes glyphs into the firmware, src/ui-touch/emoji_data.c)
# and gen-emoji-pack.py (builds the optional SD-card pack). Both must emit
# byte-identical pixels or a pack glyph would sit at a different baseline next to
# a baked one, so the conversion lives here once.
#
# Source art: googlefonts/noto-emoji png/128 (OFL). RGB565+alpha, swap=0.
# Pinned to v2.047: `main` dropped png/128 entirely (404s), and a moving tag would
# silently re-render already-baked glyphs on the next run.
import os, urllib.request
from PIL import Image
PX = 16
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.abspath(os.path.join(HERE, "..", ".."))
CACHE = os.path.join(ROOT, "data", "emoji-cache")
BASE = "https://raw.githubusercontent.com/googlefonts/noto-emoji/v2.047/png/128/emoji_u{}.png"
FLAG = (
"https://raw.githubusercontent.com/googlefonts/noto-emoji/v2.047"
"/third_party/region-flags/png/{}.png"
)
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
def _cached(name):
os.makedirs(CACHE, exist_ok=True)
return os.path.join(CACHE, name)
def fetch(stem):
fn = _cached("u_{}.png".format(stem))
if os.path.exists(fn) and os.path.getsize(fn) > 0:
return fn
for url in (BASE.format(stem), BASE.format(stem + "_fe0f")):
try:
req = urllib.request.Request(url, headers={"User-Agent": "emoji-gen"})
data = urllib.request.urlopen(req, timeout=20).read()
with open(fn, "wb") as f:
f.write(data)
return fn
except Exception:
continue
return None
def fetch_flag(iso):
fn = _cached("flag_{}.png".format(iso))
if os.path.exists(fn) and os.path.getsize(fn) > 0:
with open(fn, "rb") as f:
if f.read(8) == PNG_SIGNATURE:
return fn
return None
try:
req = urllib.request.Request(
FLAG.format(iso), headers={"User-Agent": "emoji-gen"}
)
data = urllib.request.urlopen(req, timeout=20).read()
if not data.startswith(PNG_SIGNATURE):
return None
with open(fn, "wb") as f:
f.write(data)
return fn
except Exception:
return None
def to_rgb565a8(img):
# IDENTICAL to gen-emoji-font.py: autocrop transparent margin, bottom-align to
# the text baseline, emit [lo, hi, alpha] per pixel (LV_COLOR_16_SWAP=0).
PAD_BOTTOM = 0
img = img.convert("RGBA")
bbox = img.split()[3].getbbox()
if bbox:
img = img.crop(bbox)
w, h = img.size
avail_h = PX - PAD_BOTTOM
scale = min(PX / w, avail_h / h)
nw, nh = max(1, round(w * scale)), max(1, round(h * scale))
content = img.resize((nw, nh), Image.LANCZOS)
canvas = Image.new("RGBA", (PX, PX), (0, 0, 0, 0))
canvas.paste(content, ((PX - nw) // 2, PX - PAD_BOTTOM - nh))
out = bytearray()
for r, g, b, a in canvas.getdata():
v = ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3)
out += bytes((v & 0xFF, (v >> 8) & 0xFF, a))
return out
+468
View File
@@ -0,0 +1,468 @@
#!/usr/bin/env python3
# Build the optional SD-card emoji pack. Copy the result to /emoji/emoji.pack on
# the card; the firmware loads it at boot (src/ui-touch/EmojiPack.cpp) and merges
# its glyphs and picker entries with the baked-in set.
#
# python3 scripts/build/gen-emoji-pack.py # default manifest -> ./emoji.pack
# python3 scripts/build/gen-emoji-pack.py -m my.txt -o out.pack
# python3 scripts/build/gen-emoji-pack.py --verify out.pack # dump an existing pack
#
# Manifest lines are "<category> <codepoints> <source>", '#' starts a comment:
# faces 1f929 1f929 # single codepoint, noto png stem
# activity 1f3f3+fe0f+200d+1f308 1f3f3_200d_1f308 # ZWJ sequence, one image
# flags 1f1e9+1f1ea flag:DE # regional-indicator pair, flat flag art
#
# Art comes from the same pinned Noto source as the baked glyphs, converted by the
# same to_rgb565a8(), so pack art sits on the same baseline as the built-ins.
import argparse, concurrent.futures, json, os, re, struct, sys, urllib.request
from PIL import Image
from emoji_common import PX, ROOT, fetch, fetch_flag, to_rgb565a8
MAGIC = b"WMEP"
VERSION = 1
BLOB = PX * PX * 3
HEADER = 32
ZERO_OFF = 0xFFFFFFFF
MAX_FILE = 2 * 1024 * 1024 # must match the caps in src/ui-touch/EmojiPack.cpp
MAX_INDEX = 8192
MAX_ITEMS = 4096
MAX_ITEM_LEN = 32
RI_FIRST = 0x1F1E6
RI_LAST = 0x1F1FF
FLAG_KEY_BASE = 0xF0000
RI_FLAG_KEY_COUNT = 26 * 26
TAG_FLAG_KEY_OFFSETS = {"gbeng": 0, "gbsct": 1, "gbwls": 2}
CATS = {
"faces": 0,
"gestures": 1,
"hearts": 2,
"symbols": 3,
"objects": 4,
"animals": 5,
"activity": 6,
"special": 7,
"food": 8,
"places": 9,
"flags": 10,
"extra": 255,
}
CAT_NAMES = {v: k for k, v in CATS.items()}
DEFAULT_MANIFEST = os.path.join(ROOT, "scripts", "build", "emoji-pack.txt")
BAKED_C = os.path.join(ROOT, "src", "ui-touch", "emoji_data.c")
UITASK_CPP = os.path.join(ROOT, "src", "ui-touch", "UITask.cpp")
def die(msg):
sys.exit("gen-emoji-pack: " + msg)
def baked_codepoints():
try:
src = open(BAKED_C).read()
except OSError:
return set()
return {
int(cp, 16)
for cp, ref in re.findall(r"\{\s*(0x[0-9A-Fa-f]+)u,\s*&(\w+)\s*\}", src)
if ref != "d_zero"
}
def reserved_text_codepoints():
"""Codepoints the firmware renders as TEXT, taken from its own k_special_items.
Several of them are also emoji upstream (©, ®, ™, the arrows), and the imgfont
lookup is global: claiming U+00A9 would turn the "© OpenStreetMap" status-bar
attribution into a colour emoji mid-sentence.
"""
try:
src = open(UITASK_CPP, encoding="utf-8").read()
except OSError:
return set()
m = re.search(r"k_special_items\[\]\s*=\s*\{(.*?)\n\};", src, re.S)
if not m:
return set()
out = set()
for lit in re.findall(r'"((?:[^"\\]|\\.)*)"', m.group(1)):
raw = re.sub(r"\\x([0-9A-Fa-f]{2})", lambda h: chr(int(h.group(1), 16)), lit)
try:
out.update(ord(c) for c in raw.encode("latin-1").decode("utf-8"))
except (UnicodeDecodeError, UnicodeEncodeError):
continue
return out
def parse_manifest(path):
entries = []
with open(path, encoding="utf-8") as f:
for lineno, raw in enumerate(f, 1):
line = raw.split("#", 1)[0].strip()
if not line:
continue
parts = line.split()
if len(parts) != 3:
die(
"{}:{}: expected '<category> <codepoints> <source>'".format(
path, lineno
)
)
cat, cps, src = parts
if cat not in CATS:
die(
"{}:{}: unknown category '{}' (one of {})".format(
path, lineno, cat, ", ".join(sorted(CATS))
)
)
try:
codes = [int(c, 16) for c in cps.split("+")]
except ValueError:
die("{}:{}: codepoints must be '+'-joined hex".format(path, lineno))
if not codes or any(c > 0x10FFFF for c in codes):
die("{}:{}: codepoint out of range".format(path, lineno))
entries.append((lineno, CATS[cat], codes, src))
return entries
# ---- --all: enumerate the whole upstream set --------------------------------
NOTO_TREE = (
"https://api.github.com/repos/googlefonts/noto-emoji/git/trees/v2.047?recursive=1"
)
EMOJI_TEST = "https://unicode.org/Public/emoji/15.1/emoji-test.txt"
SKIN_TONES = {0x1F3FB, 0x1F3FC, 0x1F3FD, 0x1F3FE, 0x1F3FF}
# Unicode's own grouping, one entry per picker tab.
GROUP_TO_CAT = {
"Smileys & Emotion": "faces",
"People & Body": "gestures",
"Animals & Nature": "animals",
"Food & Drink": "food",
"Travel & Places": "places",
"Activities": "activity",
"Objects": "objects",
"Symbols": "symbols",
"Flags": "flags",
}
# Subgroup overrides where Unicode's own placement misleads a picker user:
# 🏂/🏄/🏋 are filed under People & Body, not Activities.
SUBGROUP_TO_CAT = {"heart": "hearts", "person-sport": "activity"}
def http_text(url):
req = urllib.request.Request(url, headers={"User-Agent": "emoji-gen"})
return urllib.request.urlopen(req, timeout=30).read().decode("utf-8")
def unicode_categories():
"""{codepoint-tuple (FE0F stripped): category} from Unicode's emoji-test.txt."""
cats, group, sub = {}, None, None
for line in http_text(EMOJI_TEST).splitlines():
if line.startswith("# group:"):
group = line.split(":", 1)[1].strip()
continue
if line.startswith("# subgroup:"):
sub = line.split(":", 1)[1].strip()
continue
if not line or line.startswith("#") or ";" not in line:
continue
try:
key = tuple(
int(c, 16)
for c in line.split(";", 1)[0].split()
if int(c, 16) != 0xFE0F
)
except ValueError:
continue
cat = SUBGROUP_TO_CAT.get(sub) or GROUP_TO_CAT.get(group)
if cat and key not in cats:
cats[key] = cat
return cats
def tag_flag_code(codes):
if len(codes) < 4 or codes[0] != 0x1F3F4 or codes[-1] != 0xE007F:
return None
tags = codes[1:-1]
if any(c < 0xE0061 or c > 0xE007A for c in tags):
return None
return "".join(chr(c - 0xE0000) for c in tags)
def flag_sequence_key(codes):
if len(codes) == 2 and all(RI_FIRST <= c <= RI_LAST for c in codes):
return FLAG_KEY_BASE + (codes[0] - RI_FIRST) * 26 + codes[1] - RI_FIRST
tag = tag_flag_code(codes)
if tag in TAG_FLAG_KEY_OFFSETS:
return FLAG_KEY_BASE + RI_FLAG_KEY_COUNT + TAG_FLAG_KEY_OFFSETS[tag]
return None
def flag_sequence_source(codes):
if len(codes) == 2 and all(RI_FIRST <= c <= RI_LAST for c in codes):
return "".join(chr(c - RI_FIRST + ord("A")) for c in codes)
return None
def enumerate_all():
tree = json.loads(http_text(NOTO_TREE))
if tree.get("truncated"):
die("upstream tree listing was truncated; cannot enumerate reliably")
stems = sorted(
{
e["path"].split("/")[-1][len("emoji_u") : -len(".png")]
for e in tree["tree"]
if e["path"].startswith("png/128/emoji_u") and e["path"].endswith(".png")
}
)
cats = unicode_categories()
baked = baked_codepoints()
text = reserved_text_codepoints()
entries = []
skipped_skin = skipped_baked = skipped_uncat = skipped_seq = skipped_text = 0
for stem in stems:
try:
codes = [int(c, 16) for c in stem.split("_")]
except ValueError:
continue
if any(c in SKIN_TONES for c in codes):
skipped_skin += 1
continue
bare = [c for c in codes if c != 0xFE0F]
# Glyphs are keyed on their LEAD codepoint, and essentially every ZWJ
# sequence leads with a codepoint that is also a standalone emoji
# (1F468 is "man" and the lead of dozens of profession sequences), so
# including them would hijack the plain emoji. Singles only.
if len(bare) > 1:
skipped_seq += 1
continue
if codes[0] in text:
skipped_text += 1
continue
cat = cats.get(tuple(bare))
if not cat: # Component group, or art with no Unicode entry
skipped_uncat += 1
continue
# Already in the firmware: the baked art wins at lookup time, so shipping
# it again would only cost 768 bytes and a pointless warning.
if codes[0] in baked:
skipped_baked += 1
continue
entries.append((0, CATS[cat], codes, stem))
for codes, cat in cats.items():
source = flag_sequence_source(codes)
if cat != "flags" or flag_sequence_key(codes) is None or not source:
continue
entries.append((0, CATS[cat], list(codes), "flag:" + source))
print(
"upstream {} images -> {} entries (skipped {} skin-tone, {} sequences, "
"{} baked, {} text symbols, {} uncategorised)".format(
len(stems),
len(entries),
skipped_skin,
skipped_seq,
skipped_baked,
skipped_text,
skipped_uncat,
),
file=sys.stderr,
)
return entries
def prefetch(entries, workers=12):
"""Warm the art cache in parallel; the build loop then hits disk only."""
todo = [src for _, _, _, src in entries]
done = [0]
def one(src):
r = fetch_flag(src[5:]) if src.startswith("flag:") else fetch(src)
done[0] += 1
if done[0] % 200 == 0:
print(" fetched {}/{}".format(done[0], len(todo)), file=sys.stderr)
return r
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as ex:
results = list(ex.map(one, todo))
available = []
for entry, path in zip(entries, results):
if path:
available.append(entry)
elif entry[3].startswith("flag:"):
print(
" skipped unavailable flag art {}".format(entry[3][5:]),
file=sys.stderr,
)
else:
die("could not fetch art '{}'".format(entry[3]))
return available
def build(manifest, entries=None, quiet_dupes=False):
if entries is None:
entries = parse_manifest(manifest)
if not entries:
die("nothing to build")
baked = baked_codepoints()
blobs, index, items = [], {}, []
for lineno, cat, codes, src in entries:
png = fetch_flag(src[5:]) if src.startswith("flag:") else fetch(src)
if not png:
die("{}:{}: could not fetch art '{}'".format(manifest, lineno, src))
data = to_rgb565a8(Image.open(png))
if len(data) != BLOB:
die(
"{}:{}: converted to {} bytes, expected {}".format(
manifest, lineno, len(data), BLOB
)
)
lead = codes[0]
key = flag_sequence_key(codes)
if key is None:
key = lead
if key in index:
# Two entries keyed on the same lead codepoint would silently render
# as whichever sorted first.
die(
"{}:{}: key U+{:04X} is already used by another entry".format(
manifest, lineno, key
)
)
index[key] = (len(blobs) * BLOB, cat)
blobs.append(data)
if lead in baked and not quiet_dupes:
print(
"warning: {}:{}: U+{:04X} is already baked into the firmware; "
"the baked art wins on-device".format(manifest, lineno, lead),
file=sys.stderr,
)
for c in codes[1:]:
if flag_sequence_key(codes) is not None:
continue
prev = index.get(c)
if prev and prev[0] != ZERO_OFF:
die(
"{}:{}: U+{:04X} is a trailing codepoint here but the key of "
"another entry".format(manifest, lineno, c)
)
index[c] = (ZERO_OFF, cat)
utf8 = "".join(chr(c) for c in codes).encode("utf-8")
if len(utf8) > MAX_ITEM_LEN:
die(
"{}:{}: picker entry is {} UTF-8 bytes, max {}".format(
manifest, lineno, len(utf8), MAX_ITEM_LEN
)
)
items.append((cat, utf8))
idx = sorted(index.items())
if len(idx) > MAX_INDEX:
die("{} index entries, max {}".format(len(idx), MAX_INDEX))
if len(items) > MAX_ITEMS:
die("{} picker items, max {}".format(len(items), MAX_ITEMS))
index_b = b"".join(
struct.pack("<IIBBH", cp, off, cat, 0, 0) for cp, (off, cat) in idx
)
items_b = struct.pack("<H", len(items)) + b"".join(
struct.pack("<BB", cat, len(u)) + u for cat, u in items
)
blob_b = b"".join(bytes(b) for b in blobs)
items_off = HEADER + len(index_b)
blob_off = items_off + len(items_b)
header = MAGIC + struct.pack(
"<HHIIIIII",
VERSION,
PX,
len(blobs),
len(idx),
items_off,
len(items_b),
blob_off,
len(blob_b),
)
assert len(header) == HEADER
pack = header + index_b + items_b + blob_b
if len(pack) > MAX_FILE:
die(
"pack is {} bytes, over the {} byte device limit — drop some entries".format(
len(pack), MAX_FILE
)
)
return pack, len(blobs), len(idx), len(items)
def verify(path):
data = open(path, "rb").read()
if len(data) < HEADER or data[:4] != MAGIC:
die("{}: not an emoji pack".format(path))
ver, px, glyphs, idxn, ioff, ilen, boff, blen = struct.unpack(
"<HHIIIIII", data[4:HEADER]
)
print("{}: {} bytes".format(path, len(data)))
print(" version={} px={} glyphs={} index={}".format(ver, px, glyphs, idxn))
print(" items off={} len={}".format(ioff, ilen))
print(" blobs off={} len={}".format(boff, blen))
n = struct.unpack("<H", data[ioff : ioff + 2])[0]
pos = ioff + 2
per_cat, sample = {}, {}
for _ in range(n):
cat, ln = data[pos], data[pos + 1]
pos += 2
per_cat[cat] = per_cat.get(cat, 0) + 1
sample.setdefault(cat, []).append(data[pos : pos + ln].decode("utf-8"))
pos += ln
for cat in sorted(per_cat):
print(
" {:<9} {:4d} {}".format(
CAT_NAMES.get(cat, cat), per_cat[cat], " ".join(sample[cat][:12])
)
)
def main():
ap = argparse.ArgumentParser(description="Build the SD-card emoji pack.")
ap.add_argument("-m", "--manifest", default=DEFAULT_MANIFEST)
ap.add_argument("-o", "--out", default=os.path.join(ROOT, "emoji.pack"))
ap.add_argument(
"--all",
action="store_true",
help="take eligible upstream single-codepoint emoji and all country/region flags",
)
ap.add_argument(
"--verify", metavar="PACK", help="dump an existing pack instead of building"
)
args = ap.parse_args()
if args.verify:
verify(args.verify)
return
entries = None
if args.all:
entries = enumerate_all()
print("fetching art (cached in data/emoji-cache)...", file=sys.stderr)
entries = prefetch(entries)
pack, glyphs, idxn, items = build(args.manifest, entries, quiet_dupes=args.all)
with open(args.out, "wb") as f:
f.write(pack)
print(
"wrote {} — {} glyphs, {} index rows, {} picker items, {} bytes".format(
args.out, glyphs, idxn, items, len(pack)
)
)
print("copy it to /emoji/emoji.pack on the SD card")
if __name__ == "__main__":
main()