diff --git a/.gitignore b/.gitignore index 83f46fec..a41fd0a5 100644 --- a/.gitignore +++ b/.gitignore @@ -30,6 +30,10 @@ platformio.local.ini /data/ scripts/build/wifi_secrets.h +# Built SD-card emoji pack (gen-emoji-pack.py output) — an asset, rebuild it +/emoji.pack +scripts/build/__pycache__/ + # Local working notes + agent config (contain ops/infra details — never publish) CLAUDE.md .claude/ diff --git a/deploy/apps/lang/bg.lang b/deploy/apps/lang/bg.lang index cb4d75ed..5527ed43 100644 --- a/deploy/apps/lang/bg.lang +++ b/deploy/apps/lang/bg.lang @@ -2418,3 +2418,14 @@ Unread only Само непрочетени No unread chats Няма непрочетени чатове No unread channels Няма непрочетени канали No unread direct chats Няма непрочетени лични чатове +Recent Скорошни +Smileys Емотикони +People Хора +Nature Природа +Food Храна +Activity Занимания +Travel Пътуване +Objects Предмети +Symbols Символи +Flags Знамена +Chars Знаци diff --git a/deploy/apps/lang/cs.lang b/deploy/apps/lang/cs.lang index 33449652..0a11d676 100644 --- a/deploy/apps/lang/cs.lang +++ b/deploy/apps/lang/cs.lang @@ -2434,3 +2434,14 @@ Unread only Jen nepřečtené No unread chats Žádné nepřečtené chaty No unread channels Žádné nepřečtené kanály No unread direct chats Žádné nepřečtené přímé chaty +Recent Nedávné +Smileys Smajlíci +People Lidé +Nature Příroda +Food Jídlo +Activity Aktivity +Travel Cestování +Objects Objekty +Symbols Symboly +Flags Vlajky +Chars Znaky diff --git a/deploy/apps/lang/de.lang b/deploy/apps/lang/de.lang index 6692a477..f359d34c 100644 --- a/deploy/apps/lang/de.lang +++ b/deploy/apps/lang/de.lang @@ -2418,3 +2418,14 @@ Unread only Nur ungelesene No unread chats Keine ungelesenen Chats No unread channels Keine ungelesenen Kanäle No unread direct chats Keine ungelesenen Direktchats +Recent Zuletzt +Smileys Smileys +People Personen +Nature Natur +Food Essen +Activity Aktivität +Travel Reisen +Objects Objekte +Symbols Symbole +Flags Flaggen +Chars Zeichen diff --git a/deploy/apps/lang/el.lang b/deploy/apps/lang/el.lang index 0cf4587b..10c26b7c 100644 --- a/deploy/apps/lang/el.lang +++ b/deploy/apps/lang/el.lang @@ -2418,3 +2418,14 @@ Unread only Μόνο αδιάβαστα No unread chats Δεν υπάρχουν αδιάβαστες συνομιλίες No unread channels Δεν υπάρχουν αδιάβαστα κανάλια No unread direct chats Δεν υπάρχουν αδιάβαστες άμεσες συνομιλίες +Recent Πρόσφατα +Smileys Φατσούλες +People Άνθρωποι +Nature Φύση +Food Φαγητό +Activity Δραστηριότητες +Travel Ταξίδια +Objects Αντικείμενα +Symbols Σύμβολα +Flags Σημαίες +Chars Χαρακτήρες diff --git a/deploy/apps/lang/es.lang b/deploy/apps/lang/es.lang index f247f0b9..374eaedb 100644 --- a/deploy/apps/lang/es.lang +++ b/deploy/apps/lang/es.lang @@ -2418,3 +2418,14 @@ Unread only Solo sin leer No unread chats No hay chats sin leer No unread channels No hay canales sin leer No unread direct chats No hay chats directos sin leer +Recent Recientes +Smileys Caritas +People Personas +Nature Naturaleza +Food Comida +Activity Actividad +Travel Viajes +Objects Objetos +Symbols Símbolos +Flags Banderas +Chars Signos diff --git a/deploy/apps/lang/fr.lang b/deploy/apps/lang/fr.lang index 4aa7e910..27de18f5 100644 --- a/deploy/apps/lang/fr.lang +++ b/deploy/apps/lang/fr.lang @@ -2417,3 +2417,14 @@ Unread only Non lus seulement No unread chats Aucun chat non lu No unread channels Aucun canal non lu No unread direct chats Aucune discussion directe non lue +Recent Récents +Smileys Smileys +People Personnes +Nature Nature +Food Nourriture +Activity Activités +Travel Voyages +Objects Objets +Symbols Symboles +Flags Drapeaux +Chars Signes diff --git a/deploy/apps/lang/hu.lang b/deploy/apps/lang/hu.lang index 0ce44894..0c29343a 100644 --- a/deploy/apps/lang/hu.lang +++ b/deploy/apps/lang/hu.lang @@ -2428,3 +2428,14 @@ Unread only Csak olvasatlan No unread chats Nincs olvasatlan csevegés No unread channels Nincs olvasatlan csatorna No unread direct chats Nincs olvasatlan közvetlen csevegés +Recent Legutóbbi +Smileys Arcok +People Emberek +Nature Természet +Food Étel +Activity Tevékenység +Travel Utazás +Objects Tárgyak +Symbols Szimbólumok +Flags Zászlók +Chars Jelek diff --git a/deploy/apps/lang/it.lang b/deploy/apps/lang/it.lang index dfb58d44..fe289aca 100644 --- a/deploy/apps/lang/it.lang +++ b/deploy/apps/lang/it.lang @@ -2417,3 +2417,14 @@ Unread only Solo non letti No unread chats Nessuna chat non letta No unread channels Nessun canale non letto No unread direct chats Nessuna chat diretta non letta +Recent Recenti +Smileys Faccine +People Persone +Nature Natura +Food Cibo +Activity Attività +Travel Viaggi +Objects Oggetti +Symbols Simboli +Flags Bandiere +Chars Segni diff --git a/deploy/apps/lang/nl.lang b/deploy/apps/lang/nl.lang index bdbe00cd..fa85767c 100644 --- a/deploy/apps/lang/nl.lang +++ b/deploy/apps/lang/nl.lang @@ -2416,3 +2416,14 @@ Unread only Alleen ongelezen No unread chats Geen ongelezen chats No unread channels Geen ongelezen kanalen No unread direct chats Geen ongelezen directe chats +Recent Recent +Smileys Smileys +People Mensen +Nature Natuur +Food Eten +Activity Activiteit +Travel Reizen +Objects Objecten +Symbols Symbolen +Flags Vlaggen +Chars Tekens diff --git a/deploy/apps/lang/pl.lang b/deploy/apps/lang/pl.lang index a66d9d44..437c388e 100644 --- a/deploy/apps/lang/pl.lang +++ b/deploy/apps/lang/pl.lang @@ -2431,3 +2431,14 @@ Unread only Tylko nieprzeczytane No unread chats Brak nieprzeczytanych czatów No unread channels Brak nieprzeczytanych kanałów No unread direct chats Brak nieprzeczytanych czatów bezpośrednich +Recent Ostatnie +Smileys Buźki +People Ludzie +Nature Natura +Food Jedzenie +Activity Aktywność +Travel Podróże +Objects Obiekty +Symbols Symbole +Flags Flagi +Chars Znaki diff --git a/deploy/apps/lang/pt-br.lang b/deploy/apps/lang/pt-br.lang index a0149ec2..8675802e 100644 --- a/deploy/apps/lang/pt-br.lang +++ b/deploy/apps/lang/pt-br.lang @@ -2418,3 +2418,14 @@ Unread only Só não lidas No unread chats Nenhuma conversa não lida No unread channels Nenhum canal não lido No unread direct chats Nenhuma conversa direta não lida +Recent Recentes +Smileys Carinhas +People Pessoas +Nature Natureza +Food Comida +Activity Atividades +Travel Viagens +Objects Objetos +Symbols Símbolos +Flags Bandeiras +Chars Sinais diff --git a/deploy/apps/lang/ro.lang b/deploy/apps/lang/ro.lang index 5b5f3749..99858362 100644 --- a/deploy/apps/lang/ro.lang +++ b/deploy/apps/lang/ro.lang @@ -2419,3 +2419,14 @@ Unread only Doar necitite No unread chats Nicio conversație necitită No unread channels Niciun canal necitit No unread direct chats Nicio conversație directă necitită +Recent Recente +Smileys Fețe +People Oameni +Nature Natură +Food Mâncare +Activity Activități +Travel Călătorii +Objects Obiecte +Symbols Simboluri +Flags Steaguri +Chars Semne diff --git a/deploy/apps/lang/ru.lang b/deploy/apps/lang/ru.lang index f2a37d6f..2352cc53 100644 --- a/deploy/apps/lang/ru.lang +++ b/deploy/apps/lang/ru.lang @@ -2418,3 +2418,14 @@ Unread only Только непрочитанные No unread chats Нет непрочитанных чатов No unread channels Нет непрочитанных каналов No unread direct chats Нет непрочитанных личных чатов +Recent Недавние +Smileys Смайлы +People Люди +Nature Природа +Food Еда +Activity Занятия +Travel Путешествия +Objects Предметы +Symbols Символы +Flags Флаги +Chars Знаки diff --git a/deploy/apps/lang/sr.lang b/deploy/apps/lang/sr.lang index 51212251..25d4156b 100644 --- a/deploy/apps/lang/sr.lang +++ b/deploy/apps/lang/sr.lang @@ -2418,3 +2418,14 @@ Unread only Само непрочитано No unread chats Нема непрочитаних ћаскања No unread channels Нема непрочитаних канала No unread direct chats Нема непрочитаних директних ћаскања +Recent Недавно +Smileys Смајлији +People Људи +Nature Природа +Food Храна +Activity Активности +Travel Путовања +Objects Предмети +Symbols Симболи +Flags Заставе +Chars Знакови diff --git a/deploy/apps/lang/uk.lang b/deploy/apps/lang/uk.lang index 4bb90020..5cf26df9 100644 --- a/deploy/apps/lang/uk.lang +++ b/deploy/apps/lang/uk.lang @@ -2418,3 +2418,14 @@ Unread only Лише непрочитані No unread chats Немає непрочитаних чатів No unread channels Немає непрочитаних каналів No unread direct chats Немає непрочитаних особистих чатів +Recent Недавні +Smileys Смайли +People Люди +Nature Природа +Food Їжа +Activity Заняття +Travel Подорожі +Objects Предмети +Symbols Символи +Flags Прапори +Chars Знаки diff --git a/scripts/build/add-emoji.py b/scripts/build/add-emoji.py index 766dee9d..1321c579 100644 --- a/scripts/build/add-emoji.py +++ b/scripts/build/add-emoji.py @@ -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 \n", "", head) +head = head.replace( + '#include "emoji_data.h"', '#include "emoji_data.h"\n#include ', 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( diff --git a/scripts/build/check-emoji-pack.py b/scripts/build/check-emoji-pack.py new file mode 100644 index 00000000..80e32245 --- /dev/null +++ b/scripts/build/check-emoji-pack.py @@ -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( + " {})".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( + " 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(" {})".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" + ) diff --git a/scripts/build/emoji-pack.txt b/scripts/build/emoji-pack.txt new file mode 100644 index 00000000..032c1a7d --- /dev/null +++ b/scripts/build/emoji-pack.txt @@ -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 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 diff --git a/scripts/build/emoji_common.py b/scripts/build/emoji_common.py new file mode 100644 index 00000000..84a61c99 --- /dev/null +++ b/scripts/build/emoji_common.py @@ -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 diff --git a/scripts/build/gen-emoji-pack.py b/scripts/build/gen-emoji-pack.py new file mode 100644 index 00000000..23ecb018 --- /dev/null +++ b/scripts/build/gen-emoji-pack.py @@ -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 " ", '#' 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 ' '".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(" 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( + " +#include +#if defined(ESP32) +#include +#endif + +// On-disk layout (little-endian throughout): +// +// header 32 B : magic "WMEP", u16 version, u16 px, u32 glyph_count, +// u32 index_count, u32 items_off, u32 items_len, +// u32 blob_off, u32 blob_len +// index : index_count x 12 B, SORTED by cp and strictly increasing — +// u32 cp, u32 blob_rel_off (0xFFFFFFFF = zero-width), u8 cat, +// u8 flags, u16 reserved +// items : u16 count, then per item u8 cat, u8 utf8_len, utf8 bytes +// blobs : glyph_count x 768 B RGB565+alpha, same byte order as the +// baked glyphs in emoji_data.c ([lo, hi, alpha], swap=0) +// +// Regional-indicator flag pairs use reserved private-use lookup keys so pairs +// sharing a lead indicator can still resolve to different images. + +namespace +{ + + constexpr uint32_t kMagic = 0x50454D57u; // 'W','M','E','P' + constexpr uint16_t kVersion = 1; + constexpr uint16_t kPx = 16; + constexpr uint32_t kBlobBytes = (uint32_t)kPx * kPx * 3; + constexpr uint32_t kHeaderSize = 32; + constexpr uint32_t kIndexEntry = 12; + constexpr uint32_t kZeroOff = 0xFFFFFFFFu; + constexpr uint32_t kFlagKeyBase = 0xF0000u; + constexpr uint32_t kRegionalFlagKeyCount = 26u * 26u; + constexpr uint32_t kTagFlagKeyCount = 3u; + constexpr uint32_t kFlagKeyCount = kRegionalFlagKeyCount + kTagFlagKeyCount; + constexpr uint32_t kRegionalIndicatorFirst = 0x1F1E6u; + constexpr uint32_t kRegionalIndicatorLast = 0x1F1FFu; + // A skin-tone-free full Noto set is ~1.24 MB of blobs; the rest is headroom. + constexpr uint32_t kMaxFile = 2u * 1024u * 1024u; + constexpr uint32_t kMaxIndex = 8192; + constexpr uint32_t kMaxItems = 4096; + constexpr uint32_t kMaxItemLen = 32; + constexpr uint32_t kMaxGlyphs = kMaxFile / kBlobBytes; + + uint8_t *s_file = nullptr; // whole pack; every dsc points into it + uint32_t *s_cp = nullptr; // sorted codepoints, one per index entry + lv_img_dsc_t *s_dsc = nullptr; // parallel descriptors + char *s_strbuf = nullptr; // picker strings, re-copied NUL-terminated + const char **s_items = nullptr; + uint8_t *s_cats = nullptr; + + // Published last, with release ordering: a reader that sees a non-zero count is + // guaranteed to see the fully built tables above it. + std::atomic s_count{0}; + std::atomic s_items_n{0}; + + File s_in; // held open across pumps + uint32_t s_want = 0; + uint32_t s_got = 0; + + // 2x2 transparent, matching emoji_data.c's d_zero. + const uint8_t s_zero_px[12] = {0}; + + void *psAlloc(size_t n) + { + if (!n) + return nullptr; +#if defined(ESP32) + if (void *p = heap_caps_malloc(n, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)) + return p; +#endif + return malloc(n); + } + + void freeAll() + { + free(s_file); + s_file = nullptr; + free(s_cp); + s_cp = nullptr; + free(s_dsc); + s_dsc = nullptr; + free(s_strbuf); + s_strbuf = nullptr; + free(s_items); + s_items = nullptr; + free(s_cats); + s_cats = nullptr; + s_count.store(0, std::memory_order_release); + s_items_n.store(0, std::memory_order_release); + } + + inline uint32_t rd32(const uint8_t *p) + { + return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); + } + inline uint16_t rd16(const uint8_t *p) { return (uint16_t)((uint16_t)p[0] | ((uint16_t)p[1] << 8)); } + + // Picker strings reach lv_label and _lv_txt_encoded_next, which walk multi-byte + // sequences without bounds checks — reject anything malformed before it lands. + bool utf8Valid(const uint8_t *p, uint32_t n) + { + for (uint32_t i = 0; i < n;) + { + const uint8_t c = p[i]; + uint32_t extra, cp; + if (c < 0x80) + { + extra = 0; + cp = c; + } + else if (c < 0xC2) + return false; // continuation byte or overlong 2-byte lead + else if (c < 0xE0) + { + extra = 1; + cp = c & 0x1F; + } + else if (c < 0xF0) + { + extra = 2; + cp = c & 0x0F; + } + else if (c < 0xF5) + { + extra = 3; + cp = c & 0x07; + } + else + return false; + if (i + extra + 1 > n) + return false; + for (uint32_t k = 1; k <= extra; ++k) + { + if ((p[i + k] & 0xC0) != 0x80) + return false; + cp = (cp << 6) | (uint32_t)(p[i + k] & 0x3F); + } + if (cp > 0x10FFFF) + return false; + if (cp >= 0xD800 && cp <= 0xDFFF) + return false; + if (extra == 2 && cp < 0x800) + return false; // overlong + if (extra == 3 && cp < 0x10000) + return false; + i += extra + 1; + } + return true; + } + +} // namespace + +// Validates the buffered file and builds the lookup tables. Nothing is published +// until both are complete, so a partial or hostile pack leaves no trace. +namespace +{ + bool parseLoaded(size_t size) + { + const uint8_t *h = s_file; + if (rd32(h) != kMagic || rd16(h + 4) != kVersion || rd16(h + 6) != kPx) + { + freeAll(); + return false; + } + const uint32_t glyphs = rd32(h + 8); + const uint32_t idxn = rd32(h + 12); + const uint32_t ioff = rd32(h + 16); + const uint32_t ilen = rd32(h + 20); + const uint32_t boff = rd32(h + 24); + const uint32_t blen = rd32(h + 28); + + if (glyphs == 0 || glyphs > kMaxGlyphs) + { + freeAll(); + return false; + } + if (idxn == 0 || idxn > kMaxIndex) + { + freeAll(); + return false; + } + // Division rather than glyphs * kBlobBytes so a hostile glyph_count can't wrap. + if (blen % kBlobBytes || blen / kBlobBytes != glyphs) + { + freeAll(); + return false; + } + if (kHeaderSize + (uint64_t)idxn * kIndexEntry > size) + { + freeAll(); + return false; + } + if (ioff < kHeaderSize || (uint64_t)ioff + ilen > size) + { + freeAll(); + return false; + } + if (boff < kHeaderSize || (uint64_t)boff + blen > size) + { + freeAll(); + return false; + } + + s_cp = (uint32_t *)psAlloc((size_t)idxn * sizeof(uint32_t)); + s_dsc = (lv_img_dsc_t *)psAlloc((size_t)idxn * sizeof(lv_img_dsc_t)); + if (!s_cp || !s_dsc) + { + freeAll(); + return false; + } + + const uint8_t *ip = s_file + kHeaderSize; + for (uint32_t i = 0; i < idxn; ++i, ip += kIndexEntry) + { + const uint32_t cp = rd32(ip); + const uint32_t off = rd32(ip + 4); + if (cp > 0x10FFFF) + { + freeAll(); + return false; + } + if (i && cp <= s_cp[i - 1]) + { + freeAll(); + return false; + } // the lookup binary-searches this + s_cp[i] = cp; + + lv_img_dsc_t &d = s_dsc[i]; + memset(&d, 0, sizeof d); + d.header.cf = LV_IMG_CF_TRUE_COLOR_ALPHA; + if (off == kZeroOff) + { + d.header.w = 2; + d.header.h = 2; + d.data_size = sizeof s_zero_px; + d.data = s_zero_px; + } + else + { + if (off % kBlobBytes || off > blen - kBlobBytes) + { + freeAll(); + return false; + } + d.header.w = kPx; + d.header.h = kPx; + d.data_size = kBlobBytes; + d.data = s_file + boff + off; + } + } + + if (ilen < 2) + { + freeAll(); + return false; + } + const uint8_t *it = s_file + ioff; + const uint32_t n = rd16(it); + if (n > kMaxItems) + { + freeAll(); + return false; + } + + uint32_t pos = 2, bytes = 0; + for (uint32_t i = 0; i < n; ++i) + { + if (pos + 2 > ilen) + { + freeAll(); + return false; + } + const uint32_t len = it[pos + 1]; + pos += 2; + if (len == 0 || len > kMaxItemLen || pos + len > ilen) + { + freeAll(); + return false; + } + if (!utf8Valid(it + pos, len)) + { + freeAll(); + return false; + } + pos += len; + bytes += len + 1; + } + + if (n) + { + s_strbuf = (char *)psAlloc(bytes); + s_items = (const char **)psAlloc((size_t)n * sizeof(char *)); + s_cats = (uint8_t *)psAlloc(n); + if (!s_strbuf || !s_items || !s_cats) + { + freeAll(); + return false; + } + char *w = s_strbuf; + pos = 2; + for (uint32_t i = 0; i < n; ++i) + { + const uint8_t cat = it[pos]; + const uint32_t len = it[pos + 1]; + pos += 2; + memcpy(w, it + pos, len); + w[len] = '\0'; + s_items[i] = w; + s_cats[i] = cat; + w += len + 1; + pos += len; + } + } + s_items_n.store(n, std::memory_order_release); + s_count.store(idxn, std::memory_order_release); + + return true; + } +} // namespace + +bool emojiPackBegin(File f) +{ + freeAll(); + s_want = s_got = 0; + if (!f) + return false; + const size_t size = f.size(); + if (size < kHeaderSize || size > kMaxFile) + { + f.close(); + return false; + } + s_file = (uint8_t *)psAlloc(size); + if (!s_file) + { + f.close(); + return false; + } + s_in = f; + s_want = (uint32_t)size; + return true; +} + +bool emojiPackPump(size_t budget) +{ + if (!s_want) + return true; + size_t left = s_want - s_got; + if (budget > left) + budget = left; + while (budget) + { + const int n = s_in.read(s_file + s_got, budget); + if (n <= 0) + { // short read: the card went away mid-load + s_in.close(); + s_want = 0; + freeAll(); + return true; + } + s_got += (uint32_t)n; + budget -= (size_t)n; + } + if (s_got < s_want) + return false; + s_in.close(); + parseLoaded(s_got); + s_want = 0; + return true; +} + +bool emojiPackLoading() { return s_want != 0; } +bool emojiPackLoaded() { return s_count.load(std::memory_order_acquire) != 0; } + +static const lv_img_dsc_t *emojiPackLookupKey(uint32_t cp) +{ + const uint32_t n = s_count.load(std::memory_order_acquire); + if (!n) + return nullptr; + int lo = 0, hi = (int)n - 1; + while (lo <= hi) + { + const int mid = (lo + hi) >> 1; + const uint32_t v = s_cp[mid]; + if (cp == v) + return &s_dsc[mid]; + if (cp < v) + hi = mid - 1; + else + lo = mid + 1; + } + return nullptr; +} + +const lv_img_dsc_t *emojiPackLookup(uint32_t cp) +{ + if (cp >= kFlagKeyBase && cp < kFlagKeyBase + kFlagKeyCount) + return nullptr; + return emojiPackLookupKey(cp); +} + +uint32_t emojiPackFlagToken(uint32_t lead, uint32_t trail) +{ + if (lead < kRegionalIndicatorFirst || lead > kRegionalIndicatorLast || + trail < kRegionalIndicatorFirst || trail > kRegionalIndicatorLast) + return 0; + return kFlagKeyBase + (lead - kRegionalIndicatorFirst) * 26u + + (trail - kRegionalIndicatorFirst); +} + +uint32_t emojiPackTagFlagToken(const char *tag) +{ + if (!tag) + return 0; + if (strcmp(tag, "gbeng") == 0) + return kFlagKeyBase + kRegionalFlagKeyCount; + if (strcmp(tag, "gbsct") == 0) + return kFlagKeyBase + kRegionalFlagKeyCount + 1u; + if (strcmp(tag, "gbwls") == 0) + return kFlagKeyBase + kRegionalFlagKeyCount + 2u; + return 0; +} + +const lv_img_dsc_t *emojiPackSequenceLookup(uint32_t token) +{ + if (token < kFlagKeyBase || token >= kFlagKeyBase + kFlagKeyCount) + return nullptr; + return emojiPackLookupKey(token); +} + +const lv_img_dsc_t *emojiPackSequenceItemLookup(const char *utf8) +{ + if (!utf8 || !strstr(utf8, "\xE2\x80\x8D")) + return nullptr; + const uint32_t n = s_items_n.load(std::memory_order_acquire); + for (uint32_t i = 0; i < n; ++i) + { + if (strcmp(utf8, s_items[i]) != 0) + continue; + const uint8_t lead = (uint8_t)utf8[0]; + uint32_t cp; + if (lead < 0x80) + cp = lead; + else if (lead < 0xE0) + cp = ((uint32_t)(lead & 0x1F) << 6) | ((uint8_t)utf8[1] & 0x3F); + else if (lead < 0xF0) + cp = ((uint32_t)(lead & 0x0F) << 12) | (((uint8_t)utf8[1] & 0x3F) << 6) | + ((uint8_t)utf8[2] & 0x3F); + else + cp = ((uint32_t)(lead & 0x07) << 18) | (((uint8_t)utf8[1] & 0x3F) << 12) | + (((uint8_t)utf8[2] & 0x3F) << 6) | ((uint8_t)utf8[3] & 0x3F); + return emojiPackLookupKey(cp); + } + return nullptr; +} + +const lv_img_dsc_t *emojiPackFlagLookup(uint32_t lead, uint32_t trail) +{ + return emojiPackSequenceLookup(emojiPackFlagToken(lead, trail)); +} + +int emojiPackItemCount() { return (int)s_items_n.load(std::memory_order_acquire); } +const char *emojiPackItem(int i) +{ + const uint32_t n = s_items_n.load(std::memory_order_acquire); + return (i >= 0 && (uint32_t)i < n) ? s_items[i] : nullptr; +} +uint8_t emojiPackItemCat(int i) +{ + const uint32_t n = s_items_n.load(std::memory_order_acquire); + return (i >= 0 && (uint32_t)i < n) ? s_cats[i] : EMOJI_CAT_EXTRA; +} +#endif diff --git a/src/ui-touch/EmojiPack.h b/src/ui-touch/EmojiPack.h new file mode 100644 index 00000000..0573e068 --- /dev/null +++ b/src/ui-touch/EmojiPack.h @@ -0,0 +1,54 @@ +#pragma once +#include +#include "lvgl.h" + +// Optional SD-card emoji pack: extra colour glyphs plus the picker entries that +// expose them, read from /emoji/emoji.pack on the card root. Built by +// scripts/build/gen-emoji-pack.py. The pack is untrusted input, so the loader +// validates every offset before use and falls back to the baked-in set (see +// emoji_data.h) whenever the card, the file, or its contents are unusable. +// +// A full pack is over a megabyte and the card runs at 4 MHz, so the read is +// pumped from the UI loop in budgeted slices rather than blocking boot. The +// table is published in one step at the end, so a reader on the other core sees +// either no pack at all or a complete one. + +// Picker category of a pack item. The values are part of the on-disk format. +// 0-7 are the groups k_emoji_items has always had; 8+ exist only in packs. +// HEARTS stays because the built-in list groups them separately, but the picker +// files them under Smileys, where Unicode puts them. +enum : uint8_t +{ + EMOJI_CAT_FACES = 0, + EMOJI_CAT_GESTURES = 1, + EMOJI_CAT_HEARTS = 2, + EMOJI_CAT_SYMBOLS = 3, + EMOJI_CAT_OBJECTS = 4, + EMOJI_CAT_ANIMALS = 5, + EMOJI_CAT_ACTIVITY = 6, + EMOJI_CAT_SPECIAL = 7, + EMOJI_CAT_FOOD = 8, + EMOJI_CAT_PLACES = 9, + EMOJI_CAT_FLAGS = 10, + EMOJI_CAT_EXTRA = 255, // no home category — appended after every other group +}; + +// Takes over `f`. False means there is nothing to load and no pump is needed. +bool emojiPackBegin(File f); +// Reads up to `budget` bytes. True once the load has finished, either way. +bool emojiPackPump(size_t budget); +bool emojiPackLoading(); +bool emojiPackLoaded(); + +// Baked image for `cp`, or NULL when the pack has no glyph for it. Callers +// consult emojiGlyphLookup() first so an SD pack can never shadow shipped art. +const lv_img_dsc_t *emojiPackLookup(uint32_t cp); +const lv_img_dsc_t *emojiPackFlagLookup(uint32_t lead, uint32_t trail); +uint32_t emojiPackFlagToken(uint32_t lead, uint32_t trail); +uint32_t emojiPackTagFlagToken(const char *tag); +const lv_img_dsc_t *emojiPackSequenceLookup(uint32_t token); +const lv_img_dsc_t *emojiPackSequenceItemLookup(const char *utf8); + +int emojiPackItemCount(); +const char *emojiPackItem(int i); // NUL-terminated UTF-8, may be a multi-codepoint sequence +uint8_t emojiPackItemCat(int i); diff --git a/src/ui-touch/UITask.cpp b/src/ui-touch/UITask.cpp index 85068b73..455b719c 100644 --- a/src/ui-touch/UITask.cpp +++ b/src/ui-touch/UITask.cpp @@ -235,6 +235,15 @@ static_assert(ChannelSenderSplit::kMaxWireName >= (size_t)UITask::MAX_SENDER_NAM #include "i18n.h" #include "emoji_data.h" // baked Noto colour-emoji glyphs (emojiGlyphLookup) #include "AvatarText.h" // initials and the name's emoji for avatars (pure, host-tested) + #if CAP_EMOJI_PACK + #include "EmojiPack.h" // optional SD-card pack that extends the baked set + #else + enum : uint8_t { + EMOJI_CAT_FACES = 0, EMOJI_CAT_GESTURES = 1, EMOJI_CAT_HEARTS = 2, + EMOJI_CAT_SYMBOLS = 3, EMOJI_CAT_OBJECTS = 4, EMOJI_CAT_ANIMALS = 5, + EMOJI_CAT_ACTIVITY = 6, EMOJI_CAT_SPECIAL = 7, EMOJI_CAT_FLAGS = 10, + }; + #endif #include "qr_icon.h" // baked recolour-able QR glyph (qr_icon_dsc) for the Chats Share button #if defined(WADA_WEB) #include // web/platform: the canvas behind the SDL window @@ -1290,7 +1299,6 @@ static void uiFitLabelWidth(lv_obj_t* lbl, lv_coord_t max_w) { } lv_obj_set_style_text_font(lbl, &g_font_12, LV_PART_MAIN); // still wide: 12 px beats clipping a bigger font } - // ---- Button captions that fit any language (#418) --------------------------------- // A translation that fits most panels can still overflow a button on the narrowest // (the Heltec V4 with its kit) or at a large UI size, and asking translators to @@ -1471,13 +1479,92 @@ static void uiFitButtonChangeCb(lv_event_t* e) { } uiFitButtonQueue(btn); } + +// Baked set first, SD pack second — a card can extend the emoji we ship but never +// shadow them, so pack art can't silently change a glyph the UI already relies on. +static inline const lv_img_dsc_t* emojiLookupAny(uint32_t cp) { + if (const lv_img_dsc_t* d = emojiGlyphLookup(cp)) return d; +#if CAP_EMOJI_PACK + return emojiPackLookup(cp); +#else + return nullptr; +#endif +} +static bool emojiIsZeroAdvanceCodepoint(uint32_t cp) { + if (cp == 0x200Du || cp == 0x20E3u || + (cp >= 0xFE00u && cp <= 0xFE0Fu) || + (cp >= 0x1F3FBu && cp <= 0x1F3FFu) || + (cp >= 0xE0020u && cp <= 0xE007Fu)) return true; + const lv_img_dsc_t* d = emojiLookupAny(cp); + return d && d->header.w <= 2 && d->header.h <= 2; +} +static bool emojiIsRegionalIndicator(uint32_t cp) { + return cp >= 0x1F1E6 && cp <= 0x1F1FF; +} +static const lv_img_dsc_t* emojiPickerCompositeGlyph(const char* item) { + if (!item) return nullptr; + if (const lv_img_dsc_t* sequence = emojiGlyphSequenceLookup(item)) return sequence; +#if CAP_EMOJI_PACK + if (const lv_img_dsc_t* sequence = emojiPackSequenceItemLookup(item)) return sequence; +#endif + uint32_t off = 0; + const uint32_t lead = _lv_txt_encoded_next(item, &off); + if (emojiIsRegionalIndicator(lead)) { + const uint32_t trail = _lv_txt_encoded_next(item, &off); + if (!emojiIsRegionalIndicator(trail)) return nullptr; + #if CAP_EMOJI_PACK + if (const lv_img_dsc_t* d = emojiPackFlagLookup(lead, trail)) return d; + #endif + if (lead == 0x1F1F1 && trail == 0x1F1F8) return emojiGlyphLookup(lead); + return nullptr; + } +#if CAP_EMOJI_PACK + if (lead == 0x1F3F4) { + char tag[8] = {}; + size_t n = 0; + for (;;) { + const uint32_t cp = _lv_txt_encoded_next(item, &off); + if (cp == 0xE007F) break; + if (cp < 0xE0061 || cp > 0xE007A || n + 1 >= sizeof(tag)) return nullptr; + tag[n++] = static_cast(cp - 0xE0000); + } + const uint32_t token = emojiPackTagFlagToken(tag); + if (const lv_img_dsc_t* d = emojiPackSequenceLookup(token)) return d; + return emojiPackFlagLookup(0x1F1EC, 0x1F1E7); + } +#endif + return nullptr; +} #if LV_USE_IMGFONT +static bool emojiZeroAdvanceFontGetDsc(const lv_font_t* font, lv_font_glyph_dsc_t* dsc, + uint32_t unicode, uint32_t /*unicode_next*/) { + if (!emojiIsZeroAdvanceCodepoint(unicode)) return false; + memset(dsc, 0, sizeof(*dsc)); + dsc->resolved_font = font; + return true; +} + +static const uint8_t* emojiZeroAdvanceFontGetBitmap(const lv_font_t* /*font*/, uint32_t /*unicode*/) { + static const uint8_t blank = 0; + return ␣ +} + +static lv_font_t s_emoji_zero_advance_font[3] = {}; + // lv_imgfont path callback: hand back the baked colour image for an emoji // codepoint (copied into the imgfont's scratch buffer as an lv_img_dsc_t), or // false so LVGL keeps walking the fallback chain for everything else. static bool emojiImgfontPathCb(const lv_font_t* /*font*/, void* img_src, uint16_t /*len*/, uint32_t unicode, uint32_t /*unicode_next*/) { - const lv_img_dsc_t* d = emojiGlyphLookup(unicode); + if (emojiIsZeroAdvanceCodepoint(unicode)) return false; +#if CAP_EMOJI_PACK + const lv_img_dsc_t* d = emojiPackSequenceLookup(unicode); + if (!d && unicode == emojiPackFlagToken(0x1F1F1u, 0x1F1F8u)) + d = emojiGlyphLookup(0x1F1F1u); + if (!d) d = emojiLookupAny(unicode); +#else + const lv_img_dsc_t* d = emojiLookupAny(unicode); +#endif // Skin-tone modifiers (U+1F3FB-1F3FF) have no baked image: draw them as the // invisible zero glyph (the same one U+FE0F maps to), so 👍🏽 shows as 👍 (#673). if (!d && unicode >= 0x1F3FB && unicode <= 0x1F3FF) d = emojiGlyphLookup(0xFE0F); @@ -1761,8 +1848,13 @@ static void initTouchFontFallbacks() { } #endif for (int i = 0; i < 3; ++i) { + s_emoji_zero_advance_font[i].get_glyph_dsc = emojiZeroAdvanceFontGetDsc; + s_emoji_zero_advance_font[i].get_glyph_bitmap = emojiZeroAdvanceFontGetBitmap; + s_emoji_zero_advance_font[i].line_height = extras[i]->line_height; + s_emoji_zero_advance_font[i].base_line = extras[i]->base_line; + s_emoji_zero_advance_font[i].fallback = extras[i]; s_emoji_font[i] = lv_imgfont_create(16, emojiImgfontPathCb); // 16 px baked glyphs (~15% larger; sit on the text baseline) - if (s_emoji_font[i]) { s_emoji_font[i]->fallback = extras[i]; prim[i]->fallback = s_emoji_font[i]; } + if (s_emoji_font[i]) { s_emoji_font[i]->fallback = &s_emoji_zero_advance_font[i]; prim[i]->fallback = s_emoji_font[i]; } else { prim[i]->fallback = extras[i]; } // OOM: plain chain } #else @@ -4417,11 +4509,206 @@ static bool uiFontDrawsGlyph(uint32_t cp, void* font) { return lv_font_get_glyph_dsc((const lv_font_t*)font, &dsc, cp, 0) && !dsc.is_placeholder; } +static bool uiReadUtf8Codepoint(const char*& p, const char* end, uint32_t& cp) { + if (p >= end) return false; + const unsigned char c0 = static_cast(*p); + if (c0 < 0x80u) { cp = c0; ++p; return true; } + if ((c0 & 0xE0u) == 0xC0u && end - p >= 2) { + const unsigned char c1 = static_cast(p[1]); + if ((c1 & 0xC0u) == 0x80u) { + cp = (static_cast(c0 & 0x1Fu) << 6) | (c1 & 0x3Fu); + if (cp >= 0x80u) { p += 2; return true; } + } + } else if ((c0 & 0xF0u) == 0xE0u && end - p >= 3) { + const unsigned char c1 = static_cast(p[1]); + const unsigned char c2 = static_cast(p[2]); + if ((c1 & 0xC0u) == 0x80u && (c2 & 0xC0u) == 0x80u) { + cp = (static_cast(c0 & 0x0Fu) << 12) | + (static_cast(c1 & 0x3Fu) << 6) | (c2 & 0x3Fu); + if (cp >= 0x800u && !(cp >= 0xD800u && cp <= 0xDFFFu)) { p += 3; return true; } + } + } else if ((c0 & 0xF8u) == 0xF0u && end - p >= 4) { + const unsigned char c1 = static_cast(p[1]); + const unsigned char c2 = static_cast(p[2]); + const unsigned char c3 = static_cast(p[3]); + if ((c1 & 0xC0u) == 0x80u && (c2 & 0xC0u) == 0x80u && (c3 & 0xC0u) == 0x80u) { + cp = (static_cast(c0 & 0x07u) << 18) | + (static_cast(c1 & 0x3Fu) << 12) | + (static_cast(c2 & 0x3Fu) << 6) | (c3 & 0x3Fu); + if (cp >= 0x10000u && cp <= 0x10FFFFu) { p += 4; return true; } + } + } + return false; +} + +static bool uiIsGraphemeExtend(uint32_t cp) { + return (cp >= 0x0300u && cp <= 0x036Fu) || + (cp >= 0x1AB0u && cp <= 0x1AFFu) || + (cp >= 0x1DC0u && cp <= 0x1DFFu) || + (cp >= 0x20D0u && cp <= 0x20FFu) || + (cp >= 0xFE00u && cp <= 0xFE0Fu) || + (cp >= 0xFE20u && cp <= 0xFE2Fu) || + (cp >= 0x1F3FBu && cp <= 0x1F3FFu) || + (cp >= 0xE0020u && cp <= 0xE007Fu) || + (cp >= 0xE0100u && cp <= 0xE01EFu); +} + +static size_t uiPreviousGraphemeStartByte(const char* text, size_t end_byte) { + if (!text || end_byte == 0) return end_byte; + const char* p = text; + const char* end = text + end_byte; + size_t cluster_start = 0; + uint32_t previous = 0; + uint32_t regional_run = 0; + bool have_previous = false; + while (p < end) { + const char* current_start = p; + uint32_t cp = 0; + if (!uiReadUtf8Codepoint(p, end, cp)) { + p = current_start + 1; + cp = static_cast(*current_start); + } + const bool is_regional = emojiIsRegionalIndicator(cp); + const bool joined = have_previous && + (uiIsGraphemeExtend(cp) || cp == 0x200Du || previous == 0x200Du || + (is_regional && emojiIsRegionalIndicator(previous) && (regional_run & 1u))); + if (!joined) cluster_start = static_cast(current_start - text); + if (is_regional) + regional_run = joined && emojiIsRegionalIndicator(previous) ? regional_run + 1 : 1; + else if (!uiIsGraphemeExtend(cp) && cp != 0x200Du) regional_run = 0; + previous = cp; + have_previous = true; + } + return cluster_start; +} + +#if CAP_EMOJI_PACK +static uint32_t uiPackedFlagTokenAt(uint32_t cp, const char* after_cp, + const char* end, const char*& sequence_end) { + if (emojiIsRegionalIndicator(cp)) { + const char* look = after_cp; + uint32_t trail = 0; + if (uiReadUtf8Codepoint(look, end, trail) && emojiIsRegionalIndicator(trail)) { + const uint32_t token = emojiPackFlagToken(cp, trail); + if (token && emojiPackSequenceLookup(token)) { + sequence_end = look; + return token; + } + } + return 0; + } + if (cp != 0x1F3F4u) return 0; + + char tag[8] = {}; + size_t tag_len = 0; + const char* look = after_cp; + for (;;) { + uint32_t next = 0; + if (!uiReadUtf8Codepoint(look, end, next)) return 0; + if (next == 0xE007Fu && tag_len > 0) break; + if (next < 0xE0061u || next > 0xE007Au || tag_len + 1 >= sizeof(tag)) return 0; + tag[tag_len++] = static_cast(next - 0xE0000u); + } + const uint32_t tag_token = emojiPackTagFlagToken(tag); + if (!tag_token) return 0; + if (emojiPackSequenceLookup(tag_token)) { + sequence_end = look; + return tag_token; + } + const uint32_t gb_token = emojiPackFlagToken(0x1F1ECu, 0x1F1E7u); + if (emojiPackSequenceLookup(gb_token)) { + sequence_end = look; + return gb_token; + } + return 0; +} + +#else +static inline uint32_t uiPackedFlagTokenAt(uint32_t, const char*, const char*, const char*&) { + return 0; +} +#endif + +static size_t uiEncodeUtf8(uint32_t cp, char out[4]) { + if (cp < 0x80u) { out[0] = static_cast(cp); return 1; } + if (cp < 0x800u) { + out[0] = static_cast(0xC0u | (cp >> 6)); + out[1] = static_cast(0x80u | (cp & 0x3Fu)); + return 2; + } + if (cp < 0x10000u) { + out[0] = static_cast(0xE0u | (cp >> 12)); + out[1] = static_cast(0x80u | ((cp >> 6) & 0x3Fu)); + out[2] = static_cast(0x80u | (cp & 0x3Fu)); + return 3; + } + out[0] = static_cast(0xF0u | (cp >> 18)); + out[1] = static_cast(0x80u | ((cp >> 12) & 0x3Fu)); + out[2] = static_cast(0x80u | ((cp >> 6) & 0x3Fu)); + out[3] = static_cast(0x80u | (cp & 0x3Fu)); + return 4; +} + +static size_t uiExpandPackedFlagToken(uint32_t token, char out[32]) { + if (token >= 0xF0000u && token < 0xF0000u + 26u * 26u) { + const uint32_t pair = token - 0xF0000u; + char encoded[4]; + size_t n = uiEncodeUtf8(0x1F1E6u + pair / 26u, encoded); + memcpy(out, encoded, n); + n += uiEncodeUtf8(0x1F1E6u + pair % 26u, out + n); + return n; + } + if (token >= 0xF0000u + 26u * 26u && token < 0xF0000u + 26u * 26u + 3u) { + static const char* const tags[] = { "gbeng", "gbsct", "gbwls" }; + const char* tag = tags[token - (0xF0000u + 26u * 26u)]; + size_t n = uiEncodeUtf8(0x1F3F4u, out); + while (*tag) n += uiEncodeUtf8(0xE0061u + (uint32_t)(*tag++ - 'a'), out + n); + n += uiEncodeUtf8(0xE007Fu, out + n); + return n; + } + return 0; +} + +static void composerAppendCodepoint(UITask* task, uint32_t cp) { + char encoded[4]; + const size_t n = uiEncodeUtf8(cp, encoded); + for (size_t i = 0; i < n; ++i) task->composerAppendChar(encoded[i]); +} + +static void composerAppendDisplayText(UITask* task, const char* text) { + if (!task || !text) return; + const char* p = text; + const char* end = text + strlen(text); + while (p < end) { + uint32_t cp = 0; + if (!uiReadUtf8Codepoint(p, end, cp)) { + task->composerAppendChar(*p++); + continue; + } + if (cp >= 0xF0000u && cp < 0xF0000u + 26u * 26u) { + const uint32_t pair = cp - 0xF0000u; + composerAppendCodepoint(task, 0x1F1E6u + pair / 26u); + composerAppendCodepoint(task, 0x1F1E6u + pair % 26u); + continue; + } + if (cp >= 0xF0000u + 26u * 26u && cp < 0xF0000u + 26u * 26u + 3u) { + static const char* const tags[] = { "gbeng", "gbsct", "gbwls" }; + const char* tag = tags[cp - (0xF0000u + 26u * 26u)]; + composerAppendCodepoint(task, 0x1F3F4u); + while (*tag) composerAppendCodepoint(task, 0xE0061u + (uint32_t)(*tag++ - 'a')); + composerAppendCodepoint(task, 0xE007Fu); + continue; + } + composerAppendCodepoint(task, cp); + } +} + /** * Copy UTF-8 `in` → `out` (NUL-terminated, capped). Codepoints not in `font` become ASCII '*'. * Invalid UTF-8 bytes become '*'. */ -static void copyUtf8ReplacingMissingGlyphs(const lv_font_t* font, char* out, size_t out_cap, const char* in) { +static void copyUtf8ReplacingMissingGlyphs(const lv_font_t* font, char* out, size_t out_cap, + const char* in, bool pack_flag_tokens = true) { if (!out || out_cap == 0) return; out[0] = '\0'; if (!in) return; @@ -4480,6 +4767,39 @@ static void copyUtf8ReplacingMissingGlyphs(const lv_font_t* font, char* out, siz continue; } + if (!pack_flag_tokens) { + char expanded[32]; + const size_t n = uiExpandPackedFlagToken(cp, expanded); + if (n) { + if (w + n + 1 > out_cap) break; + memcpy(out + w, expanded, n); + w += n; + continue; + } + } + + if (font) { + const char* sequence_end = p; + const uint32_t token = uiPackedFlagTokenAt(cp, p, end, sequence_end); + if (token) { + if (!pack_flag_tokens) { + const size_t n = static_cast(sequence_end - seq_beg); + if (w + n + 1 > out_cap) break; + memcpy(out + w, seq_beg, n); + w += n; + p = sequence_end; + continue; + } + char encoded[4]; + const size_t n = uiEncodeUtf8(token, encoded); + if (w + n + 1 > out_cap) break; + memcpy(out + w, encoded, n); + w += n; + p = sequence_end; + continue; + } + } + if (uiFontHasGlyph(font, cp)) { // Whole sequence or nothing: a glyph split at the cap leaves invalid UTF-8. if (w + (size_t)(p - seq_beg) + 1 > out_cap) break; @@ -5413,7 +5733,7 @@ static lv_obj_t* makeGlyphAvatar(lv_obj_t* parent, const char* name, GlyphShape // The emoji table maps the invisible joiners (U+200D, U+FE0E/FE0F) to an empty // 2 x 2 image so text never shows them; as an icon that image is a blank tile (#674). static bool emojiIconVisible(uint32_t cp, void*) { - const lv_img_dsc_t* d = emojiGlyphLookup(cp); + const lv_img_dsc_t* d = emojiLookupAny(cp); return d && d->header.w > 2; } static void glyphAvatarSetEmoji(lv_obj_t* av, const char* name, const char* utf8) { @@ -5423,7 +5743,7 @@ static void glyphAvatarSetEmoji(lv_obj_t* av, const char* name, const char* utf8 if (utf8 && utf8[0]) { uint32_t off = 0; lead = _lv_txt_encoded_next(utf8, &off); - if (emojiIconVisible(lead, nullptr)) eg = emojiGlyphLookup(lead); // ZWJ glyphs are keyed on their lead codepoint + if (emojiIconVisible(lead, nullptr)) eg = emojiLookupAny(lead); // ZWJ glyphs are keyed on their lead codepoint } avatarApply(av, name); if (!eg) { @@ -6180,6 +6500,7 @@ static void applyHardwarePanelRotation(uint8_t lvgl_rot) { // used by the Tanmatsu F-keys, so it stays gated.) static void openQuickReplyPicker(LvChatPanel* p); // △ quick replies static void openActiveChatSettings(); // ○ channel settings +static bool emojiSheetIsOpen(); // swipe guard, defined with the sheet #if defined(HAS_TANMATSU) static void openEmojiPickerForComposer(lv_obj_t* ta); // □ emoji picker (Tanmatsu F-key only) #endif @@ -7507,6 +7828,8 @@ static void navArrowAction(uint32_t key) { } } +static void taDeletePreviousGrapheme(lv_obj_t* ta); + static void navPump() { if (!s_nav_queue && (bsp_input_get_queue(&s_nav_queue) != ESP_OK || !s_nav_queue)) return; // Fire-on-hold: trigger the F1/F4 long-press action the MOMENT the threshold passes while the @@ -7795,7 +8118,7 @@ static void navPump() { // Backspace in an EMPTY field = leave edit mode (matches Enter-on-empty below; // consistent with backspace-as-back everywhere else on this board). if (!lv_textarea_get_text(ta)[0]) s_nav_ta_editing = false; - else lv_textarea_del_char(ta); + else taDeletePreviousGrapheme(ta); } else if (c == '\r' || c == '\n') { // Enter on an EMPTY composer drops back to navigate mode (cursor off) so the letter-nav @@ -10082,6 +10405,11 @@ static void applySwipeGesture(int8_t swipe_x, int8_t swipe_y) { // inside a category and have their own rightward swipe-back further down, so exclude them. // (Vertical swipes are a no-op at the end of this function, so this only kills tab swipes.) if (s_apppage_title && s_settings_open_cat < 0) return; + // The emoji sheet is modal and its category tabs scroll horizontally. This + // detector reads the touch hardware directly and ignores LVGL hit-testing, so + // without this a tab drag also reached the tab switcher / swipe-back behind the + // sheet and backed out of the page underneath. + if (emojiSheetIsOpen()) return; // A slider was just being dragged — its horizontal drag must NOT be read as a // tab/back swipe (e.g. raising the volume slider rightward kept triggering the // settings "swipe right = back"). Ignore swipes briefly after any slider touch. @@ -12407,7 +12735,7 @@ static void composerSendFromPanel(LvChatPanel* p) { if (!text || !text[0]) return; g_lv.task->setComposerMode(true); g_lv.task->composerReset(); - for (const char* cp = text; *cp; ++cp) g_lv.task->composerAppendChar(*cp); + composerAppendDisplayText(g_lv.task, text); // After the copy: hideKb() unfocuses the text box, whose restyle sets its label's // text again (a realloc), which can leave `text` pointing at freed memory. hideKb(); @@ -12431,7 +12759,7 @@ static void sendFromPanelCb(lv_event_t* e) { if (!text || !text[0]) return; g_lv.task->setComposerMode(true); g_lv.task->composerReset(); - for (const char* cp = text; *cp; ++cp) g_lv.task->composerAppendChar(*cp); + composerAppendDisplayText(g_lv.task, text); // After the copy: hideKb() unfocuses the text box, whose restyle sets its label's // text again (a realloc), which can leave `text` pointing at freed memory. hideKb(); @@ -12460,8 +12788,11 @@ static lv_obj_t* s_emoji_sheet = nullptr; static lv_obj_t* s_emoji_target_ta = nullptr; // textarea to insert into static lv_obj_t* s_emoji_grid = nullptr; // the scrollable button grid static int s_emoji_sel = -1; // hardware-highlighted index (-1 = none) +static int s_emoji_painted_sel = -1; static int s_emoji_cols = 1; // grid columns (computed at open) +static bool emojiSheetIsOpen() { return s_emoji_sheet != nullptr; } + // Curated insert set, grouped. Kept in sync with what the extras fonts bake // (see scripts/build/regen-extras-fonts.sh) — a glyph here that isn't in the // font would just render as the font's notdef box, so only ship baked ones. @@ -12497,8 +12828,9 @@ static const char* const k_emoji_items[] = { // animals "\xF0\x9F\x90\xB6","\xF0\x9F\x90\xB1","\xF0\x9F\x90\xB8","\xF0\x9F\x90\xBB", "\xF0\x9F\x90\xA7","\xF0\x9F\x90\x9D", - // activity / flags (soccer, football, moai, transgender flag, Lesotho flag) + // activity "\xE2\x9A\xBD","\xF0\x9F\x8F\x88","\xF0\x9F\x97\xBF", + // flags "\xF0\x9F\x8F\xB3\xEF\xB8\x8F\xE2\x80\x8D\xE2\x9A\xA7\xEF\xB8\x8F", "\xF0\x9F\x87\xB1\xF0\x9F\x87\xB8", // special characters / punctuation / currency / math @@ -12510,6 +12842,41 @@ static const char* const k_emoji_items[] = { }; static constexpr int k_emoji_count = (int)(sizeof(k_emoji_items) / sizeof(k_emoji_items[0])); +#if CAP_EMOJI_PACK +// k_emoji_items is already grouped contiguously by the comments above; these are +// those groups made machine-readable so an SD pack's items can be interleaved +// into them instead of all landing at the end. The static_assert fires if a glyph +// is added to the list without extending the matching group. +enum : int { + EMO_N_FACES = 26, EMO_N_GESTURES = 11, EMO_N_HEARTS = 7, EMO_N_SYMBOLS = 27, + EMO_N_OBJECTS = 16, EMO_N_ANIMALS = 6, EMO_N_ACTIVITY = 3, EMO_N_FLAGS = 2, + EMO_N_SPECIAL = 24, +}; +static_assert(EMO_N_FACES + EMO_N_GESTURES + EMO_N_HEARTS + EMO_N_SYMBOLS + + EMO_N_OBJECTS + EMO_N_ANIMALS + EMO_N_ACTIVITY + EMO_N_FLAGS + EMO_N_SPECIAL == k_emoji_count, + "k_emoji_items category groups drifted — update the EMO_N_* counts"); +struct EmojiSpan { uint8_t cat; uint16_t first; uint16_t count; }; +static const EmojiSpan k_emoji_spans[] = { + { EMOJI_CAT_FACES, 0, EMO_N_FACES }, + { EMOJI_CAT_GESTURES, EMO_N_FACES, EMO_N_GESTURES }, + { EMOJI_CAT_HEARTS, EMO_N_FACES + EMO_N_GESTURES, EMO_N_HEARTS }, + { EMOJI_CAT_SYMBOLS, EMO_N_FACES + EMO_N_GESTURES + EMO_N_HEARTS, EMO_N_SYMBOLS }, + { EMOJI_CAT_OBJECTS, EMO_N_FACES + EMO_N_GESTURES + EMO_N_HEARTS + + EMO_N_SYMBOLS, EMO_N_OBJECTS }, + { EMOJI_CAT_ANIMALS, EMO_N_FACES + EMO_N_GESTURES + EMO_N_HEARTS + + EMO_N_SYMBOLS + EMO_N_OBJECTS, EMO_N_ANIMALS }, + { EMOJI_CAT_ACTIVITY, EMO_N_FACES + EMO_N_GESTURES + EMO_N_HEARTS + + EMO_N_SYMBOLS + EMO_N_OBJECTS + EMO_N_ANIMALS, EMO_N_ACTIVITY }, + { EMOJI_CAT_FLAGS, EMO_N_FACES + EMO_N_GESTURES + EMO_N_HEARTS + + EMO_N_SYMBOLS + EMO_N_OBJECTS + EMO_N_ANIMALS + + EMO_N_ACTIVITY, EMO_N_FLAGS }, + { EMOJI_CAT_SPECIAL, EMO_N_FACES + EMO_N_GESTURES + EMO_N_HEARTS + + EMO_N_SYMBOLS + EMO_N_OBJECTS + EMO_N_ANIMALS + + EMO_N_ACTIVITY + EMO_N_FLAGS, EMO_N_SPECIAL }, +}; +static constexpr int k_emoji_span_count = (int)(sizeof(k_emoji_spans) / sizeof(k_emoji_spans[0])); +#endif + // Special characters / symbols not easy to reach on a compact keyboard — their OWN picker, // separate from emoji. All render via the g_font_16 chain (montserrat ASCII base + extras_font // symbols/accents fallback), so no tofu. @@ -12533,6 +12900,287 @@ static constexpr int k_special_count = (int)(sizeof(k_special_items) / sizeof(k_ // or the special-character set when opened from the text-edit menu's "Sym" button. static const char* const* s_glyph_items = k_emoji_items; static int s_glyph_count = k_emoji_count; +static bool s_glyph_is_emoji = true; // false for the special-character set +static lv_coord_t s_emoji_cell_px = 38; + +#if CAP_EMOJI_PACK +// Built-ins merged with the SD pack's items, each pack item slotted into its own +// category group. Built once on first picker open; with no pack the picker keeps +// pointing straight at k_emoji_items and nothing is allocated. +static const char** s_emoji_merged = nullptr; +static int s_emoji_merged_count = 0; +static bool s_emoji_merge_done = false; + +// Category slices of whatever list the picker is showing. A full pack runs to +// well over a thousand entries, so the sheet shows one slice at a time behind +// tabs rather than building every cell at once. +struct EmojiGroupView { uint8_t cat; uint16_t first; uint16_t count; }; +static EmojiGroupView s_emoji_groups[16]; +static int s_emoji_group_n = 0; +static int s_emoji_tab = 0; // active category slice +static bool s_emoji_tabbed = false; +static bool s_emoji_tab_nav = false; +static lv_obj_t* s_emoji_tabrow = nullptr; +static constexpr int k_emoji_tab_threshold = 200; +static void emojiSelectTab(int tab); +static void emojiLoadRecent(); +static constexpr uint8_t EMOJI_CAT_RECENT = 254; +static constexpr int k_emoji_recent_limit = 18; +static constexpr int k_emoji_recent_slot_bytes = 33; +static char (*s_emoji_recent)[k_emoji_recent_slot_bytes] = nullptr; +static int s_emoji_recent_count = 0; +static bool s_emoji_recent_loaded = false; +static bool s_emoji_recent_visible = false; +static bool s_emoji_recent_dirty = false; +static bool s_emoji_pack_usable = false; // the SD pack added at least one drawable cell +static uint32_t s_emoji_recent_changed_ms = 0; + +// Tab order: Unicode's own emoji groups, in their order. Hearts have no tab of +// their own — they are part of Smileys & Emotion. "Chars" is ours, holding the +// built-in punctuation/accent set that is not emoji at all. +static const uint8_t k_emoji_cat_order[] = { + EMOJI_CAT_FACES, EMOJI_CAT_GESTURES, EMOJI_CAT_ANIMALS, + EMOJI_CAT_FOOD, EMOJI_CAT_ACTIVITY, EMOJI_CAT_PLACES, + EMOJI_CAT_OBJECTS, EMOJI_CAT_SYMBOLS, EMOJI_CAT_FLAGS, + EMOJI_CAT_SPECIAL, +}; + +// Which tab a category is shown under. Only hearts move. +static inline uint8_t emojiCatTab(uint8_t cat) { + return cat == EMOJI_CAT_HEARTS ? EMOJI_CAT_FACES : cat; +} + +static const char* emojiCatName(uint8_t cat) { + switch (emojiCatTab(cat)) { // hearts are listed under Smileys + case EMOJI_CAT_RECENT: return "Recent"; + case EMOJI_CAT_FACES: return "Smileys"; + case EMOJI_CAT_GESTURES: return "People"; + case EMOJI_CAT_ANIMALS: return "Nature"; + case EMOJI_CAT_FOOD: return "Food"; + case EMOJI_CAT_ACTIVITY: return "Activity"; + case EMOJI_CAT_PLACES: return "Travel"; + case EMOJI_CAT_OBJECTS: return "Objects"; + case EMOJI_CAT_SYMBOLS: return "Symbols"; + case EMOJI_CAT_FLAGS: return "Flags"; + case EMOJI_CAT_SPECIAL: return "Chars"; + default: return "More"; + } +} + +static void emojiAddGroup(uint8_t cat, int first, int count) { + if (count <= 0 || s_emoji_group_n >= (int)(sizeof s_emoji_groups / sizeof s_emoji_groups[0])) return; + s_emoji_groups[s_emoji_group_n++] = { cat, (uint16_t)first, (uint16_t)count }; +} + +// A pack item whose lead codepoint resolves to no glyph would render as the +// notdef box, so it never earns a cell. +static bool emojiPackItemDrawable(const char* s) { + if (!s || !s[0]) return false; + uint32_t flag_off = 0; + const uint32_t lead = _lv_txt_encoded_next(s, &flag_off); + const uint32_t trail = _lv_txt_encoded_next(s, &flag_off); + if (emojiIsRegionalIndicator(lead) && emojiIsRegionalIndicator(trail)) + return emojiPickerCompositeGlyph(s) != nullptr; + uint32_t off = 0; + return emojiLookupAny(_lv_txt_encoded_next(s, &off)) != nullptr; +} + +static bool emojiRecentItemAvailable(const char* item) { + for (int s = 0; s < k_emoji_span_count; ++s) { + if (k_emoji_spans[s].cat == EMOJI_CAT_SPECIAL) continue; + for (int i = 0; i < (int)k_emoji_spans[s].count; ++i) + if (strcmp(item, k_emoji_items[k_emoji_spans[s].first + i]) == 0) return true; + } + for (int i = 0, n = emojiPackItemCount(); i < n; ++i) { + const char* pack_item = emojiPackItem(i); + if (emojiPackItemCat(i) != EMOJI_CAT_SPECIAL && pack_item && + strcmp(item, pack_item) == 0 && emojiPackItemDrawable(pack_item)) return true; + } + return false; +} + +static void emojiBuildMergedList() { + if (s_emoji_merge_done) return; + s_emoji_merge_done = true; + s_emoji_group_n = 0; + s_emoji_recent_visible = false; + emojiLoadRecent(); + + const int pn = emojiPackItemCount(); + int usable = 0; + for (int i = 0; i < pn; ++i) if (emojiPackItemDrawable(emojiPackItem(i))) ++usable; + + s_emoji_pack_usable = usable > 0; + if (!usable) { // no pack: map straight onto k_emoji_items, as before the pack existed + for (int s = 0; s < k_emoji_span_count; ++s) + emojiAddGroup(k_emoji_spans[s].cat, k_emoji_spans[s].first, k_emoji_spans[s].count); + return; + } + + const size_t bytes = (size_t)(k_emoji_count + usable + s_emoji_recent_count) * sizeof(const char*); + const char** out = (const char**)heap_caps_malloc(bytes, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + if (!out) out = (const char**)heap_caps_malloc(bytes, MALLOC_CAP_8BIT); + if (!out) { + for (int s = 0; s < k_emoji_span_count; ++s) + emojiAddGroup(k_emoji_spans[s].cat, k_emoji_spans[s].first, k_emoji_spans[s].count); + return; + } + + int w = 0; + { + const int start = w; + for (int i = 0; i < s_emoji_recent_count; ++i) { + if (emojiRecentItemAvailable(s_emoji_recent[i])) out[w++] = s_emoji_recent[i]; + } + if (w > start) { + emojiAddGroup(EMOJI_CAT_RECENT, start, w - start); + s_emoji_recent_visible = true; + } + } + for (uint8_t tab : k_emoji_cat_order) { + const int start = w; + // A tab can draw on more than one built-in span (Smileys takes both faces + // and hearts), so walk them all rather than looking up a single match. + for (int s = 0; s < k_emoji_span_count; ++s) { + const EmojiSpan& sp = k_emoji_spans[s]; + if (emojiCatTab(sp.cat) != tab) continue; + for (int j = 0; j < (int)sp.count; ++j) out[w++] = k_emoji_items[sp.first + j]; + } + for (int i = 0; i < pn; ++i) { + const char* it = emojiPackItem(i); + if (emojiCatTab(emojiPackItemCat(i)) == tab && emojiPackItemDrawable(it)) out[w++] = it; + } + emojiAddGroup(tab, start, w - start); + } + // Anything the pack tagged with a category not in the tab order (EMOJI_CAT_EXTRA + // and any future value) lands after the known groups rather than being dropped. + { + const int start = w; + for (int i = 0; i < pn; ++i) { + const uint8_t tab = emojiCatTab(emojiPackItemCat(i)); + bool known = false; + for (uint8_t k : k_emoji_cat_order) if (k == tab) { known = true; break; } + const char* it = emojiPackItem(i); + if (!known && emojiPackItemDrawable(it)) out[w++] = it; + } + emojiAddGroup(EMOJI_CAT_EXTRA, start, w - start); + } + s_emoji_merged = out; + s_emoji_merged_count = w; +} + +static const char* const* emojiPickerItems() { + emojiBuildMergedList(); + return s_emoji_merged ? s_emoji_merged : k_emoji_items; +} +static int emojiPickerCount() { + emojiBuildMergedList(); + return s_emoji_merged ? s_emoji_merged_count : k_emoji_count; +} +// The pack lands a few seconds into the session, after the list may already have +// been built without it. +static bool s_emoji_invalidate_pending = false; +static void emojiInvalidateMergedList() { + if (emojiSheetIsOpen()) { + s_emoji_invalidate_pending = true; + return; + } + s_emoji_invalidate_pending = false; + if (s_emoji_merged) { free(s_emoji_merged); s_emoji_merged = nullptr; } + s_emoji_merged_count = 0; + s_emoji_merge_done = false; + s_emoji_recent_visible = false; +} + +static bool emojiRecentStringValid(const char* item) { + if (!item || !item[0]) return false; + for (const char* special : k_special_items) + if (strcmp(item, special) == 0) return false; + for (const EmojiSpan& span : k_emoji_spans) { + if (span.cat != EMOJI_CAT_SPECIAL) continue; + for (int index = 0; index < span.count; ++index) + if (strcmp(item, k_emoji_items[span.first + index]) == 0) return false; + } + const char* p = item; + const char* end = item + strlen(item); + uint32_t cp = 0; + while (p < end) if (!uiReadUtf8Codepoint(p, end, cp)) return false; + return p == end; +} + +static void emojiLoadRecent() { + if (s_emoji_recent_loaded) return; + if (!s_emoji_recent) { + s_emoji_recent = static_cast( + heap_caps_calloc(k_emoji_recent_limit, k_emoji_recent_slot_bytes, + MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); + if (!s_emoji_recent) return; + } + s_emoji_recent_loaded = true; + uint8_t blob[1 + k_emoji_recent_limit * k_emoji_recent_slot_bytes] = {}; + const size_t n = touchPrefsGetBlob("emoji_recent", blob, sizeof(blob)); + if (n < 1 || blob[0] > k_emoji_recent_limit || + n != 1 + (size_t)blob[0] * k_emoji_recent_slot_bytes) return; + + for (int i = 0; i < blob[0]; ++i) { + char item[k_emoji_recent_slot_bytes]; + memcpy(item, blob + 1 + i * k_emoji_recent_slot_bytes, sizeof(item)); + if (!memchr(item, '\0', sizeof(item)) || !emojiRecentStringValid(item)) continue; + memcpy(s_emoji_recent[s_emoji_recent_count++], item, sizeof(item)); + } +} + +static void emojiRememberRecent(const char* picked) { + if (!picked) return; + // A Recent cell's text lives in s_emoji_recent itself, and the shift below + // overwrites that slot before the copy into slot 0: work from a copy. + const size_t len = strlen(picked); + if (len >= k_emoji_recent_slot_bytes) return; + char item[k_emoji_recent_slot_bytes]; + memcpy(item, picked, len + 1); + if (!s_glyph_is_emoji || !emojiRecentStringValid(item) || !emojiRecentItemAvailable(item)) return; + emojiLoadRecent(); + if (!s_emoji_recent) return; + if (s_emoji_recent_count > 0 && strcmp(s_emoji_recent[0], item) == 0) return; + + int found = -1; + for (int i = 1; i < s_emoji_recent_count; ++i) { + if (strcmp(s_emoji_recent[i], item) == 0) { found = i; break; } + } + if (found >= 0) { + for (int i = found; i > 0; --i) + memcpy(s_emoji_recent[i], s_emoji_recent[i - 1], k_emoji_recent_slot_bytes); + } else { + const int last = s_emoji_recent_count < k_emoji_recent_limit ? s_emoji_recent_count++ : k_emoji_recent_limit - 1; + for (int i = last; i > 0; --i) + memcpy(s_emoji_recent[i], s_emoji_recent[i - 1], k_emoji_recent_slot_bytes); + } + memset(s_emoji_recent[0], 0, k_emoji_recent_slot_bytes); + memcpy(s_emoji_recent[0], item, len); + + s_emoji_recent_dirty = true; + s_emoji_recent_changed_ms = millis(); + emojiInvalidateMergedList(); +} + +static void emojiFlushRecent(uint32_t now, uint32_t last_input_ms) { + if (!s_emoji_recent_dirty || emojiSheetIsOpen() || + now - s_emoji_recent_changed_ms < 2000u || now - last_input_ms < 2000u) return; + uint8_t blob[1 + k_emoji_recent_limit * k_emoji_recent_slot_bytes] = {}; + blob[0] = (uint8_t)s_emoji_recent_count; + for (int i = 0; i < s_emoji_recent_count; ++i) + memcpy(blob + 1 + i * k_emoji_recent_slot_bytes, s_emoji_recent[i], k_emoji_recent_slot_bytes); + if (touchPrefsSetBlob("emoji_recent", blob, 1 + s_emoji_recent_count * k_emoji_recent_slot_bytes)) + s_emoji_recent_dirty = false; + else + s_emoji_recent_changed_ms = now; +} +#else +static inline const char* const* emojiPickerItems() { return k_emoji_items; } +static inline int emojiPickerCount() { return k_emoji_count; } +static inline void emojiRememberRecent(const char*) {} +static inline void emojiFlushRecent(uint32_t, uint32_t) {} +#endif // Pick-mode: when set, the next chosen glyph is handed to this callback instead // of being inserted into a textarea (used by the chat-icon chooser). Dismissing @@ -12546,8 +13194,17 @@ static void closeEmojiSheet() { popupClose(&s_emoji_sheet); s_emoji_target_ta = nullptr; s_emoji_grid = nullptr; +#if CAP_EMOJI_PACK + s_emoji_tabrow = nullptr; +#endif s_emoji_sel = -1; + s_emoji_painted_sel = -1; s_emoji_pick_cb = nullptr; + s_glyph_items = k_emoji_items; + s_glyph_count = k_emoji_count; +#if CAP_EMOJI_PACK + if (s_emoji_invalidate_pending) emojiInvalidateMergedList(); +#endif #if defined(HAS_M9_KEYBOARD) if (return_ta && lv_obj_is_valid(return_ta)) { s_m9_focus_pending = return_ta; @@ -12583,6 +13240,7 @@ static void emojiInsertIndex(int idx) { // straight into the real field. lv_obj_t* dest = (kbMirrorActive() && s_kb_bind_ta == ta && s_kb_mirror_ta) ? s_kb_mirror_ta : ta; lv_textarea_add_text(dest, g); + emojiRememberRecent(g); closeEmojiSheet(); } static void emojiPickCb(lv_event_t* e) { @@ -12594,26 +13252,26 @@ static void emojiPickCb(lv_event_t* e) { // Defined after openEmojiPicker; forward-declared next to the thread-sheet code. static void openEmojiPicker(lv_obj_t* ta, const char* const* items, int count, const char* picker_title); static void openEmojiPickerPick(void (*cb)(const char* utf8), const char* title) { - openEmojiPicker(nullptr, k_emoji_items, k_emoji_count, title); // resets pick state via closeEmojiSheet() + openEmojiPicker(nullptr, nullptr, 0, title); // resets pick state via closeEmojiSheet() s_emoji_pick_cb = cb; // arm AFTER the open (the closer clears it) } -// Paint the hardware-selected cell highlighted and the rest normal, and keep -// the selection scrolled into view. No-op when nothing is selected (touch-only). +// Update only the previous and current hardware-selected cells. static void emojiPaintSelection() { if (!s_emoji_grid) return; const uint32_t n = lv_obj_get_child_cnt(s_emoji_grid); - for (uint32_t i = 0; i < n; ++i) { - lv_obj_t* b = lv_obj_get_child(s_emoji_grid, i); - if (!b) continue; - const bool sel = ((int)i == s_emoji_sel); - lv_obj_set_style_bg_color(b, lv_color_hex(COLOR_CONTROL), LV_PART_MAIN); - lv_obj_set_style_border_width(b, 0, LV_PART_MAIN); - setSelectionGlow(b, sel, LV_PART_MAIN); + if (s_emoji_painted_sel == s_emoji_sel) return; + if (s_emoji_painted_sel >= 0 && s_emoji_painted_sel < (int)n) { + setSelectionGlow(lv_obj_get_child(s_emoji_grid, (uint32_t)s_emoji_painted_sel), + false, LV_PART_MAIN); } + s_emoji_painted_sel = s_emoji_sel; if (s_emoji_sel >= 0 && s_emoji_sel < (int)n) { lv_obj_t* b = lv_obj_get_child(s_emoji_grid, (uint32_t)s_emoji_sel); - if (b) lv_obj_scroll_to_view(b, uiAnimOn()); + if (b) { + setSelectionGlow(b, true, LV_PART_MAIN); + lv_obj_scroll_to_view(b, uiAnimOn()); + } } } @@ -12642,6 +13300,26 @@ static void emojiSelectorMove(int rawdx, int rawdy) { else if (s_emoji_acc_y <= -kEmojiSelStep) { dr = -1; s_emoji_acc_y = 0; } if (dc == 0 && dr == 0) return; // not enough travel yet +#if CAP_EMOJI_PACK + if (s_emoji_tabbed && s_emoji_tab_nav) { + if (dc && s_emoji_group_n > 0) { + int tab = (s_emoji_tab + dc + s_emoji_group_n) % s_emoji_group_n; + emojiSelectTab(tab); + } + if (dr > 0) { + s_emoji_tab_nav = false; + s_emoji_sel = 0; + emojiPaintSelection(); + } + return; + } + + if (s_emoji_tabbed && dr < 0 && s_emoji_sel >= 0 && s_emoji_sel < s_emoji_cols) { + s_emoji_tab_nav = true; + return; + } +#endif + const int cols = s_emoji_cols > 0 ? s_emoji_cols : 1; int idx = s_emoji_sel; if (dc) idx += dc; // horizontal: free move across the flat list @@ -12658,17 +13336,177 @@ static void emojiSelectorMove(int rawdx, int rawdy) { // Returns true if it consumed the click (so it isn't also injected as a tap). static bool emojiSelectorClick() { if (!s_emoji_sheet) return false; +#if CAP_EMOJI_PACK + if (s_emoji_tab_nav) { + s_emoji_tab_nav = false; + s_emoji_sel = 0; + emojiPaintSelection(); + return true; + } +#endif if (s_emoji_sel >= 0) emojiInsertIndex(s_emoji_sel); return true; // swallow the click even if nothing selected yet } -// Opened from the composer's emoji button. `ta` is the composer textarea. -static void openEmojiPicker(lv_obj_t* ta, const char* const* items = k_emoji_items, - int count = k_emoji_count, const char* picker_title = "Insert emoji / symbol") { +// Fill (or refill) the grid from the current s_glyph_items slice. +static void emojiFillGrid() { + if (!s_emoji_grid) return; + static const lv_style_prop_t no_transition_props[] = { (lv_style_prop_t)0 }; + static lv_style_transition_dsc_t no_transition; + lv_style_transition_dsc_init(&no_transition, no_transition_props, nullptr, 0, 0, nullptr); + lv_obj_clean(s_emoji_grid); + s_emoji_painted_sel = -1; + lv_obj_scroll_to_y(s_emoji_grid, 0, LV_ANIM_OFF); + for (int i = 0; i < s_glyph_count; ++i) { + lv_obj_t* b = lv_btn_create(s_emoji_grid); + lv_obj_set_size(b, s_emoji_cell_px, s_emoji_cell_px); + styleButton(b); + lv_obj_set_style_bg_color(b, lv_color_hex(COLOR_CONTROL), LV_PART_MAIN); + lv_obj_set_style_pad_all(b, 0, LV_PART_MAIN); + lv_obj_set_style_transform_width(b, 0, LV_PART_MAIN | LV_STATE_PRESSED); + lv_obj_set_style_transform_height(b, 0, LV_PART_MAIN | LV_STATE_PRESSED); + lv_obj_set_style_transition(b, &no_transition, LV_PART_MAIN); + lv_obj_add_event_cb(b, emojiPickCb, LV_EVENT_CLICKED, (void*)(intptr_t)i); + if (s_glyph_is_emoji) { + const lv_img_dsc_t* ed = emojiPickerCompositeGlyph(s_glyph_items[i]); + if (!ed) { + uint32_t goff = 0; + ed = emojiLookupAny(_lv_txt_encoded_next(s_glyph_items[i], &goff)); + } + if (ed) { + lv_obj_t* im = lv_img_create(b); + lv_img_set_src(im, ed); + lv_img_set_antialias(im, false); + lv_obj_center(im); + continue; + } + } + lv_obj_t* l = lv_label_create(b); + lv_label_set_text(l, s_glyph_items[i]); + lv_obj_set_style_text_font(l, &g_font_16, LV_PART_MAIN); + lv_obj_set_style_text_color(l, lv_color_hex(COLOR_TEXT), LV_PART_MAIN); + lv_obj_center(l); + } +} + +#if CAP_EMOJI_PACK +static void emojiPaintTabs() { + if (!s_emoji_tabrow) return; + const uint32_t n = lv_obj_get_child_cnt(s_emoji_tabrow); + for (uint32_t i = 0; i < n; ++i) { + lv_obj_t* t = lv_obj_get_child(s_emoji_tabrow, i); + if (!t) continue; + const bool on = ((int)i == s_emoji_tab); + lv_obj_set_style_bg_color(t, lv_color_hex(on ? COLOR_ACCENT : COLOR_CONTROL), LV_PART_MAIN); + } +} + +static void emojiSelectTab(int tab) { + if (tab < 0 || tab >= s_emoji_group_n || tab == s_emoji_tab) return; + s_emoji_tab = tab; + s_glyph_items = emojiPickerItems() + s_emoji_groups[tab].first; + s_glyph_count = s_emoji_groups[tab].count; + s_emoji_sel = -1; + s_emoji_acc_x = s_emoji_acc_y = 0; + emojiPaintTabs(); + emojiFillGrid(); +} + +static void emojiTabCb(lv_event_t* e) { + if (lv_event_get_code(e) != LV_EVENT_CLICKED) return; + const int g = (int)(intptr_t)lv_event_get_user_data(e); + if (g < 0 || g >= s_emoji_group_n || g == s_emoji_tab) return; + s_emoji_tab_nav = false; + emojiSelectTab(g); +} + +static void emojiTabScrollCb(lv_event_t* e) { + if (lv_event_get_code(e) != LV_EVENT_CLICKED || !s_emoji_tabrow) return; + const bool left = (intptr_t)lv_event_get_user_data(e) < 0; + lv_coord_t step = lv_obj_get_width(s_emoji_tabrow) * 3 / 4; + if (step < 24) step = 24; + lv_obj_scroll_by_bounded(s_emoji_tabrow, left ? step : -step, 0, LV_ANIM_ON); +} + +static void emojiBuildTabRow(lv_obj_t* card, lv_coord_t w, lv_coord_t y) { + lv_obj_t* row = lv_obj_create(card); + lv_obj_remove_style_all(row); + lv_obj_set_size(row, w - 48, 24); + lv_obj_set_pos(row, 24, y); + lv_obj_set_flex_flow(row, LV_FLEX_FLOW_ROW); + lv_obj_set_style_pad_column(row, 4, LV_PART_MAIN); + lv_obj_set_scroll_dir(row, LV_DIR_HOR); + lv_obj_set_scrollbar_mode(row, LV_SCROLLBAR_MODE_OFF); + lv_obj_add_flag(row, LV_OBJ_FLAG_SCROLL_ELASTIC); + // A vertical drag on the tab strip, or a horizontal one past either end, would + // otherwise chain into the card and the page behind the modal. + lv_obj_clear_flag(row, LV_OBJ_FLAG_SCROLL_CHAIN); + lv_obj_clear_flag(row, LV_OBJ_FLAG_GESTURE_BUBBLE); + s_emoji_tabrow = row; + + lv_obj_t* left = lv_btn_create(card); + lv_obj_set_size(left, 22, 24); + lv_obj_set_pos(left, 0, y); + styleButton(left); + lv_obj_add_event_cb(left, emojiTabScrollCb, LV_EVENT_CLICKED, (void*)(intptr_t)-1); + lv_obj_t* left_icon = lv_label_create(left); + lv_label_set_text(left_icon, LV_SYMBOL_LEFT); + lv_obj_set_style_text_font(left_icon, &g_font_12, LV_PART_MAIN); + lv_obj_center(left_icon); + + lv_obj_t* right = lv_btn_create(card); + lv_obj_set_size(right, 22, 24); + lv_obj_set_pos(right, w - 22, y); + styleButton(right); + lv_obj_add_event_cb(right, emojiTabScrollCb, LV_EVENT_CLICKED, (void*)(intptr_t)1); + lv_obj_t* right_icon = lv_label_create(right); + lv_label_set_text(right_icon, LV_SYMBOL_RIGHT); + lv_obj_set_style_text_font(right_icon, &g_font_12, LV_PART_MAIN); + lv_obj_center(right_icon); + + for (int i = 0; i < s_emoji_group_n; ++i) { + lv_obj_t* t = lv_btn_create(row); + lv_obj_set_height(t, 22); + lv_obj_set_style_pad_hor(t, 6, LV_PART_MAIN); + lv_obj_set_style_pad_ver(t, 0, LV_PART_MAIN); + styleButton(t); + lv_obj_add_event_cb(t, emojiTabCb, LV_EVENT_CLICKED, (void*)(intptr_t)i); + lv_obj_t* l = lv_label_create(t); + lv_label_set_text(l, TR(emojiCatName(s_emoji_groups[i].cat))); + lv_obj_set_style_text_font(l, &g_font_12, LV_PART_MAIN); + lv_obj_set_style_text_color(l, lv_color_hex(COLOR_TEXT), LV_PART_MAIN); + lv_obj_center(l); + } + emojiPaintTabs(); +} +#endif + +// Opened from the composer's emoji button. `ta` is the composer textarea. A null +// `items` means the emoji set, resolved here so it can pick up the SD pack. +static void openEmojiPicker(lv_obj_t* ta, const char* const* items = nullptr, + int count = 0, const char* picker_title = "Insert emoji / symbol") { closeEmojiSheet(); s_emoji_target_ta = ta; - s_glyph_items = items; - s_glyph_count = count; + s_glyph_is_emoji = (items == nullptr); + s_glyph_items = items ? items : emojiPickerItems(); + s_glyph_count = items ? count : emojiPickerCount(); +#if CAP_EMOJI_PACK + // Past this many cells, building them all at once costs visible seconds and + // hundreds of KB of widget tree, so switch to one category at a time. + bool has_flags_group = false; + for (int i = 0; i < s_emoji_group_n; ++i) { + if (s_emoji_groups[i].cat == EMOJI_CAT_FLAGS) { has_flags_group = true; break; } + } + s_emoji_tabbed = s_glyph_is_emoji && s_emoji_pack_usable && s_emoji_group_n > 1 && + (s_emoji_recent_visible || s_glyph_count > k_emoji_tab_threshold || has_flags_group); + if (s_emoji_tabbed) { + if (s_emoji_tab < 0 || s_emoji_tab >= s_emoji_group_n) s_emoji_tab = 0; + const EmojiGroupView& g = s_emoji_groups[s_emoji_tab]; + s_glyph_items += g.first; + s_glyph_count = g.count; + } + s_emoji_tab_nav = false; +#endif const lv_coord_t sw = lv_disp_get_hor_res(nullptr); const lv_coord_t sh = lv_disp_get_ver_res(nullptr); s_emoji_sheet = lv_obj_create(lv_layer_top()); @@ -12699,10 +13537,13 @@ static void openEmojiPicker(lv_obj_t* ta, const char* const* items = k_emoji_ite lv_obj_t* title = lv_label_create(card); lv_label_set_text(title, TR(picker_title)); + lv_label_set_long_mode(title, LV_LABEL_LONG_DOT); + lv_obj_set_width(title, cardw - 56); lv_obj_set_style_text_color(title, lv_color_hex(COLOR_TEXT), LV_PART_MAIN); lv_obj_set_style_text_font(title, &g_font_14, LV_PART_MAIN); lv_obj_set_pos(title, 2, 0); - addCloseXBadge(card, emojiSheetCloseCb); + lv_obj_t* close = addCloseXBadge(card, emojiSheetCloseCb); + lv_obj_align(close, LV_ALIGN_TOP_RIGHT, -2, -4); // Hint line: how to use the board's primary picker controls. The T-Deck Pro has no // trackball or arrow keys to drive the selector (picks are by touch), so none there. @@ -12742,64 +13583,43 @@ static void openEmojiPicker(lv_obj_t* ta, const char* const* items = k_emoji_ite } #endif - // Scrollable grid of glyph buttons. - const lv_coord_t grid_w = cardw - 16; + // Scrollable grid of glyph buttons, with a category tab row above it when the + // set is too big to build in one go. + const lv_coord_t grid_w = cardw - 16; +#if CAP_EMOJI_PACK + if (s_emoji_tabbed) { + emojiBuildTabRow(card, grid_w, grid_y); + grid_y += 26; + } +#endif lv_obj_t* grid = lv_obj_create(card); lv_obj_remove_style_all(grid); lv_obj_set_size(grid, grid_w, cardh - 16 - grid_y); lv_obj_set_pos(grid, 0, grid_y); lv_obj_set_flex_flow(grid, LV_FLEX_FLOW_ROW_WRAP); + lv_obj_set_flex_align(grid, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START); lv_obj_set_style_pad_row(grid, 4, LV_PART_MAIN); lv_obj_set_style_pad_column(grid, 4, LV_PART_MAIN); lv_obj_set_scroll_dir(grid, LV_DIR_VER); lv_obj_set_scrollbar_mode(grid, LV_SCROLLBAR_MODE_AUTO); + lv_obj_clear_flag(grid, LV_OBJ_FLAG_SCROLL_CHAIN); + lv_obj_clear_flag(grid, LV_OBJ_FLAG_GESTURE_BUBBLE); s_emoji_grid = grid; - // Emoji cells render the baked colour glyph as a ZOOMED image (70% bigger than the 16 px - // font glyph) and get a bigger cell; special-character cells stay text labels. + // Keep touch targets roomy while drawing emoji at their native image size. #if CAP_LARGE_SCREEN - const bool big_emoji = (s_glyph_items == k_emoji_items); - const lv_coord_t cell_px = big_emoji ? 48 : 38; + s_emoji_cell_px = s_glyph_is_emoji ? 48 : 38; #else - const lv_coord_t cell_px = 38; + s_emoji_cell_px = 38; #endif // Column count for the trackball selector's row jumps: floor((w + gap) / // (cell + gap)), gap=4. Matches the flex-wrap that LVGL computes. - s_emoji_cols = (int)((grid_w + 4) / (cell_px + 4)); + s_emoji_cols = (int)((grid_w + 4) / (s_emoji_cell_px + 4)); if (s_emoji_cols < 1) s_emoji_cols = 1; s_emoji_sel = -1; // start un-highlighted; first roll selects index 0 s_emoji_acc_x = s_emoji_acc_y = 0; - for (int i = 0; i < s_glyph_count; ++i) { - lv_obj_t* b = lv_btn_create(grid); - lv_obj_set_size(b, cell_px, cell_px); - styleButton(b); - lv_obj_set_style_bg_color(b, lv_color_hex(COLOR_CONTROL), LV_PART_MAIN); - lv_obj_set_style_pad_all(b, 0, LV_PART_MAIN); - lv_obj_add_event_cb(b, emojiPickCb, LV_EVENT_CLICKED, (void*)(intptr_t)i); -#if CAP_LARGE_SCREEN && LV_USE_IMGFONT - // Baked colour-emoji → draw it as a zoomed image (1.7× ≈ 70% bigger than the 16 px - // font glyph). Special chars (no emoji dsc) fall through to the text label below. - if (big_emoji) { - uint32_t goff = 0; - const lv_img_dsc_t* ed = emojiGlyphLookup(_lv_txt_encoded_next(s_glyph_items[i], &goff)); - if (ed) { - lv_obj_t* im = lv_img_create(b); - lv_img_set_src(im, ed); - lv_img_set_antialias(im, true); - if (ed->header.w && ed->header.h) - lv_img_set_pivot(im, ed->header.w / 2, ed->header.h / 2); - lv_img_set_zoom(im, 435); // 256 = 1×, 435 ≈ 1.7× - lv_obj_center(im); - continue; - } - } -#endif - lv_obj_t* l = lv_label_create(b); - lv_label_set_text(l, s_glyph_items[i]); - lv_obj_set_style_text_font(l, &g_font_16, LV_PART_MAIN); - lv_obj_set_style_text_color(l, lv_color_hex(COLOR_TEXT), LV_PART_MAIN); - lv_obj_center(l); - } + emojiFillGrid(); + #if defined(HAS_M9_KEYBOARD) if (s_glyph_count > 0) { s_emoji_sel = 0; @@ -13877,10 +14697,7 @@ static char s_clipboard[CLIPBOARD_MAX] = {0}; static void clipboardSet(const char* text, const char* tag) { if (!text) return; - size_t n = strlen(text); - if (n >= CLIPBOARD_MAX) n = CLIPBOARD_MAX - 1; - memcpy(s_clipboard, text, n); - s_clipboard[n] = '\0'; + copyUtf8ReplacingMissingGlyphs(nullptr, s_clipboard, sizeof(s_clipboard), text, false); if (g_lv.task) { char toast[60]; snprintf(toast, sizeof(toast), TR("Copied %s"), @@ -14082,6 +14899,17 @@ static void taDeleteRange(lv_obj_t* ta, uint32_t s_cp, uint32_t e_cp) { for (uint32_t k = s_cp; k < e_cp; ++k) lv_textarea_del_char(ta); } +static void taDeletePreviousGrapheme(lv_obj_t* ta) { + if (!ta) return; + const char* text = lv_textarea_get_text(ta); + const uint32_t cursor_cp = lv_textarea_get_cursor_pos(ta); + if (!text || cursor_cp == 0) return; + const uint32_t cursor_byte = taCpToByte(text, cursor_cp); + const size_t start_byte = uiPreviousGraphemeStartByte(text, cursor_byte); + const uint32_t start_cp = taByteToCp(text, (uint32_t)start_byte); + taDeleteRange(ta, start_cp, cursor_cp); +} + // ----- The floating Cut / Copy / Paste / Select-All menu ----- static lv_obj_t* s_txtmenu = nullptr; static lv_obj_t* s_txtmenu_ta = nullptr; @@ -14132,7 +14960,7 @@ static void txtMenuCellCb(lv_event_t* e) { // Emoji into any field, not just the chat composer. Asked for by Jade, who // writes Lua apps: wada.ui.input() uses this same menu, so an app's text entry // gets the picker for free, and so does every settings field. - if (act == TXT_EMOJI) { txtMenuHide(); openEmojiPicker(ta, k_emoji_items, k_emoji_count, TR("Emoji")); return; } + if (act == TXT_EMOJI) { txtMenuHide(); openEmojiPicker(ta, nullptr, 0, TR("Emoji")); return; } const char* txt = lv_textarea_get_text(ta); uint32_t s_cp = 0, e_cp = 0; bool sel = taHasSelection(ta, &s_cp, &e_cp); @@ -14287,9 +15115,12 @@ static void kbBackspaceSelCb(lv_event_t* e) { lv_obj_t* ta = lv_keyboard_get_textarea(kb); if (!ta) return; uint32_t s_cp, e_cp; - if (!taHasSelection(ta, &s_cp, &e_cp)) return; // nothing selected -> default deletes one char - taDeleteRange(ta, s_cp, e_cp); - taClearSelection(ta); + if (taHasSelection(ta, &s_cp, &e_cp)) { + taDeleteRange(ta, s_cp, e_cp); + taClearSelection(ta); + } else { + taDeletePreviousGrapheme(ta); + } accentBoxHide(); txtMenuHide(); lv_event_stop_processing(e); @@ -14544,7 +15375,7 @@ static void saveProfileNameCb(lv_event_t* e) { if (_c == LV_EVENT_DEFOCUSED) { char cur_vis[40]; const char* raw = g_lv.task->getNodeNameCstr(); - copyUtf8ReplacingMissingGlyphs(&g_font_14, cur_vis, sizeof(cur_vis), raw ? raw : ""); + copyUtf8ReplacingMissingGlyphs(&g_font_14, cur_vis, sizeof(cur_vis), raw ? raw : "", false); if (strcmp(name, cur_vis) == 0) return; } if (g_lv.task->setNodeName(name)) { @@ -16156,7 +16987,7 @@ static void buildProfileSettings() { if (g_lv.task) { char nm_vis[40]; const char* raw = g_lv.task->getNodeNameCstr(); - copyUtf8ReplacingMissingGlyphs(&g_font_14, nm_vis, sizeof(nm_vis), raw ? raw : ""); + copyUtf8ReplacingMissingGlyphs(&g_font_14, nm_vis, sizeof(nm_vis), raw ? raw : "", false); lv_textarea_set_text(g_set_modal.name_ta, nm_vis); } } @@ -43350,7 +44181,7 @@ static void makeChatDetail(LvChatPanel& p) { // The colour emoji is a fixed ~16-px baked image (it doesn't scale with the font), so it // looks tiny in the big □. Hide the label glyph and draw the same emoji as a 2x-zoomed // image so it fills the shape. - if (const lv_img_dsc_t* sm = emojiGlyphLookup(0x1F60A)) { // 😊 + if (const lv_img_dsc_t* sm = emojiLookupAny(0x1F60A)) { // 😊 lv_obj_add_flag(el, LV_OBJ_FLAG_HIDDEN); lv_obj_t* eimg = lv_img_create(p.emoji_btn); lv_img_set_src(eimg, sm); @@ -55634,7 +56465,7 @@ if (g_lv.task && g_lv.task->isManualLock()) { return; } #endif - lv_textarea_del_char(ta); + taDeletePreviousGrapheme(ta); } accentBoxHide(); } else if (key == ' ') { @@ -55707,7 +56538,7 @@ if (g_lv.task && g_lv.task->isManualLock()) { if (text && text[0]) { g_lv.task->setComposerMode(true); g_lv.task->composerReset(); - for (const char* cp = text; *cp; ++cp) g_lv.task->composerAppendChar(*cp); + composerAppendDisplayText(g_lv.task, text); if (g_lv.task->composerSend()) { lv_textarea_set_text(p->composer_ta, ""); refreshChatDetailAsync(*p); @@ -55948,7 +56779,7 @@ static void bleKbdTouchDelete(lv_obj_t* ta, bool forward) { } else if (forward) { lv_textarea_del_char_forward(ta); } else { - lv_textarea_del_char(ta); + taDeletePreviousGrapheme(ta); } accentBoxHide(); } @@ -68794,7 +69625,11 @@ static void setupShowStep(int step) { lv_textarea_set_max_length(s_setup_name_ta, 30); if (g_lv.task) { const char* cur = g_lv.task->getNodeNameCstr(); - if (cur && cur[0]) lv_textarea_set_text(s_setup_name_ta, cur); + if (cur && cur[0]) { + char cur_vis[40]; + copyUtf8ReplacingMissingGlyphs(&g_font_14, cur_vis, sizeof(cur_vis), cur, false); + lv_textarea_set_text(s_setup_name_ta, cur_vis); + } } attachSettingsTaEvents(s_setup_name_ta); setupBtn(TR("Back"), setupBackCb, false, 12, btn_y, 72); @@ -78642,6 +79477,44 @@ void UITask::begin(DisplayDriver* display, SensorManager* sensors, NodePrefs* no // largest block, so the worker could never start and tiles, the update // check and the app catalog were all silently dead. reserveTileFetchStack(); + // Optional emoji pack. Searched on the SD card and on whatever filesystem the + // profile's data lives on (the USB Files page exposes both as separate roots, + // so "the right place" is ambiguous), under /emoji/ or the root. Deliberately + // NOT /meshcomod: that folder is read-only over USB Files and is wiped by + // "erase all data". Only opened here — the read is pumped from the loop so a + // full ~850 KB pack doesn't stall boot on a 4 MHz card. Reported through the + // Set-tab diag log, since WIRE_DBG is compiled out of release builds and + // Serial belongs to the companion protocol. + { + uiDataFsReady(); + fs::FS* cands[2] = { nullptr, nullptr }; + int nc = 0; +#if CAP_SD || defined(TLORA_PAGER) + // Adopt-only: re-running the mount ladder here would SD.end() a volume + // DataStore may already hold. + if (sdAdoptLiveMount()) cands[nc++] = &SD; +#endif + if (s_ui_data_fs && (nc == 0 || cands[0] != s_ui_data_fs)) cands[nc++] = s_ui_data_fs; + + #if CAP_EMOJI_PACK + static const char* const kPackPaths[2] = { "/emoji/emoji.pack", "/emoji.pack" }; + File ep; + for (int i = 0; i < nc && !ep; ++i) + for (int p = 0; p < 2 && !ep; ++p) ep = cands[i]->open(kPackPaths[p], FILE_READ); + + char msg[DIAG_COLS]; + if (!nc) { + pushDiagLine("emoji: no storage, baked set only"); + } else if (!ep) { + snprintf(msg, sizeof msg, "emoji: no emoji.pack (%d root/s)", nc); + pushDiagLine(msg); + } else { + snprintf(msg, sizeof msg, "emoji: reading pack, %u KB", (unsigned)(ep.size() / 1024)); + pushDiagLine(msg); + if (!emojiPackBegin(ep)) pushDiagLine("emoji: pack size/PSRAM rejected"); + } +#endif + } lv_init(); initTouchFontFallbacks(); // NB: re-pointing the LVGL theme's font here does NOT work (tried, verified @@ -79987,8 +80860,28 @@ void UITask::setGpsPower(bool on) { bool UITask::setNodeName(const char* s) { if (!_node_prefs) return false; if (!s) s = ""; - // Adverts carry the name: standard Arabic letters, not presentation forms (#582). - arabicUnshape(s, _node_prefs->node_name, sizeof(_node_prefs->node_name)); + char sanitized[sizeof(_node_prefs->node_name)] = {}; + size_t written = 0; + const char* p = s; + const char* end = s + strlen(s); + while (p < end && written + 1 < sizeof(sanitized)) { + const char* codepoint_start = p; + uint32_t cp = 0; + if (!uiReadUtf8Codepoint(p, end, cp)) { + p = codepoint_start + 1; + sanitized[written++] = *codepoint_start; + continue; + } + char expanded[32]; + const size_t expanded_len = uiExpandPackedFlagToken(cp, expanded); + const char* source = expanded_len ? expanded : codepoint_start; + const size_t n = expanded_len ? expanded_len : static_cast(p - codepoint_start); + if (written + n + 1 > sizeof(sanitized)) break; + memcpy(sanitized + written, source, n); + written += n; + } + // Expand packed flag tokens before normalizing Arabic advert text. + arabicUnshape(sanitized, _node_prefs->node_name, sizeof(_node_prefs->node_name)); // Report the real write result — the "Name saved" toast used to show even // when the storage write silently failed. return the_mesh.savePrefs(); @@ -84229,6 +85122,26 @@ void UITask::loop() { #if defined(HAS_TOUCH_UI) if (!g_lv.ready) return; rx24Sample(now); // packets heard per hour, for the lock screen's activity line + emojiFlushRecent(now, _last_input_ms); + +#if CAP_EMOJI_PACK + // Budgeted slices of the SD emoji pack. A full set is ~850 KB on a 4 MHz card, + // so it arrives a couple of seconds in; emoji render from the baked set until + // then. 8 KB is ~16 ms of SPI per tick, small enough not to show as a stutter. + if (emojiPackLoading() && emojiPackPump(8 * 1024)) { + emojiInvalidateMergedList(); + char msg[DIAG_COLS]; + if (emojiPackLoaded()) { + snprintf(msg, sizeof msg, "emoji: pack ready, %d added", emojiPackItemCount()); + g_lv.dm.list_sig = 0; + g_lv.dirty_threads = true; + g_lv.dirty_timeline = true; + } else { + snprintf(msg, sizeof msg, "emoji: pack rejected (bad file)"); + } + pushDiagLine(msg); + } +#endif #if CAP_TOUCH // The Tanmatsu has NO CHSC6x cap-touch — input comes from the bsp keypad (LVGL KEYPAD indev). @@ -84831,7 +85744,7 @@ void UITask::loop() { else if (cmdLineEnter()) break; // terminal / admin CLI: run it, keep the field ready else lv_event_send(g_lv.keyboard, LV_EVENT_READY, nullptr); // settings field: confirm } - else if (key == 0x08 || key == 0x7F) lv_textarea_del_char(akb_ta); + else if (key == 0x08 || key == 0x7F) taDeletePreviousGrapheme(akb_ta); // '#' summons the on-screen keys for this editing session (hideKb clears it), // opening straight on the symbol panel: the module already types letters and // digits, so the keys are only for symbols its 5x5 matrix cannot reach. @@ -84882,7 +85795,7 @@ void UITask::loop() { for (int i = 0; i < 64 && g_web_mirror.popKey(&wk); ++i) { if (!fta) continue; // no editable field focused -> drain + drop if (wk == 0x0D || wk == 0x0A) lv_event_send(g_lv.keyboard, LV_EVENT_READY, nullptr); - else if (wk == 0x08 || wk == 0x7F) lv_textarea_del_char(fta); + else if (wk == 0x08 || wk == 0x7F) taDeletePreviousGrapheme(fta); else if (wk >= 0x20) lv_textarea_add_char(fta, (uint32_t)wk); } #endif diff --git a/src/ui-touch/device_caps.h b/src/ui-touch/device_caps.h index b4c4793d..3d84935f 100644 --- a/src/ui-touch/device_caps.h +++ b/src/ui-touch/device_caps.h @@ -331,6 +331,17 @@ #define CAP_TILES_ON_STORAGE 0 #endif +// The optional emoji pack and its tab/recent picker need both removable SD and +// 8 MB PSRAM. Every enabled SD target below has an 8 MB PSRAM board definition; +// the regular Heltec V4 has only 2 MB and no SD, so both conditions exclude it. +#if CAP_SD && defined(BOARD_HAS_PSRAM) && \ + (defined(HAS_CROWPANEL_35) || defined(HAS_TDECK_PRO) || defined(HAS_TDECK_GT911) || \ + defined(TLORA_PAGER) || defined(HAS_THINKNODE_M9) || defined(HELTEC_LORA_V4_R8)) + #define CAP_EMOJI_PACK 1 +#else + #define CAP_EMOJI_PACK 0 +#endif + // Persisted, restart-to-apply UI-size selector. Large-screen boards already // expose it; the Pager, V4-R8, ThinkNode M9, T-Deck and T-Deck Pro / Max add // font-only presets because their compact viewports cannot safely take global diff --git a/src/ui-touch/emoji_data.c b/src/ui-touch/emoji_data.c index 4002d45f..1aefd28f 100644 --- a/src/ui-touch/emoji_data.c +++ b/src/ui-touch/emoji_data.c @@ -1,5 +1,6 @@ // AUTO-GENERATED by scripts/build/gen-emoji-font.py — do not edit. #include "emoji_data.h" +#include static const uint8_t e_zero[] = {0,0,0, 0,0,0, 0,0,0, 0,0,0}; static const lv_img_dsc_t d_zero = { { LV_IMG_CF_TRUE_COLOR_ALPHA, 0, 0, 2, 2 }, sizeof(e_zero), e_zero }; @@ -855,6 +856,10 @@ static const EmojiGlyph kGlyphs[] = { { 0x1F9D0u, &d_1f9d0 }, { 0x1F9E1u, &d_1f9e1 }, }; +typedef struct { const char* utf8; const lv_img_dsc_t* dsc; } EmojiSequence; +static const EmojiSequence kSequences[] = { + { "\xF0\x9F\x8F\xB3\xEF\xB8\x8F\xE2\x80\x8D\xE2\x9A\xA7\xEF\xB8\x8F", &d_1f3f3 }, +}; const uint16_t kEmojiGlyphCount = 280; const lv_img_dsc_t* emojiGlyphLookup(uint32_t cp) { @@ -867,3 +872,10 @@ const lv_img_dsc_t* emojiGlyphLookup(uint32_t cp) { } return 0; } + +const lv_img_dsc_t* emojiGlyphSequenceLookup(const char* utf8) { + if (!utf8) return 0; + for (size_t i = 0; i < sizeof(kSequences) / sizeof(kSequences[0]); ++i) + if (strcmp(utf8, kSequences[i].utf8) == 0) return kSequences[i].dsc; + return 0; +} diff --git a/src/ui-touch/emoji_data.h b/src/ui-touch/emoji_data.h index 8c8a0949..fd865082 100644 --- a/src/ui-touch/emoji_data.h +++ b/src/ui-touch/emoji_data.h @@ -7,6 +7,8 @@ extern "C" { #endif // Returns the baked image for `cp`, or NULL if we have no glyph for it. const lv_img_dsc_t* emojiGlyphLookup(uint32_t cp); +// Returns a baked composite image for an exact UTF-8 emoji sequence, or NULL. +const lv_img_dsc_t* emojiGlyphSequenceLookup(const char* utf8); extern const uint16_t kEmojiGlyphCount; #ifdef __cplusplus } diff --git a/test/emoji_picker_scroll/repro.c b/test/emoji_picker_scroll/repro.c new file mode 100644 index 00000000..0488a816 --- /dev/null +++ b/test/emoji_picker_scroll/repro.c @@ -0,0 +1,58 @@ +#include "lvgl.h" +#include +#include + +static lv_color_t draw_pixels[320 * 40]; + +static void flush_cb(lv_disp_drv_t *driver, const lv_area_t *area, lv_color_t *pixels) +{ + (void)area; + (void)pixels; + lv_disp_flush_ready(driver); +} + +int main(int argc, char **argv) +{ + const int broken = argc > 1 && strcmp(argv[1], "null") == 0; + lv_init(); + lv_disp_draw_buf_t draw_buffer; + lv_disp_draw_buf_init(&draw_buffer, draw_pixels, NULL, 320 * 40); + lv_disp_drv_t driver; + lv_disp_drv_init(&driver); + driver.hor_res = 320; + driver.ver_res = 240; + driver.draw_buf = &draw_buffer; + driver.flush_cb = flush_cb; + lv_disp_drv_register(&driver); + + static const lv_style_prop_t no_transition_props[] = { (lv_style_prop_t)0 }; + static lv_style_transition_dsc_t no_transition; + lv_style_transition_dsc_init(&no_transition, no_transition_props, NULL, 0, 0, NULL); + lv_obj_t *grid = lv_obj_create(lv_scr_act()); + lv_obj_set_size(grid, 300, 180); + lv_obj_set_flex_flow(grid, LV_FLEX_FLOW_ROW_WRAP); + lv_obj_set_scroll_dir(grid, LV_DIR_VER); + for(int index = 0; index < 60; ++index) { + lv_obj_t *cell = lv_btn_create(grid); + lv_obj_set_size(cell, 38, 38); + lv_obj_set_style_bg_color(cell, lv_color_hex(0x303030), LV_PART_MAIN); + lv_obj_set_style_bg_color(cell, lv_color_hex(0x505050), LV_PART_MAIN | LV_STATE_PRESSED); + lv_obj_set_style_transform_width(cell, 0, LV_PART_MAIN | LV_STATE_PRESSED); + lv_obj_set_style_transform_height(cell, 0, LV_PART_MAIN | LV_STATE_PRESSED); + lv_obj_set_style_transition(cell, broken ? NULL : &no_transition, LV_PART_MAIN); + } + lv_obj_update_layout(grid); + for(int index = 0; index < 60; ++index) { + lv_obj_t *cell = lv_obj_get_child(grid, index); + lv_obj_add_state(cell, LV_STATE_PRESSED); + lv_obj_scroll_by(grid, 0, -4, LV_ANIM_OFF); + lv_obj_clear_state(cell, LV_STATE_PRESSED); + lv_tick_inc(20); + lv_timer_handler(); + if(lv_obj_get_width(cell) != 38 || lv_obj_get_height(cell) != 38 || + lv_obj_get_style_transform_width(cell, LV_PART_MAIN) != 0 || + lv_obj_get_style_transform_height(cell, LV_PART_MAIN) != 0) return 1; + } + puts("ok: 60 cell press/scroll/release cycles, unchanged cell dimensions"); + return 0; +} \ No newline at end of file diff --git a/test/emoji_picker_scroll/run.sh b/test/emoji_picker_scroll/run.sh new file mode 100644 index 00000000..cf210bb5 --- /dev/null +++ b/test/emoji_picker_scroll/run.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/../.." && pwd)" +lvgl="${1:-$root/.pio/libdeps/LilyGo_TDeck_companion_radio_touch/lvgl}" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +cc="${CC:-clang}" +flags=(-g -O1 -w -fsanitize=address -DLV_CONF_INCLUDE_SIMPLE -I"$root/test/lvgl_anim_uaf" -I"$lvgl") +mkdir -p "$work/obj" +jobs="$(sysctl -n hw.ncpu 2>/dev/null || echo 4)" +export CC_CMD="$cc -c ${flags[*]}" OBJ_DIR="$work/obj" +find "$lvgl/src" -name '*.c' -print0 | + xargs -0 -P "$jobs" -I{} sh -c \ + '$CC_CMD "$1" -o "$OBJ_DIR/$(printf %s "$1" | cksum | cut -d" " -f1).o"' _ {} +"$cc" "${flags[@]}" "$here/repro.c" "$work"/obj/*.o -o "$work/repro" +export ASAN_OPTIONS=detect_leaks=0:abort_on_error=0 +if "$work/repro" null > "$work/null.txt" 2>&1; then + echo "FAIL: null transition did not reproduce the crash" + exit 1 +fi +if ! grep -q 'lv_obj_set_state' "$work/null.txt"; then + cat "$work/null.txt" + exit 1 +fi +echo "ok: null transition reproduces the state-change crash" +"$work/repro" \ No newline at end of file