Skip to content

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

11.5 KB
Raw Blame
//! Spell checking for the message box, like Discord's: misspelled words get a
//! red wavy underline, and right-clicking one offers corrections and "Add to
//! Dictionary". The words come from Windows' own spell checker (the
//! `ISpellChecker` COM API, the same dictionaries Chrome and Discord use on
//! Windows), on a worker thread; the UI only reads a cache.

use eframe::egui;
use std::collections::HashMap;
use std::ops::Range;
use std::sync::atomic::{AtomicBool, Ordering::Relaxed};
use std::sync::mpsc::Sender;
use std::sync::{Mutex, OnceLock};

enum Job {
    Check(String),
    Suggest(String),
    Add(String),
}

#[derive(Default)]
struct Cache {
    /// word → misspelled? (`None`: asked, no answer yet).
    words: HashMap<String, Option<bool>>,
    suggestions: HashMap<String, Vec<String>>,
}

struct Shared {
    cache: Mutex<Cache>,
    jobs: Mutex<Option<Sender<Job>>>,
}

static SHARED: OnceLock<Shared> = OnceLock::new();
/// The user's "Spellcheck" switch (Settings → Text & Images, and the message
/// box's right-click menu).
pub static ENABLED: AtomicBool = AtomicBool::new(true);

fn shared() -> &'static Shared {
    SHARED.get_or_init(|| Shared { cache: Default::default(), jobs: Mutex::new(None) })
}

/// Start the worker (Windows only; elsewhere nothing is ever flagged).
pub fn install(ctx: &egui::Context) {
    #[cfg(windows)]
    {
        let (tx, rx) = std::sync::mpsc::channel::<Job>();
        *shared().jobs.lock().unwrap() = Some(tx);
        let ctx = ctx.clone();
        let _ = std::thread::Builder::new().name("spellcheck".into()).spawn(move || win::run(rx, ctx));
    }
    #[cfg(not(windows))]
    let _ = ctx;
}

fn send(job: Job) {
    if let Some(tx) = shared().jobs.lock().unwrap().as_ref() {
        let _ = tx.send(job);
    }
}

/// Byte ranges of the words in `text` worth checking: letters (with inner
/// apostrophes), skipping what Discord doesn't check either — links, mentions
/// and custom emoji (`<…>`), `:shortcodes:`, `code`, slash commands, and
/// anything with digits or underscores in it.
pub fn words(text: &str) -> Vec<Range<usize>> {
    let mut out = Vec::new();
    let mut in_code = false;
    let mut pos = 0;
    for token in text.split_inclusive(char::is_whitespace) {
        let start = pos;
        pos += token.len();
        let tok = token.trim_end();
        let ticks = tok.matches('`').count();
        let was_code = in_code;
        if ticks % 2 == 1 {
            in_code = !in_code;
        }
        if was_code || ticks > 0 || tok.is_empty() {
            continue;
        }
        let skip = tok.contains("://")
            || tok.starts_with("www.")
            || tok.starts_with('<')
            || tok.starts_with('@')
            || tok.starts_with('#')
            || tok.starts_with('/')
            || (tok.starts_with(':') && tok.ends_with(':') && tok.len() > 2)
            || tok.chars().any(|c| c.is_ascii_digit() || c == '_' || c == '@');
        if skip {
            continue;
        }
        // Words inside the token ("well,", "(maybe)", "half-done").
        let mut word_start: Option<usize> = None;
        let chars: Vec<(usize, char)> = tok.char_indices().collect();
        for (k, &(i, c)) in chars.iter().enumerate() {
            let apostrophe = matches!(c, '\'' | '’')
                && word_start.is_some()
                && chars.get(k + 1).is_some_and(|&(_, n)| n.is_alphabetic());
            if c.is_alphabetic() || apostrophe {
                word_start.get_or_insert(i);
            } else if let Some(s) = word_start.take() {
                out.push(start + s..start + i);
            }
        }
        if let Some(s) = word_start {
            out.push(start + s..start + tok.len());
        }
    }
    out
}

/// Byte ranges of the misspelled words in `text`. Words not seen before are
/// sent to the checker and show up a frame or two later. `caret` (a byte
/// offset) is where the user is typing: the word there isn't flagged until
/// they move on, like in a browser.
pub fn misspelled(text: &str, caret: Option<usize>) -> Vec<Range<usize>> {
    if !ENABLED.load(Relaxed) || text.is_empty() {
        return Vec::new();
    }
    let mut out = Vec::new();
    let mut ask = Vec::new();
    {
        let mut cache = shared().cache.lock().unwrap();
        for range in words(text) {
            if caret.is_some_and(|c| c >= range.start && c <= range.end) {
                continue;
            }
            let word = &text[range.clone()];
            // Single letters and non-Latin scripts the dictionary can't judge.
            if word.chars().count() < 2 {
                continue;
            }
            match cache.words.get(word) {
                Some(Some(true)) => out.push(range),
                Some(_) => {}
                None => {
                    cache.words.insert(word.to_string(), None);
                    ask.push(word.to_string());
                }
            }
        }
        // (Drafts don't grow this much, but don't keep words forever.)
        if cache.words.len() > 20_000 {
            cache.words.clear();
            cache.suggestions.clear();
        }
    }
    for word in ask {
        send(Job::Check(word));
    }
    out
}

/// Corrections for a misspelled word: `None` until the checker has answered.
pub fn suggestions(word: &str) -> Option<Vec<String>> {
    let cache = shared().cache.lock().unwrap();
    cache.suggestions.get(word).cloned()
}

/// Ask for a word's corrections (the answer lands in [`suggestions`]).
pub fn request_suggestions(word: &str) {
    if shared().cache.lock().unwrap().suggestions.contains_key(word) {
        return;
    }
    send(Job::Suggest(word.to_string()));
}

