Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

15.5 KB
Raw Blame
//! Unicode emoji detection and Twemoji image URLs (what Discord itself uses),
//! since egui can't render colour emoji fonts.

/// (17.x has Unicode 16 and 17's emoji; 15.1 showed those as broken images.)
const TWEMOJI_BASE: &str = "https://cdn.jsdelivr.net/gh/jdecked/[email protected]/assets/72x72";

/// In a joined (ZWJ) sequence, Twemoji's file names keep the U+FE0F after
/// these: ♀ ♂ ⚕ ⚖ ✈ ❤ ⚧ ☠ ❄ ⛓ ↔ ↕ ➡ 🏳 🌫 🏋 🏌 🕵 ⛹ (unless a skin tone
/// follows instead).
const ZWJ_KEEPS_VS: &[u32] = &[
    0x2640, 0x2642, 0x2695, 0x2696, 0x2708, 0x2764, 0x26A7, 0x2620, 0x2744, 0x26D3, 0x2194, 0x2195, 0x27A1, 0x1F3F3,
    0x1F32B, 0x1F3CB, 0x1F3CC, 0x1F575, 0x26F9,
];

/// Twemoji pictures that turned out not to exist (HTTP 404): a joined
/// sequence nobody drew shows its first emoji instead of a broken image.
static MISSING: std::sync::Mutex<Option<std::collections::HashSet<String>>> = std::sync::Mutex::new(None);
static ANY_MISSING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// Note that an image URL doesn't exist (only Twemoji ones are kept).
pub fn mark_missing(url: &str) {
    if !url.starts_with(TWEMOJI_BASE) {
        return;
    }
    if let Ok(mut m) = MISSING.lock() {
        m.get_or_insert_with(Default::default).insert(url.to_string());
        ANY_MISSING.store(true, std::sync::atomic::Ordering::Relaxed);
    }
}

/// Length (in chars) of the emoji sequence starting at `i`, if there is one.
/// (The text renderer's own test, so the two never disagree.)
pub use eframe::egui::epaint::emoji::emoji_len;

// ---- emoji in any text ------------------------------------------------------
//
// The (vendored) text renderer leaves a gap for every emoji in every text and
// asks for its picture while it tessellates (`epaint::emoji`). It can't load
// anything itself, so: it is handed the textures that are ready and notes
// which sequences it wanted; `pump_text_emoji` (once a frame) loads those
// through egui's image loaders, the same Twemoji files as everywhere else.

#[derive(Default)]
struct TextEmoji {
    /// Sequence → its texture, for the ones asked for last frame.
    ready: std::collections::HashMap<String, eframe::egui::TextureId>,
    /// Sequences the renderer asked for since the last pump.
    wanted: std::collections::HashSet<String>,
    /// Sequences whose picture couldn't be loaded (no such Twemoji, no
    /// network), and when: they are left alone for a while. Asking again on
    /// every frame kept the window redrawing flat out.
    failed: std::collections::HashMap<String, std::time::Instant>,
}

/// How long a picture that failed to load is left alone.
const RETRY_FAILED: std::time::Duration = std::time::Duration::from_secs(120);

static TEXT_EMOJI: std::sync::Mutex<Option<TextEmoji>> = std::sync::Mutex::new(None);

/// Draw the emoji in every text as Twemoji pictures. Call once at startup.
pub fn install_text_emoji(ctx: &eframe::egui::Context) {
    // The renderer asks while the context is locked, so a first sighting
    // can't request the repaint that loads it: a helper thread does.
    let (wake, woken) = std::sync::mpsc::channel::<()>();
    let repaint = ctx.clone();
    let _ = std::thread::Builder::new().name("rustcord-emoji-wake".into()).spawn(move || {
        while woken.recv().is_ok() {
            while woken.try_recv().is_ok() {}
            repaint.request_repaint();
        }
    });
    let wake = std::sync::Mutex::new(wake);
    eframe::egui::epaint::emoji::set_source(Box::new(move |seq| {
        let mut guard = TEXT_EMOJI.lock().ok()?;
        let state = guard.get_or_insert_with(Default::default);
        if state.failed.get(seq).is_some_and(|at| at.elapsed() < RETRY_FAILED) {
            return None;
        }
        let ready = state.ready.get(seq).copied();
        if !state.wanted.contains(seq) {
            state.wanted.insert(seq.to_string());
            if ready.is_none() {
                if let Ok(w) = wake.lock() {
                    let _ = w.send(());
                }
            }
        }
        ready
    }));
}

