Everything in Rust on Servo 0.7 (trimmed: no WebXR, WebGPU, multiprocess): tabs and windows, address bar with suggestions, history, bookmarks and reading list, downloads with resume and external download managers, encrypted password vault with autofill, ad blocker (adblock-rust, 22 lists), VPN through Tor or a proxy and secure DNS via a local bridge proxy, picture in picture, Discord Rich Presence, media player and visualizer, spell check, site apps, user scripts and styles, import from other browsers, gamepads, Web Bluetooth, and every setting of the original Nacre in a plain egui interface. Not compiled yet; docs/HANDOFF.md has the first build checklist. Co-Authored-By: Claude Opus 5.5 <[email protected]>
181 lines
6.7 KiB
Rust
181 lines
6.7 KiB
Rust
//! Spell check for text typed in pages. Hunspell dictionaries (read by spellbook) come from the
|
||
//! system (/usr/share/hunspell and friends) or are downloaded once into the shared cache from the
|
||
//! wooorm/dictionaries collection. Words the user adds go to a personal word list.
|
||
|
||
use std::collections::HashSet;
|
||
use std::path::{Path, PathBuf};
|
||
use std::time::Duration;
|
||
|
||
use spellbook::Dictionary;
|
||
|
||
use crate::net::fetch;
|
||
use crate::util;
|
||
|
||
/// Languages offered in settings: (code, name).
|
||
pub const LANGUAGES: &[(&str, &str)] = &[
|
||
("en_US", "English (US)"),
|
||
("en_GB", "English (UK)"),
|
||
("en_AU", "English (Australia)"),
|
||
("en_CA", "English (Canada)"),
|
||
("de_DE", "German"),
|
||
("fr_FR", "French"),
|
||
("es_ES", "Spanish"),
|
||
("it_IT", "Italian"),
|
||
("nl_NL", "Dutch"),
|
||
("pt_BR", "Portuguese (Brazil)"),
|
||
("pt_PT", "Portuguese (Portugal)"),
|
||
("pl_PL", "Polish"),
|
||
("sv_SE", "Swedish"),
|
||
("da_DK", "Danish"),
|
||
("nb_NO", "Norwegian"),
|
||
("cs_CZ", "Czech"),
|
||
("ru_RU", "Russian"),
|
||
("uk_UA", "Ukrainian"),
|
||
("tr_TR", "Turkish"),
|
||
];
|
||
|
||
/// Name in the wooorm/dictionaries collection.
|
||
fn wooorm_code(lang: &str) -> String {
|
||
match lang {
|
||
"en_US" => "en".into(),
|
||
"en_GB" => "en-GB".into(),
|
||
"en_AU" => "en-AU".into(),
|
||
"en_CA" => "en-CA".into(),
|
||
"pt_BR" => "pt".into(),
|
||
"pt_PT" => "pt-PT".into(),
|
||
"nb_NO" => "nb".into(),
|
||
other => other.split('_').next().unwrap_or(other).to_owned(),
|
||
}
|
||
}
|
||
|
||
/// The system language as a dictionary code ("en_US").
|
||
pub fn system_language() -> String {
|
||
for var in ["LC_ALL", "LC_MESSAGES", "LANG"] {
|
||
if let Ok(value) = std::env::var(var) {
|
||
let code = value.split('.').next().unwrap_or("").to_owned();
|
||
if code.len() >= 2 && code != "C" && code != "POSIX" {
|
||
return if code.contains('_') { code } else { format!("{code}_{}", code.to_uppercase()) };
|
||
}
|
||
}
|
||
}
|
||
"en_US".to_owned()
|
||
}
|
||
|
||
fn system_dirs() -> Vec<PathBuf> {
|
||
["/usr/share/hunspell", "/usr/share/myspell", "/usr/share/myspell/dicts", "/usr/local/share/hunspell"].iter().map(PathBuf::from).collect()
|
||
}
|
||
|
||
/// Paths of the .aff and .dic files for `lang`, from the system or the cache.
|
||
fn find_files(lang: &str, cache: &Path) -> Option<(PathBuf, PathBuf)> {
|
||
for dir in system_dirs().into_iter().chain(std::iter::once(cache.to_owned())) {
|
||
let aff = dir.join(format!("{lang}.aff"));
|
||
let dic = dir.join(format!("{lang}.dic"));
|
||
if aff.is_file() && dic.is_file() {
|
||
return Some((aff, dic));
|
||
}
|
||
}
|
||
None
|
||
}
|
||
|
||
/// Download a dictionary into the cache. Blocking.
|
||
pub fn download(lang: &str, cache: &Path) -> Result<(), String> {
|
||
let code = wooorm_code(lang);
|
||
let base = format!("https://raw.githubusercontent.com/wooorm/dictionaries/main/dictionaries/{code}/index");
|
||
let _ = std::fs::create_dir_all(cache);
|
||
for (ext, limit) in [("aff", 4 * 1024 * 1024), ("dic", 64 * 1024 * 1024)] {
|
||
let fetched = fetch::get(&format!("{base}.{ext}"), &[], limit, Duration::from_secs(120))?;
|
||
if !fetched.ok() {
|
||
return Err(format!("the dictionary server answered {}", fetched.status));
|
||
}
|
||
util::write_atomic(&cache.join(format!("{lang}.{ext}")), &fetched.body, false).map_err(|e| e.to_string())?;
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
pub struct Speller {
|
||
dictionaries: Vec<(String, Dictionary)>,
|
||
personal: HashSet<String>,
|
||
personal_path: PathBuf,
|
||
/// Languages that couldn't be loaded, with the reason.
|
||
pub missing: Vec<(String, String)>,
|
||
}
|
||
|
||
impl Speller {
|
||
/// Load dictionaries for `langs` (empty = system language), downloading any that are missing.
|
||
/// Blocking: run on a worker thread.
|
||
pub fn load(langs: &[String], cache: &Path, personal_path: PathBuf) -> Speller {
|
||
let langs: Vec<String> = if langs.is_empty() { vec![system_language()] } else { langs.to_vec() };
|
||
let mut dictionaries = Vec::new();
|
||
let mut missing = Vec::new();
|
||
for lang in langs {
|
||
if find_files(&lang, cache).is_none()
|
||
&& let Err(error) = download(&lang, cache)
|
||
{
|
||
missing.push((lang.clone(), error));
|
||
continue;
|
||
}
|
||
let Some((aff, dic)) = find_files(&lang, cache) else { continue };
|
||
let (Ok(aff_text), Ok(dic_text)) = (std::fs::read_to_string(&aff), std::fs::read_to_string(&dic)) else {
|
||
missing.push((lang.clone(), "the dictionary files can't be read".into()));
|
||
continue;
|
||
};
|
||
match Dictionary::new(&aff_text, &dic_text) {
|
||
Ok(dictionary) => dictionaries.push((lang, dictionary)),
|
||
Err(error) => missing.push((lang, error.to_string())),
|
||
}
|
||
}
|
||
let personal = std::fs::read_to_string(&personal_path).map(|t| t.lines().map(str::trim).filter(|l| !l.is_empty()).map(str::to_owned).collect()).unwrap_or_default();
|
||
Speller { dictionaries, personal, personal_path, missing }
|
||
}
|
||
|
||
pub fn languages(&self) -> Vec<String> {
|
||
self.dictionaries.iter().map(|(l, _)| l.clone()).collect()
|
||
}
|
||
|
||
/// A word is right if any dictionary knows it.
|
||
pub fn check(&self, word: &str) -> bool {
|
||
if self.dictionaries.is_empty() || word.chars().count() <= 1 || word.chars().any(|c| c.is_ascii_digit()) {
|
||
return true;
|
||
}
|
||
let word = word.trim_matches(['\'', '’']);
|
||
if self.personal.contains(word) || self.personal.contains(&word.to_lowercase()) {
|
||
return true;
|
||
}
|
||
// Apostrophes: dictionaries use the straight one.
|
||
let normalized = word.replace('’', "'");
|
||
self.dictionaries.iter().any(|(_, d)| d.check(&normalized))
|
||
}
|
||
|
||
pub fn misspelled(&self, words: &[String]) -> Vec<String> {
|
||
words.iter().filter(|w| !self.check(w)).cloned().collect()
|
||
}
|
||
|
||
pub fn suggest(&self, word: &str, limit: usize) -> Vec<String> {
|
||
let mut out = Vec::new();
|
||
for (_, d) in &self.dictionaries {
|
||
let mut s = Vec::new();
|
||
d.suggest(&word.replace('’', "'"), &mut s);
|
||
for w in s {
|
||
if !out.contains(&w) {
|
||
out.push(w);
|
||
}
|
||
}
|
||
if out.len() >= limit {
|
||
break;
|
||
}
|
||
}
|
||
out.truncate(limit);
|
||
out
|
||
}
|
||
|
||
pub fn add_word(&mut self, word: &str) {
|
||
let word = word.trim().to_owned();
|
||
if word.is_empty() || !self.personal.insert(word) {
|
||
return;
|
||
}
|
||
let mut words: Vec<&String> = self.personal.iter().collect();
|
||
words.sort();
|
||
let text: String = words.iter().map(|w| format!("{w}\n")).collect();
|
||
let _ = util::write_atomic(&self.personal_path, text.as_bytes(), false);
|
||
}
|
||
}
|