/// "Add to Dictionary": the word goes into the user's Windows dictionary
/// (shared with every app that uses Windows' spell checker).
pub fn add_to_dictionary(word: &str) {
    shared().cache.lock().unwrap().words.insert(word.to_string(), Some(false));
    send(Job::Add(word.to_string()));
}

#[cfg(windows)]
mod win {
    use super::{shared, Job};
    use eframe::egui;
    use std::sync::mpsc::Receiver;
    use windows::core::{HSTRING, PWSTR};
    use windows::Win32::Globalization::{GetUserDefaultLocaleName, ISpellChecker, ISpellCheckerFactory, SpellCheckerFactory};
    use windows::Win32::System::Com::{CoCreateInstance, CoInitializeEx, CoTaskMemFree, CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED};

    /// The checkers for the user's languages: their Windows display language
    /// first, then English (most Discord chat is at least partly English).
    fn checkers() -> Vec<ISpellChecker> {
        let mut out = Vec::new();
        // SAFETY: plain COM calls on this thread's own apartment.
        unsafe {
            let Ok(factory) = CoCreateInstance::<_, ISpellCheckerFactory>(&SpellCheckerFactory, None, CLSCTX_INPROC_SERVER) else {
                log::warn!("spellcheck: Windows' spell checker isn't available");
                return out;
            };
            let mut buf = [0u16; 85];
            let n = GetUserDefaultLocaleName(&mut buf);
            let locale = String::from_utf16_lossy(&buf[..(n.max(1) - 1) as usize]);
            let mut tags = vec![locale];
            for tag in ["en-US", "en-GB"] {
                if !tags.iter().any(|t| t.eq_ignore_ascii_case(tag)) {
                    tags.push(tag.to_string());
                }
            }
            for tag in tags {
                let tag_h = HSTRING::from(tag.as_str());
                if !factory.IsSupported(&tag_h).map(|b| b.as_bool()).unwrap_or(false) {
                    continue;
                }
                if let Ok(checker) = factory.CreateSpellChecker(&tag_h) {
                    log::info!("spellcheck: using Windows' {tag} dictionary");
                    out.push(checker);
                    // One extra English dictionary at most.
                    if out.len() == 2 {
                        break;
                    }
                }
            }
        }
        out
    }

    /// Misspelled in the first (main) language and not a word in any other.
    fn is_misspelled(checkers: &[ISpellChecker], word: &str) -> bool {
        let w = HSTRING::from(word);
        // SAFETY: COM calls with a valid, NUL-terminated string.
        let bad = |c: &ISpellChecker| unsafe {
            let Ok(errors) = c.Check(&w) else { return false };
            // S_OK with an error; S_FALSE and nothing when the word is fine.
            let mut error = None;
            let _ = errors.Next(&mut error);
            error.is_some_and(|e| e.Length().unwrap_or(0) > 0)
        };
        !checkers.is_empty() && checkers.iter().all(bad)
    }

    fn suggest(checkers: &[ISpellChecker], word: &str) -> Vec<String> {
        let mut out: Vec<String> = Vec::new();
        let w = HSTRING::from(word);
        for c in checkers {
            // SAFETY: COM calls; each returned string is freed with CoTaskMemFree.
            unsafe {
                let Ok(list) = c.Suggest(&w) else { continue };
                loop {
                    let mut item = [PWSTR::null()];
                    let mut fetched = 0u32;
                    let _ = list.Next(&mut item, Some(&mut fetched));
                    if fetched == 0 || item[0].is_null() {
                        break;
                    }
                    if let Ok(s) = item[0].to_string() {
                        if !out.contains(&s) && out.len() < 5 {
                            out.push(s);
                        }
                    }
                    CoTaskMemFree(Some(item[0].0 as *const _));
                }
            }
            if out.len() >= 5 {
                break;
            }
        }
        out
    }

    pub fn run(rx: Receiver<Job>, ctx: egui::Context) {
        // SAFETY: initialises COM for this worker thread only.
        unsafe {
            let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
        }
        let checkers = checkers();
        while let Ok(job) = rx.recv() {
            match job {
                Job::Check(word) => {
                    let bad = is_misspelled(&checkers, &word);
                    shared().cache.lock().unwrap().words.insert(word, Some(bad));
                }
                Job::Suggest(word) => {
                    let list = suggest(&checkers, &word);
                    shared().cache.lock().unwrap().suggestions.insert(word, list);
                }
                Job::Add(word) => {
                    if let Some(c) = checkers.first() {
                        // SAFETY: COM call with a valid string.
                        if let Err(e) = unsafe { c.Add(&HSTRING::from(word.as_str())) } {
                            log::warn!("spellcheck: couldn't add a word to the dictionary: {e}");
                        }
                    }
                }
            }
            ctx.request_repaint();
        }
    }
}

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

    fn list(text: &str) -> Vec<&str> {
        words(text).into_iter().map(|r| &text[r]).collect()
    }

    #[test]
    fn splits_words_and_keeps_apostrophes() {
        assert_eq!(list("I've never, (ever) been half-done."), ["I've", "never", "ever", "been", "half", "done"]);
        assert_eq!(list("rock 'n' roll"), ["rock", "n", "roll"]);
    }

    #[test]
    fn skips_links_mentions_emoji_and_code() {
        assert_eq!(list("see https://example.com/teh now"), ["see", "now"]);
        assert_eq!(list("hi <@123> and <:blob:42> :smile: ok"), ["hi", "and", "ok"]);
        assert_eq!(list("run `cargo biuld` then `x y z` done"), ["run", "then", "done"]);
        assert_eq!(list("/giphy teh"), ["teh"]);
        assert_eq!(list("user_name b4 word"), ["word"]);
    }
}