/// Load the pictures the text renderer asked for last frame (and keep the
/// ones still on screen alive in the texture cache). Call once per frame.
pub fn pump_text_emoji(ctx: &eframe::egui::Context) {
    use eframe::egui::load::{SizeHint, TexturePoll};
    let wanted = match TEXT_EMOJI.lock() {
        Ok(mut g) => std::mem::take(&mut g.get_or_insert_with(Default::default).wanted),
        Err(_) => return,
    };
    if wanted.is_empty() {
        if let Ok(mut g) = TEXT_EMOJI.lock() {
            if let Some(s) = g.as_mut() {
                s.ready.clear();
            }
        }
        return;
    }
    let mut ready = std::collections::HashMap::with_capacity(wanted.len());
    let mut pending = Vec::new();
    let mut failed = Vec::new();
    for seq in wanted {
        match ctx.try_load_texture(&twemoji_url(&seq), eframe::egui::TextureOptions::LINEAR, SizeHint::default()) {
            Ok(TexturePoll::Ready { texture }) => drop(ready.insert(seq, texture.id)),
            // Still downloading or decoding: ask again when the loader repaints.
            Ok(TexturePoll::Pending { .. }) => pending.push(seq),
            Err(_) => failed.push(seq),
        }
    }
    let Ok(mut g) = TEXT_EMOJI.lock() else { return };
    let state = g.get_or_insert_with(Default::default);
    let now = std::time::Instant::now();
    state.failed.retain(|_, at| at.elapsed() < RETRY_FAILED);
    state.failed.extend(failed.into_iter().map(|seq| (seq, now)));
    // A picture that just arrived: draw the frame again with it.
    if ready.iter().any(|(seq, id)| state.ready.get(seq) != Some(id)) {
        ctx.request_repaint();
    }
    state.ready = ready;
    state.wanted.extend(pending);
}

// ---- finding emoji --------------------------------------------------------------

/// An emoji's other shortcodes and its search words (see `emoji_data::SEARCH`).
fn search_terms(emoji: &str) -> Option<(&'static str, &'static str)> {
    use std::collections::HashMap;
    use std::sync::OnceLock;
    static MAP: OnceLock<HashMap<String, (&'static str, &'static str)>> = OnceLock::new();
    // (Looked up without variation selectors: "👍" and "👍️" are one emoji.)
    let key = |s: &str| s.chars().filter(|c| *c != '\u{FE0F}').collect::<String>();
    MAP.get_or_init(|| crate::emoji_data::SEARCH.iter().map(|(e, codes, words)| (key(e), (*codes, *words))).collect()).get(&key(emoji)).copied()
}

/// How well a standard emoji answers a search, like Discord's picker: by
/// its name (0 the name itself, 1 starts with it, 2 contains it), by one of
/// its other shortcodes (3), or by a word that describes it (4: "laugh"
/// finds 😂). `query` is lowercase; spaces count as underscores in names.
pub fn search_rank(emoji: &str, name: &str, query: &str) -> Option<u8> {
    let q = query.trim().trim_matches(':').replace(' ', "_");
    if q.is_empty() {
        return Some(0);
    }
    if name == q {
        return Some(0);
    }
    if name.starts_with(&q) {
        return Some(1);
    }
    if name.contains(&q) {
        return Some(2);
    }
    let (codes, words) = search_terms(emoji)?;
    if codes.split(' ').any(|c| c.contains(&q)) {
        return Some(3);
    }
    // Every word typed has to begin one of the emoji's words.
    let typed: Vec<&str> = query.split_whitespace().collect();
    (!typed.is_empty() && typed.iter().all(|t| words.split(' ').any(|w| w.starts_with(t)))).then_some(4)
}

/// The standard emoji for a shortcode typed out, by any of its names
/// (":joy:", ":tears_of_joy:", ":+1:").
pub fn by_any_name(name: &str) -> Option<&'static str> {
    use std::collections::HashMap;
    use std::sync::OnceLock;
    static MAP: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();
    let map = MAP.get_or_init(|| {
        let mut m: HashMap<&'static str, &'static str> = HashMap::new();
        for (emoji, codes, _) in crate::emoji_data::SEARCH.iter() {
            for code in codes.split(' ').filter(|c| !c.is_empty()) {
                m.entry(code).or_insert(*emoji);
            }
        }
        // (An emoji's own name wins over another's alias.)
        for (emoji, name) in crate::emoji_data::CATEGORIES.iter().flat_map(|(_, items)| items.iter()) {
            m.insert(*name, *emoji);
        }
        m
    });
    map.get(name).copied()
}

