Emoji picker (Super+.): search, tabs, skin tones, recents, text-input-v3 insertion
CI / test (push) Canceled after 0s

Compositor-drawn Win+. style picker. The focused app keeps keyboard focus so
its text-input-v3 field stays enabled; the emoji goes in with commit_string,
or onto the clipboard with a visible notice when the app has no text field.
Shortcut lives in the shortcut table (rebindable in Settings > Shortcuts).

- compositor/wayland/text_input.mbt: zwp_text_input_manager_v3 (global 12)
- compositor/emoji: Emoji 18.0 + CLDR 49 data (Unicode License), search,
  picker model, CBDT/CBLC + GSUB reader for Noto Color Emoji
- Chandra's own pinned bitmap Noto Color Emoji (scripts/fetch-emoji-font.sh,
  just emoji-font); Fedora's COLRv1 copy can't be drawn. Missing font shows
  an error panel.
- raster WIT: emoji-font, emoji-has, emoji-image; served by wasmhost
- state.edn :emoji {:recent [...] :skin-tone n}
- tests incl. a fake text-input client; docs/emoji-picker.md

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hkABDGJixotaqFv2X2
This commit is contained in:
Claude committed 2026-11-26 07:00:22 +00:00
1 parent 738928352e
commit 27252a97ab
39 files changed
+4942 -41

No files matched your search

