1use crate::inference::{self, Dictionaries, Policy, Request};
61use crate::mapping::{self, Keyboard, Mapping};
62use crate::model::Model;
63
64pub const MAX_WORD: usize = 64;
66const MAX_HISTORY: usize = 256;
67
68#[derive(Clone, Copy, Debug, PartialEq, Eq)]
70pub enum Mode {
71 En,
73 Ru,
75}
76
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81pub enum Context {
82 Boundary,
84 Ineligible,
86}
87
88#[derive(Clone, Debug, PartialEq, Eq)]
90pub enum Event {
91 Text(Vec<u16>),
95 Backspace,
97 Escape,
99 Manual,
101 Reverse,
103 Finish,
105}
106
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
109pub enum Action {
110 Pass,
112 Mark,
115 Finish,
117 Unavailable,
119}
120
121#[derive(Clone, Copy, Debug, PartialEq, Eq)]
123pub enum Disposition {
124 Pass,
126 Consumed,
128 Replan,
130}
131
132#[derive(Clone, Copy, Debug, PartialEq, Eq)]
134pub enum Outcome {
135 Verified,
137 Refused,
139 Unknown,
141}
142
143#[derive(Clone, Copy, Debug, PartialEq, Eq)]
145pub enum Error {
146 Stale,
149 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 Owned {
170 text: Vec<u16>,
172 original: Option<Vec<u16>>,
175 boundary: bool,
176 explicit: bool,
178 mode: Mode,
180 },
181 Invalidated,
182}
183
184enum Automatic<'a> {
186 Fixture(bool),
187 Model(&'a Model<'a>, Dictionaries<'a>, Policy),
188}
189
190enum HistoryEffect {
192 Keep,
193 Clear,
194 Append(Vec<u16>),
195}
196
197struct Pending {
199 id: u64,
200 state: State,
201 history: HistoryEffect,
202 mode: Mode,
203}
204
205#[derive(Clone, Debug, PartialEq, Eq)]
208pub struct Plan {
209 pub id: u64,
211 pub action: Action,
213 pub disposition: Disposition,
215 pub expected: Vec<u16>,
217 pub text: Vec<u16>,
220}
221
222#[derive(Default)]
226pub struct Session {
227 state: State,
229 pending: Option<Pending>,
230 serial: u64,
232 fixtures: bool,
233 history: Vec<u16>,
235 mode: Option<Mode>,
237 keyboard: Keyboard,
238}
239
240impl Session {
241 pub fn has_pending(&self) -> bool {
243 self.pending.is_some()
244 }
245
246 pub fn has_word(&self) -> bool {
249 matches!(self.state, State::Owned { .. })
250 }
251
252 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 original = None;
582 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 _ => {
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
616fn 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 session.set_fixtures(true).unwrap();
704 type_model(&mut session, &model, dictionaries, mode, raw);
705 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 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 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 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 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 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 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 ("`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 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 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 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 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 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 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 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 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 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 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}