taut 0.3.0

A Rust GUI library for Windows, Linux, macOS, iOS and the web that aims to be small, fast and accessible, with zero dependencies and nothing compiled in that your program doesn't use.
Documentation
//! Spell checking on macOS: the system's checker, `NSSpellChecker`, asked from the checking
//! thread (see `spell.rs`), with the user's dictionary.
//!
//! It names languages "en", "en_GB", "de": a name as the app gives it ("en-US") is matched
//! whole, then by its language alone.
use crate::macos_sys::*;
use crate::spell::{Check, OFFERED};

/// The checker for one language, by the name `NSSpellChecker` has for it.
pub(crate) struct Speller(String);

/// The shared checker.
fn checker() -> Obj {
    // SAFETY: a plain question; the checker lives as long as the program.
    unsafe { send(class(c"NSSpellChecker"), c"sharedSpellChecker", ()) }
}

impl Speller {
    /// The checker for the language of this name ("en-US", "de_DE", "fr"), if the system has
    /// one: the name whole, else its language.
    pub(crate) fn open(name: &str) -> Option<Speller> {
        let _pool = Pool::new();
        // SAFETY: a plain question; an array of strings comes back.
        let known: Vec<String> = array_items(unsafe { send(checker(), c"availableLanguages", ()) }).into_iter().filter_map(rust_string).collect();
        let name = name.replace('-', "_");
        let language = name.split('_').next().unwrap_or_default();
        let found = known.iter().find(|known| **known == name).or_else(|| known.iter().find(|known| *known == language))?;
        Some(Speller(found.clone()))
    }
}

impl Check for Speller {
    fn wrong(&self, word: &str) -> bool {
        let _pool = Pool::new();
        // SAFETY: the word and language are strings; no wrap, no document (0), no word count.
        let found: NSRange = unsafe {
            send(
                checker(),
                c"checkSpellingOfString:startingAt:language:wrap:inSpellDocumentWithTag:wordCount:",
                (ns_string(word), 0isize, ns_string(&self.0), 0 as Bool, 0isize, std::ptr::null_mut::<isize>()),
            )
        };
        found.location != NOT_FOUND && found.length > 0
    }

    fn offer(&mut self, word: &str) -> Vec<String> {
        let _pool = Pool::new();
        let whole = NSRange { location: 0, length: word.encode_utf16().count() };
        // SAFETY: the range covers the word's UTF-16 units; an array of strings (or nil) comes
        // back.
        let offers: Obj = unsafe { send(checker(), c"guessesForWordRange:inString:language:inSpellDocumentWithTag:", (whole, ns_string(word), ns_string(&self.0), 0isize)) };
        array_items(offers).into_iter().filter_map(rust_string).take(OFFERED).collect()
    }

    fn add(&mut self, word: &str) {
        let _pool = Pool::new();
        // SAFETY: the word is a string; the checker keeps it in the user's dictionary.
        unsafe { send::<()>(checker(), c"learnWord:", (ns_string(word),)) };
    }
}

/// The user's language: the first of their preferred languages ("en-US"); English where none.
pub(crate) fn own_language() -> String {
    let _pool = Pool::new();
    // SAFETY: a plain question; an array of strings comes back.
    let first = array_items(unsafe { send(class(c"NSLocale"), c"preferredLanguages", ()) }).first().copied().and_then(rust_string);
    first.filter(|name| !name.is_empty()).unwrap_or_else(|| "en-US".to_owned())
}

#[cfg(test)]
mod tests {
    use crate::spell::{OFFERED, system};

    #[test]
    fn apples_checker_checks_english_and_offers_the_right_words() {
        // (From a thread of its own, as the checking thread asks.)
        std::thread::spawn(|| {
            let mut checker = system("en-US").expect("macOS has a checker for English");
            let wrong: Vec<bool> = ["helo", "hello", "recieve", "don't", "naïve"].iter().map(|word| checker.wrong(word)).collect();
            assert_eq!(wrong, [true, false, true, false, false]);
            let offered = checker.offer("recieve");
            assert!(offered.contains(&"receive".to_owned()) && offered.len() <= OFFERED, "{offered:?}");
            // British English, in which "colour" is right; German; and a language there is none for.
            let british = system("en-GB").expect("macOS has a checker for British English");
            assert!(!british.wrong("colour") && british.wrong("helo"));
            if let Some(mut german) = system("de-DE") {
                assert!(!german.wrong("Straße") && german.wrong("Huas"));
                assert!(german.offer("Huas").iter().any(|offer| offer.starts_with("Ha")));
            }
            assert!(system("xx-YY").is_none());
            assert!(!super::own_language().is_empty());
        })
        .join()
        .unwrap();
    }
}