File diff suppressed because it is too large. Load diff
+188
View File
@@ -0,0 +1,188 @@
///| The emoji picker's data: every emoji of Unicode Emoji 18.0 in CLDR order, with its name and
/// CLDR search keywords (data.mbt, made by scripts/gen-emoji-data.py), and searching it.
///
/// Skin tone variants are not listed on their own: an emoji that takes a skin tone carries its
/// five variants (light .. dark), and the picker's skin tone choice picks one.
///| One emoji the picker lists.
pub(all) struct Emoji {
/// 1 Smileys .. 9 Flags (the picker's tab; 0 is Recent).
tab : Int
text : String
name : String
/// `name` in lower case, for searching.
lower : String
keywords : Array[String]
/// Empty, or the five skin tone variants, light to dark.
tones : Array[String]
}
///| The picker's tabs: their names and the emoji drawn on each.
pub let tab_names : Array[String] = [
"Recent", "Smileys", "People", "Animals", "Food", "Activities", "Travel", "Objects", "Symbols", "Flags",
]
///|
pub let tab_icons : Array[String] = [
"🕘", "😀", "👋", "🐻", "🍔", "⚽", "🚗", "💡", "🔣", "🏁",
]
///| Names of the skin tone choices: 0 is the default yellow, 1-5 light to dark.
pub let tone_names : Array[String] = [
"Default skin tone", "Light skin tone", "Medium-light skin tone", "Medium skin tone",
"Medium-dark skin tone", "Dark skin tone",
]
///| A hand in each skin tone, for the skin tone choice.
pub let tone_swatches : Array[String] = ["✋", "✋🏻", "✋🏼", "✋🏽", "✋🏾", "✋🏿"]
///|
let parsed : Array[Emoji] = []
///|
fn words(s : StringView) -> Array[String] {
let out : Array[String] = []
for w in s.split(" ") {
if w.length() > 0 {
out.push(w.to_string())
}
}
out
}
///| Every emoji, in picker order (parsed on first use).
pub fn all() -> Array[Emoji] {
if parsed.length() == 0 {
for line in emoji_data.split("\n") {
let f : Array[StringView] = line.split("\t").collect()
if f.length() != 5 {
abort("emoji data: bad line: " + line.to_string())
}
let tab = match f[0].to_string() {
"0" => 1
"1" => 2
"2" => 3
"3" => 4
"4" => 5
"5" => 6
"6" => 7
"7" => 8
"8" => 9
t => abort("emoji data: bad tab " + t)
}
parsed.push({
tab,
text: f[1].to_string(),
name: f[2].to_string(),
lower: f[2].to_string().to_lower(),
keywords: words(f[3]),
tones: words(f[4]),
})
}
}
parsed
}
///| `e` in skin tone `tone` (0 default, 1-5 light to dark); `e` itself when it takes no tone.
pub fn Emoji::toned(self : Emoji, tone : Int) -> String {
if tone >= 1 && tone <= 5 && self.tones.length() == 5 {
self.tones[tone - 1]
} else {
self.text
}
}
///| The emoji whose text (or one of whose skin tone variants) is `text`: its index in `all()` and
/// the tone (0 for the plain one).
pub fn find(text : String) -> (Int, Int)? {
let es = all()
for i, e in es {
if e.text == text {
return Some((i, 0))
}
for t, v in e.tones {
if v == text {
return Some((i, t + 1))
}
}
}
None
}
///| A word of a name without the punctuation around it.
fn bare(w : StringView) -> String {
w.trim_start(chars="(\"").trim_end(chars=")\":,").to_string()
}
///| How well one query word matches an emoji: lower is better, None when it doesn't.
fn word_score(e : Emoji, q : String) -> Int? {
if e.lower == q {
return Some(0)
}
let name_words = e.lower.split(" ")
for w in name_words {
if bare(w) == q {
return Some(1)
}
}
if e.lower.has_prefix(q) {
return Some(2)
}
for w in name_words {
if bare(w).has_prefix(q) {
return Some(3)
}
}
for k in e.keywords {
if k == q {
return Some(4)
}
}
for k in e.keywords {
if k.has_prefix(q) {
return Some(5)
}
}
if q.length() >= 3 && e.lower.contains(q) {
return Some(6)
}
None
}
///| The emoji matching `query`, best first: every word of the query must start a word of the
/// emoji's name or keywords (or, from three letters on, appear in its name). Case doesn't
/// matter, and a leading ':' (as in ":smile") is skipped. Only emoji `keep` accepts are listed.
pub fn search(query : String, keep? : (Int) -> Bool = _ => true) -> Array[Int] {
let q = query.to_lower().trim(chars=" ").to_string()
let q = if q.has_prefix(":") { q.trim_start(chars=":").to_string() } else { q }
let qs = words(q)
if qs.length() == 0 {
return []
}
let scored : Array[(Int, Int, Int)] = []
for i, e in all() {
let mut total = 0
let mut ok = true
for w in qs {
match word_score(e, w) {
Some(s) => total = total + s
None => {
ok = false
break
}
}
}
if ok && keep(i) {
scored.push((total, e.name.length(), i))
}
}
// Best score first; then shorter names ("red heart" before "sparkling heart"); then CLDR order.
scored.sort_by((a, b) => if a.0 != b.0 {
a.0.compare(b.0)
} else if a.1 != b.1 {
a.1.compare(b.1)
} else {
a.2.compare(b.2)
})
scored.map(s => s.2)
}
+44
View File
@@ -0,0 +1,44 @@
///|
test "the data lists every tab, in CLDR order, with skin tone variants" {
let es = @emoji.all()
assert_true(es.length() > 1800)
assert_eq(es[0].text, "😀")
assert_eq(es[0].name, "grinning face")
assert_eq(es[0].tab, 1)
for t = 1; t <= 9; t = t + 1 {
assert_true(es.iter().any(e => e.tab == t))
}
// Tabs come in order.
for i = 1; i < es.length(); i = i + 1 {
assert_true(es[i - 1].tab <= es[i].tab)
}
let (wave, tone) = @emoji.find("👋").unwrap()
assert_eq(tone, 0)
assert_eq(es[wave].toned(3), "👋🏽")
assert_eq(@emoji.find("👋🏿"), Some((wave, 5)))
// An emoji without skin tones stays as it is.
assert_eq(es[0].toned(4), "😀")
// Two people: both get the tone.
let (hands, _) = @emoji.find("🧑‍🤝‍🧑").unwrap()
assert_eq(es[hands].toned(1), "🧑🏻‍🤝‍🧑🏻")
}
///|
test "search: names first, then keywords; every word must match" {
let es = @emoji.all()
let first = fn(q : String) { es[@emoji.search(q)[0]].text }
assert_eq(first("grinning face"), "😀")
assert_eq(first("thumbs up"), "👍")
assert_eq(first(":heart"), "❤️")
assert_eq(first("PIZZA"), "🍕")
// A keyword: "lol" is not in any name.
assert_true(@emoji.search("lol").map(i => es[i].text).contains("😂"))
// Every word has to match something.
assert_eq(@emoji.search("pizza unicorn"), [])
assert_eq(@emoji.search(" "), [])
// Flags by country name.
assert_eq(first("germany"), "🇩🇪")
// A filter leaves emoji out.
let no_pizza = @emoji.search("pizza", keep=i => es[i].text != "🍕")
assert_false(no_pizza.map(i => es[i].text).contains("🍕"))
}
+512
View File
@@ -0,0 +1,512 @@
///| Colour emoji from a CBDT/CBLC font (Noto Color Emoji): the picture for an emoji sequence.
///
/// stb_truetype (which draws Chandra's text) only knows outlines, and Noto Color Emoji has none:
/// each emoji is a PNG in the font's CBDT table, found through its CBLC index. Sequences (skin
/// tones, families, flags, keycaps) become one glyph through the font's GSUB ligatures; the font
/// has no glyph for U+FE0F, so it is left out before looking up. Checked against HarfBuzz on every
/// emoji of Emoji 18.0 with Noto Color Emoji 2.047 and 2.051: the same glyph for each one the
/// font has.
///
/// This runs where the font file is (the native compositor, or the wasm host); the picker only
/// gets the pictures.
///| Chandra's own copy of Noto Color Emoji (the bitmap edition, fetched by
/// scripts/fetch-emoji-font.sh), relative to the working directory: the checkout, or
/// /usr/local/share/chandra once installed. CHANDRA_EMOJI_FONT names another CBDT font.
///
/// Not the system's: distributions ship different editions, and Fedora's (and Google Fonts')
/// Noto Color Emoji is COLRv1, vector paint graphs this reader doesn't draw.
pub let font_path : String = "assets/fonts/NotoColorEmoji.ttf"
///| What to tell someone whose emoji font is missing or unreadable.
pub fn missing_font_message(env_path : String) -> String {
if env_path.length() > 0 {
"CHANDRA_EMOJI_FONT=" + env_path + " can't be read as a bitmap (CBDT) colour emoji font. " +
"Unset it to use Chandra's own Noto Color Emoji."
} else {
"Chandra's emoji font is missing: " + font_path + " (Noto Color Emoji, bitmap edition). " +
"Run `just install` (or `just emoji-font` in a checkout), then press Super+. again."
}
}
///| A table of the font: offset and length.
priv struct Table {
off : Int
len : Int
}
///| One bitmap index range of the CBLC strike.
priv struct IndexRange {
first : Int
last : Int
/// Offset of its index subtable in the file.
sub : Int
}
///| A parsed colour emoji font.
pub struct EmojiFont {
data : Bytes
/// cmap format 12 groups: (first code point, last, first glyph).
priv groups : Array[(Int, Int, Int)]
/// GSUB ligature lookups, in lookup order: first glyph -> (rest of the glyphs, ligature glyph),
/// in the font's order of preference.
priv ligatures : Array[Map[Int, Array[(Array[Int], Int)]]]
priv ranges : Array[IndexRange]
priv cbdt : Int
/// The strike's pixels per em.
ppem : Int
}
///| Why a font can't be used.
pub(all) suberror EmojiFontError {
EmojiFontError(String)
} derive(Show)
///|
fn u8(b : Bytes, o : Int) -> Int raise EmojiFontError {
if o < 0 || o >= b.length() {
raise EmojiFontError("read past the end of the font at " + o.to_string())
}
b[o].to_int()
}
///|
fn u16(b : Bytes, o : Int) -> Int raise EmojiFontError {
(u8(b, o) << 8) | u8(b, o + 1)
}
///|
fn u32(b : Bytes, o : Int) -> Int raise EmojiFontError {
(u16(b, o) << 16) | u16(b, o + 2)
}
///|
fn tag_at(b : Bytes, o : Int) -> String raise EmojiFontError {
let sb = StringBuilder::new()
for i = 0; i < 4; i = i + 1 {
sb.write_char(Int::unsafe_to_char(u8(b, o + i)))
}
sb.to_string()
}
///| Glyphs a coverage table lists, in coverage index order.
fn coverage(b : Bytes, o : Int) -> Array[Int] raise EmojiFontError {
let out : Array[Int] = []
match u16(b, o) {
1 => {
let n = u16(b, o + 2)
for i = 0; i < n; i = i + 1 {
out.push(u16(b, o + 4 + i * 2))
}
}
2 => {
let n = u16(b, o + 2)
for i = 0; i < n; i = i + 1 {
let r = o + 4 + i * 6
for g = u16(b, r); g <= u16(b, r + 2); g = g + 1 {
out.push(g)
}
}
}
f => raise EmojiFontError("GSUB coverage format " + f.to_string() + " is unknown")
}
out
}
///| A ligature substitution subtable (GSUB lookup type 4) into `into`.
fn read_ligatures(b : Bytes, o : Int, into : Map[Int, Array[(Array[Int], Int)]]) -> Unit raise EmojiFontError {
if u16(b, o) != 1 {
raise EmojiFontError("GSUB ligature subtable format " + u16(b, o).to_string() + " is unknown")
}
let firsts = coverage(b, o + u16(b, o + 2))
let nsets = u16(b, o + 4)
for s = 0; s < nsets && s < firsts.length(); s = s + 1 {
let set = o + u16(b, o + 6 + s * 2)
let nlig = u16(b, set)
let list = match into.get(firsts[s]) {
Some(l) => l
None => {
let l = []
into.set(firsts[s], l)
l
}
}
for l = 0; l < nlig; l = l + 1 {
let lo = set + u16(b, set + 2 + l * 2)
let glyph = u16(b, lo)
let ncomp = u16(b, lo + 2)
let rest : Array[Int] = []
for c = 1; c < ncomp; c = c + 1 {
rest.push(u16(b, lo + 4 + (c - 1) * 2))
}
list.push((rest, glyph))
}
}
}
///| Parse the font in `data`.
pub fn EmojiFont::parse(data : Bytes) -> EmojiFont raise EmojiFontError {
let b = data
let tables : Map[String, Table] = {}
let ntables = u16(b, 4)
for i = 0; i < ntables; i = i + 1 {
let r = 12 + i * 16
tables.set(tag_at(b, r), { off: u32(b, r + 8), len: u32(b, r + 12) })
}
fn need(name : String) -> Table raise EmojiFontError {
match tables.get(name) {
Some(t) => t
None => raise EmojiFontError("the font has no " + name + " table (not a bitmap (CBDT) colour emoji font)")
}
}
// cmap: the format 12 subtable (all of Unicode).
let cmap = need("cmap").off
let mut f12 = -1
for i = 0; i < u16(b, cmap + 2); i = i + 1 {
let r = cmap + 4 + i * 8
let sub = cmap + u32(b, r + 4)
if u16(b, sub) == 12 {
f12 = sub
}
}
if f12 < 0 {
raise EmojiFontError("the font's cmap has no format 12 subtable (emoji past U+FFFF)")
}
let groups : Array[(Int, Int, Int)] = []
for i = 0; i < u32(b, f12 + 12); i = i + 1 {
let g = f12 + 16 + i * 12
groups.push((u32(b, g), u32(b, g + 4), u32(b, g + 8)))
}
// GSUB: every ligature lookup (type 4, or type 7 extensions of it), in order.
let ligatures : Array[Map[Int, Array[(Array[Int], Int)]]] = []
match tables.get("GSUB") {
Some(t) => {
let lookups = t.off + u16(b, t.off + 8)
for i = 0; i < u16(b, lookups); i = i + 1 {
let lk = lookups + u16(b, lookups + 2 + i * 2)
let kind = u16(b, lk)
let nsub = u16(b, lk + 4)
let m : Map[Int, Array[(Array[Int], Int)]] = {}
for s = 0; s < nsub; s = s + 1 {
let st = lk + u16(b, lk + 6 + s * 2)
if kind == 4 {
read_ligatures(b, st, m)
} else if kind == 7 && u16(b, st + 2) == 4 {
read_ligatures(b, st + u32(b, st + 4), m)
}
}
if m.size() > 0 {
ligatures.push(m)
}
}
}
None => ()
}
// CBLC: the biggest strike's index ranges.
let cblc = need("CBLC").off
let cbdt = need("CBDT").off
let nsizes = u32(b, cblc + 4)
if nsizes == 0 {
raise EmojiFontError("the font's CBLC table has no bitmap sizes")
}
let mut best = cblc + 8
for i = 1; i < nsizes; i = i + 1 {
let s = cblc + 8 + i * 48
if u8(b, s + 45) > u8(b, best + 45) {
best = s
}
}
let arr = cblc + u32(b, best)
let ranges : Array[IndexRange] = []
for i = 0; i < u32(b, best + 8); i = i + 1 {
let r = arr + i * 8
ranges.push({ first: u16(b, r), last: u16(b, r + 2), sub: arr + u32(b, r + 4) })
}
{ data, groups, ligatures, ranges, cbdt, ppem: u8(b, best + 45) }
}
///| The glyph for code point `cp`, 0 when the font has none.
fn EmojiFont::glyph(self : EmojiFont, cp : Int) -> Int {
let mut lo = 0
let mut hi = self.groups.length() - 1
while lo <= hi {
let mid = (lo + hi) / 2
let (a, z, g) = self.groups[mid]
if cp < a {
hi = mid - 1
} else if cp > z {
lo = mid + 1
} else {
return g + (cp - a)
}
}
0
}
///| The glyphs `text` shapes to: its code points' glyphs (U+FE0F left out) with the ligatures
/// applied. Empty when the font lacks one of its code points.
pub fn EmojiFont::shape(self : EmojiFont, text : String) -> Array[Int] {
let mut gs : Array[Int] = []
for c in text {
if c.to_int() == 0xFE0F {
continue
}
let g = self.glyph(c.to_int())
if g == 0 {
return []
}
gs.push(g)
}
for lk in self.ligatures {
let out : Array[Int] = []
let mut i = 0
while i < gs.length() {
let mut used = 1
let mut put = gs[i]
match lk.get(gs[i]) {
Some(ligs) =>
for l in ligs {
let (rest, glyph) = l
if i + 1 + rest.length() <= gs.length() {
let mut ok = true
for k, r in rest {
if gs[i + 1 + k] != r {
ok = false
break
}
}
if ok {
used = 1 + rest.length()
put = glyph
break
}
}
}
None => ()
}
out.push(put)
i = i + used
}
gs = out
}
gs
}
///| The PNG the font has for glyph `g`, None when it has no bitmap for it.
fn EmojiFont::glyph_png(self : EmojiFont, g : Int) -> Bytes? raise EmojiFontError {
let b = self.data
for r in self.ranges {
if g < r.first || g > r.last {
continue
}
let sub = r.sub
let index_format = u16(b, sub)
let image_format = u16(b, sub + 2)
let data_off = self.cbdt + u32(b, sub + 4)
let i = g - r.first
let (at, len) : (Int, Int) = match index_format {
1 => {
let a = u32(b, sub + 8 + i * 4)
(data_off + a, u32(b, sub + 8 + (i + 1) * 4) - a)
}
2 => {
let size = u32(b, sub + 8)
(data_off + i * size, size)
}
3 => {
let a = u16(b, sub + 8 + i * 2)
(data_off + a, u16(b, sub + 8 + (i + 1) * 2) - a)
}
4 => {
let n = u32(b, sub + 8)
let mut found = (-1, 0)
for k = 0; k < n; k = k + 1 {
let e = sub + 12 + k * 4
if u16(b, e) == g {
let a = u16(b, e + 2)
found = (data_off + a, u16(b, e + 6) - a)
break
}
}
found
}
5 => {
let size = u32(b, sub + 8)
let n = u32(b, sub + 20)
let mut found = (-1, 0)
for k = 0; k < n; k = k + 1 {
if u16(b, sub + 24 + k * 2) == g {
found = (data_off + k * size, size)
break
}
}
found
}
f => raise EmojiFontError("CBLC index format " + f.to_string() + " is unknown")
}
if at < 0 || len <= 0 {
return None
}
let png_at = match image_format {
17 => at + 9 // small metrics (5) + data length (4)
18 => at + 12 // big metrics (8) + data length (4)
19 => at + 4
f => raise EmojiFontError("CBDT image format " + f.to_string() + " is not PNG")
}
let png_len = u32(b, png_at - 4)
if png_at + png_len > b.length() {
raise EmojiFontError("a CBDT image runs past the end of the font")
}
return Some(b[png_at:png_at + png_len].to_bytes())
}
None
}
///| Whether the font has one picture for all of `text`.
pub fn EmojiFont::has(self : EmojiFont, text : String) -> Bool raise EmojiFontError {
let gs = self.shape(text)
gs.length() == 1 && self.glyph_png(gs[0]) is Some(_)
}
///| The picture for `text`, `px` x `px` (the bitmap scaled to fit and centred), straight RGBA.
/// None when the font has no single picture for it.
pub fn EmojiFont::picture(self : EmojiFont, text : String, px : Int) -> @renderer.Pixmap? raise EmojiFontError {
let gs = self.shape(text)
if gs.length() != 1 || px <= 0 {
return None
}
match self.glyph_png(gs[0]) {
None => None
Some(png) =>
match @renderer.decode_png(png) {
None => raise EmojiFontError("the font's picture for " + text + " is not a PNG Chandra can read")
Some(p) => Some(fit_square(p, px))
}
}
}
///| `p` scaled (area average, alpha weighted) to fit a `px` x `px` square, centred.
pub fn fit_square(p : @renderer.Pixmap, px : Int) -> @renderer.Pixmap {
let out = @renderer.Pixmap::new(px, px)
let side = if p.width > p.height { p.width } else { p.height }
let dw = (p.width * px + side / 2) / side
let dh = (p.height * px + side / 2) / side
let ox = (px - dw) / 2
let oy = (px - dh) / 2
for y = 0; y < dh; y = y + 1 {
let sy0 = y * p.height / dh
let sy1 = ((y + 1) * p.height / dh).max(sy0 + 1)
for x = 0; x < dw; x = x + 1 {
let sx0 = x * p.width / dw
let sx1 = ((x + 1) * p.width / dw).max(sx0 + 1)
let mut r = 0
let mut g = 0
let mut bl = 0
let mut a = 0
let mut n = 0
for sy = sy0; sy < sy1; sy = sy + 1 {
for sx = sx0; sx < sx1; sx = sx + 1 {
let o = (sy * p.width + sx) * 4
let al = p.data[o + 3].to_int()
r = r + p.data[o].to_int() * al
g = g + p.data[o + 1].to_int() * al
bl = bl + p.data[o + 2].to_int() * al
a = a + al
n = n + 1
}
}
let o = ((oy + y) * px + ox + x) * 4
if a > 0 {
out.data[o] = (r / a).to_byte()
out.data[o + 1] = (g / a).to_byte()
out.data[o + 2] = (bl / a).to_byte()
out.data[o + 3] = (a / n).to_byte()
}
}
}
out
}
///| The colour emoji font as the renderer uses it: opened on first use, pictures made once per
/// emoji and size. The native compositor's renderer and the wasm host each keep one.
pub struct EmojiSource {
priv mut state : Result[(String, EmojiFont), String]?
priv images : Map[String, UInt]
}
///|
pub fn EmojiSource::new() -> EmojiSource {
{ state: None, images: {} }
}
///| Open the font: CHANDRA_EMOJI_FONT when set, else the first of `font_paths` that parses.
/// The path, or what to tell the user. Logged once.
pub fn EmojiSource::font(self : EmojiSource) -> Result[String, String] {
let st = match self.state {
Some(s) => s
None => {
let env = @sys.getenv("CHANDRA_EMOJI_FONT")
let p = if env.length() > 0 { env } else { font_path }
let data = @sys.read_file_bytes(p)
let found : Result[(String, EmojiFont), String] = if data.length() == 0 {
Err(missing_font_message(env))
} else {
match (try Ok(EmojiFont::parse(data)) catch { e => Err(e) }) {
Ok(f) => Ok((p, f))
Err(EmojiFontError(why)) => Err(p + ": " + why + ". " + missing_font_message(env))
}
}
match found {
Ok((p, f)) => @sys.log("emoji: " + p + " (" + f.ppem.to_string() + " px pictures)")
Err(m) => @sys.log("emoji: " + m)
}
self.state = Some(found)
found
}
}
match st {
Ok((p, _)) => Ok(p)
Err(m) => Err(m)
}
}
///| For each of `texts`, whether the font has one picture for it (all false without a font).
pub fn EmojiSource::has(self : EmojiSource, texts : Array[String]) -> Array[Bool] {
ignore(self.font())
match self.state {
Some(Ok((_, f))) =>
texts.map(t => try f.has(t) catch {
EmojiFontError(why) => {
// A damaged font: say so for each emoji it can't index.
@sys.log("emoji: can't look up " + t + " in the font: " + why)
false
}
})
_ => texts.map(_ => false)
}
}
///| The picture for `text` at `px`, registered with `put` (the renderer's image store): its
/// handle, 0 when the font has none. A picture that can't be decoded is logged and gives 0.
pub fn EmojiSource::image(self : EmojiSource, text : String, px : Int, put : (@renderer.Pixmap) -> UInt) -> UInt {
let key = px.to_string() + " " + text
match self.images.get(key) {
Some(h) => return h
None => ()
}
ignore(self.font())
let h = match self.state {
Some(Ok((_, f))) =>
match (try Ok(f.picture(text, px)) catch { e => Err(e) }) {
Ok(Some(p)) => put(p)
Ok(None) => 0U
Err(EmojiFontError(why)) => {
@sys.log("emoji: no picture for " + text + ": " + why)
0U
}
}
_ => 0U
}
self.images.set(key, h)
h
}
+70
View File
@@ -0,0 +1,70 @@
///| Chandra's own copy (scripts/fetch-emoji-font.sh; `just test` fetches it).
let test_font : String = @emoji.font_path
///|
fn open_font() -> @emoji.EmojiFont {
let data = @sys.read_file_bytes(test_font)
if data.length() == 0 {
abort("font_test needs Noto Color Emoji at " + test_font + ": run scripts/fetch-emoji-font.sh")
}
@emoji.EmojiFont::parse(data) catch {
e => abort("Noto Color Emoji didn't parse: " + Show::to_string(e))
}
}
///|
test "Noto Color Emoji: the same emoji as HarfBuzz finds" {
let f = open_font()
assert_eq(f.ppem, 109)
// Counted with HarfBuzz (uharfbuzz) on Noto Color Emoji 2.051: of the 1923 listed emoji the
// font draws 1914 (some Emoji 17/18 additions are missing), and 1650 skin tone variants.
let mut base = 0
let mut tones = 0
for e in @emoji.all() {
if f.has(e.text) {
base = base + 1
}
for t in e.tones {
if f.has(t) {
tones = tones + 1
}
}
}
assert_eq(base, 1914)
assert_eq(tones, 1650)
// Ligatures: a family, a keycap, a flag and a skin tone are one picture each.
for s in ["👨‍👩‍👧‍👦", "#️⃣", "🇩🇪", "👍🏽", "🏴‍☠️", "🏴󠁧󠁢󠁳󠁣󠁴󠁿"] {
assert_eq(f.shape(s).length(), 1)
assert_true(f.has(s))
}
// Text the font can't draw as one picture.
assert_false(f.has("ab"))
let cracking = @emoji.all().filter(e => e.name == "cracking face")[0]
assert_false(f.has(cracking.text)) // Emoji 18.0, newer than this font
}
///|
test "pictures are scaled to a square, centred, with transparent corners" {
let f = open_font()
let p = f.picture("😀", 32).unwrap()
assert_eq(p.width, 32)
assert_eq(p.height, 32)
// The corner is transparent, the middle of the face is opaque yellow.
assert_eq(p.data[3].to_int(), 0)
let o = (16 * 32 + 16) * 4
assert_eq(p.data[o + 3].to_int(), 255)
assert_true(p.data[o].to_int() > 200 && p.data[o + 1].to_int() > 150 && p.data[o + 2].to_int() < 100)
assert_true(f.picture("ab", 32) is None)
}
///|
test "a file that is not a colour emoji font is an error that says why" {
let msg = try {
ignore(@emoji.EmojiFont::parse(b"\x00\x01\x00\x00\x00\x00"))
"parsed"
} catch {
e => Show::to_string(e)
}
assert_true(msg.contains("no cmap table"))
assert_true(@emoji.missing_font_message("").contains("just install"))
}
+9
View File
@@ -0,0 +1,9 @@
import {
"moonbitlang/core/builtin",
"chandra/desktop/compositor/renderer" @renderer,
"chandra/desktop/compositor/sys" @sys,
}
supported_targets = "+native+wasm"
warnings = "-44"
+235
View File
@@ -0,0 +1,235 @@
///| The emoji picker's state and keys, without drawing (compositor/host/emoji_picker.mbt draws it
/// and feeds it keys and clicks).
///
/// What is shown: the search results when something is typed, else the chosen tab (Recent, or
/// one category). The selection moves over a grid of `cols` columns; `scroll` is the first row
/// shown, kept so the selection stays in view.
///| The most recently used emoji kept.
pub let max_recent : Int = 40
///| What the picker shows in one cell: the emoji's index in `all()` and the text it inserts.
pub(all) struct Item {
index : Int
text : String
} derive(Eq, Show)
///| What a key asks the picker to do.
pub(all) enum Key {
/// A typed character goes into the search.
Type(Char)
Backspace
Left
Right
Up
Down
PageUp
PageDown
Home
End
NextTab
PrevTab
/// Ctrl+Right / Ctrl+Left: the next / previous skin tone.
NextTone
PrevTone
/// Enter: insert the selected emoji (and close; with Shift, stay open).
Choose
} derive(Eq, Show)
///| The picker.
pub(all) struct Picker {
mut query : String
/// 0 Recent, 1-9 the categories (`tab_names`).
mut tab : Int
/// The selected cell among `items()`.
mut sel : Int
/// The first grid row shown.
mut scroll : Int
/// 0 default, 1-5 light to dark.
mut tone : Int
/// Emoji inserted lately, newest first, as inserted (skin tone included).
recents : Array[String]
mut cols : Int
mut rows : Int
/// Whether an emoji (index into `all()`) can be shown; emoji the font can't draw are left out.
has : (Int) -> Bool
/// What `items()` returned last, until the query, tab or tone changes.
priv mut cache : Array[Item]?
}
///| A picker on `recents` (newest first) and skin tone `tone`. It opens on Recent when there are
/// recent emoji, else on Smileys.
pub fn Picker::new(
recents : Array[String],
tone : Int,
has? : (Int) -> Bool = _ => true,
cols? : Int = 9,
rows? : Int = 6,
) -> Picker {
let p : Picker = {
query: "",
tab: 0,
sel: 0,
scroll: 0,
tone: if tone >= 0 && tone <= 5 { tone } else { 0 },
recents: [],
cols,
rows,
has,
cache: None,
}
for r in recents {
if p.recents.length() < max_recent && find(r) is Some(_) && !p.recents.contains(r) {
p.recents.push(r)
}
}
p.tab = if p.shown_recents().length() > 0 { 0 } else { 1 }
p
}
///| The recent emoji the font can draw.
fn Picker::shown_recents(self : Picker) -> Array[Item] {
let out : Array[Item] = []
for r in self.recents {
match find(r) {
Some((i, _)) if (self.has)(i) => out.push({ index: i, text: r })
_ => ()
}
}
out
}
///| What is shown, in order.
pub fn Picker::items(self : Picker) -> Array[Item] {
match self.cache {
Some(c) => return c
None => ()
}
let es = all()
let out = if self.query.length() > 0 {
search(self.query, keep=self.has).map(i => { index: i, text: es[i].toned(self.tone) })
} else if self.tab == 0 {
self.shown_recents()
} else {
let a : Array[Item] = []
for i, e in es {
if e.tab == self.tab && (self.has)(i) {
a.push({ index: i, text: e.toned(self.tone) })
}
}
a
}
self.cache = Some(out)
out
}
///| The selected item, if anything is shown.
pub fn Picker::selected(self : Picker) -> Item? {
let items = self.items()
if self.sel >= 0 && self.sel < items.length() {
Some(items[self.sel])
} else {
None
}
}
///| Something changed what is shown: start again from the first item.
fn Picker::reset(self : Picker) -> Unit {
self.cache = None
self.sel = 0
self.scroll = 0
}
///| Show tab `t` (and clear the search).
pub fn Picker::set_tab(self : Picker, t : Int) -> Unit {
self.tab = (t % 10 + 10) % 10
self.query = ""
self.reset()
}
///| Use skin tone `t` from now on (0-5).
pub fn Picker::set_tone(self : Picker, t : Int) -> Unit {
self.tone = (t % 6 + 6) % 6
let sel = self.sel
let scroll = self.scroll
self.cache = None
self.sel = sel
self.scroll = scroll
}
///| Select item `i` (clamped) and scroll it into view.
pub fn Picker::select(self : Picker, i : Int) -> Unit {
let n = self.items().length()
self.sel = if n == 0 { 0 } else { i.max(0).min(n - 1) }
let row = self.sel / self.cols
if row < self.scroll {
self.scroll = row
} else if row >= self.scroll + self.rows {
self.scroll = row - self.rows + 1
}
}
///| Scroll by `rows` grid rows (the wheel), keeping the selection where it is.
pub fn Picker::scroll_by(self : Picker, rows : Int) -> Unit {
let total = (self.items().length() + self.cols - 1) / self.cols
self.scroll = (self.scroll + rows).min(total - self.rows).max(0)
}
///| Note that `text` was inserted: it goes first in the recent list.
pub fn Picker::used(self : Picker, text : String) -> Unit {
self.recents.retain(r => r != text)
self.recents.insert(0, text)
while self.recents.length() > max_recent {
ignore(self.recents.pop())
}
if self.query.length() == 0 && self.tab == 0 {
// The Recent tab changed under the selection.
self.cache = None
}
}
///| Do what `key` asks. Returns the emoji to insert for `Choose` (None when nothing is shown).
pub fn Picker::key(self : Picker, key : Key) -> String? {
match key {
Type(c) => {
self.query = self.query + c.to_string()
self.reset()
}
Backspace =>
if self.query.length() > 0 {
let cs = self.query.to_array()
ignore(cs.pop())
self.query = String::from_array(cs)
self.reset()
}
Left => self.select(self.sel - 1)
Right => self.select(self.sel + 1)
Up => if self.sel >= self.cols { self.select(self.sel - self.cols) }
Down => {
let n = self.items().length()
if self.sel + self.cols < n {
self.select(self.sel + self.cols)
} else if self.sel / self.cols < (n - 1) / self.cols {
// The last row is shorter: go to its last item.
self.select(n - 1)
}
}
PageUp => self.select(self.sel - self.cols * self.rows)
PageDown => self.select(self.sel + self.cols * self.rows)
Home => self.select(0)
End => self.select(self.items().length() - 1)
NextTab => self.set_tab(self.tab + 1)
PrevTab => self.set_tab(self.tab - 1)
NextTone => self.set_tone(self.tone + 1)
PrevTone => self.set_tone(self.tone - 1)
Choose =>
match self.selected() {
Some(it) => {
self.used(it.text)
return Some(it.text)
}
None => ()
}
}
None
}
+123
View File
@@ -0,0 +1,123 @@
///|
fn type_text(p : @emoji.Picker, s : String) -> Unit {
for c in s {
ignore(p.key(Type(c)))
}
}
///|
test "opens on Smileys without recents, on Recent with them" {
let p = @emoji.Picker::new([], 0)
assert_eq(p.tab, 1)
assert_eq(p.items()[0].text, "😀")
let q = @emoji.Picker::new(["🍕", "not an emoji", "👍🏽", "🍕"], 0)
assert_eq(q.tab, 0)
// Unknown text and repeats are dropped.
assert_eq(q.items().map(i => i.text), ["🍕", "👍🏽"])
}
///|
test "arrows move over the grid, rows scroll into view" {
let p = @emoji.Picker::new([], 0, cols=4, rows=2)
ignore(p.key(Right))
assert_eq(p.sel, 1)
ignore(p.key(Down))
assert_eq(p.sel, 5)
ignore(p.key(Down))
assert_eq(p.sel, 9)
assert_eq(p.scroll, 1) // row 2 shown in a 2-row grid starting at row 1
ignore(p.key(Up))
ignore(p.key(Up))
assert_eq(p.sel, 1)
assert_eq(p.scroll, 0)
ignore(p.key(Up)) // on the first row: stays
assert_eq(p.sel, 1)
ignore(p.key(Left))
ignore(p.key(Left))
assert_eq(p.sel, 0)
ignore(p.key(End))
assert_eq(p.sel, p.items().length() - 1)
ignore(p.key(Home))
assert_eq((p.sel, p.scroll), (0, 0))
ignore(p.key(PageDown))
assert_eq(p.sel, 8)
}
///|
test "Down on the row above a short last row goes to the last item" {
let p = @emoji.Picker::new([], 0, cols=4, rows=2)
type_text(p, "pizza") // a few results
let n = p.items().length()
assert_true(n >= 1)
p.select(0)
for _ in 0..<10 {
ignore(p.key(Down))
}
assert_eq(p.sel / 4, (n - 1) / 4)
}
///|
test "typing searches across every tab; Backspace and Tab clear it" {
let p = @emoji.Picker::new([], 0)
type_text(p, "pizz")
assert_eq(p.items()[0].text, "🍕")
assert_eq(p.key(Choose), Some("🍕"))
assert_eq(p.recents, ["🍕"])
for _ in 0..<4 {
ignore(p.key(Backspace))
}
assert_eq(p.query, "")
ignore(p.key(Backspace)) // nothing left: no harm
type_text(p, "zzzzqq")
assert_eq(p.items().length(), 0)
assert_eq(p.key(Choose), None)
ignore(p.key(NextTab))
assert_eq(p.query, "")
assert_eq(p.tab, 2)
ignore(p.key(PrevTab))
ignore(p.key(PrevTab))
assert_eq(p.tab, 0)
ignore(p.key(PrevTab)) // wraps to Flags
assert_eq(p.tab, 9)
assert_eq(p.items()[0].text, "🏁")
}
///|
test "skin tone applies to emoji that take one, and recents keep the tone they were used with" {
let p = @emoji.Picker::new([], 0)
type_text(p, "thumbs up")
assert_eq(p.selected().unwrap().text, "👍")
ignore(p.key(NextTone))
ignore(p.key(NextTone))
assert_eq(p.tone, 2)
assert_eq(p.selected().unwrap().text, "👍🏼")
assert_eq(p.key(Choose), Some("👍🏼"))
ignore(p.key(PrevTone))
ignore(p.key(PrevTone))
ignore(p.key(PrevTone)) // wraps to dark
assert_eq(p.tone, 5)
p.set_tab(0)
assert_eq(p.items().map(i => i.text), ["👍🏼"])
}
///|
test "recents: newest first, no repeats, at most max_recent" {
let p = @emoji.Picker::new([], 0)
let es = @emoji.all()
for i = 0; i < @emoji.max_recent + 5; i = i + 1 {
p.used(es[i].text)
}
p.used(es[3].text)
assert_eq(p.recents.length(), @emoji.max_recent)
assert_eq(p.recents[0], es[3].text)
assert_eq(p.recents.filter(r => r == es[3].text).length(), 1)
}
///|
test "emoji the font can't draw are not shown" {
let es = @emoji.all()
let p = @emoji.Picker::new([], 0, has=i => es[i].text != "😀")
assert_eq(p.items()[0].text, "😃")
type_text(p, "grinning face")
assert_false(p.items().map(i => i.text).contains("😀"))
}