Skip to main content

settings_model/
personal_dictionary.rs

1//! The person's personal vocabulary, shared by every input surface that checks or helps with
2//! spelling: the word processor, the on-screen keyboard and dictation.
3//!
4//! The words are a section of the person's settings document ([`SECTION`]) beside their other
5//! settings, so they follow them to their other devices. A consumer reads through a [`Reader`]
6//! bound to one document; a reader is revoked when the session replaces that document.
7
8use std::io;
9use std::sync::Arc;
10use std::sync::atomic::{AtomicBool, Ordering};
11
12use serde::{Deserialize, Serialize};
13use serde_json::{Map, Value};
14use unicode_normalization::UnicodeNormalization;
15
16use crate::source::{ConditionalUpdate, SettingsSource, compare_update_section};
17
18/// The person's words, as a section of their settings document.
19pub const SECTION: &str = "personal_dictionary";
20
21/// The section's one leaf: the words and the revision an edit names. One value, so a device's
22/// change reaches the person's other devices whole.
23const WORDS: &str = "words";
24
25const MAX_WORDS: usize = 1_024;
26
27/// An explicit user addition. Display spelling is retained, including casing.
28/// `None` means all languages; a tag such as `fr` restricts the hint to that
29/// language and its regional variants. Additions never mean replacement rules.
30#[cfg_attr(
31    feature = "model",
32    derive(tilo_resource::Model, tilo_resource::JsonSchema)
33)]
34#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
35pub struct Word {
36    pub spelling: String,
37    pub language: Option<String>,
38}
39
40impl Word {
41    pub fn new(spelling: &str, language: Option<&str>) -> io::Result<Self> {
42        let spelling: String = spelling.trim().nfc().collect();
43        if spelling.is_empty()
44            || spelling.chars().count() > 128
45            || !spelling.chars().any(char::is_alphabetic)
46            || spelling
47                .chars()
48                .any(|c| c.is_whitespace() || c.is_control())
49        {
50            return Err(invalid("enter one word of at most 128 characters"));
51        }
52        let language = language.map(str::to_ascii_lowercase);
53        if language.as_deref().is_some_and(|tag| {
54            tag.len() > 35
55                || tag.split('-').any(|part| {
56                    part.is_empty()
57                        || part.len() > 8
58                        || !part.bytes().all(|c| c.is_ascii_alphanumeric())
59                })
60                || !tag.split('-').next().is_some_and(|part| {
61                    (2..=8).contains(&part.len()) && part.bytes().all(|c| c.is_ascii_alphabetic())
62                })
63        }) {
64            return Err(invalid("invalid language tag"));
65        }
66        Ok(Self { spelling, language })
67    }
68
69    fn same_key(&self, other: &Self) -> bool {
70        self.language == other.language && folded(&self.spelling) == folded(&other.spelling)
71    }
72
73    fn applies(&self, language: &str) -> bool {
74        self.language.as_deref().is_none_or(|tag| {
75            language.eq_ignore_ascii_case(tag)
76                || language
77                    .to_ascii_lowercase()
78                    .strip_prefix(tag)
79                    .is_some_and(|tail| tail.starts_with('-'))
80        })
81    }
82}
83
84fn folded(word: &str) -> String {
85    word.nfc().flat_map(char::to_lowercase).nfc().collect()
86}
87
88#[cfg_attr(
89    feature = "model",
90    derive(tilo_resource::Model, tilo_resource::JsonSchema)
91)]
92#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
93pub struct Snapshot {
94    pub revision: u64,
95    pub words: Vec<Word>,
96}
97
98impl Snapshot {
99    /// The words `edit` makes of these, with the revision after it.
100    pub fn preview(&self, edit: Edit) -> io::Result<Self> {
101        let mut next = self.clone();
102        match edit {
103            Edit::Add(word) => insert(&mut next.words, validate(&word)?)?,
104            Edit::Replace { old, new } => {
105                let new = validate(&new)?;
106                let index = next
107                    .words
108                    .iter()
109                    .position(|word| word.same_key(&old))
110                    .ok_or_else(|| invalid("the word no longer exists"))?;
111                if next
112                    .words
113                    .iter()
114                    .enumerate()
115                    .any(|(i, word)| i != index && word.same_key(&new))
116                {
117                    return Err(invalid("the edited word already exists"));
118                }
119                if let Some(word) = next.words.get_mut(index) {
120                    *word = new;
121                }
122            }
123            Edit::Remove(old) => next.words.retain(|word| !word.same_key(&old)),
124            Edit::Reset => next.words.clear(),
125        }
126        next.revision = next
127            .revision
128            .checked_add(1)
129            .ok_or_else(|| invalid("dictionary revision exhausted"))?;
130        Ok(next)
131    }
132    pub fn hints<'a>(&'a self, language: &'a str) -> impl Iterator<Item = &'a str> {
133        self.words
134            .iter()
135            .filter(move |w| w.applies(language))
136            .map(|w| w.spelling.as_str())
137    }
138
139    pub fn contains(&self, typed: &str, language: &str) -> bool {
140        let key = folded(typed);
141        self.hints(language).any(|hint| folded(hint) == key)
142    }
143
144    pub fn completions(&self, prefix: &str, language: &str, limit: usize) -> Vec<String> {
145        if prefix.is_empty() || limit == 0 {
146            return Vec::new();
147        }
148        let key = folded(prefix);
149        let mut result = Vec::new();
150        for word in self.hints(language).filter(|w| folded(w).starts_with(&key)) {
151            if !result.iter().any(|w: &String| folded(w) == folded(word)) {
152                result.push(word.to_owned());
153            }
154            if result.len() == limit {
155                break;
156            }
157        }
158        result
159    }
160}
161
162pub trait Vocabulary: Send + Sync {
163    fn snapshot(&self) -> io::Result<Snapshot>;
164}
165
166#[derive(Clone, Serialize, Deserialize)]
167pub enum Edit {
168    Add(Word),
169    Replace { old: Word, new: Word },
170    Remove(Word),
171    Reset,
172}
173
174/// The person's dictionary as `source` holds it. A missing or unreadable section is empty: a
175/// settings read never fails.
176#[must_use]
177pub fn snapshot_in(source: &dyn SettingsSource) -> Snapshot {
178    snapshot_of(&source.load())
179}
180
181/// [`snapshot_in`] of a document already loaded.
182#[must_use]
183pub fn snapshot_of(document: &Map<String, Value>) -> Snapshot {
184    document
185        .get(SECTION)
186        .and_then(Value::as_object)
187        .and_then(|section| section.get(WORDS))
188        .cloned()
189        .and_then(|value| serde_json::from_value::<Snapshot>(value).ok())
190        .filter(|snapshot| {
191            snapshot.words.len() <= MAX_WORDS
192                && snapshot.words.iter().all(|word| {
193                    Word::new(&word.spelling, word.language.as_deref())
194                        .is_ok_and(|valid| valid == *word)
195                })
196        })
197        .unwrap_or_default()
198}
199
200/// Apply `edit` to the dictionary `revision` was read from.
201///
202/// # Errors
203///
204/// [`io::ErrorKind::WouldBlock`] when another edit landed since `revision`; [`io::ErrorKind::InvalidData`]
205/// when the edit is not a valid change to the words; otherwise the source's own error.
206pub fn edit_in(source: &dyn SettingsSource, revision: u64, edit: Edit) -> io::Result<Snapshot> {
207    let document = source.load();
208    let current = snapshot_of(&document);
209    if current.revision != revision {
210        return Err(changed());
211    }
212    let next = current.preview(edit)?;
213    if serde_json::to_vec(&next.words)
214        .map_err(io::Error::other)?
215        .len()
216        > crate::MAX_PERSONAL_VALUE_BYTES
217    {
218        return Err(invalid("personal dictionary is full"));
219    }
220    let mut values = Map::new();
221    values.insert(
222        WORDS.to_owned(),
223        serde_json::to_value(&next).map_err(io::Error::other)?,
224    );
225    let expected = match document.get(SECTION) {
226        Some(Value::Object(section)) => section.clone(),
227        _ => Map::new(),
228    };
229    match compare_update_section(source, SECTION, &expected, values)? {
230        ConditionalUpdate::Stored => Ok(next),
231        ConditionalUpdate::Superseded => Err(changed()),
232    }
233}
234
235/// One document's view of the person's dictionary. Revoking it makes every clone fail, as the
236/// session does when it replaces the document a recognizer was reading.
237#[derive(Clone)]
238pub struct Reader {
239    source: Arc<dyn SettingsSource>,
240    revoked: Arc<AtomicBool>,
241}
242
243impl Reader {
244    #[must_use]
245    pub fn bind(source: Arc<dyn SettingsSource>) -> Self {
246        Self {
247            source,
248            revoked: Arc::new(AtomicBool::new(false)),
249        }
250    }
251
252    pub fn revoke(&self) {
253        self.revoked.store(true, Ordering::Release);
254    }
255
256    /// Whether `other` reads the same document: two readers of it stay interchangeable while the
257    /// words change.
258    #[must_use]
259    pub fn same_binding(&self, other: &Self) -> bool {
260        self.reads(&other.source)
261    }
262
263    /// Whether this reader reads `source`.
264    #[must_use]
265    pub fn reads(&self, source: &Arc<dyn SettingsSource>) -> bool {
266        Arc::ptr_eq(&self.source, source)
267    }
268}
269
270impl Vocabulary for Reader {
271    fn snapshot(&self) -> io::Result<Snapshot> {
272        if self.revoked.load(Ordering::Acquire) {
273            return Err(denied());
274        }
275        Ok(snapshot_in(self.source.as_ref()))
276    }
277}
278
279fn validate(word: &Word) -> io::Result<Word> {
280    Word::new(&word.spelling, word.language.as_deref())
281}
282
283fn insert(words: &mut Vec<Word>, word: Word) -> io::Result<()> {
284    if words.iter().any(|held| held.same_key(&word)) {
285        return Ok(());
286    }
287    if words.len() == MAX_WORDS {
288        return Err(invalid("personal dictionary is full"));
289    }
290    words.push(word);
291    Ok(())
292}
293
294fn changed() -> io::Error {
295    io::Error::new(
296        io::ErrorKind::WouldBlock,
297        "dictionary changed; reload before editing",
298    )
299}
300
301fn invalid(message: &str) -> io::Error {
302    io::Error::new(io::ErrorKind::InvalidData, message)
303}
304
305fn denied() -> io::Error {
306    io::Error::new(
307        io::ErrorKind::PermissionDenied,
308        "personal dictionary reader was revoked",
309    )
310}
311
312#[cfg(test)]
313mod tests;