// ---- skin tones ---------------------------------------------------------------

/// The skin tone the emoji picker is set to: 0 none (yellow), 1 light … 5
/// dark. Discord's "diversity" selector; kept in RustCord's own preferences.
static SKIN_TONE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);

pub fn skin_tone() -> u8 {
    SKIN_TONE.load(std::sync::atomic::Ordering::Relaxed)
}

pub fn set_skin_tone(tone: u8) {
    SKIN_TONE.store(tone.min(5), std::sync::atomic::Ordering::Relaxed);
}

/// `emoji` in a skin tone (1..=5), if it comes in tones.
pub fn toned(emoji: &str, tone: u8) -> Option<&'static str> {
    use std::collections::HashMap;
    use std::sync::OnceLock;
    static MAP: OnceLock<HashMap<String, &'static [&'static str; 5]>> = OnceLock::new();
    if !(1..=5).contains(&tone) {
        return None;
    }
    // (Looked up without variation selectors: "☝" and "☝️" are one emoji.)
    let key = |s: &str| s.chars().filter(|c| *c != '\u{FE0F}').collect::<String>();
    let map = MAP.get_or_init(|| crate::emoji_data::SKIN_TONES.iter().map(|(base, tones)| (key(base), tones)).collect());
    map.get(&key(emoji)).map(|tones| tones[tone as usize - 1])
}

/// `emoji` as the picker's skin tone setting shows and sends it.
pub fn in_chosen_tone(emoji: &str) -> std::borrow::Cow<'_, str> {
    match toned(emoji, skin_tone()) {
        Some(t) => std::borrow::Cow::Borrowed(t),
        None => std::borrow::Cow::Borrowed(emoji),
    }
}

/// The emoji for a shortcode ("military_helmet" → 🪖), Discord/Slack names.
pub fn from_shortcode(name: &str) -> Option<String> {
    use std::collections::HashMap;
    use std::sync::OnceLock;
    static MAP: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();
    let map = MAP.get_or_init(|| crate::shortcodes::SHORTCODES.iter().copied().collect());
    let hex = map.get(name.trim_matches(':'))?;
    hex.split('-').map(|h| u32::from_str_radix(h, 16).ok().and_then(char::from_u32)).collect()
}

/// The shortcode for an emoji (👍 → "thumbsup"), for tooltips like
/// Discord's "reacted with :tada:".
pub fn shortcode_of(emoji: &str) -> Option<&'static str> {
    use std::collections::HashMap;
    use std::sync::OnceLock;
    static MAP: OnceLock<HashMap<String, &'static str>> = OnceLock::new();
    let key = |s: &str| s.chars().filter(|c| *c as u32 != 0xFE0F).map(|c| format!("{:x}", c as u32)).collect::<Vec<_>>().join("-");
    let map = MAP.get_or_init(|| {
        let mut m = HashMap::new();
        for (name, hex) in crate::shortcodes::SHORTCODES.iter() {
            let k: String = hex.split('-').filter(|h| *h != "fe0f").collect::<Vec<_>>().join("-");
            // The first (alphabetical) name wins, except Discord's thumbs.
            let e = m.entry(k).or_insert(*name);
            if *name == "thumbsup" || *name == "thumbsdown" {
                *e = *name;
            }
        }
        m
    });
    map.get(&key(emoji)).copied()
}

/// Image for an emoji sequence: Discord's Twemoji, as in its own clients.
pub fn twemoji_url(seq: &str) -> String {
    let url = twemoji_png(seq);
    if ANY_MISSING.load(std::sync::atomic::Ordering::Relaxed) && MISSING.lock().is_ok_and(|m| m.as_ref().is_some_and(|m| m.contains(&url))) {
        // (Up to the first joiner; failing that, the first character alone.)
        let head = seq.split('\u{200D}').next().unwrap_or(seq);
        let first: String = seq.chars().take(1).collect();
        for part in [head, first.as_str()] {
            let alt = twemoji_png(part);
            if alt != url {
                return alt;
            }
        }
    }
    url
}

