app: cherry-pick rune's pause and sound fixes onto the checkout

Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch
ported, carrying the four commits of upstream issues 1320 (a pause while
a clip is layered holds the layer's picture and time) and 1325 (a video's
sound is read ahead of the clock and leads it). Both were written against
eb9f1104 and ported across the refactors since. The faults are the first
two and the third in docs/rune-upstream.md; the app's workarounds in
review.rs stay until the fixes arrive upstream.
This commit is contained in:
vhaudiquet committed 2026-11-22 22:16:30 +01:00
1 parent 80fef698ce
commit 5bf262b82b
3795 files changed
+663463 -28

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
[package]
name = "rune-spell"
version = "0.0.1"
edition.workspace = true
license.workspace = true
description = "Platform spell checking for Rune: Windows ISpellChecker, macOS NSSpellChecker, and web Hunspell via spellbook."
[dependencies]
rune-core = { workspace = true }
rustc-hash = { workspace = true }
[target.'cfg(target_os = "macos")'.dependencies]
objc2-app-kit = { workspace = true, features = ["std", "NSSpellChecker"] }
objc2-foundation = { workspace = true, features = ["std", "NSArray", "NSEnumerator", "NSObject", "NSRange", "NSString"] }
[target.'cfg(target_os = "windows")'.dependencies]
windows = { workspace = true, features = ["Win32_Foundation", "Win32_Globalization", "Win32_System_Com"] }
windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_System_LibraryLoader"] }
[target.'cfg(target_arch = "wasm32")'.dependencies]
js-sys = { workspace = true }
spellbook = "0.4"
unicode-segmentation = { workspace = true }
wasm-bindgen = { workspace = true }
wasm-bindgen-futures = { workspace = true }
web-sys = { workspace = true, features = ["console"] }
[lints]
workspace = true
+463
View File
@@ -0,0 +1,463 @@
//! The platform's spell checker for text fields that ask for it (`El::spellcheck`): Windows'
//! spell checking API (`ISpellChecker`), AppKit's `NSSpellChecker` on macOS, Hunspell
//! dictionaries a page fetches in a browser (`web.rs`), none elsewhere.
//! A field's misspelled words get a red marker under them and their suggestions in its menu.
//!
//! Where the platform checks one language at a time (Windows), an app picks the dictionaries:
//! [`available_languages`], [`set_languages`] and the fields' Spellcheck Languages menu
//! (`El::on_spellcheck_languages`). A word is misspelled when every chosen dictionary says so,
//! as Chromium's multilingual checking does. macOS picks each text's language itself.
//! Apps normally reach this crate through `rune::spell`.
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
#[doc(hidden)]
pub mod pause;
#[cfg(target_os = "macos")]
#[path = "macos.rs"]
mod platform;
#[cfg(target_arch = "wasm32")]
#[path = "web.rs"]
mod platform;
#[cfg(target_os = "windows")]
#[path = "windows.rs"]
mod platform;
#[cfg(not(any(target_os = "windows", target_os = "macos", target_arch = "wasm32")))]
mod platform {
pub(super) const OFF_THREAD: bool = false;
pub(super) fn misspelled(_: &str) -> Vec<(usize, usize)> { Vec::new() }
pub(super) fn suggest(_: &str) -> Vec<String> { Vec::new() }
pub(super) fn learn(_: &str) {}
pub(super) fn available() -> Vec<String> { Vec::new() }
pub(super) fn preferred() -> Vec<String> { Vec::new() }
pub(super) fn english_name(tag: &str) -> String { tag.to_owned() }
pub(super) fn name_in(_: &str, _: &str) -> Option<String> { None }
pub(super) fn sort_in<T>(_: &mut [(String, T)], _: &str) -> bool { false }
}
/// The most suggestions a field's menu offers, as Chromium's.
const MAX_SUGGESTIONS: usize = 5;
/// A text's misspelled words, as byte ranges.
#[doc(hidden)]
pub type Ranges = Rc<Vec<(usize, usize)>>;
/// The dictionaries [`set_languages`] chose; empty follows the system languages.
static CHOSEN: Mutex<Vec<String>> = Mutex::new(Vec::new());
/// Bumped on each [`set_languages`], so each thread's checkers and checked texts start over.
static GENERATION: AtomicU64 = AtomicU64::new(0);
thread_local! {
/// Each checked text's misspelled words, by the text's hash, for one generation.
static CHECKED: RefCell<(u64, HashMap<u64, Ranges>)> = RefCell::new((0, HashMap::new()));
/// Each checked word's misspelled parts, for one generation (`Words`): a key typed into a
/// long draft checks the one word it changed, not the draft.
static WORDS: RefCell<Words> = RefCell::new(Words::default());
}
/// The most words [`WORDS`] keeps before it starts over.
const MAX_WORDS: usize = 8192;
/// The dictionaries a field's Spellcheck Languages menu offers, as language tags (`en-US`).
/// Empty where the platform finds each text's language itself (macOS) or has no checker.
pub fn available_languages() -> Vec<String> {
let mut found = platform::available();
found.sort_by_key(|tag| language_name(tag));
found
}
/// The dictionaries checking text now: those [`set_languages`] chose that the platform has, else
/// one per system language (matched exactly or by base language, `de-AT` to `de` or `de-DE`),
/// with US English added when none of them is English, as Desktop's `defaultSpellcheckLanguages`.
pub fn languages() -> Vec<String> {
let available = platform::available();
let chosen = CHOSEN.lock().map(|c| c.clone()).unwrap_or_default();
resolve_languages(&available, &chosen, &platform::preferred())
}
/// In a browser, the Hunspell dictionaries the page has beside it, as `spell/<tag>.aff` and
/// `spell/<tag>.dic` (`en-US`): each is fetched the first time a field checks text in it.
#[cfg(target_arch = "wasm32")]
pub fn set_web_dictionaries(tags: &[&str]) {
platform::set_tags(tags.iter().map(|t| (*t).to_owned()).collect());
GENERATION.fetch_add(1, Ordering::Relaxed);
}
/// Check with these dictionaries. None, or none the platform has, follows the system languages.
pub fn set_languages(tags: &[String]) {
if let Ok(mut chosen) = CHOSEN.lock() {
if chosen.as_slice() == tags {
return;
}
*chosen = tags.to_vec();
}
GENERATION.fetch_add(1, Ordering::Relaxed);
}
/// A language tag's English name as a browser's `Intl.DisplayNames` gives it: `en-US` is
/// "American English", `fr-FR` "French (France)".
pub fn language_name(tag: &str) -> String {
DIALECTS.iter().find(|(t, _)| tags_match(t, tag)).map_or_else(|| platform::english_name(tag), |(_, name)| (*name).to_owned())
}
/// A language tag's name in `locale`'s language as a browser's `Intl.DisplayNames(locale)`
/// gives it, from the platform's ICU: `en-US` in `de` is "Amerikanisches Englisch". `None`
/// where the platform has no ICU to ask (only Windows has dictionaries to name).
#[doc(hidden)]
pub fn language_name_in(tag: &str, locale: &str) -> Option<String> {
platform::name_in(tag, locale)
}
/// Sorts `items` by their names as `locale` sorts text (`String.localeCompare`), else by their
/// lowercased names.
#[doc(hidden)]
pub fn sort_names_in<T>(items: &mut [(String, T)], locale: &str) {
if !platform::sort_in(items, locale) {
items.sort_by_cached_key(|(name, _)| name.to_lowercase());
}
}
/// CLDR's English dialect names, which `Intl.DisplayNames` uses over "Language (Region)".
const DIALECTS: &[(&str, &str)] = &[
("ar-001", "Modern Standard Arabic"),
("de-AT", "Austrian German"),
("de-CH", "Swiss High German"),
("en-AU", "Australian English"),
("en-CA", "Canadian English"),
("en-GB", "British English"),
("en-US", "American English"),
("es-419", "Latin American Spanish"),
("es-ES", "European Spanish"),
("es-MX", "Mexican Spanish"),
("fa-AF", "Dari"),
("fr-CA", "Canadian French"),
("fr-CH", "Swiss French"),
("nl-BE", "Flemish"),
("pt-BR", "Brazilian Portuguese"),
("pt-PT", "European Portuguese"),
("ro-MD", "Moldavian"),
("sw-CD", "Congo Swahili"),
("zh-Hans", "Simplified Chinese"),
("zh-Hant", "Traditional Chinese"),
];
/// Primary language subtag of a BCP 47 / POSIX tag (`en-AU` and `en_AU` both yield `en`).
fn base_language(tag: &str) -> &str {
let tag = tag.trim();
tag.split(['-', '_']).next().unwrap_or(tag)
}
/// Exact tag equality ignoring ASCII case and `-` vs `_` separators.
pub(crate) fn tags_match(a: &str, b: &str) -> bool {
let (a, b) = (a.trim().as_bytes(), b.trim().as_bytes());
let norm = |c: u8| if c == b'_' { b'-' } else { c.to_ascii_lowercase() };
a.len() == b.len() && a.iter().zip(b).all(|(&x, &y)| norm(x) == norm(y))
}
/// Finds the best available dictionary for `requested`: exact match (case/`_`-insensitive),
/// then a bare base-language dictionary (`de`), then any regional dictionary sharing the
/// exact primary language subtag (`de-DE`), never matching unrelated languages by prefix.
fn match_tag(available: &[String], requested: &str) -> Option<String> {
let base = base_language(requested);
if base.is_empty() {
return None;
}
available
.iter()
.find(|a| tags_match(a, requested))
.or_else(|| available.iter().find(|a| tags_match(a, base)))
.or_else(|| available.iter().find(|a| base_language(a).eq_ignore_ascii_case(base)))
.cloned()
}
/// Resolves active dictionaries from explicit `chosen` overrides, falling back to `preferred`.
fn resolve_languages(available: &[String], chosen: &[String], preferred: &[String]) -> Vec<String> {
let mut resolved = Vec::new();
for tag in chosen {
if let Some(matched) = match_tag(available, tag)
&& !resolved.iter().any(|existing: &String| tags_match(existing, &matched))
{
resolved.push(matched);
}
}
if !resolved.is_empty() {
return resolved;
}
default_languages(available, preferred)
}
/// Filters loaded dictionaries to only those in `active`, so deselected web dictionaries stop
/// being consulted without needing to unload them.
#[cfg_attr(not(any(target_arch = "wasm32", test)), allow(dead_code))]
pub(crate) fn active_dicts<'a, T>(loaded: &'a [(String, T)], active: &[String]) -> Vec<&'a T> {
loaded
.iter()
.filter(|(tag, _)| active.iter().any(|wanted| tags_match(tag, wanted)))
.map(|(_, dict)| dict)
.collect()
}
/// Desktop's `defaultSpellcheckLanguages` (spellcheck-languages.ts): one dictionary per preferred
/// language, then US English when none of them is English, as prompts mix prose with English
/// code terms.
fn default_languages(available: &[String], preferred: &[String]) -> Vec<String> {
let mut found: Vec<String> = Vec::new();
for tag in preferred {
if let Some(language) = match_tag(available, tag)
&& !found.iter().any(|f| base_language(f).eq_ignore_ascii_case(base_language(&language)))
{
found.push(language);
}
}
if found.iter().any(|f| base_language(f).eq_ignore_ascii_case("en")) {
return found;
}
if let Some(us) = available.iter().find(|a| tags_match(a, "en-US")) {
found.push(us.clone());
}
found
}
/// The current generation, for a thread's checkers to know when to start over.
pub(crate) fn generation() -> u64 { GENERATION.load(Ordering::Relaxed) }
/// The byte ranges of `text`'s misspelled words. Where the platform's checker is slow to call
/// (Windows' answers from another process, a cross-process call per misspelled word), the words
/// it hasn't seen go to a thread of its own and show marked once they're back: the frame never
/// waits on it. `wake` is the window to draw again then.
#[doc(hidden)]
pub fn misspelled(text: &str, wake: Option<&std::sync::Arc<rune_core::live::Wake>>) -> Ranges {
if text.trim().is_empty() {
return Rc::default();
}
let key = {
use std::hash::{Hash, Hasher};
let mut h = rustc_hash::FxHasher::default();
text.hash(&mut h);
h.finish()
};
CHECKED.with_borrow_mut(|(generation, checked)| {
if *generation != self::generation() {
*generation = self::generation();
checked.clear();
}
if let Some(found) = checked.get(&key) {
return found.clone();
}
// Typing checks a new text per key: keep the cache to the latest few hundred.
if checked.len() > 256 {
checked.clear();
}
// macOS finds each text's language from the text, so it checks the whole of it.
// A page fetches its dictionaries the first time it checks: until they're in, nothing is
// marked and nothing kept, and the window asking is woken when they arrive.
#[cfg(target_arch = "wasm32")]
let ready = platform::prepare(wake);
#[cfg(not(target_arch = "wasm32"))]
let ready = true;
let (found, whole) = if cfg!(any(target_os = "windows", target_arch = "wasm32")) { by_words(text, wake) } else { (platform::misspelled(text), true) };
let whole = whole && ready;
let found = Rc::new(found);
// A text with words still on the checker thread is put together again when they're back.
if whole {
checked.insert(key, found.clone());
}
found
})
}
/// `text`'s misspelled words, from each line's and word's cached answers, and whether every word
/// had one. The words not yet checked go to the platform together, one per line (on the checker
/// thread where it's slow to call). Words are what whitespace separates: the checker marks
/// nothing across it, and repeated words, its only check that reads neighbours, go unmarked. A
/// line's answer is kept once all its words have one, so a key in a long draft looks up the
/// lines it didn't change, not their words.
fn by_words(text: &str, wake: Option<&std::sync::Arc<rune_core::live::Wake>>) -> (Vec<(usize, usize)>, bool) {
use std::hash::{Hash, Hasher};
let line_key = |line: &str| {
let mut h = rustc_hash::FxHasher::default();
line.hash(&mut h);
h.finish()
};
WORDS.with_borrow_mut(|w| {
if w.generation != self::generation() {
*w = Words { generation: self::generation(), ..Words::default() };
}
w.take_done();
if w.lines.len() > MAX_WORDS { w.lines.clear(); }
// The lines without a kept answer, and their words.
// Each line is hashed once: a key in a 2,000-line draft hashes its lines, not twice.
let keys: Vec<u64> = text.split('\n').map(line_key).collect();
let mut open: Vec<(usize, &str, u64)> = Vec::new();
let mut at = 0;
for (line, &k) in text.split('\n').zip(&keys) {
if !w.lines.contains_key(&k) { open.push((at, line, k)); }
at += line.len() + 1;
}
let mut fresh: Vec<&str> = open.iter().flat_map(|&(_, l, _)| words(l).map(|(_, s)| s)).filter(|s| !w.known.contains_key(*s) && !w.asked.contains(*s)).collect();
fresh.sort_unstable();
fresh.dedup();
if !fresh.is_empty() {
if w.known.len() + fresh.len() > MAX_WORDS { w.known.clear(); }
if platform::OFF_THREAD {
w.asked.extend(fresh.iter().map(|&s| Box::<str>::from(s)));
worker::ask(w.generation, fresh.iter().map(|&s| s.to_owned()).collect(), wake);
} else {
w.known.extend(check_words(&fresh));
}
}
let mut whole = true;
for &(_, line, k) in &open {
if words(line).all(|(_, s)| w.known.contains_key(s)) {
let parts: Box<[(u32, u32)]> = words(line).flat_map(|(o, s)| w.known.get(s).into_iter().flatten().map(move |&(a, b)| (o as u32 + a, o as u32 + b))).collect();
w.lines.insert(k, parts);
} else {
whole = false;
}
}
let mut found = Vec::new();
let mut at = 0;
for (line, k) in text.split('\n').zip(&keys) {
match w.lines.get(k) {
Some(parts) => found.extend(parts.iter().map(|&(a, b)| (at + a as usize, at + b as usize))),
None => found.extend(words(line).flat_map(|(o, s)| w.known.get(s).into_iter().flatten().map(move |&(a, b)| (at + o + a as usize, at + o + b as usize)))),
}
at += line.len() + 1;
}
(found, whole)
})
}
/// `line`'s words and where each starts in it.
fn words(line: &str) -> impl Iterator<Item = (usize, &str)> + '_ {
line.split_whitespace().map(move |s| (s.as_ptr() as usize - line.as_ptr() as usize, s))
}
/// `words`' misspelled parts, as byte ranges in each word, from one call to the checker: each
/// call costs about the same whatever it's given.
fn check_words<S: AsRef<str>>(words: &[S]) -> Vec<(Box<str>, Box<[(u32, u32)]>)> {
let batch = words.iter().map(AsRef::as_ref).collect::<Vec<_>>().join("\n");
let found = platform::misspelled(&batch);
let mut start = 0;
words.iter().map(|word| {
let word = word.as_ref();
let end = start + word.len();
let parts = found.iter().filter(|&&(a, b)| a >= start && b <= end).map(|&(a, b)| ((a - start) as u32, (b - start) as u32)).collect();
start = end + 1;
(word.into(), parts)
}).collect()
}
/// A thread's checked words, for one generation of the chosen dictionaries.
#[derive(Default)]
struct Words {
generation: u64,
/// Each checked word's misspelled parts, as byte ranges in the word.
known: HashMap<Box<str>, Box<[(u32, u32)]>>,
/// Each line's misspelled words once all its words are checked, by the line's hash.
lines: HashMap<u64, Box<[(u32, u32)]>>,
/// Words on the checker thread.
asked: std::collections::HashSet<Box<str>>,
}
impl Words {
/// Takes in what the checker thread brought back for this generation.
fn take_done(&mut self) {
let done = std::mem::take(&mut *worker::DONE.lock().unwrap_or_else(|e| e.into_inner()));
for (generation, word, parts) in done {
self.asked.remove(&word);
if generation == self.generation {
self.known.insert(word, parts);
}
}
}
}
/// How many times the checker thread has brought words back, for a window to draw them.
pub(crate) fn arrivals() -> u64 { worker::ARRIVED.load(Ordering::Acquire) }
/// The checker thread, where the platform's checker is slow to call.
mod worker {
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock, Weak, mpsc};
/// Words to check: the generation they're for, and the window to wake.
pub(super) struct Job {
generation: u64,
words: Vec<String>,
wake: Option<Weak<rune_core::live::Wake>>,
}
/// Words checked and not taken in yet: generation, word, its misspelled parts.
pub(super) static DONE: Mutex<Vec<(u64, Box<str>, Box<[(u32, u32)]>)>> = Mutex::new(Vec::new());
pub(super) static ARRIVED: AtomicU64 = AtomicU64::new(0);
static JOBS: OnceLock<Option<mpsc::Sender<Job>>> = OnceLock::new();
pub(super) fn ask(generation: u64, words: Vec<String>, wake: Option<&Arc<rune_core::live::Wake>>) {
let jobs = JOBS.get_or_init(|| {
let (send, take) = mpsc::channel::<Job>();
std::thread::Builder::new().name("rune-spell".into()).spawn(move || run(take)).ok().map(|_| send)
});
if let Some(send) = jobs {
send.send(Job { generation, words, wake: wake.map(Arc::downgrade) }).ok();
}
}
fn run(take: mpsc::Receiver<Job>) {
while let Ok(first) = take.recv() {
// A burst of keys asks for each word they made: check what's waiting in one call.
let mut jobs = vec![first];
jobs.extend(take.try_iter());
let generation = super::generation();
jobs.retain(|j| j.generation == generation);
let words: Vec<&str> = jobs.iter().flat_map(|j| j.words.iter().map(String::as_str)).collect();
// A word still out draws unmarked, as a correct one does: only an answer that marks
// one changes what a window shows, so only that draws it again. The others are
// taken when the window next builds (`take_done`).
let mut marks = false;
if !words.is_empty() {
let found = super::check_words(&words);
marks = found.iter().any(|(_, parts)| !parts.is_empty());
DONE.lock().unwrap_or_else(|e| e.into_inner()).extend(found.into_iter().map(|(w, p)| (generation, w, p)));
// The count a window's next frame compares to draw again (`pause::tick`): only
// what marks a word counts.
if marks {
ARRIVED.fetch_add(1, Ordering::AcqRel);
}
}
if marks {
for wake in jobs.iter().filter_map(|j| j.wake.as_ref()?.upgrade()) {
wake.notify();
}
}
}
}
}
/// The misspelled word of `text` at byte `at` (in it or at its end), once its words are checked.
#[doc(hidden)]
pub fn misspelled_at(text: &str, at: usize) -> Option<(usize, usize)> {
misspelled(text, None).iter().copied().find(|&(a, b)| a <= at && at <= b)
}
/// The checker's suggestions for misspelled `word`, best first.
#[doc(hidden)]
pub fn suggest(word: &str) -> Vec<String> {
let mut found = platform::suggest(word);
found.retain(|s| s != word);
found.truncate(MAX_SUGGESTIONS);
found
}
/// Adds `word` to the user's dictionary, so it's no longer marked anywhere.
#[doc(hidden)]
pub fn learn(word: &str) {
platform::learn(word);
CHECKED.with_borrow_mut(|(_, checked)| checked.clear());
WORDS.with_borrow_mut(|w| *w = Words::default());
}
#[cfg(test)]
mod tests;
+61
View File
@@ -0,0 +1,61 @@
//! AppKit's shared `NSSpellChecker`, which picks each text's language itself as Chromium's
//! does on macOS.
use objc2_app_kit::NSSpellChecker;
use objc2_foundation::{NSRange, NSString};
/// AppKit's checker runs in this process: lines are checked where they're asked for.
pub(super) const OFF_THREAD: bool = false;
/// `NSNotFound`, the location of a range that found nothing.
const NOT_FOUND: usize = isize::MAX as usize;
pub(super) fn misspelled(text: &str) -> Vec<(usize, usize)> {
// Each UTF-16 unit's byte offset, and the text's end.
let mut bytes = Vec::with_capacity(text.len() + 1);
for (i, c) in text.char_indices() {
bytes.extend(std::iter::repeat_n(i, c.len_utf16()));
}
bytes.push(text.len());
let string = NSString::from_str(text);
let mut found = Vec::new();
let mut from = 0usize;
let checker = NSSpellChecker::sharedSpellChecker();
while from < bytes.len() - 1 {
let range = checker.checkSpellingOfString_startingAt(&string, from as isize);
if range.location == NOT_FOUND || range.length == 0 || range.location < from {
break;
}
let (a, b) = (range.location, range.location + range.length);
if let (Some(&a), Some(&b)) = (bytes.get(a), bytes.get(b)) {
found.push((a, b));
}
from = b;
}
found
}
pub(super) fn suggest(word: &str) -> Vec<String> {
let string = NSString::from_str(word);
let range = NSRange::new(0, string.length());
let checker = NSSpellChecker::sharedSpellChecker();
let Some(guesses) = checker.guessesForWordRange_inString_language_inSpellDocumentWithTag(range, &string, None, 0) else {
return Vec::new();
};
guesses.iter().map(|g| g.to_string()).collect()
}
/// None to choose: AppKit finds each text's language itself, as Desktop leaves it on macOS.
pub(super) fn available() -> Vec<String> { Vec::new() }
pub(super) fn preferred() -> Vec<String> { Vec::new() }
pub(super) fn english_name(tag: &str) -> String { tag.to_owned() }
/// Unused: macOS has no dictionaries to choose, so no list names them.
pub(super) fn name_in(_: &str, _: &str) -> Option<String> { None }
pub(super) fn sort_in<T>(_: &mut [(String, T)], _: &str) -> bool { false }
pub(super) fn learn(word: &str) {
NSSpellChecker::sharedSpellChecker().learnWord(&NSString::from_str(word));
}
+115
View File
@@ -0,0 +1,115 @@
//! When a field marks the misspelled word its caret is in, as Chromium's idle spell checker
//! does (`idle_spell_check_controller.cc`, `hot_mode_spell_check_requester.cc`): while the caret
//! stands where typing left it, the word it's in waits (`CurrentWordIfTypingInPartialWord`);
//! the full check that marks it runs a second after the typing stops (`kColdModeTimerInterval`).
//! Moving the caret without typing checks the word it leaves at once, as the selection change
//! does.
/// From the last keystroke to the check that marks the word being typed.
pub(crate) const PAUSE: f64 = 1.0;
/// The focused field's word at the caret.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Pause {
/// The caret at byte `caret` is where typing left it; its word shows unmarked until `until`
/// (the runtime clock, seconds).
Typing { caret: usize, until: f64 },
/// Every misspelled word shows marked.
Settled,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Event {
/// The text changed under the caret, now at byte `caret`.
Typed { caret: usize, now: f64 },
/// The caret moved, or a range was selected, with no typing.
CaretMoved,
/// The clock reached `now`.
Tick { now: f64 },
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Effect {
/// Wake the runtime at `at` (the runtime clock) to end the pause.
WakeAt(f64),
/// The word at the caret now shows its mark: draw again.
Redraw,
}
pub(crate) fn step(state: Pause, event: Event) -> (Pause, Option<Effect>) {
match (state, event) {
(_, Event::Typed { caret, now }) => (Pause::Typing { caret, until: now + PAUSE }, Some(Effect::WakeAt(now + PAUSE))),
(Pause::Typing { .. }, Event::CaretMoved) => (Pause::Settled, Some(Effect::Redraw)),
(Pause::Typing { until, .. }, Event::Tick { now }) if now >= until => (Pause::Settled, Some(Effect::Redraw)),
(state, _) => (state, None),
}
}
/// The byte whose word waits unmarked: the caret, while typing has it.
pub(crate) fn waiting(state: Pause) -> Option<usize> {
match state {
Pause::Typing { caret, .. } => Some(caret),
Pause::Settled => None,
}
}
/// What the runtime last saw of the focused spellchecked field: its path, text (hashed) and
/// selection, the machine, and a wake the paint asked for, which the next frame schedules.
#[doc(hidden)]
#[derive(Clone, Debug)]
pub struct Watch {
path: String,
text: u64,
range: (usize, usize),
pause: Pause,
#[doc(hidden)]
pub wake: Option<f64>,
/// The checker thread's deliveries it has drawn (`super::arrivals`).
seen: u64,
}
/// Steps the focused field `path`'s machine by what changed since the last paint, and returns
/// the byte whose word waits unmarked. A field just focused starts settled, as the selection
/// change that focuses it checks it.
#[doc(hidden)]
pub fn observe(watch: &mut Option<Watch>, path: &str, text: &str, range: (usize, usize), now: f64) -> Option<usize> {
let hash = {
use std::hash::{Hash, Hasher};
let mut h = rustc_hash::FxHasher::default();
text.hash(&mut h);
h.finish()
};
let w = match watch {
Some(w) if w.path == path => w,
_ => watch.insert(Watch { path: path.to_owned(), text: hash, range, pause: Pause::Settled, wake: None, seen: super::arrivals() }),
};
let event = if w.text != hash {
Some(Event::Typed { caret: range.1, now })
} else if w.range != range {
Some(Event::CaretMoved)
} else {
None
};
(w.text, w.range) = (hash, range);
if let Some(e) = event {
let (next, effect) = step(w.pause, e);
w.pause = next;
if let Some(Effect::WakeAt(at)) = effect {
w.wake = Some(at);
}
}
waiting(w.pause).filter(|_| range.0 == range.1)
}
/// The frame's turn: hands over the wake the paint asked for, and ends a pause that's due.
/// Returns whether the field must draw again: also when the checker thread brought words back.
#[doc(hidden)]
pub fn tick(watch: &mut Option<Watch>, now: f64) -> (Option<f64>, bool) {
let Some(w) = watch else { return (None, false) };
let wake = w.wake.take();
let (next, effect) = step(w.pause, Event::Tick { now });
w.pause = next;
let arrived = super::arrivals();
let fresh = std::mem::replace(&mut w.seen, arrived) != arrived;
(wake, effect == Some(Effect::Redraw) || fresh)
}
+89
View File
@@ -0,0 +1,89 @@
use super::*;
fn s(tags: &[&str]) -> Vec<String> {
tags.iter().map(|t| (*t).to_owned()).collect()
}
#[test]
fn regional_variants_and_underscores_match_available_dictionaries() {
assert_eq!(
default_languages(&s(&["de-DE", "en-US"]), &s(&["de-AT"])),
s(&["de-DE", "en-US"]),
"de-AT should fall back to de-DE when de is not listed"
);
assert_eq!(
default_languages(&s(&["en-GB"]), &s(&["en-AU"])),
s(&["en-GB"]),
"en-AU should fall back to en-GB when only en-GB is available"
);
assert_eq!(
default_languages(&s(&["en-US"]), &s(&["en_US"])),
s(&["en-US"]),
"underscore separator should match hyphenated dictionary"
);
assert_eq!(
default_languages(&s(&["en_US", "fr-FR"]), &s(&["fr-CA"])),
s(&["fr-FR", "en_US"]),
"en-US fallback should match case/underscore variants and preserve the dictionary's own tag"
);
}
#[test]
fn exact_and_bare_matches_win_over_regional_fallback() {
assert_eq!(
default_languages(&s(&["de-DE", "de", "de-AT"]), &s(&["de-AT"])),
s(&["de-AT"])
);
assert_eq!(
default_languages(&s(&["de-DE", "de"]), &s(&["de-AT"])),
s(&["de"]),
"bare base tag wins over another regional variant"
);
}
#[test]
fn prefix_similar_language_tags_do_not_cross_match() {
assert_eq!(
default_languages(&s(&["est-EE", "en-US"]), &s(&["es-MX"])),
s(&["en-US"]),
"es must not match est-EE by prefix"
);
assert_eq!(
default_languages(&s(&["eng-GB"]), &s(&["en-AU"])),
Vec::<String>::new(),
"en must not match eng-GB by prefix"
);
}
#[test]
fn chosen_languages_match_case_underscores_and_regional_variants() {
assert_eq!(
resolve_languages(&s(&["en-US", "de-DE"]), &s(&["en_us", "de-AT"]), &s(&["fr-FR"])),
s(&["en-US", "de-DE"])
);
assert_eq!(
resolve_languages(&s(&["en-GB", "en-US"]), &s(&["en-GB", "en-US"]), &s(&[])),
s(&["en-GB", "en-US"]),
"explicit selection keeps multiple regional variants of the same language"
);
assert_eq!(
resolve_languages(&s(&["en-US"]), &s(&["fr-FR"]), &s(&["en-AU"])),
s(&["en-US"]),
"unmatched chosen list falls back to preferred languages"
);
}
#[test]
fn active_dicts_excludes_deselected_loaded_dictionaries() {
let loaded = vec![("en-US".to_owned(), 1u8), ("de-DE".to_owned(), 2u8)];
assert_eq!(active_dicts(&loaded, &s(&["en-US"])), vec![&1]);
assert_eq!(active_dicts(&loaded, &s(&["de_de"])), vec![&2]);
assert_eq!(active_dicts(&loaded, &s(&["en-US", "de-DE"])), vec![&1, &2]);
assert!(active_dicts(&loaded, &s(&["fr-FR"])).is_empty());
}
#[test]
fn dialect_names_normalize_case_and_underscores() {
assert_eq!(language_name("en_US"), "American English");
assert_eq!(language_name("en-au"), "Australian English");
}
+5
View File
@@ -0,0 +1,5 @@
export async function fetchBytes(url) {
const response = await fetch(new URL(url, document.baseURI));
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return new Uint8Array(await response.arrayBuffer());
}
+167
View File
@@ -0,0 +1,167 @@
//! A page's spell checker. No browser lets a page ask its own checker, so the page checks with
//! Hunspell dictionaries (spellbook, in the module) it fetches the first time a field asks:
//! `spell/<tag>.aff` and `spell/<tag>.dic` beside the page, for the tags the app named
//! ([`super::set_web_dictionaries`]). Until a dictionary is in, nothing is marked; when it
//! arrives the window checks again. A word is misspelled when every dictionary loaded says so.
use std::cell::RefCell;
use std::sync::{Arc, Weak};
use wasm_bindgen::prelude::wasm_bindgen;
#[wasm_bindgen(module = "/src/web.js")]
extern "C" {
/// Resolves to the `Uint8Array` body of `url`, relative to the page.
#[wasm_bindgen(js_name = fetchBytes)]
fn fetch_bytes(url: &str) -> js_sys::Promise;
}
pub(super) const OFF_THREAD: bool = false;
enum Dict {
Loading,
Ready(Box<spellbook::Dictionary>),
Failed,
}
#[derive(Default)]
struct State {
/// The tags the page has dictionaries for.
tags: Vec<String>,
dicts: Vec<(String, Dict)>,
/// Windows that asked while a dictionary was on its way.
waiting: Vec<Weak<rune_core::live::Wake>>,
}
thread_local! {
static STATE: RefCell<State> = RefCell::default();
}
pub(super) fn set_tags(tags: Vec<String>) {
STATE.with_borrow_mut(|s| s.tags = tags);
}
/// Whether every dictionary checking text now is in; one not asked for yet is fetched, and the
/// window asking (`wake`) is woken once it arrives.
pub(super) fn prepare(wake: Option<&Arc<rune_core::live::Wake>>) -> bool {
let tags = super::languages();
STATE.with_borrow_mut(|s| {
let mut ready = true;
for tag in &tags {
match s.dicts.iter().find(|(t, _)| super::tags_match(t, tag)) {
Some((_, Dict::Loading)) => ready = false,
Some(_) => {}
None => {
s.dicts.push((tag.clone(), Dict::Loading));
load(tag.clone());
ready = false;
}
}
}
if !ready && let Some(w) = wake { s.waiting.push(Arc::downgrade(w)); }
ready
})
}
/// Fetches `tag`'s dictionary; once it's in, every text is checked again.
fn load(tag: String) {
let aff = fetch_bytes(&format!("spell/{tag}.aff"));
let dic = fetch_bytes(&format!("spell/{tag}.dic"));
wasm_bindgen_futures::spawn_local(async move {
let text = |v: Result<wasm_bindgen::JsValue, wasm_bindgen::JsValue>| v.ok().and_then(|b| String::from_utf8(js_sys::Uint8Array::new(&b).to_vec()).ok());
let aff = text(wasm_bindgen_futures::JsFuture::from(aff).await);
let dic = text(wasm_bindgen_futures::JsFuture::from(dic).await);
let dict = match (aff, dic) {
(Some(aff), Some(dic)) => match spellbook::Dictionary::new(&aff, &dic) {
Ok(d) => Dict::Ready(Box::new(d)),
Err(e) => { web_sys::console::warn_1(&format!("rune: the {tag} dictionary didn't parse: {e}").into()); Dict::Failed }
},
_ => { web_sys::console::warn_1(&format!("rune: the {tag} dictionary didn't load").into()); Dict::Failed }
};
let waiting = STATE.with_borrow_mut(|s| {
if let Some((_, slot)) = s.dicts.iter_mut().find(|(t, _)| super::tags_match(t, &tag)) { *slot = dict; }
std::mem::take(&mut s.waiting)
});
super::GENERATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
for w in waiting.iter().filter_map(Weak::upgrade) { w.notify(); }
});
}
/// Calls `f` with the active loaded dictionaries, if any.
fn with_ready<R>(f: impl FnOnce(&[&spellbook::Dictionary]) -> R) -> Option<R> {
let active = super::languages();
STATE.with_borrow(|s| {
let ready: Vec<&spellbook::Dictionary> = super::active_dicts(&s.dicts, &active)
.into_iter()
.filter_map(|d| match d { Dict::Ready(d) => Some(&**d), _ => None })
.collect();
(!ready.is_empty()).then(|| f(&ready))
})
}
pub(super) fn misspelled(text: &str) -> Vec<(usize, usize)> {
use unicode_segmentation::UnicodeSegmentation;
with_ready(|dicts| {
let mut out = Vec::new();
for (chunk_at, chunk) in text.split_whitespace().map(|c| (c.as_ptr() as usize - text.as_ptr() as usize, c)) {
// Paths, URLs, addresses and code are not prose.
if chunk.contains(['/', '@', '`', '_', '\\', '=', '<', '>', '{', '}']) || chunk.contains("::") { continue; }
for (at, word) in chunk.split_word_bound_indices() {
if !checked(word) { continue; }
if dicts.iter().all(|d| !d.check(word)) { out.push((chunk_at + at, chunk_at + at + word.len())); }
}
}
out
}).unwrap_or_default()
}
/// A word worth checking: letters (an apostrophe inside), at least two, no digits, and no
/// capital after its first letter (an acronym or an identifier).
fn checked(word: &str) -> bool {
let letters = word.chars().filter(|c| c.is_alphabetic()).count();
letters >= 2
&& word.chars().all(|c| c.is_alphabetic() || c == '\'' || c == '\u{2019}')
&& !word.chars().skip(1).any(char::is_uppercase)
}
pub(super) fn suggest(word: &str) -> Vec<String> {
with_ready(|dicts| {
let mut out = Vec::new();
for d in dicts {
let mut found = Vec::new();
d.suggest(word, &mut found);
for s in found {
if !out.contains(&s) { out.push(s); }
}
}
out
}).unwrap_or_default()
}
pub(super) fn learn(word: &str) {
let active = super::languages();
STATE.with_borrow_mut(|s| {
for (tag, d) in &mut s.dicts {
if active.iter().any(|wanted| super::tags_match(tag, wanted))
&& let Dict::Ready(d) = d
{
d.add(word).ok();
}
}
});
}
pub(super) fn available() -> Vec<String> {
STATE.with_borrow(|s| s.tags.clone())
}
/// The browser's preferred languages (`navigator.languages`).
pub(super) fn preferred() -> Vec<String> {
let navigator = js_sys::Reflect::get(&js_sys::global(), &"navigator".into()).ok();
let languages = navigator.and_then(|n| js_sys::Reflect::get(&n, &"languages".into()).ok());
languages.filter(js_sys::Array::is_array).map(|l| js_sys::Array::from(&l).iter().filter_map(|v| v.as_string()).collect()).unwrap_or_default()
}
pub(super) fn english_name(tag: &str) -> String { tag.to_owned() }
pub(super) fn name_in(_: &str, _: &str) -> Option<String> { None }
pub(super) fn sort_in<T>(_: &mut [(String, T)], _: &str) -> bool { false }
+289
View File
@@ -0,0 +1,289 @@
//! Windows' spell checking API: one checker per chosen dictionary (`super::languages`), made on
//! each thread that checks and made again when the choice changes.
#![allow(unsafe_code)]
use std::cell::RefCell;
use windows::Win32::Globalization::{
CORRECTIVE_ACTION_GET_SUGGESTIONS, CORRECTIVE_ACTION_REPLACE, GetLocaleInfoEx, GetUserPreferredUILanguages, ISpellChecker,
ISpellCheckerFactory, ISpellingError, LOCALE_SENGLISHDISPLAYNAME, MUI_LANGUAGE_NAME, SpellCheckerFactory,
};
use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED, CoCreateInstance, CoInitializeEx, CoTaskMemFree, IEnumString};
use windows::core::{HSTRING, PCWSTR, PWSTR};
/// Each check is a cross-process call per misspelled word: lines go to the checker thread.
pub(super) const OFF_THREAD: bool = true;
/// A thread's checkers, for the generation they were made in.
struct Checkers {
generation: u64,
list: Vec<ISpellChecker>,
}
thread_local! {
// Never released: releasing the checkers' out-of-process provider as the thread exits can
// wait on it forever, holding the process open. A changed choice makes new ones while the
// thread runs, where releasing the old ones is safe.
static FACTORY: std::mem::ManuallyDrop<Option<ISpellCheckerFactory>> = std::mem::ManuallyDrop::new(factory());
static CHECKERS: std::mem::ManuallyDrop<RefCell<Checkers>> =
std::mem::ManuallyDrop::new(RefCell::new(Checkers { generation: u64::MAX, list: Vec::new() }));
}
fn factory() -> Option<ISpellCheckerFactory> {
// SAFETY: COM calls on this thread's apartment.
unsafe {
// The window's thread already has an apartment; a headless one may not.
CoInitializeEx(None, COINIT_APARTMENTTHREADED).ok().ok();
CoCreateInstance(&SpellCheckerFactory, None, CLSCTX_INPROC_SERVER).ok()
}
}
/// Runs `f` over this thread's checkers for the chosen dictionaries.
fn with_checkers<T>(f: impl FnOnce(&[ISpellChecker]) -> T) -> T {
CHECKERS.with(|checkers| {
let mut checkers = checkers.borrow_mut();
let generation = super::generation();
if checkers.generation != generation {
let list = FACTORY.with(|factory| {
let Some(factory) = &**factory else { return Vec::new() };
// SAFETY: the factory is this thread's, and each tag outlives its call.
super::languages().into_iter().filter_map(|tag| unsafe { factory.CreateSpellChecker(&HSTRING::from(tag)).ok() }).collect()
});
*checkers = Checkers { generation, list };
}
f(&checkers.list)
})
}
/// The dictionaries Windows has: those of the languages added in Settings › Time & language.
pub(super) fn available() -> Vec<String> {
FACTORY.with(|factory| {
let Some(factory) = &**factory else { return Vec::new() };
// SAFETY: the factory is this thread's; each string `Next` hands over is freed once read.
unsafe { factory.SupportedLanguages().map(|list| strings(&list)).unwrap_or_default() }
})
}
/// The user's display languages, most preferred first.
pub(super) fn preferred() -> Vec<String> {
let (mut count, mut len) = (0u32, 0u32);
// SAFETY: the first call sizes the buffer the second fills; the buffer outlives both.
unsafe {
if GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &mut count, None, &mut len).is_err() || len == 0 {
return Vec::new();
}
let mut buffer = vec![0u16; len as usize];
if GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &mut count, Some(PWSTR(buffer.as_mut_ptr())), &mut len).is_err() {
return Vec::new();
}
buffer.split(|&c| c == 0).filter(|s| !s.is_empty()).map(String::from_utf16_lossy).collect()
}
}
/// The language's English name, "French (France)".
pub(super) fn english_name(tag: &str) -> String {
let name = HSTRING::from(tag);
let mut buffer = [0u16; 128];
// SAFETY: `name` and `buffer` outlive the call, which writes at most the buffer's length.
let len = unsafe { GetLocaleInfoEx(PCWSTR(name.as_ptr()), LOCALE_SENGLISHDISPLAYNAME, Some(&mut buffer)) };
if len <= 1 {
return tag.to_owned();
}
String::from_utf16_lossy(&buffer[..len as usize - 1])
}
/// `tag`'s name in `locale`'s language from the ICU in Windows, as Chromium's
/// `Intl.DisplayNames(locale, { type: "language" })` asks its own: full length, dialect names.
pub(super) fn name_in(tag: &str, locale: &str) -> Option<String> {
let icu = icu()?;
let (locale, tag) = (icu_id(locale)?, icu_id(tag)?);
let mut contexts = [UDISPCTX_LENGTH_FULL, UDISPCTX_DIALECT_NAMES, UDISPCTX_NO_SUBSTITUTE];
let mut buffer = [0u16; 256];
let mut error = 0;
// SAFETY: icu.dll's C API with NUL-terminated ids, a context array and a buffer that outlive
// the calls; the display names object is closed before returning.
let len = unsafe {
let names = (icu.open)(locale.as_ptr(), contexts.as_mut_ptr(), contexts.len() as i32, &mut error);
if names.is_null() || error > 0 {
return None;
}
let len = (icu.name)(names, tag.as_ptr(), buffer.as_mut_ptr(), buffer.len() as i32, &mut error);
(icu.close)(names);
len
};
(error <= 0 && len > 0 && len as usize <= buffer.len()).then(|| String::from_utf16_lossy(&buffer[..len as usize]))
}
/// Sorts `items` by their names as `locale` sorts text, with ICU's collator, as
/// `String.localeCompare` does. False, leaving them as they were, where there's no collator.
pub(super) fn sort_in<T>(items: &mut [(String, T)], locale: &str) -> bool {
let (Some(icu), Some(locale)) = (icu(), icu_id(locale)) else { return false };
let mut error = 0;
// SAFETY: icu.dll's C API; the collator is closed once the sort is done.
let collator = unsafe { (icu.collator)(locale.as_ptr(), &mut error) };
if collator.is_null() || error > 0 {
return false;
}
items.sort_by(|(a, _), (b, _)| {
let (a, b): (Vec<u16>, Vec<u16>) = (a.encode_utf16().collect(), b.encode_utf16().collect());
// SAFETY: the collator is live, and the strings outlive the call.
unsafe { (icu.collate)(collator, a.as_ptr(), a.len() as i32, b.as_ptr(), b.len() as i32) }.cmp(&0)
});
// SAFETY: closes the collator opened above, used no more.
unsafe { (icu.close_collator)(collator) };
true
}
const UDISPCTX_DIALECT_NAMES: i32 = 1;
const UDISPCTX_LENGTH_FULL: i32 = 0x200;
const UDISPCTX_NO_SUBSTITUTE: i32 = 0x301;
type Opaque = *mut std::ffi::c_void;
/// The few calls of icu.dll (Windows 10 1903 and later) these use, loaded on first use.
struct Icu {
open: unsafe extern "C" fn(*const u8, *mut i32, i32, *mut i32) -> Opaque,
name: unsafe extern "C" fn(Opaque, *const u8, *mut u16, i32, *mut i32) -> i32,
close: unsafe extern "C" fn(Opaque),
collator: unsafe extern "C" fn(*const u8, *mut i32) -> Opaque,
collate: unsafe extern "C" fn(Opaque, *const u16, i32, *const u16, i32) -> i32,
close_collator: unsafe extern "C" fn(Opaque),
}
// SAFETY: the function pointers are plain exports of a module that stays loaded.
unsafe impl Send for Icu {}
// SAFETY: as above; ICU's C API is thread-safe for separately opened objects.
unsafe impl Sync for Icu {}
fn icu() -> Option<&'static Icu> {
use windows_sys::Win32::System::LibraryLoader::{LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW};
static ICU: std::sync::OnceLock<Option<Icu>> = std::sync::OnceLock::new();
ICU.get_or_init(|| {
let dll: Vec<u16> = "icu.dll".encode_utf16().chain([0]).collect();
// SAFETY: loads a system DLL from System32, kept for the process, and reads exports whose
// C signatures are ICU's stable API (uldn_openForContext, uldn_localeDisplayName,
// uldn_close, ucol_open, ucol_strcoll, ucol_close).
unsafe {
let module = LoadLibraryExW(dll.as_ptr(), std::ptr::null_mut(), LOAD_LIBRARY_SEARCH_SYSTEM32);
if module.is_null() {
return None;
}
Some(Icu {
open: export(module, c"uldn_openForContext")?,
name: export(module, c"uldn_localeDisplayName")?,
close: export(module, c"uldn_close")?,
collator: export(module, c"ucol_open")?,
collate: export(module, c"ucol_strcoll")?,
close_collator: export(module, c"ucol_close")?,
})
}
})
.as_ref()
}
/// Export `name` of `module` as the function pointer type `F`.
///
/// # Safety
/// `F` must be a function pointer type with the export's exact signature.
unsafe fn export<F: Copy>(module: windows_sys::Win32::Foundation::HMODULE, name: &std::ffi::CStr) -> Option<F> {
// SAFETY: the module is loaded; the name is NUL-terminated.
let found = unsafe { windows_sys::Win32::System::LibraryLoader::GetProcAddress(module, name.as_ptr().cast()) }?;
// SAFETY: per this function's contract, both are function pointers of the same size.
Some(unsafe { std::mem::transmute_copy::<unsafe extern "system" fn() -> isize, F>(&found) })
}
/// A BCP 47 tag as an ICU locale id (`en-029` as `en_029`), NUL-terminated.
fn icu_id(tag: &str) -> Option<Vec<u8>> {
tag.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_').then(|| tag.bytes().map(|b| if b == b'-' { b'_' } else { b }).chain([0]).collect())
}
/// Reads a COM string list to its end.
///
/// # Safety
/// `list` must be a live enumerator on this thread.
unsafe fn strings(list: &IEnumString) -> Vec<String> {
let mut found = Vec::new();
loop {
let mut one = [PWSTR::null()];
let mut fetched = 0u32;
// SAFETY: per this function's contract; each string handed over is freed once read.
unsafe {
if list.Next(&mut one, Some(&mut fetched)).is_err() || fetched == 0 || one[0].is_null() {
break;
}
found.extend(one[0].to_string().ok());
CoTaskMemFree(Some(one[0].0 as *const _));
}
}
found
}
pub(super) fn misspelled(text: &str) -> Vec<(usize, usize)> {
with_checkers(|checkers| {
// A word is misspelled when every dictionary says so, as Chromium's multilingual checking.
let mut lists = checkers.iter().map(|checker| check(checker, text));
let Some(first) = lists.next() else { return Vec::new() };
lists.fold(first, |found, other| found.into_iter().filter(|range| other.contains(range)).collect())
})
}
/// One dictionary's misspelled words in `text`, as byte ranges.
fn check(checker: &ISpellChecker, text: &str) -> Vec<(usize, usize)> {
// Each UTF-16 unit's byte offset, and the text's end.
let mut bytes = Vec::with_capacity(text.len() + 1);
for (i, c) in text.char_indices() {
bytes.extend(std::iter::repeat_n(i, c.len_utf16()));
}
bytes.push(text.len());
let mut found = Vec::new();
// SAFETY: the checker is this thread's, and the text outlives the call.
unsafe {
let Ok(errors) = checker.Check(&HSTRING::from(text)) else { return found };
loop {
let mut error: Option<ISpellingError> = None;
if errors.Next(&mut error).is_err() {
break;
}
let Some(error) = error else { break };
// A repeated word ("the the") is a delete: Chromium leaves it unmarked.
let action = error.CorrectiveAction().unwrap_or_default();
if action != CORRECTIVE_ACTION_GET_SUGGESTIONS && action != CORRECTIVE_ACTION_REPLACE {
continue;
}
let (Ok(start), Ok(len)) = (error.StartIndex(), error.Length()) else { continue };
let (a, b) = (start as usize, start as usize + len as usize);
if let (Some(&a), Some(&b)) = (bytes.get(a), bytes.get(b))
&& a < b
{
found.push((a, b));
}
}
}
found
}
pub(super) fn suggest(word: &str) -> Vec<String> {
with_checkers(|checkers| {
let mut found: Vec<String> = Vec::new();
for checker in checkers {
// SAFETY: as in `check`; the list is read to its end on this thread.
let more = unsafe { checker.Suggest(&HSTRING::from(word)).map(|list| strings(&list)).unwrap_or_default() };
for s in more {
if !found.contains(&s) {
found.push(s);
}
}
}
found
})
}
pub(super) fn learn(word: &str) {
with_checkers(|checkers| {
for checker in checkers {
// SAFETY: the checker is this thread's, and the word outlives the call.
unsafe { checker.Add(&HSTRING::from(word)) }.ok();
}
});
}