Skip to main content

keyrill_core/
session.rs

1//! The word session: one owned word at a time, advanced only by verified acknowledgements.
2//!
3//! While a word is typed, the adapter keeps it in the host as an owned composition, marked text
4//! that Keyrill inserted and can still replace as a whole. The session is the Rust record of
5//! that word; it never touches the host. For each event the adapter asks for a [`Plan`], performs
6//! the one native action the plan permits, verifies it and reports the [`Outcome`]. Proposing
7//! changes nothing the session has confirmed: the proposed state waits in the session until
8//! [`Session::acknowledge`] receives a verified outcome for that plan's id, and a newer proposal
9//! makes an older plan stale.
10//!
11//! ```text
12//! adapter                                          Session
13//! key event      --- propose_*(event) -------->    plan the event against the confirmed state
14//!                <-- Plan { id: n, .. } -------    keep the proposed state as pending
15//! the mark still holds `expected`?
16//!   no: report Refused, nothing written
17//! perform `action` with `text`, at most one write
18//! read the result back
19//!                --- acknowledge(n, outcome) -->   Verified: adopt the pending state
20//!                                                  Refused or Unknown: Invalidated
21//! pass the key, consume it or propose it again, as `disposition` says
22//! ```
23//!
24//! The word moves through four states. `ARCHITECTURE.md` uses these names; in the code Composing
25//! and BoundaryRetained are one `Owned` state with the `boundary` flag clear or set.
26//!
27//! ```text
28//!                   letter at a boundary: Mark
29//!    +------+ ---------------------------------> +-----------+  letter, Backspace,
30//!    | Idle |                                    | Composing |  Manual, Reverse: Mark
31//!    +------+ <--------------------------------- +-----------+
32//!       ^      Backspace to empty: Mark (empty)        |
33//!       |      Escape or any other event: Finish       | Space: infer, then Mark the word
34//!       |                                              v        and the Space
35//!       |      Escape or any other event: Finish  +------------------+
36//!       +---------------------------------------- | BoundaryRetained |  Manual, Reverse: Mark
37//!              (a letter is then planned again)   +------------------+
38//!
39//!    Idle passes every other event. Manual or Reverse with nothing to act on is consumed
40//!    without a write, in every state.
41//!
42//!    From any state, a Refused or Unknown outcome, a mode change while a word is owned or an
43//!    exhausted token counter leads to Invalidated, which refuses every proposal; reset()
44//!    returns to Idle, except after exhaustion.
45//! ```
46//!
47//! A receipt is the text the word had before the session first converted it, automatically at
48//! Space or by a manual command. While the same word is owned, Reverse restores it once, and
49//! Escape restores it and finishes the word; an edit expires it, and so does finishing. Manual
50//! and Reverse also set explicit intent, which stops inference for the rest of that word, so
51//! inference never undoes a choice the user made. A Backspace is not intent, and a corrected
52//! typo still converts.
53//!
54//! Language context comes from the session's own finished words, never from the document. A
55//! word that ends in its Space and is finished by the letter that starts the next word is
56//! appended once that finish is verified, up to 256 UTF-16 units. Any other finish, and any
57//! event the host handles, clears it, because the host can then move the caret or edit the
58//! text; so do a mode change, a refused or unknown outcome and reset.
59
60use crate::inference::{self, Dictionaries, Policy, Request};
61use crate::mapping::{self, Keyboard, Mapping};
62use crate::model::Model;
63
64/// Maximum composing word length in UTF-16 units, excluding retained Space.
65pub const MAX_WORD: usize = 64;
66const MAX_HISTORY: usize = 256;
67
68/// Input mode: the layout Keyrill types in.
69#[derive(Clone, Copy, Debug, PartialEq, Eq)]
70pub enum Mode {
71    /// English mode.
72    En,
73    /// Russian mode.
74    Ru,
75}
76
77/// What the adapter verified before the caret. It matters only when no word is owned: a letter
78/// starts a word only at [`Context::Boundary`], so the session never takes over the tail of a
79/// token already in the document.
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81pub enum Context {
82    /// Start of document or whitespace.
83    Boundary,
84    /// Anything else, or a prefix the adapter could not establish.
85    Ineligible,
86}
87
88/// Input supplied by the native controller, without document offsets.
89#[derive(Clone, Debug, PartialEq, Eq)]
90pub enum Event {
91    /// Text units the key would insert. A single letter, or in English mode a single
92    /// provisional unit, starts or continues a word; a single Space takes an owned word to its
93    /// boundary; anything else finishes an owned word and goes to the host.
94    Text(Vec<u16>),
95    /// Delete the last owned unit; at the boundary it finishes the word and goes to the host.
96    Backspace,
97    /// Restore the original and finish if a receipt exists; otherwise finish as typed and pass.
98    Escape,
99    /// Convert the owned word key by key to the other layout; a conversion sets explicit intent.
100    Manual,
101    /// Restore the receipt's text exactly while the same word is owned, with explicit intent.
102    Reverse,
103    /// Finish the owned word as it stands and let the host handle the event.
104    Finish,
105}
106
107/// The one native operation a plan permits.
108#[derive(Clone, Copy, Debug, PartialEq, Eq)]
109pub enum Action {
110    /// No native mutation.
111    Pass,
112    /// Set the owned mark to `text`, or start one if none is owned. An empty `text` ends the
113    /// composition with nothing in it.
114    Mark,
115    /// Commit `text` in place of the owned mark, once, and end the composition.
116    Finish,
117    /// A reserved command (Manual or Reverse) with nothing to act on; nothing is written.
118    Unavailable,
119}
120
121/// What happens to the key event once the plan's action is verified.
122#[derive(Clone, Copy, Debug, PartialEq, Eq)]
123pub enum Disposition {
124    /// Let the host handle the event once.
125    Pass,
126    /// The event is handled; the host does not see it.
127    Consumed,
128    /// Finish was acknowledged; plan the same event again from Idle.
129    Replan,
130}
131
132/// Native effect acknowledgement.
133#[derive(Clone, Copy, Debug, PartialEq, Eq)]
134pub enum Outcome {
135    /// Native effect and readback verified, or the plan had no native effect.
136    Verified,
137    /// Rejected before any native write.
138    Refused,
139    /// Write attempted but outcome cannot be established.
140    Unknown,
141}
142
143/// Session protocol errors; no raw text is included.
144#[derive(Clone, Copy, Debug, PartialEq, Eq)]
145pub enum Error {
146    /// The id is not the pending plan: a later proposal superseded it, it was already
147    /// acknowledged, or a reset expired it.
148    Stale,
149    /// Session invalidated or token counter exhausted.
150    Invalidated,
151}
152
153impl std::fmt::Display for Error {
154    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155        f.write_str(match self {
156            Self::Stale => "plan is not the latest proposal",
157            Self::Invalidated => "session is invalidated",
158        })
159    }
160}
161
162impl std::error::Error for Error {}
163
164#[derive(Clone, Debug, Default, PartialEq, Eq)]
165enum State {
166    #[default]
167    Idle,
168    /// Composing while `boundary` is clear, BoundaryRetained once the Space has joined the mark.
169    Owned {
170        /// What the owned mark holds, including the Space once `boundary` is set.
171        text: Vec<u16>,
172        /// The receipt: the text before the word was first converted; `None` if it was never
173        /// converted, or after an edit or a Reverse.
174        original: Option<Vec<u16>>,
175        boundary: bool,
176        /// Set by Manual or Reverse; Space then keeps the word without inference.
177        explicit: bool,
178        /// Input mode the word was started in.
179        mode: Mode,
180    },
181    Invalidated,
182}
183
184/// Automatic correction at Space: the fixture policy, on or off, or the model.
185enum Automatic<'a> {
186    Fixture(bool),
187    Model(&'a Model<'a>, Dictionaries<'a>, Policy),
188}
189
190/// What a verified plan does to the language history.
191enum HistoryEffect {
192    Keep,
193    Clear,
194    Append(Vec<u16>),
195}
196
197/// The proposed state of the latest plan, adopted only by a verified acknowledgement.
198struct Pending {
199    id: u64,
200    state: State,
201    history: HistoryEffect,
202    mode: Mode,
203}
204
205/// Copied proposal for native validation and a single native effect. It owns its text and
206/// borrows nothing from the session, the model or the vocabulary snapshots.
207#[derive(Clone, Debug, PartialEq, Eq)]
208pub struct Plan {
209    /// Latest-only acknowledgement token.
210    pub id: u64,
211    /// Permitted native operation.
212    pub action: Action,
213    /// Event disposition after verification.
214    pub disposition: Disposition,
215    /// The UTF-16 units the owned mark must hold before the action; empty when none is owned.
216    pub expected: Vec<u16>,
217    /// The UTF-16 units to mark or commit; empty for [`Action::Pass`] and
218    /// [`Action::Unavailable`].
219    pub text: Vec<u16>,
220}
221
222/// One controller's bounded word state; contains no native objects or callbacks. It holds at
223/// most one word of [`MAX_WORD`] units plus its Space, the word's receipt, and 256 UTF-16 units
224/// of history.
225#[derive(Default)]
226pub struct Session {
227    /// Confirmed state.
228    state: State,
229    pending: Option<Pending>,
230    /// Last issued token; never reset, so no later plan can reuse an expired id.
231    serial: u64,
232    fixtures: bool,
233    /// Finished words in document order, each followed by its Space.
234    history: Vec<u16>,
235    /// Input mode of the last verified plan; history is consulted only under the same mode.
236    mode: Option<Mode>,
237    keyboard: Keyboard,
238}
239
240impl Session {
241    /// Whether a copied proposal is awaiting acknowledgement.
242    pub fn has_pending(&self) -> bool {
243        self.pending.is_some()
244    }
245
246    /// Whether the session holds an owned word. This is not evidence that the host still shows
247    /// the mark, and it grants no native authority.
248    pub fn has_word(&self) -> bool {
249        matches!(self.state, State::Owned { .. })
250    }
251
252    /// Invalidate outstanding tokens and drop all text/receipts on native lifecycle change.
253    /// The session returns to Idle with no history; the keyboard and fixture selections stay.
254    pub fn reset(&mut self) {
255        self.pending = None;
256        self.state = State::Idle;
257        self.history.clear();
258        self.mode = None;
259    }
260
261    /// Enable the deterministic fixture policy of [`Session::propose`], which converts only
262    /// `ghbdtn` and `руддщ`, while idle.
263    ///
264    /// # Errors
265    ///
266    /// [`Error::Invalidated`] if a word is owned or a proposal awaits acknowledgement.
267    pub fn set_fixtures(&mut self, enabled: bool) -> Result<(), Error> {
268        if self.state != State::Idle || self.pending.is_some() {
269            return Err(Error::Invalidated);
270        }
271        self.fixtures = enabled;
272        Ok(())
273    }
274
275    /// Select the Russian keyboard map for manual conversion and inference while idle. The
276    /// default is [`Keyboard::Apple`], and [`Session::reset`] keeps the selection. A change
277    /// keeps the word history, which holds finished document text rather than key positions.
278    ///
279    /// # Errors
280    ///
281    /// [`Error::Invalidated`] if a word is owned or a proposal awaits acknowledgement.
282    pub fn set_keyboard(&mut self, keyboard: Keyboard) -> Result<(), Error> {
283        if self.state != State::Idle || self.pending.is_some() {
284            return Err(Error::Invalidated);
285        }
286        self.keyboard = keyboard;
287        Ok(())
288    }
289
290    /// Construct a proposal using only the opt-in fixture policy.
291    /// Confirmed state and context remain unchanged until acknowledgement.
292    ///
293    /// # Errors
294    ///
295    /// [`Error::Invalidated`] if the session was invalidated or its token counter is exhausted.
296    pub fn propose(&mut self, event: &Event, mode: Mode, context: Context) -> Result<Plan, Error> {
297        self.propose_using(event, mode, context, Automatic::Fixture(self.fixtures))
298    }
299
300    /// Construct a manual-only proposal, ignoring both the model and the fixture policy.
301    ///
302    /// # Errors
303    ///
304    /// [`Error::Invalidated`] if the session was invalidated or its token counter is exhausted.
305    pub fn propose_without_automatic(
306        &mut self,
307        event: &Event,
308        mode: Mode,
309        context: Context,
310    ) -> Result<Plan, Error> {
311        self.propose_using(event, mode, context, Automatic::Fixture(false))
312    }
313
314    /// Construct a model-backed proposal with explicit borrowed protection snapshots and policy.
315    /// Only Space evaluates inference, and not after explicit intent. Context comes from this
316    /// session's verified finished words; the pending operation retains no model, vocabulary
317    /// reference or native callback. See the [crate-level example](crate#example) for a
318    /// complete word.
319    ///
320    /// # Errors
321    ///
322    /// [`Error::Invalidated`] if the session was invalidated or its token counter is exhausted.
323    pub fn propose_with_inference(
324        &mut self,
325        event: &Event,
326        mode: Mode,
327        context: Context,
328        model: &Model<'_>,
329        dictionaries: Dictionaries<'_>,
330        policy: Policy,
331    ) -> Result<Plan, Error> {
332        self.propose_using(
333            event,
334            mode,
335            context,
336            Automatic::Model(model, dictionaries, policy),
337        )
338    }
339
340    fn propose_using(
341        &mut self,
342        event: &Event,
343        mode: Mode,
344        context: Context,
345        automatic: Automatic<'_>,
346    ) -> Result<Plan, Error> {
347        if self.state == State::Invalidated {
348            return Err(Error::Invalidated);
349        }
350        // Exhaustion is permanent: reset keeps the counter, so every later proposal fails too
351        let Some(id) = self.serial.checked_add(1) else {
352            self.state = State::Invalidated;
353            self.pending = None;
354            self.history.clear();
355            self.mode = None;
356            return Err(Error::Invalidated);
357        };
358        self.serial = id;
359        let expected = match &self.state {
360            State::Owned { text, .. } => text.clone(),
361            _ => Vec::new(),
362        };
363        let (action, disposition, text, next) = self.transition(event, mode, context, automatic);
364        // Only a word finished by the letter that starts the next one is appended: the session
365        // saw everything around it
366        let history = if next == State::Invalidated
367            || self.mode.is_some_and(|previous| previous != mode)
368            || matches!(event, Event::Finish | Event::Escape)
369        {
370            HistoryEffect::Clear
371        } else if action == Action::Finish && disposition == Disposition::Replan {
372            HistoryEffect::Append(text.clone())
373        } else if action == Action::Finish
374            || (action == Action::Pass && disposition == Disposition::Pass)
375        {
376            // An unowned host action can navigate or edit outside this history
377            HistoryEffect::Clear
378        } else {
379            HistoryEffect::Keep
380        };
381        self.pending = Some(Pending {
382            id,
383            state: next,
384            history,
385            mode,
386        });
387        Ok(Plan {
388            id,
389            action,
390            disposition,
391            expected,
392            text,
393        })
394    }
395
396    /// Confirm the latest proposal, or drop authority after refusal/unknown effect.
397    ///
398    /// [`Outcome::Verified`] advances the session to the proposed state. Any other outcome
399    /// invalidates the word, its receipt and the language history, and the session refuses
400    /// proposals until [`Session::reset`].
401    ///
402    /// # Errors
403    ///
404    /// [`Error::Stale`] if `id` is not the pending proposal; state is unchanged.
405    pub fn acknowledge(&mut self, id: u64, outcome: Outcome) -> Result<(), Error> {
406        if self.pending.as_ref().map(|p| p.id) != Some(id) {
407            return Err(Error::Stale);
408        }
409        let pending = self.pending.take().ok_or(Error::Stale)?;
410        if outcome == Outcome::Verified {
411            match pending.history {
412                HistoryEffect::Keep => (),
413                HistoryEffect::Clear => self.history.clear(),
414                HistoryEffect::Append(text) => {
415                    self.history.extend(text);
416                    // Trim at a Space so the window starts at a whole word; this can drop one
417                    // word more than the bound requires
418                    if self.history.len() > MAX_HISTORY {
419                        let minimum = self.history.len() - MAX_HISTORY;
420                        let remove = self.history[minimum..]
421                            .iter()
422                            .position(|&unit| unit == 32)
423                            .map_or(self.history.len(), |at| minimum + at + 1);
424                        self.history.drain(..remove);
425                    }
426                }
427            }
428            self.mode = Some(pending.mode);
429            self.state = pending.state;
430        } else {
431            self.state = State::Invalidated;
432            self.history.clear();
433            self.mode = None;
434        }
435        Ok(())
436    }
437
438    /// The transition table: the plan's action, disposition and text, and the proposed state.
439    /// Reads the confirmed state and changes nothing.
440    fn transition(
441        &self,
442        event: &Event,
443        mode: Mode,
444        context: Context,
445        automatic: Automatic<'_>,
446    ) -> (Action, Disposition, Vec<u16>, State) {
447        use Action::{Finish, Mark, Pass, Unavailable};
448        use Disposition::{Consumed, Replan};
449        // In English mode the keys that type Russian letters can start or continue a word
450        let letter = match event {
451            Event::Text(units)
452                if units.len() == 1
453                    && (mapping::is_letter(units[0])
454                        || (mode == Mode::En
455                            && inference::is_provisional(units[0], self.keyboard))) =>
456            {
457                Some(units[0])
458            }
459            _ => None,
460        };
461        match &self.state {
462            State::Idle => {
463                if let Some(unit) = letter.filter(|_| context == Context::Boundary) {
464                    let text = vec![unit];
465                    let next = State::Owned {
466                        text: text.clone(),
467                        original: None,
468                        boundary: false,
469                        explicit: false,
470                        mode,
471                    };
472                    return (Mark, Consumed, text, next);
473                }
474                // A reserved command is consumed even with nothing to act on
475                let reserved = matches!(event, Event::Manual | Event::Reverse);
476                (
477                    if reserved { Unavailable } else { Pass },
478                    if reserved {
479                        Consumed
480                    } else {
481                        Disposition::Pass
482                    },
483                    Vec::new(),
484                    State::Idle,
485                )
486            }
487            State::Owned {
488                text,
489                original,
490                boundary,
491                explicit,
492                mode: owned_mode,
493            } => {
494                // A word is never finished or converted under a mode it was not typed in
495                if mode != *owned_mode {
496                    return (Pass, Disposition::Pass, Vec::new(), State::Invalidated);
497                }
498                let mut text = text.clone();
499                let mut original = original.clone();
500                let mut boundary = *boundary;
501                let mut explicit = *explicit;
502                match event {
503                    Event::Manual => {
504                        // Provisional units are owned as Russian letters, so they convert too
505                        let converted: Vec<u16> = text
506                            .iter()
507                            .map(|&unit| {
508                                let mapping = if mode == Mode::En
509                                    && inference::is_provisional(unit, self.keyboard)
510                                {
511                                    Mapping::EnToRu
512                                } else {
513                                    Mapping::Manual
514                                };
515                                mapping::convert(&[unit], self.keyboard, mapping)[0]
516                            })
517                            .collect();
518                        if converted == text {
519                            return (Pass, Consumed, Vec::new(), self.state.clone());
520                        }
521                        // A second conversion keeps the first receipt, so Reverse returns to
522                        // what was typed
523                        original = Some(original.unwrap_or_else(|| text.clone()));
524                        text = converted;
525                        explicit = true;
526                    }
527                    Event::Reverse => {
528                        let Some(raw) = original.take() else {
529                            return (Unavailable, Consumed, Vec::new(), self.state.clone());
530                        };
531                        text = raw;
532                        explicit = true;
533                    }
534                    Event::Escape => {
535                        return match original {
536                            Some(raw) => (Finish, Consumed, raw, State::Idle),
537                            None => (Finish, Disposition::Pass, text, State::Idle),
538                        };
539                    }
540                    Event::Text(units) if units == &[32] && !boundary => {
541                        if !explicit {
542                            let converted = match automatic {
543                                Automatic::Fixture(true) => fixture(&text, mode),
544                                Automatic::Fixture(false) => None,
545                                Automatic::Model(model, dictionaries, policy) => {
546                                    inference::infer(
547                                        model,
548                                        dictionaries,
549                                        policy,
550                                        Request {
551                                            word: &text,
552                                            active: Some(mode),
553                                            context: if self.mode == Some(mode) {
554                                                inference::detect_context(model, &self.history)
555                                            } else {
556                                                None
557                                            },
558                                            keyboard: self.keyboard,
559                                            explicit_intent: explicit,
560                                        },
561                                    )
562                                    .replacement
563                                }
564                            };
565                            if let Some(converted) = converted {
566                                original = Some(text.clone());
567                                text = converted;
568                            }
569                        }
570                        // The Space joins the mark, and the receipt, so that Reverse replaces
571                        // the word and its Space as one owned range
572                        text.push(32);
573                        if let Some(raw) = &mut original {
574                            raw.push(32);
575                        }
576                        boundary = true;
577                    }
578                    Event::Backspace if !boundary => {
579                        text.pop();
580                        // An edit expires the conversion receipt
581                        original = None;
582                        // An empty mark is its own native operation and ends the word
583                        if text.is_empty() {
584                            return (Mark, Consumed, text, State::Idle);
585                        }
586                    }
587                    Event::Text(_) if letter.is_some() && !boundary && text.len() < MAX_WORD => {
588                        text.push(letter.expect("classified letter"));
589                        original = None;
590                    }
591                    // After the boundary a letter starts the next word, so it is planned again
592                    // from Idle; any other event, or a letter past MAX_WORD, goes to the host
593                    _ => {
594                        let disposition = if boundary && letter.is_some() {
595                            Replan
596                        } else {
597                            Disposition::Pass
598                        };
599                        return (Finish, disposition, text, State::Idle);
600                    }
601                }
602                let next = State::Owned {
603                    text: text.clone(),
604                    original,
605                    boundary,
606                    explicit,
607                    mode,
608                };
609                (Mark, Consumed, text, next)
610            }
611            State::Invalidated => unreachable!("checked by propose"),
612        }
613    }
614}
615
616/// The fixture policy: converts exactly `ghbdtn` and `руддщ`, and nothing else.
617fn fixture(text: &[u16], mode: Mode) -> Option<Vec<u16>> {
618    let (source, target) = match mode {
619        Mode::En => ("ghbdtn", "привет"),
620        Mode::Ru => ("руддщ", "hello"),
621    };
622    (text.iter().copied().eq(source.encode_utf16())).then(|| target.encode_utf16().collect())
623}
624
625#[cfg(test)]
626mod tests {
627    use super::*;
628
629    fn apply(s: &mut Session, e: Event) -> Plan {
630        let p = s.propose(&e, Mode::En, Context::Boundary).unwrap();
631        s.acknowledge(p.id, Outcome::Verified).unwrap();
632        p
633    }
634    fn type_word(s: &mut Session, word: &str) {
635        for u in word.encode_utf16() {
636            apply(s, Event::Text(vec![u]));
637        }
638    }
639
640    fn model_apply(
641        session: &mut Session,
642        model: &Model<'_>,
643        dictionaries: Dictionaries<'_>,
644        mode: Mode,
645        event: Event,
646    ) -> Plan {
647        let mut plan = session
648            .propose_with_inference(
649                &event,
650                mode,
651                Context::Boundary,
652                model,
653                dictionaries,
654                Policy::default(),
655            )
656            .unwrap();
657        session.acknowledge(plan.id, Outcome::Verified).unwrap();
658        if plan.disposition == Disposition::Replan {
659            plan = session
660                .propose_with_inference(
661                    &event,
662                    mode,
663                    Context::Boundary,
664                    model,
665                    dictionaries,
666                    Policy::default(),
667                )
668                .unwrap();
669            assert_ne!(plan.disposition, Disposition::Replan);
670            session.acknowledge(plan.id, Outcome::Verified).unwrap();
671        }
672        plan
673    }
674
675    fn type_model(
676        session: &mut Session,
677        model: &Model<'_>,
678        dictionaries: Dictionaries<'_>,
679        mode: Mode,
680        text: &str,
681    ) -> Plan {
682        text.encode_utf16()
683            .map(|unit| model_apply(session, model, dictionaries, mode, Event::Text(vec![unit])))
684            .last()
685            .unwrap()
686    }
687
688    #[test]
689    fn actual_model_space_and_owned_reversal_in_both_directions() {
690        let model = Model::embedded().unwrap();
691        let empty = crate::vocabulary::Vocabulary::parse(b"").unwrap();
692        let dictionaries = Dictionaries {
693            en: Some(&empty),
694            ru: Some(&empty),
695            learned: &[],
696        };
697        for (mode, raw, corrected) in [
698            (Mode::En, "cgbcjr", "список "),
699            (Mode::Ru, "цщкдв", "world "),
700        ] {
701            let mut session = Session::default();
702            // The fixture policy cannot convert these words, so a conversion proves the model ran
703            session.set_fixtures(true).unwrap();
704            type_model(&mut session, &model, dictionaries, mode, raw);
705            // Context is consulted only to start a word; an owned word converts whatever it says
706            let boundary = session
707                .propose_with_inference(
708                    &Event::Text(vec![32]),
709                    mode,
710                    Context::Ineligible,
711                    &model,
712                    dictionaries,
713                    Policy::default(),
714                )
715                .unwrap();
716            assert_eq!(boundary.expected, raw.encode_utf16().collect::<Vec<_>>());
717            assert_eq!(boundary.text, corrected.encode_utf16().collect::<Vec<_>>());
718            assert!(matches!(
719                &session.state,
720                State::Owned {
721                    boundary: false,
722                    ..
723                }
724            ));
725            assert!(session.history.is_empty());
726            session.acknowledge(boundary.id, Outcome::Verified).unwrap();
727            let reversed = model_apply(&mut session, &model, dictionaries, mode, Event::Reverse);
728            assert_eq!(
729                reversed.text,
730                format!("{raw} ").encode_utf16().collect::<Vec<_>>()
731            );
732            model_apply(&mut session, &model, dictionaries, mode, Event::Backspace);
733            assert_eq!(session.state, State::Idle);
734            assert!(session.history.is_empty());
735        }
736    }
737
738    #[test]
739    fn model_boundary_uses_ready_last_good_snapshots_without_retaining_borrows() {
740        use crate::vocabulary::Snapshot;
741
742        let model = Model::embedded().unwrap();
743        let mut en = Snapshot::default();
744        let mut ru = Snapshot::default();
745        ru.replace(b"").unwrap();
746        let ru = ru.current().unwrap();
747        let mut session = Session::default();
748        // A missing source stops automatic correction but not manual conversion
749        let missing = Dictionaries {
750            en: None,
751            ru: Some(&ru),
752            learned: &[],
753        };
754        assert_eq!(
755            type_model(&mut session, &model, missing, Mode::En, "cgbcjr ").text,
756            "cgbcjr ".encode_utf16().collect::<Vec<_>>()
757        );
758        assert_eq!(
759            model_apply(&mut session, &model, missing, Mode::En, Event::Manual).text,
760            "список ".encode_utf16().collect::<Vec<_>>()
761        );
762        session.reset();
763        // A rejected candidate cannot change the snapshot a reader already holds
764        en.replace(b"cgbcjr").unwrap();
765        let protected = en.current().unwrap();
766        assert!(en.replace(b"invalid\0").is_err());
767        let dictionaries = Dictionaries {
768            en: Some(&protected),
769            ru: Some(&ru),
770            learned: &[],
771        };
772        assert_eq!(
773            type_model(&mut session, &model, dictionaries, Mode::En, "cgbcjr ").text,
774            "cgbcjr ".encode_utf16().collect::<Vec<_>>()
775        );
776        session.reset();
777        en.replace(b"").unwrap();
778        let ready = en.current().unwrap();
779        let dictionaries = Dictionaries {
780            en: Some(&ready),
781            ru: Some(&ru),
782            learned: &[],
783        };
784        // Of two proposals for one Space only the latest, made with the protecting snapshot,
785        // can be acknowledged, so a decision from the earlier snapshot never lands
786        type_model(&mut session, &model, dictionaries, Mode::En, "cgbcjr");
787        let superseded = session
788            .propose_with_inference(
789                &Event::Text(vec![32]),
790                Mode::En,
791                Context::Boundary,
792                &model,
793                dictionaries,
794                Policy::default(),
795            )
796            .unwrap();
797        let latest = session
798            .propose_with_inference(
799                &Event::Text(vec![32]),
800                Mode::En,
801                Context::Boundary,
802                &model,
803                Dictionaries {
804                    en: Some(&protected),
805                    ru: Some(&ru),
806                    learned: &[],
807                },
808                Policy::default(),
809            )
810            .unwrap();
811        assert_eq!(
812            session.acknowledge(superseded.id, Outcome::Verified),
813            Err(Error::Stale)
814        );
815        assert_eq!(latest.text, "cgbcjr ".encode_utf16().collect::<Vec<_>>());
816        session.acknowledge(latest.id, Outcome::Verified).unwrap();
817    }
818
819    #[test]
820    fn colloquial_corrections_wait_for_space_and_keep_owned_reversal() {
821        let model = Model::embedded().unwrap();
822        let empty = crate::vocabulary::Vocabulary::parse(b"").unwrap();
823        let dictionaries = Dictionaries {
824            en: Some(&empty),
825            ru: Some(&empty),
826            learned: &[],
827        };
828        for (raw, target) in [("[eq", "хуй"), (",kz", "бля"), ("pft,bcm", "заебись")] {
829            let units = |text: &str| text.encode_utf16().collect::<Vec<_>>();
830            let mut session = Session::default();
831            type_model(&mut session, &model, dictionaries, Mode::En, raw);
832            assert_eq!(
833                model_apply(&mut session, &model, dictionaries, Mode::En, Event::Finish).text,
834                units(raw)
835            );
836            session.reset();
837            let corrected = type_model(
838                &mut session,
839                &model,
840                dictionaries,
841                Mode::En,
842                &format!("{raw} "),
843            );
844            assert_eq!(corrected.expected, units(raw));
845            assert_eq!(corrected.text, units(&format!("{target} ")));
846            assert_eq!(
847                model_apply(&mut session, &model, dictionaries, Mode::En, Event::Reverse).text,
848                units(&format!("{raw} "))
849            );
850        }
851    }
852
853    #[test]
854    fn explicit_reverse_and_typo_edit_have_distinct_model_boundary_behavior() {
855        let model = Model::embedded().unwrap();
856        let empty = crate::vocabulary::Vocabulary::parse(b"").unwrap();
857        let dictionaries = Dictionaries {
858            en: Some(&empty),
859            ru: Some(&empty),
860            learned: &[],
861        };
862        // Manual then Reverse is explicit intent and Space keeps the typed word; a Backspace and
863        // a retyped letter are not, so that word still converts
864        let mut session = Session::default();
865        type_model(&mut session, &model, dictionaries, Mode::En, "cgbcjr");
866        model_apply(&mut session, &model, dictionaries, Mode::En, Event::Manual);
867        model_apply(&mut session, &model, dictionaries, Mode::En, Event::Reverse);
868        assert_eq!(
869            model_apply(
870                &mut session,
871                &model,
872                dictionaries,
873                Mode::En,
874                Event::Text(vec![32])
875            )
876            .text,
877            "cgbcjr ".encode_utf16().collect::<Vec<_>>()
878        );
879        session.reset();
880        type_model(&mut session, &model, dictionaries, Mode::En, "cgbcjj");
881        model_apply(
882            &mut session,
883            &model,
884            dictionaries,
885            Mode::En,
886            Event::Backspace,
887        );
888        assert_eq!(
889            type_model(&mut session, &model, dictionaries, Mode::En, "r ").text,
890            "список ".encode_utf16().collect::<Vec<_>>()
891        );
892    }
893
894    #[test]
895    fn verified_finished_context_changes_the_real_space_decision() {
896        let model = Model::embedded().unwrap();
897        let empty = crate::vocabulary::Vocabulary::parse(b"").unwrap();
898        let dictionaries = Dictionaries {
899            en: Some(&empty),
900            ru: Some(&empty),
901            learned: &[],
902        };
903        let mut neutral = Session::default();
904        assert_eq!(
905            type_model(&mut neutral, &model, dictionaries, Mode::En, "yfv ").text,
906            "нам ".encode_utf16().collect::<Vec<_>>()
907        );
908        let mut source = Session::default();
909        assert_eq!(
910            type_model(
911                &mut source,
912                &model,
913                dictionaries,
914                Mode::En,
915                "hello world yfv "
916            )
917            .text,
918            "yfv ".encode_utf16().collect::<Vec<_>>()
919        );
920        assert_eq!(
921            source.history,
922            "hello world ".encode_utf16().collect::<Vec<_>>()
923        );
924        let mut target = Session::default();
925        assert_eq!(
926            type_model(
927                &mut target,
928                &model,
929                dictionaries,
930                Mode::En,
931                "ghbdtn cgbcjr dfv "
932            )
933            .text,
934            "вам ".encode_utf16().collect::<Vec<_>>()
935        );
936        assert_eq!(
937            target.history,
938            "привет список ".encode_utf16().collect::<Vec<_>>()
939        );
940        let mut neutral = Session::default();
941        assert_eq!(
942            type_model(&mut neutral, &model, dictionaries, Mode::En, "dfv ").text,
943            "dfv ".encode_utf16().collect::<Vec<_>>()
944        );
945        // History holds the reversed word as typed; no lexicon has `ghbdtn`, so there is no
946        // context and `dfv` stays
947        let mut reversed = Session::default();
948        type_model(&mut reversed, &model, dictionaries, Mode::En, "ghbdtn ");
949        model_apply(
950            &mut reversed,
951            &model,
952            dictionaries,
953            Mode::En,
954            Event::Reverse,
955        );
956        assert_eq!(
957            type_model(&mut reversed, &model, dictionaries, Mode::En, "cgbcjr dfv ").text,
958            "dfv ".encode_utf16().collect::<Vec<_>>()
959        );
960        assert_eq!(
961            reversed.history,
962            "ghbdtn список ".encode_utf16().collect::<Vec<_>>()
963        );
964    }
965
966    #[test]
967    fn history_is_acknowledged_bounded_and_expires_with_authority() {
968        let model = Model::embedded().unwrap();
969        let empty = crate::vocabulary::Vocabulary::parse(b"").unwrap();
970        let dictionaries = Dictionaries {
971            en: Some(&empty),
972            ru: Some(&empty),
973            learned: &[],
974        };
975        // A proposal or a stale acknowledgement never changes history, trimming keeps whole
976        // words, and Refused, Unknown, Finish, a mode change in Idle or while owned, reset and
977        // token exhaustion all clear it
978        let mut session = Session::default();
979        type_model(&mut session, &model, dictionaries, Mode::En, "hello ");
980        let event = Event::Text(vec![119]);
981        let propose = |session: &mut Session| {
982            session
983                .propose_with_inference(
984                    &event,
985                    Mode::En,
986                    Context::Boundary,
987                    &model,
988                    dictionaries,
989                    Policy::default(),
990                )
991                .unwrap()
992        };
993        let stale = propose(&mut session);
994        let latest = propose(&mut session);
995        assert_eq!(
996            (latest.action, latest.disposition),
997            (Action::Finish, Disposition::Replan)
998        );
999        assert!(session.history.is_empty());
1000        assert_eq!(
1001            session.acknowledge(stale.id, Outcome::Verified),
1002            Err(Error::Stale)
1003        );
1004        assert!(session.history.is_empty());
1005        session.acknowledge(latest.id, Outcome::Verified).unwrap();
1006        assert_eq!(session.history, "hello ".encode_utf16().collect::<Vec<_>>());
1007        let next = propose(&mut session);
1008        assert_eq!(
1009            session.acknowledge(stale.id, Outcome::Verified),
1010            Err(Error::Stale)
1011        );
1012        assert_eq!(session.history, "hello ".encode_utf16().collect::<Vec<_>>());
1013        session.acknowledge(next.id, Outcome::Verified).unwrap();
1014        type_model(&mut session, &model, dictionaries, Mode::En, "orld ");
1015        for _ in 0..60 {
1016            type_model(&mut session, &model, dictionaries, Mode::En, "hello world ");
1017            assert!(session.history.len() <= 256);
1018            for word in session
1019                .history
1020                .split(|&unit| unit == 32)
1021                .filter(|word| !word.is_empty())
1022            {
1023                assert!(word == [104, 101, 108, 108, 111] || word == [119, 111, 114, 108, 100]);
1024            }
1025        }
1026        for outcome in [Outcome::Refused, Outcome::Unknown] {
1027            let plan = propose(&mut session);
1028            session.acknowledge(plan.id, outcome).unwrap();
1029            assert!(session.history.is_empty());
1030            session.reset();
1031            type_model(&mut session, &model, dictionaries, Mode::En, "hello world ");
1032        }
1033        model_apply(&mut session, &model, dictionaries, Mode::En, Event::Finish);
1034        assert!(session.history.is_empty());
1035        type_model(&mut session, &model, dictionaries, Mode::En, "hello world ");
1036        let finish = propose(&mut session);
1037        session.acknowledge(finish.id, Outcome::Verified).unwrap();
1038        assert_eq!(session.state, State::Idle);
1039        assert!(!session.history.is_empty());
1040        model_apply(
1041            &mut session,
1042            &model,
1043            dictionaries,
1044            Mode::Ru,
1045            Event::Text(vec![0x430]),
1046        );
1047        assert!(session.history.is_empty());
1048        assert!(matches!(session.state, State::Owned { mode: Mode::Ru, .. }));
1049        session.reset();
1050        type_model(&mut session, &model, dictionaries, Mode::En, "hello world ");
1051        model_apply(
1052            &mut session,
1053            &model,
1054            dictionaries,
1055            Mode::Ru,
1056            Event::Text(vec![0x430]),
1057        );
1058        assert!(session.history.is_empty());
1059        assert_eq!(session.state, State::Invalidated);
1060        session.reset();
1061        type_model(&mut session, &model, dictionaries, Mode::En, "hello world ");
1062        let pending = propose(&mut session);
1063        session.reset();
1064        assert!(session.history.is_empty());
1065        assert_eq!(session.mode, None);
1066        assert_eq!(
1067            session.acknowledge(pending.id, Outcome::Verified),
1068            Err(Error::Stale)
1069        );
1070        type_model(&mut session, &model, dictionaries, Mode::En, "hello world ");
1071        session.serial = u64::MAX;
1072        assert_eq!(
1073            session.propose(&Event::Finish, Mode::En, Context::Boundary),
1074            Err(Error::Invalidated)
1075        );
1076        assert!(session.history.is_empty());
1077    }
1078
1079    #[test]
1080    fn english_mode_keys_for_russian_letters_join_the_word_and_otherwise_stay_typed() {
1081        let model = Model::embedded().unwrap();
1082        let empty = crate::vocabulary::Vocabulary::parse(b"").unwrap();
1083        let dictionaries = Dictionaries {
1084            en: Some(&empty),
1085            ru: Some(&empty),
1086            learned: &[],
1087        };
1088        for (typed, marked) in [
1089            ("[jhjij ", "хорошо "),
1090            (";bpym ", "жизнь "),
1091            ("\"nj ", "Это "),
1092            ("\\krf ", "ёлка "),
1093            ("hello, ", "hello, "),
1094            ("it. ", "it. "),
1095            ("... ", "... "),
1096            ("; ", "; "),
1097            ("'quoted' ", "'quoted' "),
1098            // On Apple the backtick is not the ё key: it goes to the host and the word starts at k
1099            ("`krf ", "krf "),
1100        ] {
1101            let mut session = Session::default();
1102            let plan = type_model(&mut session, &model, dictionaries, Mode::En, typed);
1103            assert_eq!(plan.action, Action::Mark, "{typed}");
1104            assert_eq!(String::from_utf16(&plan.text).unwrap(), marked, "{typed}");
1105        }
1106
1107        // The backtick is the ё key only on the PC layout
1108        let mut session = Session::default();
1109        session.set_keyboard(Keyboard::Pc).unwrap();
1110        let plan = type_model(&mut session, &model, dictionaries, Mode::En, "`krf ");
1111        assert_eq!(String::from_utf16(&plan.text).unwrap(), "ёлка ");
1112
1113        // Russian mode passes these keys to the host and starts no word
1114        let mut session = Session::default();
1115        let plan = model_apply(
1116            &mut session,
1117            &model,
1118            dictionaries,
1119            Mode::Ru,
1120            Event::Text(vec![u16::from(b'[')]),
1121        );
1122        assert_eq!(
1123            (plan.action, plan.disposition),
1124            (Action::Pass, Disposition::Pass)
1125        );
1126        assert!(!session.has_word());
1127    }
1128
1129    #[test]
1130    fn proposal_is_not_installed_and_latest_token_wins() {
1131        let mut s = Session::default();
1132        let a = s
1133            .propose(&Event::Text(vec![97]), Mode::En, Context::Boundary)
1134            .unwrap();
1135        let b = s
1136            .propose(&Event::Text(vec![98]), Mode::En, Context::Boundary)
1137            .unwrap();
1138        assert!(b.expected.is_empty());
1139        assert_eq!(s.acknowledge(a.id, Outcome::Verified), Err(Error::Stale));
1140        s.acknowledge(b.id, Outcome::Verified).unwrap();
1141        assert_eq!(apply(&mut s, Event::Text(vec![99])).expected, [98]);
1142    }
1143
1144    #[test]
1145    fn manual_space_reversal_and_expiry() {
1146        let mut s = Session::default();
1147        s.set_fixtures(true).unwrap();
1148        type_word(&mut s, "ghbdtn");
1149        assert_eq!(
1150            apply(&mut s, Event::Manual).text,
1151            "привет".encode_utf16().collect::<Vec<_>>()
1152        );
1153        assert_eq!(
1154            apply(&mut s, Event::Text(vec![32])).text,
1155            "привет ".encode_utf16().collect::<Vec<_>>()
1156        );
1157        assert_eq!(
1158            apply(&mut s, Event::Reverse).text,
1159            "ghbdtn ".encode_utf16().collect::<Vec<_>>()
1160        );
1161        let finish = apply(&mut s, Event::Text(vec![120]));
1162        assert_eq!(
1163            (finish.action, finish.disposition),
1164            (Action::Finish, Disposition::Replan)
1165        );
1166        assert_eq!(apply(&mut s, Event::Reverse).action, Action::Unavailable);
1167    }
1168
1169    #[test]
1170    fn fixture_opt_in_and_both_directions() {
1171        for mode in [Mode::En, Mode::Ru] {
1172            for enabled in [false, true] {
1173                let mut s = Session::default();
1174                s.set_fixtures(enabled).unwrap();
1175                let (raw, corrected) = if mode == Mode::En {
1176                    ("ghbdtn", "привет ")
1177                } else {
1178                    ("руддщ", "hello ")
1179                };
1180                for u in raw.encode_utf16().chain([32]) {
1181                    let p = s
1182                        .propose(&Event::Text(vec![u]), mode, Context::Boundary)
1183                        .unwrap();
1184                    if u == 32 {
1185                        let expected = if enabled {
1186                            corrected.to_owned()
1187                        } else {
1188                            format!("{raw} ")
1189                        };
1190                        assert_eq!(p.text, expected.encode_utf16().collect::<Vec<_>>());
1191                    }
1192                    s.acknowledge(p.id, Outcome::Verified).unwrap();
1193                }
1194            }
1195        }
1196    }
1197
1198    #[test]
1199    fn unknown_refused_and_reset_expire_pending_and_receipt() {
1200        for outcome in [Outcome::Unknown, Outcome::Refused] {
1201            let mut s = Session::default();
1202            type_word(&mut s, "x");
1203            let p = s
1204                .propose(&Event::Manual, Mode::En, Context::Boundary)
1205                .unwrap();
1206            s.acknowledge(p.id, outcome).unwrap();
1207            assert_eq!(
1208                s.propose(&Event::Reverse, Mode::En, Context::Boundary),
1209                Err(Error::Invalidated)
1210            );
1211            s.reset();
1212            assert_eq!(s.acknowledge(p.id, Outcome::Verified), Err(Error::Stale));
1213            assert_eq!(apply(&mut s, Event::Reverse).action, Action::Unavailable);
1214        }
1215    }
1216
1217    #[test]
1218    fn bounds_and_technical_prefix_never_start_suffix() {
1219        let mut s = Session::default();
1220        assert_eq!(
1221            s.propose(&Event::Text(vec![97]), Mode::En, Context::Ineligible)
1222                .unwrap()
1223                .action,
1224            Action::Pass
1225        );
1226        s.reset();
1227        type_word(&mut s, &"a".repeat(MAX_WORD));
1228        let p = apply(&mut s, Event::Text(vec![98]));
1229        assert_eq!(
1230            (p.action, p.disposition, p.text.len()),
1231            (Action::Finish, Disposition::Pass, MAX_WORD)
1232        );
1233        assert_eq!(
1234            s.propose(&Event::Text(vec![99]), Mode::En, Context::Ineligible)
1235                .unwrap()
1236                .action,
1237            Action::Pass
1238        );
1239    }
1240
1241    #[test]
1242    fn empty_deletion_and_escape_use_owned_text() {
1243        let units = |s: &str| s.encode_utf16().collect::<Vec<_>>();
1244        let mut s = Session::default();
1245        s.set_fixtures(true).unwrap();
1246        type_word(&mut s, "x");
1247        let p = apply(&mut s, Event::Backspace);
1248        assert_eq!(p.action, Action::Mark);
1249        assert!(p.text.is_empty());
1250        let idle = apply(&mut s, Event::Escape);
1251        assert_eq!(
1252            (idle.action, idle.disposition),
1253            (Action::Pass, Disposition::Pass)
1254        );
1255
1256        // A receipt is restored and Escape is consumed
1257        for (typed, command, restored) in [
1258            ("ghbdtn", Some(Event::Manual), "ghbdtn"),
1259            ("ghbdtn ", None, "ghbdtn "),
1260        ] {
1261            type_word(&mut s, typed);
1262            if let Some(command) = command {
1263                apply(&mut s, command);
1264            }
1265            let p = apply(&mut s, Event::Escape);
1266            assert_eq!(
1267                (p.action, p.disposition, p.expected.len()),
1268                (Action::Finish, Disposition::Consumed, typed.len())
1269            );
1270            assert_eq!(p.text, units(restored));
1271            assert_eq!(s.state, State::Idle);
1272        }
1273
1274        // Without a receipt the word finishes as typed and the host gets Escape
1275        for (typed, edit) in [("test", false), ("test ", false), ("ghbdtnn", true)] {
1276            type_word(&mut s, typed);
1277            if edit {
1278                apply(&mut s, Event::Manual);
1279                // An edit expires the receipt, so Escape cannot restore the typed word
1280                apply(&mut s, Event::Backspace);
1281            }
1282            let expected = match &s.state {
1283                State::Owned { text, .. } => text.clone(),
1284                _ => unreachable!("word is owned"),
1285            };
1286            let p = apply(&mut s, Event::Escape);
1287            assert_eq!(
1288                (p.action, p.disposition),
1289                (Action::Finish, Disposition::Pass)
1290            );
1291            assert_eq!(p.text, expected);
1292            assert_eq!(s.state, State::Idle);
1293            assert!(s.history.is_empty());
1294        }
1295        assert_eq!(apply(&mut s, Event::Reverse).action, Action::Unavailable);
1296    }
1297
1298    #[test]
1299    fn keyboard_selects_the_yo_key_for_manual_conversion_while_idle() {
1300        let units = |s: &str| s.encode_utf16().collect::<Vec<_>>();
1301        let propose = |s: &mut Session, event: Event| {
1302            let plan = s.propose(&event, Mode::Ru, Context::Boundary).unwrap();
1303            s.acknowledge(plan.id, Outcome::Verified).unwrap();
1304            plan
1305        };
1306        let mut s = Session::default();
1307        for (keyboard, converted) in [
1308            (None, "\\krf"),
1309            (Some(Keyboard::Pc), "`krf"),
1310            (Some(Keyboard::Apple), "\\krf"),
1311        ] {
1312            if let Some(keyboard) = keyboard {
1313                s.set_keyboard(keyboard).unwrap();
1314            }
1315            for unit in "ёлка".encode_utf16() {
1316                propose(&mut s, Event::Text(vec![unit]));
1317            }
1318            assert_eq!(s.set_keyboard(Keyboard::Pc), Err(Error::Invalidated));
1319            assert_eq!(propose(&mut s, Event::Manual).text, units(converted));
1320            assert_eq!(propose(&mut s, Event::Reverse).text, units("ёлка"));
1321            let pending = s
1322                .propose(&Event::Finish, Mode::Ru, Context::Boundary)
1323                .unwrap();
1324            assert_eq!(s.set_keyboard(Keyboard::Pc), Err(Error::Invalidated));
1325            s.acknowledge(pending.id, Outcome::Verified).unwrap();
1326        }
1327
1328        // Reset keeps the selection; a change keeps verified history
1329        s.set_keyboard(Keyboard::Pc).unwrap();
1330        s.reset();
1331        type_word(&mut s, "hello ");
1332        let finish = s
1333            .propose(&Event::Text(vec![119]), Mode::En, Context::Boundary)
1334            .unwrap();
1335        assert_eq!(
1336            (finish.action, finish.disposition),
1337            (Action::Finish, Disposition::Replan)
1338        );
1339        s.acknowledge(finish.id, Outcome::Verified).unwrap();
1340        assert_eq!(s.state, State::Idle);
1341        s.set_keyboard(Keyboard::Apple).unwrap();
1342        s.set_keyboard(Keyboard::Pc).unwrap();
1343        assert_eq!(s.history, units("hello "));
1344        for unit in "ё".encode_utf16() {
1345            propose(&mut s, Event::Text(vec![unit]));
1346        }
1347        assert_eq!(propose(&mut s, Event::Manual).text, units("`"));
1348    }
1349
1350    #[test]
1351    fn mode_change_and_token_exhaustion_cannot_restore_authority() {
1352        // A command in another mode invalidates instead of converting under the wrong map
1353        let mut s = Session::default();
1354        type_word(&mut s, "x");
1355        assert_eq!(s.set_fixtures(true), Err(Error::Invalidated));
1356        let p = s
1357            .propose(&Event::Manual, Mode::Ru, Context::Boundary)
1358            .unwrap();
1359        assert_eq!((p.action, p.disposition), (Action::Pass, Disposition::Pass));
1360        s.acknowledge(p.id, Outcome::Verified).unwrap();
1361        assert_eq!(
1362            s.propose(&Event::Reverse, Mode::En, Context::Boundary),
1363            Err(Error::Invalidated)
1364        );
1365        s.reset();
1366        let old = s
1367            .propose(&Event::Text(vec![97]), Mode::En, Context::Boundary)
1368            .unwrap();
1369        s.serial = u64::MAX;
1370        assert_eq!(
1371            s.propose(&Event::Manual, Mode::En, Context::Boundary),
1372            Err(Error::Invalidated)
1373        );
1374        assert_eq!(s.acknowledge(old.id, Outcome::Verified), Err(Error::Stale));
1375    }
1376
1377    #[test]
1378    fn corrected_typo_remains_eligible_and_manual_noop_preserves_first_receipt() {
1379        let mut s = Session::default();
1380        s.set_fixtures(true).unwrap();
1381        type_word(&mut s, "ghbdtx");
1382        apply(&mut s, Event::Backspace);
1383        type_word(&mut s, "n");
1384        assert_eq!(
1385            apply(&mut s, Event::Text(vec![32])).text,
1386            "привет ".encode_utf16().collect::<Vec<_>>()
1387        );
1388        s.reset();
1389        // In Russian mode `[` is not part of the word, so a second conversion is a no-op
1390        let ru = |s: &mut Session, event: Event| {
1391            let plan = s.propose(&event, Mode::Ru, Context::Boundary).unwrap();
1392            s.acknowledge(plan.id, Outcome::Verified).unwrap();
1393            plan
1394        };
1395        ru(&mut s, Event::Text("х".encode_utf16().collect()));
1396        assert_eq!(ru(&mut s, Event::Manual).text, [u16::from(b'[')]);
1397        let noop = ru(&mut s, Event::Manual);
1398        assert_eq!(
1399            (noop.action, noop.disposition),
1400            (Action::Pass, Disposition::Consumed)
1401        );
1402        assert_eq!(
1403            ru(&mut s, Event::Reverse).text,
1404            "х".encode_utf16().collect::<Vec<_>>()
1405        );
1406    }
1407
1408    #[test]
1409    fn english_mode_manual_conversion_maps_provisional_letters_and_reverses_exactly() {
1410        let units = |s: &str| s.encode_utf16().collect::<Vec<_>>();
1411        for (keyboard, typed, converted) in [
1412            (Keyboard::Apple, "[jhjij", "хорошо"),
1413            (Keyboard::Apple, ";bpym", "жизнь"),
1414            (Keyboard::Apple, "\"nj", "Это"),
1415            (Keyboard::Apple, "{jhjij", "Хорошо"),
1416            (Keyboard::Apple, "\\krf", "ёлка"),
1417            (Keyboard::Pc, "`krf", "ёлка"),
1418            (Keyboard::Pc, "~krf", "Ёлка"),
1419            (Keyboard::Apple, "ghbdtn,", "приветб"),
1420            (Keyboard::Apple, "[jhjij ", "хорошо "),
1421        ] {
1422            let mut s = Session::default();
1423            s.set_keyboard(keyboard).unwrap();
1424            type_word(&mut s, typed);
1425            let manual = apply(&mut s, Event::Manual);
1426            assert_eq!(
1427                (manual.action, manual.expected.clone(), manual.text.clone()),
1428                (Action::Mark, units(typed), units(converted)),
1429                "{typed}"
1430            );
1431            // Converting again maps the Russian letters back to their keys
1432            assert_eq!(apply(&mut s, Event::Manual).text, units(typed), "{typed}");
1433            apply(&mut s, Event::Manual);
1434            assert_eq!(apply(&mut s, Event::Reverse).text, units(typed), "{typed}");
1435            let finish = apply(&mut s, Event::Finish);
1436            assert_eq!((finish.action, finish.text), (Action::Finish, units(typed)));
1437        }
1438
1439        // Russian mode keeps letter-only manual conversion
1440        let mut s = Session::default();
1441        for unit in "хорошо".encode_utf16() {
1442            let plan = s
1443                .propose(&Event::Text(vec![unit]), Mode::Ru, Context::Boundary)
1444                .unwrap();
1445            s.acknowledge(plan.id, Outcome::Verified).unwrap();
1446        }
1447        let manual = s
1448            .propose(&Event::Manual, Mode::Ru, Context::Boundary)
1449            .unwrap();
1450        assert_eq!(manual.text, units("[jhjij"));
1451    }
1452}