/// Twemoji PNG for an emoji sequence, however it was typed: the variation
/// selectors people's keyboards add or leave out (🤷‍♂ vs 🤷‍♂️) are dropped
/// and put back the way Twemoji names its files.
pub fn twemoji_png(seq: &str) -> String {
    let cps: Vec<u32> = seq.chars().map(|c| c as u32).filter(|c| !matches!(c, 0xFE0F | 0xFE0E)).collect();
    let zwj = cps.contains(&0x200D);
    let mut code: Vec<String> = Vec::with_capacity(cps.len() + 2);
    for (i, c) in cps.iter().enumerate() {
        code.push(format!("{c:x}"));
        let toned = cps.get(i + 1).is_some_and(|n| (0x1F3FB..=0x1F3FF).contains(n));
        if zwj && !toned && ZWJ_KEEPS_VS.contains(c) {
            code.push("fe0f".into());
        }
    }
    format!("{TWEMOJI_BASE}/{}.png", code.join("-"))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn first(s: &str) -> Option<String> {
        let chars: Vec<char> = s.chars().collect();
        emoji_len(&chars, 0).map(|n| chars[..n].iter().collect())
    }

    #[test]
    fn detects_sequences() {
        assert_eq!(first("🦀 hi").as_deref(), Some("🦀"));
        assert_eq!(first("👨‍💻!").as_deref(), Some("👨‍💻"));
        assert_eq!(first("👍🏽x").as_deref(), Some("👍🏽"));
        assert_eq!(first("🇨🇿").as_deref(), Some("🇨🇿"));
        assert_eq!(first("❤️").as_deref(), Some("❤️"));
        assert_eq!(first("1️⃣").as_deref(), Some("1️⃣"));
        assert_eq!(first("❤ plain"), None);
        assert_eq!(first("1 apple"), None);
        assert_eq!(first("a"), None);
    }

    #[test]
    fn urls() {
        assert!(twemoji_png("🦀").ends_with("/1f980.png"));
        assert!(twemoji_png("❤️").ends_with("/2764.png"));
        assert!(twemoji_png("👨‍💻").ends_with("/1f468-200d-1f4bb.png"));
        // With or without the variation selector: the same file.
        assert!(twemoji_png("\u{1F937}\u{200D}\u{2642}").ends_with("/1f937-200d-2642-fe0f.png"));
        assert!(twemoji_png("\u{1F937}\u{200D}\u{2642}\u{FE0F}").ends_with("/1f937-200d-2642-fe0f.png"));
        assert!(twemoji_png("\u{1F3F3}\u{200D}\u{1F308}").ends_with("/1f3f3-fe0f-200d-1f308.png"));
        assert!(twemoji_png("\u{1F3CC}\u{1F3FD}\u{200D}\u{2642}\u{FE0F}").ends_with("/1f3cc-1f3fd-200d-2642-fe0f.png"));
        assert!(twemoji_png("\u{1F441}\u{FE0F}\u{200D}\u{1F5E8}\u{FE0F}").ends_with("/1f441-200d-1f5e8.png"));
        assert!(twemoji_png("\u{1F469}\u{200D}\u{2764}\u{200D}\u{1F468}").ends_with("/1f469-200d-2764-fe0f-200d-1f468.png"));
        assert!(twemoji_png("1\u{FE0F}\u{20E3}").ends_with("/31-20e3.png"));
    }

    #[test]
    fn search() {
        assert_eq!(search_rank("😂", "joy", "joy"), Some(0));
        assert_eq!(search_rank("😂", "joy", "jo"), Some(1));
        assert_eq!(search_rank("😂", "joy", "tears"), Some(3));
        assert_eq!(search_rank("😂", "joy", "laugh"), Some(4));
        assert_eq!(search_rank("👍", "thumbsup", "thumbs up"), Some(3));
        assert_eq!(search_rank("👍", "thumbsup", "like"), Some(4));
        assert_eq!(search_rank("😂", "joy", "crab"), None);
        assert_eq!(by_any_name("joy"), Some("😂"));
        assert_eq!(by_any_name("tears_of_joy"), Some("😂"));
        assert_eq!(by_any_name("nope_nothing"), None);
    }

    #[test]
    fn skin_tones() {
        assert_eq!(toned("👍", 3), Some("👍🏽"));
        assert_eq!(toned("👍", 0), None);
        assert_eq!(toned("🦀", 3), None);
        // With or without the variation selector.
        assert!(toned("\u{261D}", 5).is_some() && toned("\u{261D}\u{FE0F}", 5).is_some());
        assert!(twemoji_png(toned("🤷", 1).unwrap()).ends_with("/1f937-1f3fb.png"));
    }
}