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
+4940 -39

No files matched your search

+1
View File
@@ -13,3 +13,4 @@ host-native/target/
compositor/*/pkg.generated.mbti compositor/*/pkg.generated.mbti
wasmhost/*/pkg.generated.mbti wasmhost/*/pkg.generated.mbti
__pycache__/ __pycache__/
assets/fonts/NotoColorEmoji.ttf
+1
View File
@@ -136,6 +136,7 @@ new keys)
| Print / Super+Print / Super+Ctrl+Print | Screenshot of the full screen / active window / window under the pointer | | Print / Super+Print / Super+Ctrl+Print | Screenshot of the full screen / active window / window under the pointer |
| Super+Shift+R | Record a region or window (Enter starts) | | Super+Shift+R | Record a region or window (Enter starts) |
| Super+Alt+R / Super+Ctrl+R | Record the whole screen / the window under the pointer | | Super+Alt+R / Super+Ctrl+R | Record the whole screen / the window under the pointer |
| Super+. | Emoji picker: type to search, arrows and Enter to insert into the app you're typing in ([docs/emoji-picker.md](docs/emoji-picker.md)) |
Every screenshot opens in the screenshot editor first: annotate it (arrow, line, rectangle, Every screenshot opens in the screenshot editor first: annotate it (arrow, line, rectangle,
ellipse, pen, highlighter, text, numbered markers), hide parts of it (blur, pixelate, redact) or ellipse, pen, highlighter, text, numbered markers), hide parts of it (blur, pixelate, redact) or
+95
View File
@@ -0,0 +1,95 @@
Noto Color Emoji (assets/fonts/NotoColorEmoji.ttf, fetched by scripts/fetch-emoji-font.sh from
https://github.com/googlefonts/noto-emoji, v2.051): Copyright 2013-2025 Google LLC.
This Font Software is licensed under the SIL Open Font License,
Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font
creation efforts of academic and linguistic communities, and to
provide a free and open framework in which fonts may be shared and
improved in partnership with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply to
any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software
components as distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to,
deleting, or substituting -- in part or in whole -- any of the
components of the Original Version, by changing formats or by porting
the Font Software to a new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed,
modify, redistribute, and sell modified and unmodified copies of the
Font Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components, in
Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the
corresponding Copyright Holder. This restriction only applies to the
primary font name as presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created using
the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
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). /// and where pictures go ("" for ~/Pictures/Screenshots).
mut shot : ShotOverlay? mut shot : ShotOverlay?
mut shot_toast : ShotToast? 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 shot_request : (ShotMode, Int)?
mut rec_request : (ShotMode, Int)? mut rec_request : (ShotMode, Int)?
mut frames_built : Int mut frames_built : Int
@@ -412,6 +419,10 @@ pub fn ChandraCompositor::new(
session_check_at: 0UL, session_check_at: 0UL,
shot: None, shot: None,
shot_toast: None, shot_toast: None,
emoji_ui: None,
emoji_swallow: [],
emoji_cover: None,
emoji_saved: None,
shot_request: None, shot_request: None,
rec_request: None, rec_request: None,
frames_built: 0, frames_built: 0,
@@ -1162,6 +1173,7 @@ fn ChandraCompositor::build_scene(
panel_ops.append(self.switcher_ops()) panel_ops.append(self.switcher_ops())
} }
panel_ops.append(self.screenshot_ops()) panel_ops.append(self.screenshot_ops())
panel_ops.append(self.emoji_ops())
panel_ops.append(self.face_window_ops()) panel_ops.append(self.face_window_ops())
panel_ops.append(self.auth_ops()) panel_ops.append(self.auth_ops())
panel_ops.append(self.auth_notice_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) { if self.screenshot_input(ev, time_ms) {
return 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/network" @network,
"chandra/desktop/compositor/portal" @portal, "chandra/desktop/compositor/portal" @portal,
"chandra/desktop/compositor/polkit" @polkit, "chandra/desktop/compositor/polkit" @polkit,
"chandra/desktop/compositor/emoji" @emoji,
} }
supported_targets = "+native+wasm" 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] { fn offset_ops(ops : Array[@scene.DrawOp], dx : Int, dy : Int) -> Array[@scene.DrawOp] {
ops.map(op => match op { 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) 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 other => other
}) })
} }
+1
View File
@@ -135,6 +135,7 @@ pub fn ChandraCompositor::run_shortcut(self : ChandraCompositor, action : @shell
RecordScreen => self.toggle_recording(ShotMode::FullScreen) RecordScreen => self.toggle_recording(ShotMode::FullScreen)
RecordWindow => self.toggle_recording(ShotMode::WindowUnderCursor) RecordWindow => self.toggle_recording(ShotMode::WindowUnderCursor)
DockApps => ignore(self.open_dock_app(1)) 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"), ("record-window", "Super+Ctrl+R"),
("dock-apps", "Super+1"), ("dock-apps", "Super+1"),
("overview", "Super+W"), ("overview", "Super+W"),
("emoji-picker", "Super+Period"),
] ]
let sc = @shell.Shortcuts::defaults() let sc = @shell.Shortcuts::defaults()
assert_eq(@shell.shortcut_table.length(), want.length()) assert_eq(@shell.shortcut_table.length(), want.length())
+1
View File
@@ -3,6 +3,7 @@ import {
"chandra/desktop/compositor/scene" @scene, "chandra/desktop/compositor/scene" @scene,
"chandra/desktop/compositor/renderer" @renderer, "chandra/desktop/compositor/renderer" @renderer,
"chandra/desktop/compositor/sys" @sys, "chandra/desktop/compositor/sys" @sys,
"chandra/desktop/compositor/emoji" @emoji,
"chandra/desktop/interface/chandra/host/raster" @hostraster, "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 /// 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`. /// its windows forward. See `Shortcuts::dock_app`.
DockApps DockApps
/// The emoji picker (compositor/host/emoji_picker.mbt), like Windows' Win+.
EmojiPicker
} derive(Eq, Debug) } derive(Eq, Debug)
///| One row of the shortcut table. ///| 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: "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: "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: "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). ///| 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 /// :restore-session false ; don't reopen them (absent: reopen); the session settings module
/// ; or a hand edit sets it /// ; or a hand edit sets it
/// :remember-windows false ; don't place windows where they were left (absent: do) /// :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) /// ; 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 /// 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 /// 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) 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 ///| 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. /// 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 { 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) ObjPrimaryOffer(UInt, UInt)
ObjCursorShapeMgr ObjCursorShapeMgr
ObjCursorShapeDev 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 mut next_offer : UInt
/// wp_cursor_shape_v1 shape the client last asked for (0 = never set). /// wp_cursor_shape_v1 shape the client last asked for (0 = never set).
mut cursor_shape : UInt mut cursor_shape : UInt
/// zwp_text_input_v3 objects, by id (text_input.mbt).
text_inputs : Map[UInt, TextInputState]
mut alive : Bool mut alive : Bool
} }
@@ -272,6 +277,7 @@ fn ClientConn::new(client_id : UInt, fd : Int) -> ClientConn {
source_actions: {}, source_actions: {},
next_offer: 0xff000000U, next_offer: 0xff000000U,
cursor_shape: 0U, cursor_shape: 0U,
text_inputs: {},
alive: true, alive: true,
} }
} }
@@ -345,6 +351,9 @@ pub(all) struct WaylandServer {
mut primary : (UInt, UInt)? mut primary : (UInt, UInt)?
/// Client that currently has keyboard focus (receives selection events). /// Client that currently has keyboard focus (receives selection events).
mut kbd_client : UInt? 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 /// 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. /// (the parent window id is passed). The host sets this; the default never constrains.
mut popup_bounds : (UInt64) -> (Int, Int, Int, Int) mut popup_bounds : (UInt64) -> (Int, Int, Int, Int)
@@ -388,6 +397,7 @@ pub fn WaylandServer::listen(
keymap: Bytes::from_array([]), keymap: Bytes::from_array([]),
selection: None, selection: None,
kbd_client: None, kbd_client: None,
kbd_surface: None,
primary: None, primary: None,
popup_bounds: fn(_) { (-1000000, -1000000, 2000000, 2000000) }, popup_bounds: fn(_) { (-1000000, -1000000, 2000000, 2000000) },
own_mimes: [], own_mimes: [],
@@ -460,6 +470,7 @@ fn emit_registry_globals(c : ClientConn, reg_id : UInt) -> Unit {
(9U, "wp_cursor_shape_manager_v1", 1U), (9U, "wp_cursor_shape_manager_v1", 1U),
(10U, "org_kde_kwin_server_decoration_manager", 1U), (10U, "org_kde_kwin_server_decoration_manager", 1U),
(11U, "zwp_primary_selection_device_manager_v1", 1U), (11U, "zwp_primary_selection_device_manager_v1", 1U),
(12U, "zwp_text_input_manager_v3", 1U),
] ]
for g in globals { for g in globals {
let w = WireWriter::new() let w = WireWriter::new()
@@ -680,6 +691,8 @@ fn WaylandServer::dispatch_msg(
c.data_ver = ver c.data_ver = ver
} else if iface == "zwp_primary_selection_device_manager_v1" { } else if iface == "zwp_primary_selection_device_manager_v1" {
c.objects.set(new_id, ObjPrimaryManager) 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" { } else if iface == "wl_subcompositor" {
c.objects.set(new_id, ObjSubcompositor) c.objects.set(new_id, ObjSubcompositor)
} else if iface == "wl_output" { } else if iface == "wl_output" {
@@ -1072,6 +1085,7 @@ fn WaylandServer::dispatch_msg(
let id = reader.u32() let id = reader.u32()
c.objects.set(id, ObjCursorShapeDev) c.objects.set(id, ObjCursorShapeDev)
} }
ObjTextInputMgr | ObjTextInput => self.text_input_request(c, kind, obj_id, opcode, reader)
ObjCursorShapeDev => ObjCursorShapeDev =>
if opcode == 1U { if opcode == 1U {
// set_shape(serial, shape) // set_shape(serial, shape)
@@ -2058,6 +2072,7 @@ pub fn WaylandServer::keyboard_enter(self : WaylandServer, win_id : UInt64) -> U
None => () None => ()
Some((c, tl)) => { Some((c, tl)) => {
self.kbd_client = Some(c.client_id) self.kbd_client = Some(c.client_id)
self.kbd_surface = Some((c.client_id, tl.wl_surface_id))
self.send_selection(c) self.send_selection(c)
self.send_primary(c) self.send_primary(c)
for kid in c.keyboard_ids { for kid in c.keyboard_ids {
@@ -2067,6 +2082,7 @@ pub fn WaylandServer::keyboard_enter(self : WaylandServer, win_id : UInt64) -> U
w.array([]) w.array([])
c.send_msg(w.finish_msg(kid, 1U)) 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 { pub fn WaylandServer::keyboard_leave(self : WaylandServer, win_id : UInt64) -> Unit {
match self.win_client(win_id) { match self.win_client(win_id) {
None => () None => ()
Some((c, tl)) => Some((c, tl)) => {
for kid in c.keyboard_ids { for kid in c.keyboard_ids {
let w = WireWriter::new() let w = WireWriter::new()
w.u32(self.next_serial()) w.u32(self.next_serial())
w.u32(tl.wl_surface_id) w.u32(tl.wl_surface_id)
c.send_msg(w.finish_msg(kid, 2U)) 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
}
}
}
+93
View File
@@ -0,0 +1,93 @@
# Emoji picker (Super+.)
Like Windows' Win+.: **Super+.** opens a panel at the text cursor with a search field, category
tabs, a grid of emoji and a skin tone choice. The emoji you pick goes where you were typing.
![The picker over an app](screenshots/emoji-picker.png)
## Using it
| Key | Does |
|---|---|
| typing | searches every category: names and CLDR keywords ("lol", "yay", "germany"); a leading `:` is skipped |
| arrows, Page Up/Down, Home/End | move the selection |
| Enter | insert the selected emoji and close |
| Shift+Enter | insert it and stay open (for several in a row) |
| Tab / Shift+Tab | next / previous category (clears the search) |
| Ctrl+Right / Ctrl+Left | next / previous skin tone |
| Backspace | delete the last search letter |
| Esc, Super+., a click outside | close |
With the mouse: click an emoji to insert it (Shift+click keeps the picker open), click a tab or
a skin tone, scroll the grid with the wheel.
Tabs: Recent, Smileys, People, Animals, Food, Activities, Travel, Objects, Symbols, Flags. The
picker opens on Recent when you have used emoji before, else on Smileys. The skin tone applies to
every emoji that has skin tone variants; recent emoji keep the tone they were inserted with.
The shortcut is the "Emoji picker" row of Settings > Shortcuts (id `emoji-picker` in state.edn's
`:shortcuts`), so it can be rebound. `chandra-ctl shortcut emoji-picker` opens it from a terminal.
## Where the emoji goes
The app keeps the keyboard focus while the picker is up (the picker takes the keys, as an input
method's popup does), so its text field stays active. Then:
- **The app has a text field active (text-input-v3):** the emoji is typed into it at the cursor
(`zwp_text_input_v3.commit_string`), in any keyboard layout. The picker is placed under the
cursor when the app says where that is.
- **It doesn't:** the emoji is put on the clipboard and a notification says so, with the reason
("Emoji copied: paste it with Ctrl+V"). Chandra doesn't press Ctrl+V for the app: in a terminal
that is a control character, not paste.
Apps that speak text-input-v3, and so get the emoji typed in: GTK 3 and GTK 4 apps (GNOME apps,
gedit, Ghostty), Qt 6 apps (Kate, KWrite, Konsole, Dolphin), Firefox, foot, kitty, Alacritty.
Chrome, Chromium and Electron apps only with `--enable-wayland-ime` on their command line;
without it they get the clipboard. Qt 5 apps speak an older protocol (text-input v2) and get the
clipboard. This was tested with a fake text-input client in the compositor tests (and the
headless host); the app list is what those toolkits document, not checked one by one here.
## The emoji font
The pictures come from Noto Color Emoji, the bitmap (CBDT) edition: Chandra reads the PNG for each
emoji from the font and the font's ligatures for sequences (skin tones, families, flags,
keycaps). This was checked against HarfBuzz on all 3,963 emoji of Emoji 18.0: the same picture for
every one the font has. stb_truetype, which draws Chandra's text, has no colour glyphs.
Chandra uses its own copy, `assets/fonts/NotoColorEmoji.ttf` (v2.051, OFL), not the system's:
distributions ship different editions, and Fedora's is COLRv1 (vector paint graphs), which this
reader doesn't draw. `scripts/fetch-emoji-font.sh` downloads it (pinned by SHA-256); `just
install`, `just run*` and `just test` run it, or run `just emoji-font`. Without it the picker
opens with an error that says what is missing and how to get it. `CHANDRA_EMOJI_FONT=/path` uses
another bitmap emoji font (its errors are shown the same way).
Emoji newer than the font (9 of Emoji 18.0's with v2.051) aren't listed; the log says how many.
## Data
`compositor/emoji/data.mbt` is generated by `scripts/gen-emoji-data.py` from Unicode
`emoji-test.txt` (Emoji 18.0: every emoji in CLDR order with its group and name) and the CLDR 49
English annotations (search keywords): 1,923 emoji, 332 with skin tones. Both sources are under
the Unicode License v3 (`third_party/unicode-emoji/`). Run the script to regenerate it.
## state.edn
:emoji {:recent ["👍🏽" "🍕"] :skin-tone 3}
Recent emoji (newest first, at most 40, as inserted) and the skin tone (0 default, 1 light .. 5
dark). Read at the first Super+. of a session and written when they change.
## Code and cost
- `compositor/emoji/`: the data and search (emoji.mbt), the picker's state and keys without
drawing (picker.mbt), and the font reader (font.mbt: cmap format 12, GSUB ligatures, CBLC/CBDT).
- `compositor/wayland/text_input.mbt`: zwp_text_input_manager_v3 (enter/leave with keyboard focus,
double-buffered enable/disable/cursor rectangle, commit_string + done).
- `compositor/host/emoji_picker.mbt`: drawing, keys, clicks, insertion, the notification.
- `wit/host/raster.wit`: `emoji-font`, `emoji-has`, `emoji-image`. The wasm host reads the font
and decodes the pictures (a native call each); the compositor component only gets image handles.
Each emoji is decoded once per size (28 px in the grid, 20 px on the tabs and tones, 48 px in the
notification) and kept, about 3 KB a picture; a screenful is about 70 of them. Nothing is drawn or
kept running while the picker is closed, and an open picker costs nothing until a key or the
pointer changes it (0% CPU idle, measured on the headless host).
Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

+35 -15
View File
@@ -15,6 +15,15 @@ fn wasmImportThumbnail(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int = "chandra
///| ///|
fn wasmImportImagePixels(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int) -> Int = "chandra:host/raster@0.1.0" "image-pixels" fn wasmImportImagePixels(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int) -> Int = "chandra:host/raster@0.1.0" "image-pixels"
///|
fn wasmImportEmojiFont(p0 : Int) = "chandra:host/raster@0.1.0" "emoji-font"
///|
fn wasmImportEmojiHas(p0 : Int, p1 : Int, p2 : Int) = "chandra:host/raster@0.1.0" "emoji-has"
///|
fn wasmImportEmojiImage(p0 : Int, p1 : Int, p2 : Int) -> Int = "chandra:host/raster@0.1.0" "emoji-image"
///| ///|
fn wasmImportSubmit(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int, p5 : Int, p6 : Int, p7 : Int, p8 : Int, p9 : Int, p10 : Int, p11 : Int, p12 : Int) = "chandra:host/raster@0.1.0" "submit" fn wasmImportSubmit(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int, p5 : Int, p6 : Int, p7 : Int, p8 : Int, p9 : Int, p10 : Int, p11 : Int, p12 : Int) = "chandra:host/raster@0.1.0" "submit"
@@ -43,10 +52,25 @@ fn wasmImportSnapshotPng(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int) = "ch
fn wasmImportSnapshotPixels(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int, p5 : Int, p6 : Int) = "chandra:host/raster@0.1.0" "snapshot-pixels" fn wasmImportSnapshotPixels(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int, p5 : Int, p6 : Int) = "chandra:host/raster@0.1.0" "snapshot-pixels"
///| ///|
#owned(str) extern "wasm" fn mbt_ffi_free(position : Int) =
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int = #|(func (param i32) local.get 0 call $moonbit.decref)
///|
extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
#|(func (param i32) (param i32) (result i32)
#| local.get 0
#| local.get 1 call $moonbit.init_array16
#| local.get 0)
///|
#owned(bytes)
extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int =
#|(func (param i32) (result i32) local.get 0) #|(func (param i32) (result i32) local.get 0)
///|
extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load8_u)
///| ///|
extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) = extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8) #|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8)
@@ -55,19 +79,6 @@ extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) =
extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) = extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store) #|(func (param i32) (param i32) local.get 0 local.get 1 i32.store)
///|
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load)
///|
#owned(bytes)
extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int =
#|(func (param i32) (result i32) local.get 0)
///|
extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref)
///| ///|
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
#|(func (param i32) (result i32) (local i32) #|(func (param i32) (result i32) (local i32)
@@ -75,6 +86,15 @@ extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
#| local.tee 1 i32.const 0 call $moonbit.init_array8 #| local.tee 1 i32.const 0 call $moonbit.init_array8
#| local.get 1) #| local.get 1)
///|
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load)
///|
#owned(str)
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int =
#|(func (param i32) (result i32) local.get 0)
///| ///|
extern "wasm" fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] = extern "wasm" fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] =
#|(func (param i32) (param i32) (result i32) #|(func (param i32) (param i32) (result i32)
+34 -9
View File
@@ -26,8 +26,18 @@ fn wasmImportImagePixels(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int) -> In
} }
///| ///|
fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int { fn wasmImportEmojiFont(p0 : Int) -> Unit {
abort("wasm-only") abort("wasm-only host import")
}
///|
fn wasmImportEmojiHas(p0 : Int, p1 : Int, p2 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportEmojiImage(p0 : Int, p1 : Int, p2 : Int) -> Int {
abort("wasm-only host import")
} }
///| ///|
@@ -76,7 +86,22 @@ fn wasmImportSnapshotPixels(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int, p5
} }
///| ///|
fn mbt_ffi_str2ptr(str : String) -> Int { fn mbt_ffi_free(position : Int) -> Unit {
abort("wasm-only")
}
///|
fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String {
abort("wasm-only")
}
///|
fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int {
abort("wasm-only")
}
///|
fn mbt_ffi_load8_u(offset : Int) -> Int {
abort("wasm-only") abort("wasm-only")
} }
@@ -90,18 +115,18 @@ fn mbt_ffi_store32(offset : Int, value : Int) -> Unit {
abort("wasm-only") abort("wasm-only")
} }
///|
fn mbt_ffi_malloc(size : Int) -> Int {
abort("wasm-only")
}
///| ///|
fn mbt_ffi_load32(offset : Int) -> Int { fn mbt_ffi_load32(offset : Int) -> Int {
abort("wasm-only") abort("wasm-only")
} }
///| ///|
fn mbt_ffi_free(position : Int) -> Unit { fn mbt_ffi_str2ptr(str : String) -> Int {
abort("wasm-only")
}
///|
fn mbt_ffi_malloc(size : Int) -> Int {
abort("wasm-only") abort("wasm-only")
} }
+78 -2
View File
@@ -105,8 +105,83 @@ pub fn image_pixels(w : Int, h : Int, rgba : FixedArray[Byte], reuse : UInt) ->
let ptr = mbt_ffi_bytes2ptr(rgba) let ptr = mbt_ffi_bytes2ptr(rgba)
let result : Int = wasmImportImagePixels(w, h, ptr, rgba.length(), (reuse).reinterpret_as_int()); let result : Int = wasmImportImagePixels(w, h, ptr, rgba.length(), (reuse).reinterpret_as_int());
mbt_ffi_free(ptr)
let ret = (result).reinterpret_as_uint() let ret = (result).reinterpret_as_uint()
mbt_ffi_free(ptr)
return ret
}
///|
/// Open the colour emoji font (Noto Color Emoji from the usual places, or the file
/// CHANDRA_EMOJI_FONT names) for the emoji picker: the path it was read from, or a message
/// saying why there is none and what to install. Read once; later calls give the same answer.
pub fn emoji_font() -> Result[String, String] {
let return_area = mbt_ffi_malloc(12)
wasmImportEmojiFont(return_area);
let lifted = match (mbt_ffi_load8_u((return_area) + 0)) {
0 => {
let result = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 4), mbt_ffi_load32((return_area) + 8))
Result::Ok(result)
}
1 => {
let result0 = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 4), mbt_ffi_load32((return_area) + 8))
Result::Err(result0)
}
_ => panic()
}
let ret = lifted
mbt_ffi_free(return_area)
return ret
}
///|
/// For each emoji in `texts`, whether the font has one picture for it.
pub fn emoji_has(texts : Array[String]) -> Array[Bool] {
let cleanup_list : Array[Int] = []
let address = mbt_ffi_malloc((texts).length() * 8);
for index = 0; index < (texts).length(); index = index + 1 {
let iter_elem : String = (texts)[(index)]
let iter_base = address + (index * 8);
let ptr = mbt_ffi_str2ptr(iter_elem)
mbt_ffi_store32((iter_base) + 4, iter_elem.length())
mbt_ffi_store32((iter_base) + 0, ptr)
cleanup_list.push(ptr)
}
let return_area = mbt_ffi_malloc(8)
wasmImportEmojiHas(address, (texts).length(), return_area);
let array : Array[Bool] = [];
for index0 = 0; index0 < (mbt_ffi_load32((return_area) + 4)); index0 = index0 + 1 {
let iter_base = (mbt_ffi_load32((return_area) + 0)) + (index0 * 1)
array.push((mbt_ffi_load8_u((iter_base) + 0) != 0))
}
mbt_ffi_free(mbt_ffi_load32((return_area) + 0))
let ret = array
mbt_ffi_free(address)
mbt_ffi_free(return_area)
cleanup_list.each(mbt_ffi_free)
return ret
}
///|
/// The font's picture for emoji `text`, scaled to fit `px` x `px`, as an image for `draw-image`
/// (the same text and size give the same handle). 0 when the font has none or isn't open.
pub fn emoji_image(text : String, px : Int) -> UInt {
let ptr = mbt_ffi_str2ptr(text)
let result : Int = wasmImportEmojiImage(ptr, text.length(), px);
let ret = (result).reinterpret_as_uint()
mbt_ffi_free(ptr)
return ret return ret
} }
@@ -650,7 +725,7 @@ pub fn write_frame_png(path : String) -> Bool {
/// the queue is full (the encoder is behind). /// the queue is full (the encoder is behind).
pub fn grab_recording_frame(x : Int, y : Int, w : Int, h : Int, pointer : Bool, px : Int, py : Int) -> Bool { pub fn grab_recording_frame(x : Int, y : Int, w : Int, h : Int, pointer : Bool, px : Int, py : Int) -> Bool {
let result : Int = wasmImportGrabRecordingFrame(x, y, w, h, if pointer { 1 } else { 0 }, px, py); let result : Int = wasmImportGrabRecordingFrame(x, y, w, h, (if pointer { 1 } else { 0 }), px, py);
let ret = (result != 0) let ret = (result != 0)
return ret return ret
@@ -704,3 +779,4 @@ pub fn snapshot_pixels(x : Int, y : Int, w : Int, h : Int, out_w : Int, out_h :
return ret return ret
} }
+13 -9
View File
@@ -26,6 +26,10 @@ tcc-build:
make -j"$(nproc)" >/dev/null make -j"$(nproc)" >/dev/null
make install >/dev/null make install >/dev/null
# Fetch the emoji picker's font (Noto Color Emoji, bitmap edition) into assets/fonts, once: scripts/fetch-emoji-font.sh.
emoji-font:
scripts/fetch-emoji-font.sh
# Build the panel's wasm modules (application menu, task list, clock, ...) into build/components. # Build the panel's wasm modules (application menu, task list, clock, ...) into build/components.
modules: modules:
pixi run modules pixi run modules
@@ -48,17 +52,17 @@ auth-demo mode="password":
python3 session/chandra-ctl auth-demo {{mode}} python3 session/chandra-ctl auth-demo {{mode}}
# Run the compositor, built as a wasm component, in a window on your current Wayland session (close the window or Ctrl-C to stop). Connect clients via `just client`. # Run the compositor, built as a wasm component, in a window on your current Wayland session (close the window or Ctrl-C to stop). Connect clients via `just client`.
run: compositor-wasm wasmhost modules run: compositor-wasm wasmhost modules emoji-font
rm -f {{socket}} rm -f {{socket}}
build/wasmhost build/compositor.wasm --socket {{socket}} --theme {{theme}} --window build/wasmhost build/compositor.wasm --socket {{socket}} --theme {{theme}} --window
# On an X server (NVIDIA's proprietary driver, docs/x11.md): a window under a window manager, or the whole screen without one. # On an X server (NVIDIA's proprietary driver, docs/x11.md): a window under a window manager, or the whole screen without one.
run-x11: compositor-wasm wasmhost modules run-x11: compositor-wasm wasmhost modules emoji-font
rm -f {{socket}} rm -f {{socket}}
build/wasmhost build/compositor.wasm --socket {{socket}} --theme {{theme}} --x11 build/wasmhost build/compositor.wasm --socket {{socket}} --theme {{theme}} --x11
# Run the native compositor (tcc debug build, with the wasm panel modules) in a window on your current Wayland session. # Run the native compositor (tcc debug build, with the wasm panel modules) in a window on your current Wayland session.
run-native: build modules run-native: build modules emoji-font
rm -f {{socket}} rm -f {{socket}}
{{exe}} --window --socket {{socket}} --theme {{theme}} {{exe}} --window --socket {{socket}} --theme {{theme}}
@@ -84,14 +88,14 @@ run-headless: build modules
{{exe}} --socket {{socket}} --theme {{theme}} {{exe}} --socket {{socket}} --theme {{theme}}
# Run the wasm compositor on the real display (DRM/KMS + libinput, through the host). Run from a login VT (Ctrl+Alt+F3), not inside another session. Ctrl+Alt+Backspace quits, Ctrl+Alt+F<n> switches VT. # Run the wasm compositor on the real display (DRM/KMS + libinput, through the host). Run from a login VT (Ctrl+Alt+F3), not inside another session. Ctrl+Alt+Backspace quits, Ctrl+Alt+F<n> switches VT.
run-drm: compositor-wasm wasmhost modules run-drm: compositor-wasm wasmhost modules emoji-font
rm -f {{socket}} rm -f {{socket}}
# Let D-Bus-activated helpers (gcr-prompter's keyring unlock prompt, portals) open windows here. # Let D-Bus-activated helpers (gcr-prompter's keyring unlock prompt, portals) open windows here.
-dbus-update-activation-environment --systemd WAYLAND_DISPLAY=$(basename {{socket}}) XDG_SESSION_TYPE=wayland XDG_CURRENT_DESKTOP=chandra 2>/dev/null -dbus-update-activation-environment --systemd WAYLAND_DISPLAY=$(basename {{socket}}) XDG_SESSION_TYPE=wayland XDG_CURRENT_DESKTOP=chandra 2>/dev/null
build/wasmhost build/compositor.wasm --drm --socket {{socket}} --theme {{theme}} build/wasmhost build/compositor.wasm --drm --socket {{socket}} --theme {{theme}}
# The same on the native compositor (system-cc release build), for comparison. # The same on the native compositor (system-cc release build), for comparison.
run-drm-native: build-release modules run-drm-native: build-release modules emoji-font
rm -f {{socket}} rm -f {{socket}}
-dbus-update-activation-environment --systemd WAYLAND_DISPLAY=$(basename {{socket}}) XDG_SESSION_TYPE=wayland XDG_CURRENT_DESKTOP=chandra 2>/dev/null -dbus-update-activation-environment --systemd WAYLAND_DISPLAY=$(basename {{socket}}) XDG_SESSION_TYPE=wayland XDG_CURRENT_DESKTOP=chandra 2>/dev/null
{{release_exe}} --drm --socket {{socket}} --theme {{theme}} {{release_exe}} --drm --socket {{socket}} --theme {{theme}}
@@ -100,11 +104,11 @@ run-drm-native: build-release modules
install *flags: install *flags:
#!/usr/bin/env bash #!/usr/bin/env bash
set -euo pipefail set -euo pipefail
builds="compositor-wasm wasmhost modules auth-agent" builds="compositor-wasm wasmhost modules auth-agent emoji-font"
face=1 face=1
for f in {{flags}}; do for f in {{flags}}; do
case "$f" in case "$f" in
--native) builds="build-release modules auth-agent" ;; --native) builds="build-release modules auth-agent emoji-font" ;;
--rust) echo "just install: --rust is gone: the Rust host was removed (2026-11-26); the MoonBit host is the only one" >&2; exit 2 ;; --rust) echo "just install: --rust is gone: the Rust host was removed (2026-11-26); the MoonBit host is the only one" >&2; exit 2 ;;
--no-face) face=0 ;; --no-face) face=0 ;;
--link|--pam|--no-models) ;; --link|--pam|--no-models) ;;
@@ -150,8 +154,8 @@ remote-build *targets:
scripts/remote-build.sh {{targets}} scripts/remote-build.sh {{targets}}
# Compositor + wasm component + lib tests. # Compositor + wasm component + lib tests.
test: modules test: modules emoji-font
XDG_CONFIG_HOME="$(mktemp -d)" CHANDRA_TEST_CONFIG=1 moon test --target native --warn-list -a compositor/renderer compositor/wasm compositor/host XDG_CONFIG_HOME="$(mktemp -d)" CHANDRA_TEST_CONFIG=1 moon test --target native --warn-list -a compositor/renderer compositor/wasm compositor/emoji compositor/host
moon test --target wasm --warn-list -a lib/shell lib/panel lib/clock lib/launcher lib/wm lib/taskbar lib/layoutpick lib/modmgr moon test --target wasm --warn-list -a lib/shell lib/panel lib/clock lib/launcher lib/wm lib/taskbar lib/layoutpick lib/modmgr
# Render one composed frame to _build/e2e_frame.png (via the e2e test). # Render one composed frame to _build/e2e_frame.png (via the e2e test).
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env bash
# Fetch Chandra's colour emoji font: Noto Color Emoji 2.051, the bitmap (CBDT) edition, into
# assets/fonts/NotoColorEmoji.ttf (SIL Open Font License 1.1, see assets/fonts/LICENSE-NotoColorEmoji).
#
# Chandra reads its own copy rather than the system's: distributions ship different editions, and
# Fedora's is COLRv1 (vector paint graphs), which Chandra's emoji picker can't draw. `just install`,
# `just run*` and `just test` run this; it downloads only when the file is missing or different.
set -euo pipefail
cd "$(dirname "$0")/.."
version=v2.051
sha=72a635cb3d2f3524c51620cdde406b217204e8a6a06c6a096ff8ed4b5fd6e27b
url=https://raw.githubusercontent.com/googlefonts/noto-emoji/$version/fonts/NotoColorEmoji.ttf
dst=assets/fonts/NotoColorEmoji.ttf
if [ -f "$dst" ] && echo "$sha $dst" | sha256sum --check --status; then
exit 0
fi
echo "fetching Noto Color Emoji $version (10 MB) from $url" >&2
tmp=$(mktemp "$dst.XXXXXX")
trap 'rm -f "$tmp"' EXIT
if ! curl -fL --retry 3 -o "$tmp" "$url"; then
echo "error: couldn't download Noto Color Emoji from $url; the emoji picker (Super+.) needs it at $dst" >&2
exit 1
fi
if ! echo "$sha $tmp" | sha256sum --check --status; then
echo "error: $url is not the expected Noto Color Emoji $version (sha256 differs: $(sha256sum "$tmp" | cut -d' ' -f1))" >&2
exit 1
fi
mv "$tmp" "$dst"
trap - EXIT
echo "installed $dst" >&2
+141
View File
@@ -0,0 +1,141 @@
#!/usr/bin/env python3
"""Generate compositor/emoji/data.mbt: the emoji picker's emoji, names and search keywords.
Sources (Unicode License v3, see third_party/unicode-emoji/LICENSE):
- Unicode emoji-test.txt (Emoji 18.0): every emoji, in CLDR order, with its group and name.
- CLDR annotations (en.xml and annotationsDerived/en.xml, release 49): search keywords.
scripts/gen-emoji-data.py # downloads the pinned sources
scripts/gen-emoji-data.py DIR # reads emoji-test.txt, en.xml, en-derived.xml from DIR
One line per emoji the picker lists (skin tone variants are not listed: they hang off their base):
GROUP \t EMOJI \t NAME \t KEYWORDS \t TONES
GROUP is the picker tab (0 Smileys .. 8 Flags), KEYWORDS are space-separated lowercase words,
TONES is empty or the five skin tone variants (light .. dark) separated by spaces.
"""
import os
import sys
import urllib.request
import xml.etree.ElementTree as ET
EMOJI_TEST = "https://www.unicode.org/Public/18.0.0/emoji/emoji-test.txt"
CLDR = "https://raw.githubusercontent.com/unicode-org/cldr/release-49/common/"
SOURCES = {
"emoji-test.txt": EMOJI_TEST,
"en.xml": CLDR + "annotations/en.xml",
"en-derived.xml": CLDR + "annotationsDerived/en.xml",
}
# emoji-test.txt group -> picker tab. "Component" (bare skin tones, hair styles) is not listed.
GROUPS = {
"Smileys & Emotion": 0,
"People & Body": 1,
"Animals & Nature": 2,
"Food & Drink": 3,
"Activities": 4,
"Travel & Places": 5,
"Objects": 6,
"Symbols": 7,
"Flags": 8,
}
TONES = [0x1F3FB, 0x1F3FC, 0x1F3FD, 0x1F3FE, 0x1F3FF]
def read_sources(src_dir):
out = {}
for name, url in SOURCES.items():
if src_dir:
path = os.path.join(src_dir, name)
if not os.path.exists(path):
sys.exit(f"gen-emoji-data: {path} is missing (expected {url})")
with open(path, encoding="utf-8") as f:
out[name] = f.read()
else:
with urllib.request.urlopen(url) as r:
out[name] = r.read().decode("utf-8")
return out
def annotations(xml_text):
"""CLDR annotation keywords and names, keyed by the emoji without FE0F."""
words, names = {}, {}
root = ET.fromstring(xml_text)
for a in root.iter("annotation"):
cp = a.get("cp")
if a.get("type") == "tts":
names[cp] = a.text.strip()
else:
words[cp] = [w.strip() for w in a.text.split("|") if w.strip()]
return words, names
def keyword_list(seq_key, words, name):
seen, out = set(), []
for phrase in words.get(seq_key, []):
for w in phrase.lower().replace(":", " ").replace(",", " ").split():
if w not in seen and w not in name.split():
seen.add(w)
out.append(w)
return out
def main():
src = read_sources(sys.argv[1] if len(sys.argv) > 1 else None)
words, _ = annotations(src["en.xml"])
dwords, _ = annotations(src["en-derived.xml"])
words = {**dwords, **words}
entries = [] # [tab, emoji, name, keywords, tones]
by_key = {} # base without FE0F and tones -> entry
group = None
for line in src["emoji-test.txt"].splitlines():
if line.startswith("# group:"):
group = line.split(":", 1)[1].strip()
continue
if not line or line.startswith("#") or "; fully-qualified" not in line:
continue
if group not in GROUPS:
if group != "Component":
sys.exit(f"gen-emoji-data: unknown group {group!r}")
continue
cps = [int(x, 16) for x in line.split(";")[0].split()]
name = line.split("#", 1)[1].strip().split(" ", 2)[2] # "😀 E1.0 grinning face"
seq = "".join(chr(c) for c in cps)
key = tuple(c for c in cps if c != 0xFE0F and c not in TONES)
tones = {c for c in cps if c in TONES}
if not tones:
e = [GROUPS[group], seq, name, keyword_list(seq.replace("️", ""), words, name), [""] * 5]
entries.append(e)
by_key[key] = e
elif len(tones) == 1 and key in by_key:
# One tone for every person in it: the variant the picker's skin tone choice picks.
by_key[key][4][TONES.index(tones.pop())] = seq
for e in entries:
if any(e[4]) and not all(e[4]):
sys.exit(f"gen-emoji-data: {e[2]} has only some skin tones: {e[4]}")
entries.sort(key=lambda e: e[0]) # stable: CLDR order within each tab
lines = []
for tab, seq, name, kws, tones in entries:
for field in (seq, name, *kws, *tones):
if "\t" in field or "\n" in field or '"' in field or "\\" in field:
sys.exit(f"gen-emoji-data: unexpected character in {field!r}")
lines.append("\t".join([str(tab), seq, name, " ".join(kws), " ".join(tones) if any(tones) else ""]))
out = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "compositor", "emoji", "data.mbt")
with open(out, "w", encoding="utf-8") as f:
f.write("// Generated by scripts/gen-emoji-data.py from Unicode emoji-test.txt (Emoji 18.0) and CLDR\n")
f.write("// annotations (release 49); Unicode License v3, see third_party/unicode-emoji/LICENSE. Don't edit.\n\n")
f.write("///| One line per emoji: tab, emoji, name, keywords, skin tone variants (tab-separated).\n")
f.write("let emoji_data : String =\n")
for ln in lines:
f.write(" #|" + ln + "\n")
toned = sum(1 for e in entries if any(e[4]))
print(f"gen-emoji-data: {len(entries)} emoji ({toned} with skin tones) -> {os.path.normpath(out)}")
if __name__ == "__main__":
main()
+3 -1
View File
@@ -50,8 +50,10 @@ if [ -d "$WASMER/lib" ]; then
export LIBRARY_PATH="$WASMER/lib${LIBRARY_PATH:+:$LIBRARY_PATH}" export LIBRARY_PATH="$WASMER/lib${LIBRARY_PATH:+:$LIBRARY_PATH}"
export LD_LIBRARY_PATH="$WASMER/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" export LD_LIBRARY_PATH="$WASMER/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
fi fi
# The emoji picker's font (Noto Color Emoji, bitmap edition): compositor/emoji's tests read it.
scripts/fetch-emoji-font.sh
XDG_CONFIG_HOME="$(mktemp -d)" CHANDRA_TEST_CONFIG=1 \ XDG_CONFIG_HOME="$(mktemp -d)" CHANDRA_TEST_CONFIG=1 \
moon test --target native --warn-list -a compositor/renderer compositor/gfx compositor/wasm \ moon test --target native --warn-list -a compositor/renderer compositor/gfx compositor/wasm \
compositor/network compositor/portal compositor/polkit compositor/x11 compositor/host compositor/network compositor/portal compositor/polkit compositor/x11 compositor/emoji compositor/host
scripts/test-private-bus.sh scripts/test-private-bus.sh
moon build --target native --warn-list -a compositor/bin moon build --target native --warn-list -a compositor/bin
+39
View File
@@ -0,0 +1,39 @@
UNICODE LICENSE V3
COPYRIGHT AND PERMISSION NOTICE
Copyright © 1991-2026 Unicode, Inc.
NOTICE TO USER: Carefully read the following legal agreement. BY
DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR
SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
Permission is hereby granted, free of charge, to any person obtaining a
copy of data files and any associated documentation (the "Data Files") or
software and any associated documentation (the "Software") to deal in the
Data Files or Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, and/or sell
copies of the Data Files or Software, and to permit persons to whom the
Data Files or Software are furnished to do so, provided that either (a)
this copyright and permission notice appear with all copies of the Data
Files or Software, or (b) this copyright and permission notice appear in
associated Documentation.
THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA
FILES OR SOFTWARE.
Except as contained in this notice, the name of a copyright holder shall
not be used in advertising or otherwise to promote the sale, use or other
dealings in these Data Files or Software without prior written
authorization of the copyright holder.
+11
View File
@@ -0,0 +1,11 @@
# Unicode emoji data
compositor/emoji/data.mbt (the emoji picker's emoji, names and search keywords) is generated by
`scripts/gen-emoji-data.py` from:
- Unicode `emoji-test.txt`, Emoji 18.0: https://www.unicode.org/Public/18.0.0/emoji/emoji-test.txt
- CLDR annotations, release 49: `common/annotations/en.xml` and `common/annotationsDerived/en.xml`
from https://github.com/unicode-org/cldr
Both are under the Unicode License v3 (LICENSE here). Only the generated file is in the tree; the
script downloads the pinned sources again to regenerate it.
+1
View File
@@ -6,6 +6,7 @@ import {
"chandra/desktop/compositor/sys" @sys, "chandra/desktop/compositor/sys" @sys,
"chandra/desktop/compositor/font" @font, "chandra/desktop/compositor/font" @font,
"chandra/desktop/compositor/renderer" @renderer, "chandra/desktop/compositor/renderer" @renderer,
"chandra/desktop/compositor/emoji" @emoji,
"chandra/desktop/compositor/wasm" @wasm, "chandra/desktop/compositor/wasm" @wasm,
"chandra/desktop/compositor/kms" @kms, "chandra/desktop/compositor/kms" @kms,
"chandra/desktop/interface/chandra/desktop/types" @types, "chandra/desktop/interface/chandra/desktop/types" @types,
+28 -1
View File
@@ -848,6 +848,21 @@ fn load_image(path : String) -> Int {
h h
} }
///| The colour emoji font, for the emoji picker (`emoji-*`).
let emoji_source : @emoji.EmojiSource = @emoji.EmojiSource::new()
///| Handles of the emoji pictures made so far (shared, like path images: never overwritten).
let emoji_handles : Array[Int] = []
///|
fn emoji_image(text : String, px : Int) -> UInt {
emoji_source.image(text, px, p => {
let h = rs_image_put(0, p.width, p.height, p.data)
emoji_handles.push(h)
h.reinterpret_as_uint()
})
}
///| ///|
fn is_path_image(h : Int) -> Bool { fn is_path_image(h : Int) -> Bool {
for _, v in image_paths { for _, v in image_paths {
@@ -855,7 +870,7 @@ fn is_path_image(h : Int) -> Bool {
return true return true
} }
} }
false emoji_handles.contains(h)
} }
// ---------------------------------------------------------------- the interfaces // ---------------------------------------------------------------- the interfaces
@@ -918,6 +933,18 @@ fn raster_funcs() -> Array[(String, (Array[@wt.Val]) -> Array[@wt.Val])] {
}, },
), ),
("load-image", a => [U32(load_image(a[0].to_string()).reinterpret_as_uint())]), ("load-image", a => [U32(load_image(a[0].to_string()).reinterpret_as_uint())]),
(
"emoji-font",
_ => match emoji_source.font() {
Ok(path) => [Result(true, Some(Str(path)))]
Err(why) => [Result(false, Some(Str(why)))]
},
),
(
"emoji-has",
a => [List(emoji_source.has(a[0].to_list().map(v => v.to_string())).map(b => Bool(b)))],
),
("emoji-image", a => [U32(emoji_image(a[0].to_string(), a[1].to_int()))]),
( (
"image-pixels", "image-pixels",
a => { a => {
+9
View File
@@ -66,6 +66,15 @@ interface raster {
/// picture). `reuse`: an earlier handle from this function or `thumbnail` to overwrite in place, /// picture). `reuse`: an earlier handle from this function or `thumbnail` to overwrite in place,
/// 0 for a new one. 0 when the size is silly or `rgba` is too short. /// 0 for a new one. 0 when the size is silly or `rgba` is too short.
image-pixels: func(w: s32, h: s32, rgba: list<u8>, reuse: u32) -> u32; image-pixels: func(w: s32, h: s32, rgba: list<u8>, reuse: u32) -> u32;
/// Open the colour emoji font (Noto Color Emoji from the usual places, or the file
/// CHANDRA_EMOJI_FONT names) for the emoji picker: the path it was read from, or a message
/// saying why there is none and what to install. Read once; later calls give the same answer.
emoji-font: func() -> result<string, string>;
/// For each emoji in `texts`, whether the font has one picture for it.
emoji-has: func(texts: list<string>) -> list<bool>;
/// The font's picture for emoji `text`, scaled to fit `px` x `px`, as an image for `draw-image`
/// (the same text and size give the same handle). 0 when the font has none or isn't open.
emoji-image: func(text: string, px: s32) -> u32;
/// Draw a frame into the host framebuffer. /// Draw a frame into the host framebuffer.
submit: func(f: frame); submit: func(f: frame);
/// The framebuffer as RGBA8888 (for screenshots and tests; the display path never needs it). /// The framebuffer as RGBA8888 (for screenshots and tests; the display path never needs it).