1#![deny(unsafe_op_in_unsafe_fn)]
37
38pub mod vocabulary_source;
39
40pub mod vocabulary_host;
41
42mod compatibility;
43mod dictionary;
44
45pub use dictionary::{
46 Dictionary, kr_adopt_dictionaries, kr_dictionary_free, kr_dictionary_parse_utf8,
47 kr_prepare_model,
48};
49
50#[cfg(all(test, unix))]
52fn descriptor_flags(file: &std::fs::File) -> i32 {
53 use std::os::fd::AsRawFd;
54 unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GETFL) }
56}
57
58use keyrill_core::inference::{Dictionaries, Policy};
59use keyrill_core::mapping::Keyboard;
60use keyrill_core::model::{Model, ModelError};
61use keyrill_core::session::{Action, Context, Disposition, Event, Mode, Outcome, Session};
62use keyrill_core::vocabulary::{MAX_SOURCE_BYTES, Snapshot, Vocabulary};
63use std::panic::{AssertUnwindSafe, catch_unwind};
64use std::sync::{Arc, OnceLock};
65
66const OK: u32 = 0;
68const NULL: u32 = 1;
69const BOUNDS: u32 = 2;
70const BAD_TAG: u32 = 3;
71const STALE: u32 = 4;
72const STATE: u32 = 5;
73const POISONED: u32 = 6;
74const VERSION: u32 = 7;
75const MODEL_ASSET: u32 = 8;
76const DICTIONARY_DATA: u32 = 9;
77const ABI: u32 = 0x0000_0003;
79
80#[derive(Default, PartialEq, Eq)]
83enum Backend {
84 #[default]
85 Unselected,
86 Composition,
87 Compatibility,
88}
89
90#[derive(Clone, Copy)]
93struct CompatibilityPending {
94 id: u64,
95 rewrite: bool,
96 boundary: bool,
97 word_boundary: bool,
98 collect: bool,
99}
100
101fn compatible_abi(abi: u32) -> bool {
103 abi == ABI
104}
105
106#[derive(Default)]
108enum Automatic {
109 #[default]
110 Off,
111 Fixture,
112 Model(Model<'static>),
113}
114
115pub struct Engine {
120 session: Session,
121 poisoned: bool,
122 automatic: Automatic,
123 dictionaries: [Snapshot; 2],
125 learned: Vec<Arc<Vocabulary>>,
127 backend: Backend,
128 compatibility_boundary: bool,
131 compatibility_word_boundary: bool,
133 compatibility_collect: bool,
136 compatibility_pending: Option<CompatibilityPending>,
137}
138
139#[repr(C)]
141#[derive(Clone, Copy)]
142pub struct NativeEvent {
143 role: u32,
144 mode: u32,
145 context: u32,
146 len: u32,
147 units: [u16; 8],
148}
149
150#[repr(C)]
153pub struct NativePlan {
154 plan_id: u64,
155 action: u32,
156 disposition: u32,
157 expected_len: u32,
158 mark_len: u32,
159 expected: [u16; 128],
160 mark: [u16; 128],
161}
162
163impl NativeEvent {
164 pub fn new(role: u32, mode: u32, context: u32, units: &[u16]) -> Result<Self, u32> {
177 if units.len() > 8 {
178 return Err(BOUNDS);
179 }
180 let mut event = Self {
181 role,
182 mode,
183 context,
184 len: units.len() as u32,
185 units: [0; 8],
186 };
187 event.units[..units.len()].copy_from_slice(units);
188 Ok(event)
189 }
190
191 pub fn view(&self) -> Result<NativeEventView<'_>, u32> {
196 if self.len > 8 {
197 return Err(BOUNDS);
198 }
199 Ok(NativeEventView {
200 role: self.role,
201 mode: self.mode,
202 context: self.context,
203 units: &self.units[..self.len as usize],
204 })
205 }
206}
207
208pub struct NativeEventView<'a> {
210 pub role: u32,
212 pub mode: u32,
214 pub context: u32,
216 pub units: &'a [u16],
218}
219
220pub struct NativePlanView<'a> {
222 pub plan_id: u64,
224 pub action: u32,
226 pub disposition: u32,
228 pub expected: &'a [u16],
230 pub mark: &'a [u16],
232}
233
234impl NativePlan {
235 pub fn view(&self) -> NativePlanView<'_> {
239 NativePlanView {
240 plan_id: self.plan_id,
241 action: self.action,
242 disposition: self.disposition,
243 expected: &self.expected[..self.expected_len as usize],
244 mark: &self.mark[..self.mark_len as usize],
245 }
246 }
247}
248
249#[repr(C)]
251pub struct CompatibilityPlan {
252 plan_id: u64,
253 operation: u32,
254 disposition: u32,
255 delete_units: u32,
256 replacement_len: u32,
257 replacement: [u16; 128],
258}
259
260const _: () = assert!(size_of::<CompatibilityPlan>() == 280);
262
263const _: () = assert!(size_of::<NativeEvent>() == 32);
264const _: () = assert!(size_of::<NativePlan>() == 536);
265const _: () = assert!(std::mem::offset_of!(NativePlan, expected) == 24);
266const _: () = assert!(keyrill_core::session::MAX_WORD < 128);
268const _: () = assert!(MAX_SOURCE_BYTES == 1_048_576);
270
271fn embedded_model() -> Result<Model<'static>, ModelError> {
273 static MODEL: OnceLock<Result<Model<'static>, ModelError>> = OnceLock::new();
274 *MODEL.get_or_init(Model::embedded)
275}
276
277fn set_policy(
279 engine: &mut Engine,
280 policy: u32,
281 model: impl FnOnce() -> Result<Model<'static>, ModelError>,
282) -> u32 {
283 if policy > 2 {
284 return BAD_TAG;
285 }
286 if let Err(error) = engine.session.set_fixtures(policy == 1) {
288 return status(error);
289 }
290 if matches!(
291 (&engine.automatic, policy),
292 (Automatic::Off, 0) | (Automatic::Fixture, 1) | (Automatic::Model(_), 2)
293 ) {
294 return OK;
295 }
296 engine.session.reset();
297 engine.compatibility_pending = None;
298 engine.compatibility_boundary = false;
299 engine.compatibility_word_boundary = false;
300 engine.compatibility_collect = true;
301 engine.automatic = Automatic::Off;
303 engine.automatic = match policy {
304 0 => Automatic::Off,
305 1 => Automatic::Fixture,
306 _ => match model() {
307 Ok(model) => Automatic::Model(model),
308 Err(_) => return MODEL_ASSET,
309 },
310 };
311 OK
312}
313
314fn status(error: keyrill_core::session::Error) -> u32 {
315 match error {
316 keyrill_core::session::Error::Stale => STALE,
317 keyrill_core::session::Error::Invalidated => STATE,
318 }
319}
320
321fn decode_event(event: &NativeEvent) -> Result<(Event, Mode, Context), u32> {
322 if event.len > 8 {
323 return Err(BOUNDS);
324 }
325 let mode = match event.mode {
326 1 => Mode::En,
327 2 => Mode::Ru,
328 _ => return Err(BAD_TAG),
329 };
330 let context = match event.context {
331 0 => Context::Boundary,
332 1 => Context::Ineligible,
333 _ => return Err(BAD_TAG),
334 };
335 if event.role != 1 && event.len != 0 {
336 return Err(BAD_TAG);
337 }
338 let input = match event.role {
339 1 => Event::Text(event.units[..event.len as usize].to_vec()),
340 2 => Event::Backspace,
341 3 => Event::Escape,
342 4 => Event::Manual,
343 5 => Event::Reverse,
344 6 => Event::Finish,
345 _ => return Err(BAD_TAG),
346 };
347 Ok((input, mode, context))
348}
349
350fn propose(
353 engine: &mut Engine,
354 input: &Event,
355 mode: Mode,
356 context: Context,
357 automatic: bool,
358) -> Result<keyrill_core::session::Plan, keyrill_core::session::Error> {
359 if !automatic {
360 return engine
361 .session
362 .propose_without_automatic(input, mode, context);
363 }
364 match &engine.automatic {
365 Automatic::Model(model) => {
366 let en = engine.dictionaries[0].current();
367 let ru = engine.dictionaries[1].current();
368 engine.session.propose_with_inference(
369 input,
370 mode,
371 context,
372 model,
373 Dictionaries {
374 en: en.as_deref(),
375 ru: ru.as_deref(),
376 learned: &engine.learned,
377 },
378 Policy::default(),
379 )
380 }
381 _ => engine.session.propose(input, mode, context),
382 }
383}
384
385unsafe fn with_engine(pointer: *mut Engine, f: impl FnOnce(&mut Engine) -> u32) -> u32 {
391 if pointer.is_null() {
392 return NULL;
393 }
394 let engine = unsafe { &mut *pointer };
397 if engine.poisoned {
398 return POISONED;
399 }
400 match catch_unwind(AssertUnwindSafe(|| f(engine))) {
401 Ok(result) => result,
402 Err(_) => {
403 engine.poisoned = true;
404 engine.session.reset();
405 engine.compatibility_pending = None;
406 POISONED
407 }
408 }
409}
410
411#[unsafe(no_mangle)]
413pub extern "C" fn kr_abi_version() -> u32 {
414 ABI
415}
416
417#[unsafe(no_mangle)]
424pub unsafe extern "C" fn kr_engine_new(abi: u32, out: *mut *mut Engine) -> u32 {
425 if out.is_null() {
426 return NULL;
427 }
428 unsafe {
431 out.write(std::ptr::null_mut());
432 }
433 if !compatible_abi(abi) {
434 return VERSION;
435 }
436 match catch_unwind(|| {
437 Box::new(Engine {
438 session: Session::default(),
439 poisoned: false,
440 automatic: Automatic::Off,
441 dictionaries: [Snapshot::default(), Snapshot::default()],
442 learned: Vec::new(),
443 backend: Backend::Unselected,
444 compatibility_boundary: false,
445 compatibility_word_boundary: false,
446 compatibility_collect: true,
447 compatibility_pending: None,
448 })
449 }) {
450 Ok(engine) => {
451 unsafe {
453 out.write(Box::into_raw(engine));
454 }
455 OK
456 }
457 Err(_) => POISONED,
458 }
459}
460
461#[unsafe(no_mangle)]
467pub unsafe extern "C" fn kr_engine_free(pointer: *mut Engine) {
468 if !pointer.is_null() {
469 let _ = catch_unwind(AssertUnwindSafe(|| {
471 drop(unsafe { Box::from_raw(pointer) });
473 }));
474 }
475}
476
477#[unsafe(no_mangle)]
484pub unsafe extern "C" fn kr_reset(pointer: *mut Engine) -> u32 {
485 unsafe {
487 with_engine(pointer, |engine| {
488 engine.session.reset();
489 engine.compatibility_pending = None;
490 engine.compatibility_boundary = false;
491 engine.compatibility_word_boundary = false;
492 engine.compatibility_collect = true;
493 OK
494 })
495 }
496}
497
498#[unsafe(no_mangle)]
503pub unsafe extern "C" fn kr_set_automatic_policy(pointer: *mut Engine, policy: u32) -> u32 {
504 unsafe { with_engine(pointer, |engine| set_policy(engine, policy, embedded_model)) }
506}
507
508#[unsafe(no_mangle)]
513pub unsafe extern "C" fn kr_set_keyboard(pointer: *mut Engine, keyboard: u32) -> u32 {
514 unsafe {
516 with_engine(pointer, |engine| {
517 let keyboard = match keyboard {
518 0 => Keyboard::Apple,
519 1 => Keyboard::Pc,
520 _ => return BAD_TAG,
521 };
522 engine
523 .session
524 .set_keyboard(keyboard)
525 .map_or_else(status, |()| OK)
526 })
527 }
528}
529
530#[unsafe(no_mangle)]
539pub unsafe extern "C" fn kr_set_dictionary_utf8(
540 pointer: *mut Engine,
541 language: u32,
542 bytes: *const u8,
543 len: u32,
544) -> u32 {
545 unsafe {
547 with_engine(pointer, |engine| {
548 let index = match language {
549 1 => 0,
550 2 => 1,
551 _ => return BAD_TAG,
552 };
553 if engine.session.has_pending() {
554 return STATE;
555 }
556 if len as usize > MAX_SOURCE_BYTES {
557 return BOUNDS;
558 }
559 let source = if len == 0 {
560 &[]
561 } else {
562 if bytes.is_null() {
563 return NULL;
564 }
565 std::slice::from_raw_parts(bytes, len as usize)
569 };
570 engine.dictionaries[index]
571 .replace(source)
572 .map_or(DICTIONARY_DATA, |()| OK)
573 })
574 }
575}
576
577#[unsafe(no_mangle)]
583pub unsafe extern "C" fn kr_clear_dictionary(pointer: *mut Engine, language: u32) -> u32 {
584 unsafe {
586 with_engine(pointer, |engine| {
587 let index = match language {
588 1 => 0,
589 2 => 1,
590 _ => return BAD_TAG,
591 };
592 if engine.session.has_pending() {
593 return STATE;
594 }
595 engine.dictionaries[index] = Snapshot::default();
596 OK
597 })
598 }
599}
600
601#[unsafe(no_mangle)]
607pub unsafe extern "C" fn kr_dictionary_skipped_lines(
608 pointer: *mut Engine,
609 language: u32,
610 out: *mut u32,
611) -> u32 {
612 if out.is_null() {
613 return NULL;
614 }
615 unsafe {
618 with_engine(pointer, |engine| {
619 let index = match language {
620 1 => 0,
621 2 => 1,
622 _ => return BAD_TAG,
623 };
624 let Some(source) = engine.dictionaries[index].current() else {
625 return STATE;
626 };
627 out.write(source.skipped() as u32);
629 OK
630 })
631 }
632}
633
634#[unsafe(no_mangle)]
640pub unsafe extern "C" fn kr_plan_event(
641 pointer: *mut Engine,
642 event: *const NativeEvent,
643 out: *mut NativePlan,
644) -> u32 {
645 if event.is_null() || out.is_null() {
646 return NULL;
647 }
648 unsafe {
652 with_engine(pointer, |engine| {
653 let event = &*event;
654 let (input, mode, context) = match decode_event(event) {
655 Ok(decoded) => decoded,
656 Err(error) => return error,
657 };
658 if engine.backend == Backend::Compatibility {
659 return STATE;
660 }
661 let proposal = propose(engine, &input, mode, context, true);
662 let plan = match proposal {
663 Ok(plan) => plan,
664 Err(error) => return status(error),
665 };
666 engine.backend = Backend::Composition;
668 let mut copied = NativePlan {
669 plan_id: plan.id,
670 action: match plan.action {
671 Action::Pass => 0,
672 Action::Mark => 1,
673 Action::Finish => 2,
674 Action::Unavailable => 3,
675 },
676 disposition: match plan.disposition {
677 Disposition::Pass => 0,
678 Disposition::Consumed => 1,
679 Disposition::Replan => 2,
680 },
681 expected_len: plan.expected.len() as u32,
682 mark_len: plan.text.len() as u32,
683 expected: [0; 128],
684 mark: [0; 128],
685 };
686 copied.expected[..plan.expected.len()].copy_from_slice(&plan.expected);
688 copied.mark[..plan.text.len()].copy_from_slice(&plan.text);
689 out.write(copied);
690 OK
691 })
692 }
693}
694
695#[unsafe(no_mangle)]
701pub unsafe extern "C" fn kr_commit(pointer: *mut Engine, token: u64, outcome: u32) -> u32 {
702 unsafe {
704 with_engine(pointer, |engine| {
705 let outcome = match outcome {
706 0 => Outcome::Verified,
707 1 => Outcome::Refused,
708 2 => Outcome::Unknown,
709 _ => return BAD_TAG,
710 };
711 if engine.backend == Backend::Compatibility {
712 return STATE;
713 }
714 engine
715 .session
716 .acknowledge(token, outcome)
717 .map_or_else(status, |()| OK)
718 })
719 }
720}
721
722#[cfg(test)]
723mod tests {
724 use super::*;
725
726 #[test]
727 fn rust_adapter_event_construction_and_borrowed_plan_match_the_abi() {
728 assert!(matches!(NativeEvent::new(1, 1, 0, &[0; 9]), Err(BOUNDS)));
729 for role in 2..=6 {
730 assert!(NativeEvent::new(role, 2, 1, &[]).is_ok());
731 }
732 let mut source = [b'g' as u16];
733 let event = NativeEvent::new(1, 1, 0, &source).unwrap();
734 source[0] = b'x' as u16;
735 assert_eq!(source, [b'x' as u16]);
736 let mut engine = std::ptr::null_mut();
737 let mut storage = std::mem::MaybeUninit::uninit();
738 unsafe {
740 assert_eq!(kr_engine_new(ABI, &mut engine), OK);
741 for event in [
742 NativeEvent::new(2, 1, 0, &[1]),
743 NativeEvent::new(7, 1, 0, &[]),
744 NativeEvent::new(1, 0, 0, &[]),
745 NativeEvent::new(1, 1, 2, &[]),
746 ] {
747 let invalid = event.unwrap();
748 assert_eq!(
749 kr_plan_event(engine, &invalid, storage.as_mut_ptr()),
750 BAD_TAG
751 );
752 }
753 assert_eq!(kr_plan_event(engine, &event, storage.as_mut_ptr()), OK);
754 let plan = storage.assume_init();
755 let view = plan.view();
756 assert_eq!(view.action, 1);
757 assert_eq!(view.disposition, 1);
758 assert_eq!(view.expected, &[]);
759 assert_eq!(view.mark, &[b'g' as u16]);
760 assert_eq!(kr_commit(engine, view.plan_id, 0), OK);
761 kr_engine_free(engine);
762 }
763 }
764
765 pub(super) unsafe fn apply_event(engine: *mut Engine, event: &NativeEvent) -> NativePlan {
768 unsafe {
770 for attempt in 0..2 {
771 let mut out = std::mem::MaybeUninit::<NativePlan>::uninit();
772 assert_eq!(kr_plan_event(engine, event, out.as_mut_ptr()), OK);
773 let plan = out.assume_init();
774 assert_eq!(kr_commit(engine, plan.plan_id, 0), OK);
775 if plan.disposition != 2 {
776 return plan;
777 }
778 assert_eq!((attempt, plan.action), (0, 2));
779 }
780 unreachable!("a second replan is a protocol error")
781 }
782 }
783
784 pub(super) unsafe fn type_text(engine: *mut Engine, mode: u32, text: &str) -> NativePlan {
786 unsafe {
788 text.encode_utf16()
789 .map(|unit| {
790 let mut units = [0; 8];
791 units[0] = unit;
792 apply_event(
793 engine,
794 &NativeEvent {
795 role: 1,
796 mode,
797 context: 0,
798 len: 1,
799 units,
800 },
801 )
802 })
803 .last()
804 .unwrap()
805 }
806 }
807
808 #[test]
813 fn dictionary_buffers_configuration_and_failed_asset_are_transactional() {
814 use keyrill_core::vocabulary::Membership;
815 use std::sync::Arc;
816
817 unsafe {
820 let mut engine = std::ptr::null_mut();
821 assert_eq!(kr_abi_version(), 0x0000_0003);
822 assert_eq!(kr_engine_new(ABI, &mut engine), OK);
823 assert_eq!(kr_set_automatic_policy(std::ptr::null_mut(), 0), NULL);
824 assert_eq!(kr_clear_dictionary(std::ptr::null_mut(), 1), NULL);
825 assert_eq!(
826 kr_set_dictionary_utf8(std::ptr::null_mut(), 1, std::ptr::null(), 0),
827 NULL
828 );
829 assert_eq!(kr_set_automatic_policy(engine, 3), BAD_TAG);
830 assert_eq!(
831 kr_set_dictionary_utf8(engine, 0, std::ptr::null(), 0),
832 BAD_TAG
833 );
834 assert_eq!(kr_clear_dictionary(engine, 3), BAD_TAG);
835 assert_eq!(kr_set_dictionary_utf8(engine, 1, std::ptr::null(), 1), NULL);
836 assert_eq!(
837 kr_set_dictionary_utf8(engine, 1, std::ptr::null(), MAX_SOURCE_BYTES as u32 + 1),
838 BOUNDS
839 );
840 let mut source = b"cgbcjr".to_vec();
841 assert_eq!(
842 kr_set_dictionary_utf8(engine, 1, source.as_ptr(), source.len() as u32),
843 OK
844 );
845 let old = (*engine).dictionaries[0].current().unwrap();
846 source.fill(b'x');
847 let original: Vec<_> = "cgbcjr".encode_utf16().collect();
848 assert_eq!(old.lookup(&original), Membership::Recognized);
849 for invalid in [b"a\0b".as_slice(), b"/encoding=latin1\nword"] {
850 assert_eq!(
851 kr_set_dictionary_utf8(engine, 1, invalid.as_ptr(), invalid.len() as u32),
852 DICTIONARY_DATA
853 );
854 assert!(Arc::ptr_eq(
855 &old,
856 &(*engine).dictionaries[0].current().unwrap()
857 ));
858 }
859 let event = NativeEvent {
860 role: 1,
861 mode: 1,
862 context: 0,
863 len: 1,
864 units: [97; 8],
865 };
866 let mut out = std::mem::MaybeUninit::<NativePlan>::uninit();
867 assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), OK);
868 let pending = out.assume_init_read();
869 assert_eq!(
870 kr_set_dictionary_utf8(engine, 1, source.as_ptr(), source.len() as u32),
871 STATE
872 );
873 assert_eq!(kr_clear_dictionary(engine, 1), STATE);
874 assert_eq!(kr_set_automatic_policy(engine, 2), STATE);
875 assert!(Arc::ptr_eq(
876 &old,
877 &(*engine).dictionaries[0].current().unwrap()
878 ));
879 assert_eq!(kr_commit(engine, pending.plan_id, 0), OK);
880 assert_eq!(kr_set_automatic_policy(engine, 2), STATE);
881 assert_eq!(kr_set_dictionary_utf8(engine, 1, source.as_ptr(), 0), OK);
882 assert!((*engine).dictionaries[0].current().unwrap().is_empty());
883 assert_eq!(kr_set_dictionary_utf8(engine, 2, std::ptr::null(), 0), OK);
884 assert_eq!(kr_clear_dictionary(engine, 1), OK);
885 assert!((*engine).dictionaries[0].current().is_none());
886 assert!((*engine).dictionaries[1].current().unwrap().is_empty());
887 assert_eq!(old.lookup(&original), Membership::Recognized);
888 assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), OK);
889 assert_eq!(kr_commit(engine, out.assume_init_read().plan_id, 2), OK);
890 assert_eq!(kr_clear_dictionary(engine, 2), OK);
891 assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), STATE);
892 assert_eq!(kr_reset(engine), OK);
893 assert_eq!(kr_set_automatic_policy(engine, 1), OK);
894 assert_eq!(
895 with_engine(engine, |engine| set_policy(engine, 2, || Err(
896 ModelError::Magic
897 ))),
898 MODEL_ASSET
899 );
900 let plan = type_text(engine, 1, "ghbdtn ");
901 assert_eq!(
902 &plan.mark[..plan.mark_len as usize],
903 "ghbdtn ".encode_utf16().collect::<Vec<_>>()
904 );
905 assert_eq!(kr_reset(engine), OK);
906 assert_eq!(
907 with_engine(engine, |_| panic!("synthetic policy containment test")),
908 POISONED
909 );
910 assert_eq!(kr_set_automatic_policy(engine, 0), POISONED);
911 assert_eq!(
912 kr_set_dictionary_utf8(engine, 1, std::ptr::null(), 0),
913 POISONED
914 );
915 assert_eq!(kr_clear_dictionary(engine, 1), POISONED);
916 kr_engine_free(engine);
917
918 assert_eq!(kr_engine_new(0x0001_0000, &mut engine), VERSION);
919 assert!(engine.is_null());
920 assert_eq!(kr_engine_new(ABI - 1, &mut engine), VERSION);
921 assert!(engine.is_null());
922 }
923 }
924
925 #[test]
930 fn keyboard_selection_and_skipped_lines_follow_the_configuration_contract() {
931 let units = |s: &str| s.encode_utf16().collect::<Vec<_>>();
932 let event = |role, mode| NativeEvent {
933 role,
934 mode,
935 context: 0,
936 len: 0,
937 units: [0; 8],
938 };
939 unsafe {
942 let mut engine = std::ptr::null_mut();
943 assert_eq!(kr_engine_new(ABI, &mut engine), OK);
944 assert_eq!(kr_set_keyboard(std::ptr::null_mut(), 0), NULL);
945 for (keyboard, converted) in [(None, "\\krf"), (Some(1), "`krf"), (Some(0), "\\krf")] {
946 if let Some(keyboard) = keyboard {
947 assert_eq!(kr_set_keyboard(engine, keyboard), OK);
948 assert_eq!(kr_set_keyboard(engine, keyboard), OK);
949 }
950 assert_eq!(kr_reset(engine), OK);
951 type_text(engine, 2, "ёлка");
952 assert_eq!(kr_set_keyboard(engine, 1), STATE);
953 let manual = apply_event(engine, &event(4, 2));
954 assert_eq!(&manual.mark[..manual.mark_len as usize], units(converted));
955 let reverse = apply_event(engine, &event(5, 2));
956 assert_eq!(&reverse.mark[..reverse.mark_len as usize], units("ёлка"));
957 apply_event(engine, &event(6, 2));
958 }
959 for tag in [2, u32::MAX] {
960 assert_eq!(kr_set_keyboard(engine, tag), BAD_TAG);
961 }
962
963 assert_eq!(kr_set_keyboard(engine, 1), OK);
965 let mut out = std::mem::MaybeUninit::<NativePlan>::uninit();
966 let mut letter = event(1, 2);
967 letter.len = 1;
968 letter.units[0] = 0x451;
969 assert_eq!(kr_plan_event(engine, &letter, out.as_mut_ptr()), OK);
970 let pending = out.assume_init_read();
971 assert_eq!(kr_set_keyboard(engine, 0), STATE);
972 assert_eq!(kr_commit(engine, pending.plan_id, 0), OK);
973 assert_eq!(kr_set_keyboard(engine, 0), STATE);
974 assert_eq!(kr_reset(engine), OK);
975 type_text(engine, 2, "ё");
976 let manual = apply_event(engine, &event(4, 2));
977 assert_eq!(&manual.mark[..manual.mark_len as usize], units("`"));
978 let plan = apply_event(engine, &event(3, 2));
979 assert_eq!((plan.action, plan.disposition, plan.mark_len), (2, 1, 1));
980 assert_eq!(plan.mark[0], 0x451);
981 type_text(engine, 2, "ё");
982 let plan = apply_event(engine, &event(3, 2));
983 assert_eq!((plan.action, plan.disposition, plan.mark_len), (2, 0, 1));
984
985 let mut skipped = 77;
986 assert_eq!(kr_dictionary_skipped_lines(engine, 1, &mut skipped), STATE);
987 assert_eq!(skipped, 77);
988 let mut removed = "ёж".as_bytes().to_vec();
989 removed[0] = b'#';
990 let mut source = b"keep\nbad/*\n/future\n\xff\n".to_vec();
991 source.extend_from_slice(&removed);
992 assert_eq!(
993 kr_set_dictionary_utf8(engine, 1, source.as_ptr(), source.len() as u32),
994 OK
995 );
996 assert_eq!(kr_dictionary_skipped_lines(engine, 1, &mut skipped), OK);
997 assert_eq!(skipped, 3);
998 assert_eq!((*engine).dictionaries[0].current().unwrap().len(), 1);
999 assert_eq!(
1000 kr_dictionary_skipped_lines(engine, 1, std::ptr::null_mut()),
1001 NULL
1002 );
1003 assert_eq!(
1004 kr_dictionary_skipped_lines(std::ptr::null_mut(), 1, &mut skipped),
1005 NULL
1006 );
1007 assert_eq!(
1008 kr_dictionary_skipped_lines(engine, 3, &mut skipped),
1009 BAD_TAG
1010 );
1011 assert_eq!(kr_dictionary_skipped_lines(engine, 2, &mut skipped), STATE);
1012 assert_eq!(
1013 kr_set_dictionary_utf8(engine, 1, b"\0a".as_ptr(), 2),
1014 DICTIONARY_DATA
1015 );
1016 assert_eq!(kr_dictionary_skipped_lines(engine, 1, &mut skipped), OK);
1017 assert_eq!(skipped, 3);
1018 assert_eq!(kr_set_dictionary_utf8(engine, 1, std::ptr::null(), 0), OK);
1019 assert_eq!(kr_dictionary_skipped_lines(engine, 1, &mut skipped), OK);
1020 assert_eq!(skipped, 0);
1021
1022 assert_eq!(
1023 with_engine(engine, |_| panic!("synthetic keyboard containment test")),
1024 POISONED
1025 );
1026 assert_eq!(kr_set_keyboard(engine, 0), POISONED);
1027 assert_eq!(
1028 kr_dictionary_skipped_lines(engine, 1, &mut skipped),
1029 POISONED
1030 );
1031 kr_engine_free(engine);
1032 }
1033 }
1034
1035 #[test]
1040 fn model_policy_bridge_preserves_configuration_context_and_receipts() {
1041 unsafe {
1044 let mut engine = std::ptr::null_mut();
1045 assert_eq!(kr_engine_new(ABI, &mut engine), OK);
1046 assert_eq!(kr_set_automatic_policy(engine, 2), OK);
1047 let plan = type_text(engine, 1, "cgbcjr ");
1048 assert_eq!(
1049 &plan.mark[..plan.mark_len as usize],
1050 "cgbcjr ".encode_utf16().collect::<Vec<_>>()
1051 );
1052 let manual = apply_event(
1053 engine,
1054 &NativeEvent {
1055 role: 4,
1056 mode: 1,
1057 context: 0,
1058 len: 0,
1059 units: [0; 8],
1060 },
1061 );
1062 assert_eq!(
1063 &manual.mark[..manual.mark_len as usize],
1064 "список ".encode_utf16().collect::<Vec<_>>()
1065 );
1066 assert_eq!(kr_reset(engine), OK);
1067 assert_eq!(kr_set_dictionary_utf8(engine, 1, std::ptr::null(), 0), OK);
1068 assert_eq!(kr_set_dictionary_utf8(engine, 2, std::ptr::null(), 0), OK);
1069 for (mode, raw, corrected) in [(1, "cgbcjr ", "список "), (2, "цщкдв ", "world ")]
1070 {
1071 assert_eq!(kr_reset(engine), OK);
1072 let plan = type_text(engine, mode, raw);
1073 assert_eq!(
1074 &plan.mark[..plan.mark_len as usize],
1075 corrected.encode_utf16().collect::<Vec<_>>()
1076 );
1077 let source = "cgbcjr\nцщкдв\n".as_bytes();
1078 assert_eq!(
1079 kr_set_dictionary_utf8(engine, 1, source.as_ptr(), source.len() as u32),
1080 OK
1081 );
1082 let reverse = apply_event(
1083 engine,
1084 &NativeEvent {
1085 role: 5,
1086 mode,
1087 context: 0,
1088 len: 0,
1089 units: [0; 8],
1090 },
1091 );
1092 assert_eq!(
1093 &reverse.mark[..reverse.mark_len as usize],
1094 raw.encode_utf16().collect::<Vec<_>>()
1095 );
1096 assert_eq!(kr_set_dictionary_utf8(engine, 1, std::ptr::null(), 0), OK);
1097 }
1098 assert_eq!(kr_reset(engine), OK);
1099 assert_eq!(kr_clear_dictionary(engine, 2), OK);
1100 let plan = type_text(engine, 2, "цщкдв ");
1101 assert_eq!(
1102 &plan.mark[..plan.mark_len as usize],
1103 "цщкдв ".encode_utf16().collect::<Vec<_>>()
1104 );
1105 assert_eq!(kr_reset(engine), OK);
1106 assert_eq!(kr_set_dictionary_utf8(engine, 2, std::ptr::null(), 0), OK);
1107 type_text(engine, 1, "hello world ");
1108 let event = NativeEvent {
1109 role: 1,
1110 mode: 1,
1111 context: 0,
1112 len: 1,
1113 units: [121; 8],
1114 };
1115 let mut out = std::mem::MaybeUninit::<NativePlan>::uninit();
1116 assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), OK);
1117 let finish = out.assume_init_read();
1118 assert_eq!((finish.action, finish.disposition), (2, 2));
1119 assert_eq!(kr_commit(engine, finish.plan_id, 0), OK);
1120 assert_eq!(kr_set_automatic_policy(engine, 2), OK);
1121 let preserved = type_text(engine, 1, "yfv ");
1122 assert_eq!(
1123 &preserved.mark[..preserved.mark_len as usize],
1124 "yfv ".encode_utf16().collect::<Vec<_>>()
1125 );
1126 assert_eq!(kr_reset(engine), OK);
1127 type_text(engine, 1, "hello world ");
1128 assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), OK);
1129 assert_eq!(kr_commit(engine, out.assume_init_read().plan_id, 0), OK);
1130 assert_eq!(kr_set_automatic_policy(engine, 0), OK);
1131 assert_eq!(kr_set_automatic_policy(engine, 2), OK);
1132 let neutral = type_text(engine, 1, "yfv ");
1133 assert_eq!(
1134 &neutral.mark[..neutral.mark_len as usize],
1135 "нам ".encode_utf16().collect::<Vec<_>>()
1136 );
1137 assert_eq!(kr_reset(engine), OK);
1138 assert_eq!(kr_set_automatic_policy(engine, 0), OK);
1139 let disabled = type_text(engine, 1, "cgbcjr ");
1140 assert_eq!(
1141 &disabled.mark[..disabled.mark_len as usize],
1142 "cgbcjr ".encode_utf16().collect::<Vec<_>>()
1143 );
1144 kr_engine_free(engine);
1145 }
1146 }
1147
1148 #[test]
1151 fn abi_null_version_bounds_stale_and_poison_contracts() {
1152 unsafe {
1155 let mut engine = std::ptr::null_mut();
1156 assert_eq!(kr_engine_new(ABI + 1, &mut engine), VERSION);
1157 assert!(engine.is_null());
1158 assert_eq!(kr_engine_new(ABI, &mut engine), OK);
1159 assert_eq!(kr_reset(std::ptr::null_mut()), NULL);
1160 let mut event = NativeEvent {
1161 role: 1,
1162 mode: 1,
1163 context: 0,
1164 len: 9,
1165 units: [97; 8],
1166 };
1167 let mut out = std::mem::MaybeUninit::<NativePlan>::uninit();
1168 assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), BOUNDS);
1169 event.len = 1;
1170 assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), OK);
1171 let plan = out.assume_init();
1172 assert_eq!(plan.mark[..plan.mark_len as usize], [97]);
1173 assert_eq!(kr_reset(engine), OK);
1174 assert_eq!(kr_commit(engine, plan.plan_id, 0), STALE);
1175 assert_eq!(
1176 with_engine(engine, |_| panic!("synthetic containment test")),
1177 POISONED
1178 );
1179 assert_eq!(kr_reset(engine), POISONED);
1180 kr_engine_free(engine);
1181 kr_engine_free(std::ptr::null_mut());
1182 }
1183 }
1184
1185 #[test]
1188 fn copied_plans_manual_boundary_reverse_and_unknown_effect() {
1189 unsafe {
1192 let mut engine = std::ptr::null_mut();
1193 assert_eq!(kr_engine_new(ABI, &mut engine), OK);
1194 assert_eq!(kr_set_automatic_policy(engine, 3), BAD_TAG);
1195 assert_eq!(kr_set_automatic_policy(engine, 1), OK);
1196 let mut event = NativeEvent {
1197 role: 1,
1198 mode: 1,
1199 context: 0,
1200 len: 1,
1201 units: [0; 8],
1202 };
1203 let mut out = std::mem::MaybeUninit::<NativePlan>::uninit();
1204 for unit in "ghbdtn".encode_utf16().chain([32]) {
1205 event.units[0] = unit;
1206 assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), OK);
1207 let p = out.assume_init_read();
1208 assert_eq!(p.action, 1);
1209 if unit == 32 {
1210 assert_eq!(
1211 &p.mark[..p.mark_len as usize],
1212 "привет ".encode_utf16().collect::<Vec<_>>()
1213 );
1214 }
1215 assert_eq!(kr_commit(engine, p.plan_id, 0), OK);
1216 }
1217 event.role = 5;
1218 event.len = 0;
1219 assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), OK);
1220 let reversed = out.assume_init_read();
1221 assert_eq!(
1222 &reversed.mark[..reversed.mark_len as usize],
1223 "ghbdtn ".encode_utf16().collect::<Vec<_>>()
1224 );
1225 assert_eq!(kr_commit(engine, reversed.plan_id, 2), OK);
1226 assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), STATE);
1227 assert_eq!(kr_reset(engine), OK);
1228 event.role = 1;
1229 event.len = 1;
1230 event.units[0] = 120;
1231 assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), OK);
1232 assert_eq!(kr_commit(engine, out.assume_init_read().plan_id, 0), OK);
1233 event.role = 2;
1234 event.len = 0;
1235 assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), OK);
1236 let empty = out.assume_init_read();
1237 assert_eq!((empty.action, empty.mark_len), (1, 0));
1238 assert_eq!(kr_commit(engine, empty.plan_id, 1), OK);
1239 assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), STATE);
1240 kr_engine_free(engine);
1241 }
1242 }
1243
1244 #[test]
1246 fn invalid_native_tags_never_produce_a_usable_plan() {
1247 unsafe {
1250 assert_eq!(kr_engine_new(ABI, std::ptr::null_mut()), NULL);
1251 let mut engine = std::ptr::null_mut();
1252 assert_eq!(kr_engine_new(ABI, &mut engine), OK);
1253 let mut out = std::mem::MaybeUninit::<NativePlan>::uninit();
1254 let mut event = NativeEvent {
1255 role: 1,
1256 mode: 1,
1257 context: 0,
1258 len: 1,
1259 units: [97; 8],
1260 };
1261 assert_eq!(
1262 kr_plan_event(engine, std::ptr::null(), out.as_mut_ptr()),
1263 NULL
1264 );
1265 assert_eq!(kr_plan_event(engine, &event, std::ptr::null_mut()), NULL);
1266 for (role, mode, context, len) in [
1267 (0, 1, 0, 0),
1268 (7, 1, 0, 0),
1269 (1, 0, 0, 1),
1270 (1, 1, 2, 1),
1271 (4, 1, 0, 1),
1272 ] {
1273 event.role = role;
1274 event.mode = mode;
1275 event.context = context;
1276 event.len = len;
1277 assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), BAD_TAG);
1278 }
1279 assert_eq!(kr_commit(engine, 1, 3), BAD_TAG);
1280 kr_engine_free(engine);
1281 }
1282 }
1283}