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("😀"))
}
+15
View File
@@ -242,6 +242,13 @@ pub(all) struct ChandraCompositor {
/// and where pictures go ("" for ~/Pictures/Screenshots).
mut shot : ShotOverlay?
mut shot_toast : ShotToast?
/// The emoji picker while it is up (emoji_picker.mbt), keys whose release it swallows, and
/// which emoji the font can draw (asked once).
mut emoji_ui : EmojiUi?
emoji_swallow : Array[UInt]
mut emoji_cover : Array[Bool]?
/// Recent emoji (newest first) and skin tone, read from state.edn at the first Super+.
mut emoji_saved : (Array[String], Int)?
mut shot_request : (ShotMode, Int)?
mut rec_request : (ShotMode, Int)?
mut frames_built : Int
@@ -412,6 +419,10 @@ pub fn ChandraCompositor::new(
session_check_at: 0UL,
shot: None,
shot_toast: None,
emoji_ui: None,
emoji_swallow: [],
emoji_cover: None,
emoji_saved: None,
shot_request: None,
rec_request: None,
frames_built: 0,
@@ -1162,6 +1173,7 @@ fn ChandraCompositor::build_scene(
panel_ops.append(self.switcher_ops())
}
panel_ops.append(self.screenshot_ops())
panel_ops.append(self.emoji_ops())
panel_ops.append(self.face_window_ops())
panel_ops.append(self.auth_ops())
panel_ops.append(self.auth_notice_ops())
@@ -1944,6 +1956,9 @@ pub fn ChandraCompositor::handle_input(
}
_ => ()
}
if self.emoji_input(ev, time_ms) {
return
}
if self.screenshot_input(ev, time_ms) {
return
}
+629
View File
@@ -0,0 +1,629 @@
///| The emoji picker, like Windows' Win+.: Super+. (the "emoji-picker" shortcut) opens a panel
/// with a search field, category tabs, a grid of emoji and a skin tone choice. The chosen emoji
/// goes where the user was typing.
///
/// Drawn by the compositor, like the screenshot editor: it needs the keyboard while it is up,
/// colour emoji pictures (read from Noto Color Emoji on the host, @raster.emoji_image) and the
/// text-input protocol to type into the app, none of which a panel module has.
///
/// Keyboard: while the picker is up every key is its own (type to search, arrows move, Enter
/// inserts, Shift+Enter inserts and stays open, Tab / Shift+Tab change tabs, Ctrl+Left/Right the
/// skin tone, Esc closes); only modifier keys still reach the app, so its modifier state stays
/// right. Unlike the editor, the app keeps its keyboard focus (no wl_keyboard.leave), the way an
/// input method's popup works, so its text field stays active to receive the emoji.
///
/// Inserting: when the focused window has an enabled text input (zwp_text_input_v3), the emoji is
/// typed in with commit_string. Otherwise it is put on the clipboard and a notification says so
/// and why ("paste it with Ctrl+V"); Chandra doesn't press Ctrl+V for the app, which would do
/// something else in a terminal.
///
/// Recent emoji and the skin tone are kept in state.edn (`:emoji`).
///| Sizes: a grid cell, the emoji in it, the padding, the search field and tab row heights.
let ep_cell : Int = 40
///|
let ep_emoji : Int = 28
///|
let ep_pad : Int = 12
///|
let ep_bar : Int = 34
///|
let ep_cols : Int = 9
///|
let ep_rows : Int = 6
///| What a click on the picker hits.
priv enum EmojiHit {
Cell(Int)
Tab(Int)
Tone(Int)
Panel
} derive(Eq)
///| The picker while it is up.
pub(all) struct EmojiUi {
/// None when there is no colour emoji font: `error` says why.
picker : @emoji.Picker?
error : String
/// The panel on screen.
mut rect : @scene.Rect
/// The cell under the pointer.
mut hover : Int?
}
///| Whether the picker is up.
pub fn ChandraCompositor::emoji_picker_open(self : ChandraCompositor) -> Bool {
self.emoji_ui is Some(_)
}
///| The picker's state (tests).
pub fn ChandraCompositor::emoji_picker(self : ChandraCompositor) -> @emoji.Picker? {
match self.emoji_ui {
Some(ui) => ui.picker
None => None
}
}
///| The message the picker shows instead of emoji ("" when it has emoji).
pub fn ChandraCompositor::emoji_picker_error(self : ChandraCompositor) -> String {
match self.emoji_ui {
Some(ui) => ui.error
None => ""
}
}
///| Which emoji the font can draw, asked once per session.
fn ChandraCompositor::emoji_coverage(self : ChandraCompositor) -> Array[Bool] {
match self.emoji_cover {
Some(c) => c
None => {
let c = @raster.emoji_has(@emoji.all().map(e => e.text))
let missing = c.filter(b => !b).length()
if missing > 0 {
@sys.log("emoji: the font has no picture for " + missing.to_string() + " of " + c.length().to_string() + " emoji (newer than the font); they are not listed")
}
self.emoji_cover = Some(c)
c
}
}
}
///| Super+.: open the picker, or close it.
pub fn ChandraCompositor::toggle_emoji_picker(self : ChandraCompositor) -> Unit {
if self.emoji_ui is Some(_) {
self.close_emoji_picker()
return
}
if self.shell.inspecting() || self.auth is Some(_) || self.shot is Some(_) || self.shot_edit is Some(_) {
return
}
// The launcher's search has the keyboard otherwise; the emoji are for the app.
if self.shell.launcher_open() {
self.shell.toggle_launcher()
self.overview_sync()
}
let ui : EmojiUi = match @raster.emoji_font() {
Err(why) => { picker: None, error: why, rect: @scene.Rect::new(0, 0, 0, 0), hover: None }
Ok(_) => {
let cover = self.emoji_coverage()
let (recent, tone) = match self.emoji_saved {
Some(st) => st
None => {
let st = self.shell.load_emoji()
self.emoji_saved = Some(st)
st
}
}
let p = @emoji.Picker::new(recent, tone, has=i => cover[i], cols=ep_cols, rows=ep_rows)
{ picker: Some(p), error: "", rect: @scene.Rect::new(0, 0, 0, 0), hover: None }
}
}
self.emoji_ui = Some(ui)
self.emoji_place(ui)
self.damage.mark_full()
}
///| Keep the picker's recents and skin tone for the next time, and in state.edn when they changed.
fn ChandraCompositor::emoji_remember(self : ChandraCompositor, p : @emoji.Picker) -> Unit {
let now = (p.recents.copy(), p.tone)
match self.emoji_saved {
Some((r, t)) if r == now.0 && t == now.1 => ()
_ => {
self.emoji_saved = Some(now)
self.shell.save_emoji(now.0, now.1)
}
}
}
///| Take the picker down (keeping its recents and skin tone).
pub fn ChandraCompositor::close_emoji_picker(self : ChandraCompositor) -> Unit {
match self.emoji_ui {
Some(ui) => {
match ui.picker {
Some(p) => self.emoji_remember(p)
None => ()
}
self.emoji_ui = None
self.damage.mark_full()
}
None => ()
}
}
///| The panel's size.
fn ChandraCompositor::emoji_size(self : ChandraCompositor, ui : EmojiUi) -> (Int, Int) {
let w = ep_pad * 2 + ep_cols * ep_cell
match ui.picker {
Some(_) => (w, ep_pad + ep_bar + 8 + ep_bar + 8 + ep_rows * ep_cell + 8 + 32 + ep_pad)
None => (w, 150 + self.theme.font_size * 3)
}
}
///| Put the panel under the caret of the focused text field when the app says where it is,
/// else in the middle of the focused window, else of the screen; always on screen.
fn ChandraCompositor::emoji_place(self : ChandraCompositor, ui : EmojiUi) -> Unit {
let (w, h) = self.emoji_size(ui)
let sw = self.output_w
let sh = self.output_h
let mut x = (sw - w) / 2
let mut y = (sh - h) / 2
match self.kbd_win {
Some(wid) =>
match self.windows.get(wid) {
Some(win) =>
match self.server.text_input_cursor(wid) {
Some((cx, cy, _, ch)) => {
let (ox, oy) = win.surface_origin()
x = ox + cx
y = oy + cy + ch + 6
if y + h > sh - self.theme.panel_height {
y = oy + cy - h - 6 // no room under the caret: above it
}
}
None => {
let r = win.client_rect()
x = r.x + (r.w - w) / 2
y = r.y + (r.h - h) / 2
}
}
None => ()
}
None => ()
}
x = x.min(sw - w - 8).max(8)
y = y.min(sh - h - 8).max(8)
ui.rect = @scene.Rect::new(x, y, w, h)
}
///| The search field, the tabs, the grid and the skin tones, on screen.
fn emoji_search_rect(r : @scene.Rect) -> @scene.Rect {
@scene.Rect::new(r.x + ep_pad, r.y + ep_pad, r.w - ep_pad * 2, ep_bar)
}
///|
fn emoji_tab_rect(r : @scene.Rect, t : Int) -> @scene.Rect {
let tw = (r.w - ep_pad * 2) / 10
@scene.Rect::new(r.x + ep_pad + t * tw, r.y + ep_pad + ep_bar + 8, tw, ep_bar)
}
///|
fn emoji_grid_rect(r : @scene.Rect) -> @scene.Rect {
@scene.Rect::new(r.x + ep_pad, r.y + ep_pad + ep_bar * 2 + 16, ep_cols * ep_cell, ep_rows * ep_cell)
}
///|
fn emoji_tone_rect(r : @scene.Rect, t : Int) -> @scene.Rect {
let g = emoji_grid_rect(r)
let s = 28
@scene.Rect::new(r.x + r.w - ep_pad - (6 - t) * (s + 2), g.y + g.h + 10, s, s)
}
///| What is at (x, y).
fn ChandraCompositor::emoji_hit(self : ChandraCompositor, ui : EmojiUi, x : Int, y : Int) -> EmojiHit? {
let r = ui.rect
if !r.contains(x, y) {
return None
}
match ui.picker {
None => Some(Panel)
Some(p) => {
let g = emoji_grid_rect(r)
if g.contains(x, y) {
let i = (p.scroll + (y - g.y) / ep_cell) * ep_cols + (x - g.x) / ep_cell
return if i < p.items().length() { Some(Cell(i)) } else { Some(Panel) }
}
for t = 0; t < 10; t = t + 1 {
if emoji_tab_rect(r, t).contains(x, y) {
return Some(Tab(t))
}
}
for t = 0; t < 6; t = t + 1 {
if emoji_tone_rect(r, t).contains(x, y) {
return Some(Tone(t))
}
}
Some(Panel)
}
}
}
///| evdev codes the picker reads (Enter and the arrows are in screenshot.mbt / switcher.mbt).
///|
let key_tab : UInt = 15
///|
let key_pgup : UInt = 104
///|
let key_pgdn : UInt = 109
///|
let key_home : UInt = 102
///|
let key_end : UInt = 107
///| Input while the picker is up. True when it was the picker's.
fn ChandraCompositor::emoji_input(self : ChandraCompositor, ev : @nested.InputEvent, time_ms : UInt) -> Bool {
match ev {
Key(code, false) =>
// Releases of keys the picker took (also after it closed).
if self.emoji_swallow.contains(code) {
self.emoji_swallow.retain(c => c != code)
return true
}
_ => ()
}
let ui = match self.emoji_ui {
Some(ui) => ui
None => return false
}
match ev {
// Other releases (the '.' of Super+., a key held since before) take the usual path.
Key(_, false) => false
Key(code, true) => {
if code == key_lsuper || code == key_rsuper {
// Super never reaches clients anyway; a Super tap doesn't open the launcher over the picker.
self.super_solo = false
return true
}
if @shell.is_modifier_key(code) {
return false // the app keeps its modifier state right
}
self.emoji_swallow.push(code)
if self.shell.shortcuts.lookup({ mods: self.held_mods(), key: code }) == Some(EmojiPicker) {
self.close_emoji_picker() // Super+. again
} else {
self.emoji_key(ui, code)
}
true
}
Modifiers(_, _, _, _) => false
PointerMove(x, y) => {
let hit = self.emoji_hit(ui, x.to_int(), y.to_int())
let hover = match hit {
Some(Cell(i)) => Some(i)
_ => None
}
if hover != ui.hover {
ui.hover = hover
self.damage.mark_full()
}
if hit is Some(_) {
self.ptr_x = x
self.ptr_y = y
self.leave_pointer()
true
} else {
false
}
}
PointerButton(button, pressed) => {
let hit = self.emoji_hit(ui, self.ptr_x.to_int(), self.ptr_y.to_int())
match hit {
None => {
// A click elsewhere closes the picker and goes on as usual.
if pressed {
self.close_emoji_picker()
}
false
}
Some(h) => {
if pressed && button == 272U {
self.emoji_click(ui, h, (self.mods & mod_shift) != 0U, time_ms)
}
true
}
}
}
Scroll(axis, v, discrete) =>
match self.emoji_hit(ui, self.ptr_x.to_int(), self.ptr_y.to_int()) {
None => false
Some(_) => {
match ui.picker {
Some(p) if axis == 0U => {
let rows = if discrete != 0 { discrete } else if v > 0.0 { 1 } else if v < 0.0 { -1 } else { 0 }
p.scroll_by(rows)
self.damage.mark_full()
}
_ => ()
}
true
}
}
}
}
///| A key press on the picker.
fn ChandraCompositor::emoji_key(self : ChandraCompositor, ui : EmojiUi, code : UInt) -> Unit {
self.damage.mark_full()
if code == key_esc {
self.close_emoji_picker()
return
}
let p = match ui.picker {
Some(p) => p
None => return // only Esc (or a click) does anything on the error panel
}
let shift = (self.mods & mod_shift) != 0U
let ctrl = (self.mods & mod_ctrl) != 0U
let key : @emoji.Key? = if code == key_enter || code == key_kp_enter {
Some(Choose)
} else if code == key_backspace {
Some(Backspace)
} else if code == key_tab {
Some(if shift { PrevTab } else { NextTab })
} else if code == key_left {
Some(if ctrl { PrevTone } else { Left })
} else if code == key_right {
Some(if ctrl { NextTone } else { Right })
} else if code == key_up {
Some(Up)
} else if code == key_down {
Some(Down)
} else if code == key_pgup {
Some(PageUp)
} else if code == key_pgdn {
Some(PageDown)
} else if code == key_home {
Some(Home)
} else if code == key_end {
Some(End)
} else if ctrl || (self.held_mods() & @shell.mod_alt) != 0U {
None
} else {
let mods = self.mods | self.mods_latched | self.mods_locked
match self.auth_keymap().char_for(code, mods, self.mods_group) {
Some(c) if c.to_int() >= 32 => Some(Type(c))
_ => None
}
}
match key {
Some(k) =>
match p.key(k) {
Some(text) => ignore(self.emoji_insert(text, shift))
None => ()
}
None => ()
}
}
///| A click on the picker.
fn ChandraCompositor::emoji_click(self : ChandraCompositor, ui : EmojiUi, h : EmojiHit, keep_open : Bool, _time_ms : UInt) -> Unit {
self.damage.mark_full()
match ui.picker {
None => ()
Some(p) =>
match h {
Cell(i) => {
p.select(i)
match p.key(Choose) {
Some(text) => ignore(self.emoji_insert(text, keep_open))
None => ()
}
}
Tab(t) => p.set_tab(t)
Tone(t) => p.set_tone(t)
Panel => ()
}
}
}
///| Mime types the emoji is offered as on the clipboard.
let text_mimes : Array[String] = ["text/plain;charset=utf-8", "text/plain", "UTF8_STRING", "TEXT", "STRING"]
///| How an emoji reached the app, for tests and the log.
pub(all) enum EmojiDelivery {
/// Typed into the focused text field (text-input-v3).
Typed
/// Put on the clipboard: (why it couldn't be typed).
Copied(String)
} derive(Eq, Show, Debug)
///| Put `text` where the user was typing: into the focused window's text field when it has
/// one active, else on the clipboard with a notification saying so. Closes the picker unless
/// `keep_open`. Saves the recents.
pub fn ChandraCompositor::emoji_insert(self : ChandraCompositor, text : String, keep_open : Bool) -> EmojiDelivery {
let target = self.kbd_win
let delivery = match target {
Some(w) if self.server.text_input_commit(w, text) => Typed
Some(w) => {
let app = match self.windows.get(w) {
Some(win) if win.title.length() > 0 => win.title
_ => "The focused window"
}
Copied(app + " has no text field taking typed text (text-input-v3)")
}
None => Copied("No window has the keyboard")
}
match delivery {
Typed => ()
Copied(why) => {
self.server.set_own_selection(text_mimes, @utf8.encode(text))
@sys.log("emoji: copied to the clipboard: " + why)
let img = @raster.emoji_image(text, 48)
self.shot_toast = Some({
title: "Emoji copied: paste it with Ctrl+V",
detail: why,
until: @sys.monotonic_ms() + 6000UL,
thumb: if img != 0U { [@scene.DrawOp::Image(@scene.Rect::new(0, 0, 48, 48), img)] } else { [] },
tw: 48,
th: 48,
})
}
}
match self.emoji_ui {
Some(ui) =>
match ui.picker {
Some(p) => {
p.used(text) // (already done when it came from the picker's keys or a click)
self.emoji_remember(p)
}
None => ()
}
None => ()
}
if !keep_open || delivery != Typed {
self.close_emoji_picker()
}
self.damage.mark_full()
delivery
}
///| An emoji picture at `r` (centred, `px` square), or a box with "?" when the font has none.
fn ChandraCompositor::emoji_pic(self : ChandraCompositor, text : String, r : @scene.Rect, px : Int, ops : Array[@scene.DrawOp]) -> Unit {
let x = r.x + (r.w - px) / 2
let y = r.y + (r.h - px) / 2
let h = @raster.emoji_image(text, px)
if h != 0U {
ops.push(@scene.DrawOp::Image(@scene.Rect::new(x, y, px, px), h))
} else {
let p = self.theme.palette
ops.push(@scene.DrawOp::StrokeRect(@scene.Rect::new(x + 2, y + 2, px - 4, px - 4), p.foreground_muted, 1, 3))
ops.push(@scene.DrawOp::Text(x + px / 2, y + px / 2, "?", self.theme.font_size, p.foreground_muted, @scene.TextAlign::Center, false))
}
}
///| The picker's draw ops.
fn ChandraCompositor::emoji_ops(self : ChandraCompositor) -> Array[@scene.DrawOp] {
let ops : Array[@scene.DrawOp] = []
let ui = match self.emoji_ui {
Some(ui) => ui
None => return ops
}
let (w, h) = self.emoji_size(ui)
if ui.rect.w != w || ui.rect.h != h || ui.rect.x + w > self.output_w || ui.rect.y + h > self.output_h {
self.emoji_place(ui)
}
let r = ui.rect
let pal = self.theme.palette
let fs = self.theme.font_size
let rad = self.theme.radius + 4
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(r.x + 2, r.y + 4, r.w, r.h), @scene.Rgba::new(0, 0, 0, 70), rad))
// Opaque: whatever is behind would show through the grid.
let bg = pal.surface_popup
ops.push(@scene.DrawOp::FillRect(r, { r: bg.r, g: bg.g, b: bg.b, a: b'\xff' }, rad))
ops.push(@scene.DrawOp::StrokeRect(r, pal.border, 1, rad))
let p = match ui.picker {
Some(p) => p
None => {
// No colour emoji font: say so, and what to install.
ops.push(@scene.DrawOp::Text(r.x + ep_pad, r.y + ep_pad + fs, "Emoji need a colour emoji font", fs + 1, @scene.Rgba::from_hex("#f87171"), @scene.TextAlign::Left, true))
let mut y = r.y + ep_pad + fs * 3
for line in wrap_text(ui.error, fs - 1, false, false, r.w - ep_pad * 2) {
ops.push(@scene.DrawOp::Text(r.x + ep_pad, y, line, fs - 1, pal.foreground, @scene.TextAlign::Left, false))
y = y + fs + 5
}
ops.push(@scene.DrawOp::Text(r.x + r.w - ep_pad, r.y + r.h - ep_pad - fs / 2, "Esc: close", fs - 2, pal.foreground_muted, @scene.TextAlign::Right, false))
return ops
}
}
// The search field.
let s = emoji_search_rect(r)
ops.push(@scene.DrawOp::FillRect(s, pal.surface, self.theme.radius))
ops.push(@scene.DrawOp::StrokeRect(s, pal.accent, 1, self.theme.radius))
let tx = s.x + 10
if p.query.length() == 0 {
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(tx, s.y + 8, 1, s.h - 16), pal.foreground, 0))
ops.push(@scene.DrawOp::Text(tx + 4, s.y + s.h / 2, "Type to search emoji", fs, pal.foreground_muted, @scene.TextAlign::Left, false))
} else {
ops.push(@scene.DrawOp::Text(tx, s.y + s.h / 2, p.query, fs, pal.foreground, @scene.TextAlign::Left, false))
let cw = @renderer.text_width(p.query, fs, false, false)
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(tx + cw + 1, s.y + 8, 1, s.h - 16), pal.foreground, 0))
}
// The tabs (dimmed while searching: results come from every tab).
for t = 0; t < 10; t = t + 1 {
let tr = emoji_tab_rect(r, t)
let on = t == p.tab && p.query.length() == 0
if on {
ops.push(@scene.DrawOp::FillRect(tr, pal.surface_hover, self.theme.radius))
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(tr.x + 8, tr.y + tr.h - 3, tr.w - 16, 3), pal.accent, 1))
} else if tr.contains(self.ptr_x.to_int(), self.ptr_y.to_int()) {
ops.push(@scene.DrawOp::FillRect(tr, pal.surface_hover, self.theme.radius))
}
self.emoji_pic(@emoji.tab_icons[t], tr, 20, ops)
}
// The grid.
let g = emoji_grid_rect(r)
let items = p.items()
if items.length() == 0 {
let msg = if p.query.length() > 0 {
"No emoji match “" + p.query + "”"
} else if p.tab == 0 {
"Emoji you use show up here"
} else {
"The emoji font has none of these"
}
ops.push(@scene.DrawOp::Text(g.x + g.w / 2, g.y + g.h / 2, msg, fs, pal.foreground_muted, @scene.TextAlign::Center, false))
}
ops.push(@scene.DrawOp::PushClip(g))
let first = p.scroll * ep_cols
let last = (first + ep_cols * ep_rows).min(items.length())
for i = first; i < last; i = i + 1 {
let k = i - first
let cell = @scene.Rect::new(g.x + k % ep_cols * ep_cell, g.y + k / ep_cols * ep_cell, ep_cell, ep_cell)
if i == p.sel {
ops.push(@scene.DrawOp::FillRect(cell, pal.accent, self.theme.radius))
} else if ui.hover == Some(i) {
ops.push(@scene.DrawOp::FillRect(cell, pal.surface_hover, self.theme.radius))
}
self.emoji_pic(items[i].text, cell, ep_emoji, ops)
}
ops.push(@scene.DrawOp::PopClip)
// A scroll bar when there is more than one screenful.
let total_rows = (items.length() + ep_cols - 1) / ep_cols
if total_rows > ep_rows {
let bar_h = (g.h * ep_rows / total_rows).max(16)
let bar_y = g.y + (g.h - bar_h) * p.scroll / (total_rows - ep_rows)
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(r.x + r.w - 7, bar_y, 3, bar_h), pal.foreground_muted, 1))
}
// The selected emoji's name, and the skin tones.
// (The skin tone shows on the swatches beside it.)
let name = match p.selected() {
Some(it) => @emoji.all()[it.index].name
None => ""
}
let ty = g.y + g.h + 24
let tone0 = emoji_tone_rect(r, 0)
ops.push(@scene.DrawOp::PushClip(@scene.Rect::new(r.x + ep_pad, ty - fs, tone0.x - r.x - ep_pad - 6, fs * 2)))
ops.push(@scene.DrawOp::Text(r.x + ep_pad, ty, name, fs, pal.foreground, @scene.TextAlign::Left, false))
ops.push(@scene.DrawOp::PopClip)
for t = 0; t < 6; t = t + 1 {
let tr = emoji_tone_rect(r, t)
if t == p.tone {
ops.push(@scene.DrawOp::StrokeRect(tr, pal.accent, 2, self.theme.radius))
}
self.emoji_pic(@emoji.tone_swatches[t], tr, 20, ops)
}
ops
}
+253
View File
@@ -0,0 +1,253 @@
///| The emoji picker (Super+.): opening, searching, keys, insertion through text-input-v3 into a
/// fake client, the clipboard when the app has no text field, and recents in state.edn.
///| evdev codes typed in these tests (US layout: tests have no keymap).
fn type_keys(comp : @host.ChandraCompositor, codes : Array[UInt], t : UInt) -> Unit {
for i, k in codes {
comp.handle_input(@nested.InputEvent::Key(k, true), t + i.reinterpret_as_uint() * 2U)
comp.handle_input(@nested.InputEvent::Key(k, false), t + i.reinterpret_as_uint() * 2U + 1U)
}
}
///| p i z z a
let pizza_keys : Array[UInt] = [25U, 23U, 44U, 44U, 30U]
///| Press Super+. the way a keyboard does it.
fn press_super_period(comp : @host.ChandraCompositor, t : UInt) -> Unit {
comp.handle_input(@nested.InputEvent::Key(125U, true), t)
comp.handle_input(@nested.InputEvent::Key(52U, true), t + 1U)
comp.handle_input(@nested.InputEvent::Key(52U, false), t + 2U)
comp.handle_input(@nested.InputEvent::Key(125U, false), t + 3U)
ignore(comp.compose_frame())
}
///| The string argument of a message's words (length word, then the bytes).
fn words_string(args : Array[UInt]) -> String {
let n = args[0].reinterpret_as_int() - 1
let b : Array[Byte] = []
for i = 0; i < n; i = i + 1 {
let w = args[1 + i / 4]
b.push(((w >> ((i % 4) * 8)) & 0xFFU).to_byte())
}
@utf8.decode_lossy(Bytes::from_array(b))
}
///| A client with a zwp_text_input_v3 on its seat: (text input id, keyboard id).
fn text_input_for(comp : @host.ChandraCompositor, c : TestWaylandClient) -> (UInt, UInt) {
let seat = bind_global(c, 2U, "wl_seat", 7U)
let kbd = c.alloc_id()
let wk = @wayland.WireWriter::new()
wk.u32(kbd)
c.send(wk.finish_msg(seat, 1U)) // get_keyboard
let mgr = bind_global(c, 2U, "zwp_text_input_manager_v3", 1U)
let ti = c.alloc_id()
let w = @wayland.WireWriter::new()
w.u32(ti)
w.u32(seat)
c.send(w.finish_msg(mgr, 1U))
for _i = 0; _i < 5; _i = _i + 1 {
comp.step()
@sys.sleep_ms(2)
}
(ti, kbd)
}
///| enable (or disable) the text input with the caret at (x, y, 2, h), then commit.
fn text_input_state(comp : @host.ChandraCompositor, c : TestWaylandClient, ti : UInt, on : Bool, x : Int, y : Int, h : Int) -> Unit {
c.send(@wayland.WireWriter::new().finish_msg(ti, if on { 1U } else { 2U }))
if on {
let r = @wayland.WireWriter::new()
r.i32(x)
r.i32(y)
r.i32(2)
r.i32(h)
c.send(r.finish_msg(ti, 6U))
}
c.send(@wayland.WireWriter::new().finish_msg(ti, 7U))
for _i = 0; _i < 5; _i = _i + 1 {
comp.step()
@sys.sleep_ms(2)
}
}
///|
test "Super+. opens the picker; typing searches, Enter types the emoji into the app's text field" {
let socket_path = "/tmp/wayland-moon-emoji-" + @sys.getpid().to_string() + ".sock"
let comp = @host.ChandraCompositor::new(socket_path, @scene.ThemeTokens::moon_night(), 1280, 720).unwrap()
let (a, shm_a, surf_a, xdg_a, _, _) = open_and_configure_client(comp, socket_path, "Editor", "editor")
commit_shm_frame(comp, a, shm_a, surf_a, xdg_a, 1UL)
assert_eq(comp.kbd_win, Some(1UL))
let (ti, kbd) = text_input_for(comp, a)
// Created while its window has the keyboard: told so at once (enter with the surface).
let first = drain_args(a)
let enter = first.iter().find_first(m => m.0 == ti && m.1 == 0U).unwrap()
assert_eq(enter.2[0], surf_a)
// The app enables it with the caret at (100, 50) in its surface.
text_input_state(comp, a, ti, true, 100, 50, 18)
assert_true(comp.server.text_input_active(1UL))
press_super_period(comp, 10U)
assert_true(comp.emoji_picker_open())
assert_eq(comp.emoji_picker_error(), "")
// The panel sits under the caret.
let (ox, oy) = comp.windows.get(1UL).unwrap().surface_origin()
let r = comp.emoji_ui.unwrap().rect
assert_eq((r.x, r.y), (ox + 100, oy + 50 + 18 + 6))
type_keys(comp, pizza_keys, 20U)
let p = comp.emoji_picker().unwrap()
assert_eq(p.query, "pizza")
assert_eq(p.selected().unwrap().text, "🍕")
ignore(drain_args(a))
type_keys(comp, [28U], 40U) // Enter
assert_false(comp.emoji_picker_open())
let msgs = drain_args(a)
// commit_string("🍕") then done(serial 1: one commit so far), and no key reached the app.
let commit = msgs.iter().find_first(m => m.0 == ti && m.1 == 3U).unwrap()
assert_eq(words_string(commit.2), "🍕")
let done = msgs.iter().find_first(m => m.0 == ti && m.1 == 5U).unwrap()
assert_eq(done.2[0], 1U)
assert_eq(count_msgs(msgs, kbd, 3U), 0) // wl_keyboard.key
assert_eq(count_msgs(msgs, kbd, 2U), 0) // the app never lost the keyboard
assert_false(comp.screenshot_toast_shown())
// Keys reach the app again.
type_keys(comp, [30U], 50U)
assert_eq(count_msgs(drain_args(a), kbd, 3U), 2)
comp.close()
}
///|
test "without an active text field the emoji goes to the clipboard, and a notice says so" {
let socket_path = "/tmp/wayland-moon-emoji2-" + @sys.getpid().to_string() + ".sock"
let comp = @host.ChandraCompositor::new(socket_path, @scene.ThemeTokens::moon_night(), 1280, 720).unwrap()
let (a, shm_a, surf_a, xdg_a, _, _) = open_and_configure_client(comp, socket_path, "Terminal", "term")
commit_shm_frame(comp, a, shm_a, surf_a, xdg_a, 1UL)
let (ti, _) = text_input_for(comp, a)
text_input_state(comp, a, ti, true, 10, 10, 16)
text_input_state(comp, a, ti, false, 0, 0, 0) // the app turned it off again
assert_false(comp.server.text_input_active(1UL))
press_super_period(comp, 10U)
ignore(drain_args(a))
match comp.emoji_picker().unwrap().selected() {
Some(it) => assert_eq(comp.emoji_insert(it.text, false), Copied("Terminal has no text field taking typed text (text-input-v3)"))
None => fail("nothing selected")
}
assert_false(comp.emoji_picker_open())
assert_true(comp.server.owns_selection())
assert_true(comp.screenshot_toast_shown())
// Nothing was typed into the app.
assert_eq(count_msgs(drain_args(a), ti, 3U), 0)
comp.close()
}
///|
test "picker keys: arrows, tabs, skin tone, Esc; clicks outside close it" {
let comp = new_comp("emoji-keys")
press_super_period(comp, 10U)
let p = comp.emoji_picker().unwrap()
assert_eq(p.tab, 1) // no recents yet: Smileys
type_keys(comp, [106U, 108U], 20U) // Right, Down
assert_eq(p.sel, 1 + 9)
type_keys(comp, [15U], 30U) // Tab: People
assert_eq((p.tab, p.sel), (2, 0))
// Ctrl+Right twice: medium-light skin tone, applied to the waving hand.
comp.handle_input(@nested.InputEvent::Modifiers(4U, 0U, 0U, 0U), 40U)
type_keys(comp, [106U, 106U], 41U)
comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 0U, 0U), 45U)
assert_eq(p.tone, 2)
assert_eq(p.selected().unwrap().text, "👋🏼")
// Backspace with nothing typed does nothing; Esc closes.
type_keys(comp, [14U], 50U)
assert_true(comp.emoji_picker_open())
type_keys(comp, [1U], 60U)
assert_false(comp.emoji_picker_open())
// Super+. again opens it; a click outside closes it.
press_super_period(comp, 70U)
assert_true(comp.emoji_picker_open())
click_at(comp, 5, 300, 80U)
assert_false(comp.emoji_picker_open())
// Super+. twice: open, then closed.
press_super_period(comp, 90U)
press_super_period(comp, 100U)
assert_false(comp.emoji_picker_open())
}
///|
test "clicking an emoji in the grid picks it; Shift keeps the picker open" {
let comp = new_comp("emoji-click")
press_super_period(comp, 10U)
let r = comp.emoji_ui.unwrap().rect
// The grid starts under the search field and the tabs: its third cell.
let gx = r.x + 12 + 2 * 40 + 20
let gy = r.y + 12 + 34 * 2 + 16 + 20
comp.handle_input(@nested.InputEvent::Modifiers(1U, 0U, 0U, 0U), 20U)
click_at(comp, gx, gy, 21U)
comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 0U, 0U), 25U)
// No window: copied, and the picker closes (there is nothing to keep typing into).
assert_false(comp.emoji_picker_open())
assert_true(comp.server.owns_selection())
press_super_period(comp, 30U)
let p = comp.emoji_picker().unwrap()
assert_eq(p.tab, 0) // the recent emoji
assert_eq(p.items().map(i => i.text), [@emoji.all()[2].text])
}
///|
test "recent emoji and the skin tone are kept in state.edn" {
if @sys.getenv("CHANDRA_TEST_CONFIG") == "1" {
write_state_edn("{:note \"keep\"}\n")
let a = new_comp("emoji-save-a")
a.shell.persist = true
press_super_period(a, 10U)
let p = a.emoji_picker().unwrap()
p.set_tone(3)
ignore(a.emoji_insert("👍🏽", false))
press_super_period(a, 20U)
ignore(a.emoji_insert("🍕", false))
// read_state_edn reads the file as ASCII; the emoji are UTF-8.
let dir = @sys.getenv("XDG_CONFIG_HOME")
let text = @utf8.decode_lossy(@sys.read_file_bytes(dir + "/chandra/state.edn"))
assert_true(text.contains(":emoji"))
assert_true(text.contains("\"🍕\" \"👍🏽\""))
assert_true(text.contains(":skin-tone 3"))
assert_true(text.contains(":note \"keep\""))
let b = new_comp("emoji-save-b")
b.shell.persist = true
press_super_period(b, 10U)
let q = b.emoji_picker().unwrap()
assert_eq(q.tab, 0)
assert_eq(q.tone, 3)
assert_eq(q.items().map(i => i.text), ["🍕", "👍🏽"])
}
}
///| CHANDRA_EMOJI_SHOTS=<dir>: pictures of the picker over a window (docs, the thread).
test "screenshots of the picker" {
let dir = @sys.getenv("CHANDRA_EMOJI_SHOTS")
if dir.length() > 0 {
ignore(@sys.mkdir_p(dir))
let socket_path = "/tmp/wayland-moon-emojishots-" + @sys.getpid().to_string() + ".sock"
let comp = @host.ChandraCompositor::new(socket_path, @scene.ThemeTokens::moon_night(), 1280, 720).unwrap()
let (a, shm_a, surf_a, xdg_a, _, _) = open_and_configure_client(comp, socket_path, "Notes", "notes")
commit_shm_frame(comp, a, shm_a, surf_a, xdg_a, 1UL)
let (ti, _) = text_input_for(comp, a)
text_input_state(comp, a, ti, true, 120, 90, 18)
let shot = fn(name : String) raise {
let frame = comp.compose_frame()
assert_eq(@sys.write_file_bytes(dir + "/" + name, @renderer.encode_png_compressed(frame)), 0)
}
press_super_period(comp, 10U)
shot("picker-smileys.png")
type_keys(comp, [35U, 18U, 30U, 19U, 20U], 20U) // h e a r t
shot("picker-search.png")
type_keys(comp, [14U, 14U, 14U, 14U, 14U, 15U], 40U) // clear, then Tab: People
comp.handle_input(@nested.InputEvent::Modifiers(4U, 0U, 0U, 0U), 60U)
type_keys(comp, [106U, 106U, 106U], 61U) // Ctrl+Right x3: medium skin tone
comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 0U, 0U), 70U)
type_keys(comp, [106U, 108U], 71U)
shot("picker-people-tone.png")
// The clipboard notice: the app turns its text field off, then an emoji is chosen.
text_input_state(comp, a, ti, false, 0, 0, 0)
type_keys(comp, [28U], 80U)
shot("picker-copied-notice.png")
comp.close()
}
}
+1
View File
@@ -16,6 +16,7 @@ import {
"chandra/desktop/compositor/network" @network,
"chandra/desktop/compositor/portal" @portal,
"chandra/desktop/compositor/polkit" @polkit,
"chandra/desktop/compositor/emoji" @emoji,
}
supported_targets = "+native+wasm"
+2
View File
@@ -579,6 +579,8 @@ fn thumbnail_ops(p : @renderer.Pixmap, max_w : Int, max_h : Int) -> (Array[@scen
fn offset_ops(ops : Array[@scene.DrawOp], dx : Int, dy : Int) -> Array[@scene.DrawOp] {
ops.map(op => match op {
FillRect(r, c, rad) => @scene.DrawOp::FillRect(@scene.Rect::new(r.x + dx, r.y + dy, r.w, r.h), c, rad)
// The emoji picker's notification shows the emoji as its thumbnail.
Image(r, h) => @scene.DrawOp::Image(@scene.Rect::new(r.x + dx, r.y + dy, r.w, r.h), h)
other => other
})
}
+1
View File
@@ -135,6 +135,7 @@ pub fn ChandraCompositor::run_shortcut(self : ChandraCompositor, action : @shell
RecordScreen => self.toggle_recording(ShotMode::FullScreen)
RecordWindow => self.toggle_recording(ShotMode::WindowUnderCursor)
DockApps => ignore(self.open_dock_app(1))
EmojiPicker => self.toggle_emoji_picker()
}
}
+1
View File
@@ -36,6 +36,7 @@ test "the default shortcuts are the compositor's long-standing combos" {
("record-window", "Super+Ctrl+R"),
("dock-apps", "Super+1"),
("overview", "Super+W"),
("emoji-picker", "Super+Period"),
]
let sc = @shell.Shortcuts::defaults()
assert_eq(@shell.shortcut_table.length(), want.length())
+1
View File
@@ -3,6 +3,7 @@ import {
"chandra/desktop/compositor/scene" @scene,
"chandra/desktop/compositor/renderer" @renderer,
"chandra/desktop/compositor/sys" @sys,
"chandra/desktop/compositor/emoji" @emoji,
"chandra/desktop/interface/chandra/host/raster" @hostraster,
}
+18
View File
@@ -76,3 +76,21 @@ pub fn load_image(path : String) -> UInt {
}
}
}
///| The colour emoji font, for the software renderer.
let emoji_source : @emoji.EmojiSource = @emoji.EmojiSource::new()
///| Open the colour emoji font: its path, or what to tell the user (see `@emoji.EmojiSource`).
pub fn emoji_font() -> Result[String, String] {
emoji_source.font()
}
///| For each of `texts`, whether the font has one picture for it.
pub fn emoji_has(texts : Array[String]) -> Array[Bool] {
emoji_source.has(texts)
}
///| The picture for emoji `text` scaled to fit `px` x `px`, for `Image` draw ops; 0 when none.
pub fn emoji_image(text : String, px : Int) -> UInt {
emoji_source.image(text, px, p => @renderer.add_image(p))
}
+15
View File
@@ -148,3 +148,18 @@ pub fn load_image(path : String) -> UInt {
}
}
}
///| Open the colour emoji font (on the host): its path, or what to tell the user.
pub fn emoji_font() -> Result[String, String] {
@hostraster.emoji_font()
}
///| For each of `texts`, whether the font has one picture for it.
pub fn emoji_has(texts : Array[String]) -> Array[Bool] {
@hostraster.emoji_has(texts)
}
///| The picture for emoji `text` scaled to fit `px` x `px`, for `Image` draw ops; 0 when none.
pub fn emoji_image(text : String, px : Int) -> UInt {
@hostraster.emoji_image(text, px)
}
+3
View File
@@ -56,6 +56,8 @@ pub(all) enum ShortcutAction {
/// second to ninth (when the combo's key is 1). Like clicking the icon: start the app or bring
/// its windows forward. See `Shortcuts::dock_app`.
DockApps
/// The emoji picker (compositor/host/emoji_picker.mbt), like Windows' Win+.
EmojiPicker
} derive(Eq, Debug)
///| One row of the shortcut table.
@@ -85,6 +87,7 @@ pub let shortcut_table : Array[ShortcutDef] = [
{ id: "record-window", label: "Record a window", action: RecordWindow, default_text: "Super+Ctrl+R" },
{ id: "dock-apps", label: "Open dock app 1-9", action: DockApps, default_text: "Super+1" },
{ id: "overview", label: "Overview of all windows", action: Overview, default_text: "Super+W" },
{ id: "emoji-picker", label: "Emoji picker", action: EmojiPicker, default_text: "Super+Period" },
]
///| evdev code -> key name, for the keys a combo can end in (US layout names).
+65 -1
View File
@@ -21,8 +21,11 @@
/// :restore-session false ; don't reopen them (absent: reopen); the session settings module
/// ; or a hand edit sets it
/// :remember-windows false ; don't place windows where they were left (absent: do)
/// :auth-agent :system} ; passwords for run0/pkexec/polkit go to the system's polkit
/// :auth-agent :system ; passwords for run0/pkexec/polkit go to the system's polkit
/// ; agent instead of Chandra's own dialog (absent: :chandra)
/// :emoji {:recent ["👍🏽" "🍕"] :skin-tone 3}}
/// ; the emoji picker's recently used emoji (newest first, as
/// ; inserted) and skin tone, 0 default .. 5 dark (emoji_picker.mbt)
///
/// Saving merges into what is already in the file, so keys this build doesn't know (a future
/// widget's state, hand-written notes) survive. Everything is a no-op unless `persist` is on
@@ -577,6 +580,67 @@ pub fn DesktopShell::save_session(self : DesktopShell, session : Array[SessionEn
write_state_file(entries)
}
///| The emoji picker's saved state: recent emoji (newest first) and skin tone (0-5). Empty and 0
/// without `persist` or when state.edn doesn't say.
pub fn DesktopShell::load_emoji(self : DesktopShell) -> (Array[String], Int) {
if !self.persist {
return ([], 0)
}
let recent : Array[String] = []
let mut tone = 0
match lookup_key(read_state_file(), "emoji") {
Some(Mapping(m)) => {
match lookup_key(m, "recent") {
Some(Vector(vs)) =>
for v in vs {
match v {
Text(t) => recent.push(t)
_ => ()
}
}
_ => ()
}
match lookup_key(m, "skin-tone") {
Some(Integer(n)) =>
match parse_int_str(n) {
Some(t) if t >= 0 && t <= 5 => tone = t
_ => ()
}
_ => ()
}
}
_ => ()
}
(recent, tone)
}
///| Write the emoji picker's recent emoji and skin tone as `:emoji`, keeping every other key.
/// A no-op without `persist`.
pub fn DesktopShell::save_emoji(self : DesktopShell, recent : Array[String], tone : Int) -> Unit {
if !self.persist {
return
}
let value = @edn.Value::Mapping([
(@edn.Value::Keyword("recent"), @edn.Value::Vector(recent.map(r => @edn.Value::Text(r)))),
(@edn.Value::Keyword("skin-tone"), @edn.Value::Integer(tone.to_string())),
])
let entries : Array[(@edn.Value, @edn.Value)] = []
let mut placed = false
for e in read_state_file() {
match e.0 {
Keyword("emoji") => {
entries.push((e.0, value))
placed = true
}
_ => entries.push(e)
}
}
if !placed {
entries.push((@edn.Value::Keyword("emoji"), value))
}
write_state_file(entries)
}
///| Start the app whose windows carry `app_id` (see `resolve_app_id`), without counting it as
/// a recent launch. False when no installed app matches or it could not be started.
pub fn DesktopShell::launch_app_id(self : DesktopShell, app_id : String) -> Bool {
+22 -1
View File
@@ -103,6 +103,9 @@ enum ObjKind {
ObjPrimaryOffer(UInt, UInt)
ObjCursorShapeMgr
ObjCursorShapeDev
/// zwp_text_input_manager_v3 and its zwp_text_input_v3 objects (text_input.mbt).
ObjTextInputMgr
ObjTextInput
}
///|
@@ -241,6 +244,8 @@ struct ClientConn {
mut next_offer : UInt
/// wp_cursor_shape_v1 shape the client last asked for (0 = never set).
mut cursor_shape : UInt
/// zwp_text_input_v3 objects, by id (text_input.mbt).
text_inputs : Map[UInt, TextInputState]
mut alive : Bool
}
@@ -272,6 +277,7 @@ fn ClientConn::new(client_id : UInt, fd : Int) -> ClientConn {
source_actions: {},
next_offer: 0xff000000U,
cursor_shape: 0U,
text_inputs: {},
alive: true,
}
}
@@ -345,6 +351,9 @@ pub(all) struct WaylandServer {
mut primary : (UInt, UInt)?
/// Client that currently has keyboard focus (receives selection events).
mut kbd_client : UInt?
/// The surface with keyboard focus: (client id, wl_surface id). Text inputs created while it
/// has focus are told so at once.
mut kbd_surface : (UInt, UInt)?
/// Area a popup must stay inside, as (x, y, w, h) relative to its parent's content origin
/// (the parent window id is passed). The host sets this; the default never constrains.
mut popup_bounds : (UInt64) -> (Int, Int, Int, Int)
@@ -388,6 +397,7 @@ pub fn WaylandServer::listen(
keymap: Bytes::from_array([]),
selection: None,
kbd_client: None,
kbd_surface: None,
primary: None,
popup_bounds: fn(_) { (-1000000, -1000000, 2000000, 2000000) },
own_mimes: [],
@@ -460,6 +470,7 @@ fn emit_registry_globals(c : ClientConn, reg_id : UInt) -> Unit {
(9U, "wp_cursor_shape_manager_v1", 1U),
(10U, "org_kde_kwin_server_decoration_manager", 1U),
(11U, "zwp_primary_selection_device_manager_v1", 1U),
(12U, "zwp_text_input_manager_v3", 1U),
]
for g in globals {
let w = WireWriter::new()
@@ -680,6 +691,8 @@ fn WaylandServer::dispatch_msg(
c.data_ver = ver
} else if iface == "zwp_primary_selection_device_manager_v1" {
c.objects.set(new_id, ObjPrimaryManager)
} else if iface == "zwp_text_input_manager_v3" {
c.objects.set(new_id, ObjTextInputMgr)
} else if iface == "wl_subcompositor" {
c.objects.set(new_id, ObjSubcompositor)
} else if iface == "wl_output" {
@@ -1072,6 +1085,7 @@ fn WaylandServer::dispatch_msg(
let id = reader.u32()
c.objects.set(id, ObjCursorShapeDev)
}
ObjTextInputMgr | ObjTextInput => self.text_input_request(c, kind, obj_id, opcode, reader)
ObjCursorShapeDev =>
if opcode == 1U {
// set_shape(serial, shape)
@@ -2058,6 +2072,7 @@ pub fn WaylandServer::keyboard_enter(self : WaylandServer, win_id : UInt64) -> U
None => ()
Some((c, tl)) => {
self.kbd_client = Some(c.client_id)
self.kbd_surface = Some((c.client_id, tl.wl_surface_id))
self.send_selection(c)
self.send_primary(c)
for kid in c.keyboard_ids {
@@ -2067,6 +2082,7 @@ pub fn WaylandServer::keyboard_enter(self : WaylandServer, win_id : UInt64) -> U
w.array([])
c.send_msg(w.finish_msg(kid, 1U))
}
text_inputs_enter(c, tl.wl_surface_id)
}
}
}
@@ -2075,13 +2091,18 @@ pub fn WaylandServer::keyboard_enter(self : WaylandServer, win_id : UInt64) -> U
pub fn WaylandServer::keyboard_leave(self : WaylandServer, win_id : UInt64) -> Unit {
match self.win_client(win_id) {
None => ()
Some((c, tl)) =>
Some((c, tl)) => {
for kid in c.keyboard_ids {
let w = WireWriter::new()
w.u32(self.next_serial())
w.u32(tl.wl_surface_id)
c.send_msg(w.finish_msg(kid, 2U))
}
text_inputs_leave(c, tl.wl_surface_id)
if self.kbd_surface == Some((c.client_id, tl.wl_surface_id)) {
self.kbd_surface = None
}
}
}
}
+193
View File
@@ -0,0 +1,193 @@
///| text-input-v3 (zwp_text_input_v3): how Chandra types into apps, the way an input method does.
///
/// An app with a text field focused enables its text input; the compositor can then send it text
/// (commit_string) that the app inserts at its caret, whatever the keyboard layout. The emoji
/// picker uses it (compositor/host/emoji_picker.mbt). GTK 3 and 4, Qt 6, Firefox, foot and
/// Ghostty speak it; Chromium only with --enable-wayland-ime.
///
/// The protocol follows keyboard focus: a text input gets `enter` with the focused surface when
/// its client has the keyboard (or at once when created while it does) and `leave` when it goes.
/// enable / disable / set_cursor_rectangle are double-buffered and take effect on commit; `done`
/// carries how many commits the client has made, as the protocol asks.
///| One zwp_text_input_v3.
struct TextInputState {
/// The surface it was sent `enter` for (0: none).
mut surface : UInt
mut enabled : Bool
mut pend_enabled : Bool
/// The caret, surface-local (x, y, w, h); None until the client says.
mut cursor : (Int, Int, Int, Int)?
mut pend_cursor : (Int, Int, Int, Int)?
/// commit requests received (the serial `done` carries).
mut commits : UInt
}
///| Requests on the manager and on text inputs.
fn WaylandServer::text_input_request(
self : WaylandServer,
c : ClientConn,
kind : ObjKind,
obj_id : UInt,
opcode : UInt,
reader : WireReader,
) -> Unit {
match kind {
ObjTextInputMgr =>
if opcode == 0U {
// destroy
c.objects.remove(obj_id)
send_delete_id(c, obj_id)
} else if opcode == 1U {
// get_text_input(id: new_id, seat)
let id = reader.u32()
c.objects.set(id, ObjTextInput)
let ti : TextInputState = {
surface: 0U,
enabled: false,
pend_enabled: false,
cursor: None,
pend_cursor: None,
commits: 0U,
}
c.text_inputs.set(id, ti)
match self.kbd_surface {
Some((cid, sid)) if cid == c.client_id && c.surfaces.contains(sid) => {
ti.surface = sid
send_text_input_surface(c, id, 0U, sid)
}
_ => ()
}
}
ObjTextInput =>
match c.text_inputs.get(obj_id) {
None => ()
Some(ti) =>
match opcode {
0U => {
// destroy
c.text_inputs.remove(obj_id)
c.objects.remove(obj_id)
send_delete_id(c, obj_id)
}
1U => {
// enable: also resets the pending state
ti.pend_enabled = true
ti.pend_cursor = None
}
2U => ti.pend_enabled = false // disable
6U => {
// set_cursor_rectangle(x, y, width, height)
let x = reader.i32()
let y = reader.i32()
let w = reader.i32()
let h = reader.i32()
ti.pend_cursor = Some((x, y, w, h))
}
7U => {
// commit
ti.commits = ti.commits + 1U
ti.enabled = ti.pend_enabled
match ti.pend_cursor {
Some(r) => ti.cursor = Some(r)
None => if !ti.enabled { ti.cursor = None }
}
}
// set_surrounding_text, set_text_change_cause, set_content_type: not needed to
// insert text.
_ => ()
}
}
_ => ()
}
}
///| enter (opcode 0) or leave (1) for `surface`.
fn send_text_input_surface(c : ClientConn, id : UInt, opcode : UInt, surface : UInt) -> Unit {
let w = WireWriter::new()
w.u32(surface)
c.send_msg(w.finish_msg(id, opcode))
}
///| The client's keyboard focus moved to `surface`: tell its text inputs.
fn text_inputs_enter(c : ClientConn, surface : UInt) -> Unit {
for id, ti in c.text_inputs {
if ti.surface != 0U && ti.surface != surface {
send_text_input_surface(c, id, 1U, ti.surface)
}
if ti.surface != surface {
ti.surface = surface
send_text_input_surface(c, id, 0U, surface)
}
}
}
///| The client lost keyboard focus on `surface`.
fn text_inputs_leave(c : ClientConn, surface : UInt) -> Unit {
for id, ti in c.text_inputs {
if ti.surface == surface {
ti.surface = 0U
// The client disables it in answer; until it commits that, it can't take text anyway.
ti.enabled = false
send_text_input_surface(c, id, 1U, surface)
}
}
}
///| The enabled text inputs on window `win_id`'s surface: (client, ids).
fn WaylandServer::active_text_inputs(self : WaylandServer, win_id : UInt64) -> (ClientConn, Array[UInt])? {
match self.win_client(win_id) {
None => None
Some((c, tl)) => {
let ids : Array[UInt] = []
for id, ti in c.text_inputs {
if ti.enabled && ti.surface == tl.wl_surface_id {
ids.push(id)
}
}
if ids.length() == 0 {
None
} else {
Some((c, ids))
}
}
}
}
///| Whether window `win_id` has a text field taking text right now (an enabled text input on its
/// focused surface).
pub fn WaylandServer::text_input_active(self : WaylandServer, win_id : UInt64) -> Bool {
self.active_text_inputs(win_id) is Some(_)
}
///| The caret of window `win_id`'s active text input, relative to its surface: (x, y, w, h).
pub fn WaylandServer::text_input_cursor(self : WaylandServer, win_id : UInt64) -> (Int, Int, Int, Int)? {
match self.active_text_inputs(win_id) {
Some((c, ids)) =>
match c.text_inputs.get(ids[0]) {
Some(ti) => ti.cursor
None => None
}
None => None
}
}
///| Type `text` into window `win_id`'s focused text field (commit_string + done). False when it
/// has no enabled text input: nothing was sent.
pub fn WaylandServer::text_input_commit(self : WaylandServer, win_id : UInt64, text : String) -> Bool {
match self.active_text_inputs(win_id) {
None => false
Some((c, ids)) => {
for id in ids {
let ti = c.text_inputs.get(id).unwrap()
let w = WireWriter::new()
w.str(text)
c.send_msg(w.finish_msg(id, 3U)) // commit_string
let d = WireWriter::new()
d.u32(ti.commits)
c.send_msg(d.finish_msg(id, 5U)) // done
}
true
}
}
}