1use core::ffi::{c_char, c_void};
2use core::ops::{BitOr, BitOrAssign};
3use core::ptr;
4use std::path::Path;
5use std::sync::OnceLock;
6
7use serde::de::DeserializeOwned;
8use serde::{Deserialize, Serialize};
9
10use crate::error::VisionKitError;
11use crate::ffi;
12use crate::image_analysis::ImageAnalysis;
13use crate::private::{
14 error_from_status, json_cstring, parse_json_ptr, path_to_cstring, string_from_ptr,
15 vec_from_buffer_ptr,
16};
17
18type BoolQueryFn = unsafe extern "C" fn(
19 token: *mut c_void,
20 out_value: *mut i32,
21 out_error_message: *mut *mut c_char,
22) -> i32;
23type TypesQueryFn = unsafe extern "C" fn(
24 token: *mut c_void,
25 out_types_raw: *mut u64,
26 out_error_message: *mut *mut c_char,
27) -> i32;
28type BoolSetterFn = unsafe extern "C" fn(
29 token: *mut c_void,
30 value: i32,
31 out_error_message: *mut *mut c_char,
32) -> i32;
33type PointBoolQueryFn = unsafe extern "C" fn(
34 token: *mut c_void,
35 x: f64,
36 y: f64,
37 out_value: *mut i32,
38 out_error_message: *mut *mut c_char,
39) -> i32;
40type RectQueryFn = unsafe extern "C" fn(
41 token: *mut c_void,
42 out_x: *mut f64,
43 out_y: *mut f64,
44 out_width: *mut f64,
45 out_height: *mut f64,
46 out_error_message: *mut *mut c_char,
47) -> i32;
48type JsonQueryFn = unsafe extern "C" fn(
49 token: *mut c_void,
50 out_json: *mut *mut c_char,
51 out_error_message: *mut *mut c_char,
52) -> i32;
53type JsonSetterFn = unsafe extern "C" fn(
54 token: *mut c_void,
55 json: *const c_char,
56 out_error_message: *mut *mut c_char,
57) -> i32;
58type OptionalTokenQueryFn = unsafe extern "C" fn(
59 token: *mut c_void,
60 out_token: *mut *mut c_void,
61 out_error_message: *mut *mut c_char,
62) -> i32;
63#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
64pub struct Point {
66 pub x: f64,
68 pub y: f64,
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
73pub struct Rect {
75 pub x: f64,
77 pub y: f64,
79 pub width: f64,
81 pub height: f64,
83}
84
85impl Rect {
86 #[must_use]
87 pub fn is_empty(self) -> bool {
89 self.width <= 0.0 || self.height <= 0.0
90 }
91}
92
93#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
94pub struct Size {
96 pub width: f64,
98 pub height: f64,
100}
101
102impl Size {
103 #[must_use]
104 pub fn is_empty(self) -> bool {
106 self.width <= 0.0 || self.height <= 0.0
107 }
108}
109
110#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
111pub struct EdgeInsets {
113 pub top: f64,
115 pub left: f64,
117 pub bottom: f64,
119 pub right: f64,
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
124#[serde(rename_all = "camelCase")]
125pub struct LiveTextTextRange {
127 pub location: usize,
129 pub length: usize,
131}
132
133impl LiveTextTextRange {
134 #[must_use]
135 pub const fn new(location: usize, length: usize) -> Self {
137 Self { location, length }
138 }
139
140 #[must_use]
141 pub const fn end(self) -> usize {
143 self.location.saturating_add(self.length)
144 }
145}
146
147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
148#[serde(rename_all = "camelCase")]
149pub struct LiveTextAttributedTextAttribute {
151 pub name: String,
153 pub value: String,
155}
156
157#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
158#[serde(rename_all = "camelCase")]
159pub struct LiveTextAttributedTextRun {
161 pub range: LiveTextTextRange,
163 pub attributes: Vec<LiveTextAttributedTextAttribute>,
165}
166
167#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
168#[serde(rename_all = "camelCase")]
169pub struct LiveTextAttributedText {
171 pub text: String,
173 pub runs: Vec<LiveTextAttributedTextRun>,
175}
176
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
178#[serde(transparent)]
179pub struct LiveTextMenuTag(i64);
181
182impl LiveTextMenuTag {
183 #[must_use]
184 pub const fn new(raw_value: i64) -> Self {
186 Self(raw_value)
187 }
188
189 #[must_use]
190 pub const fn raw_value(self) -> i64 {
192 self.0
193 }
194
195 pub fn copy_image() -> Result<Self, VisionKitError> {
197 Ok(Self(live_text_menu_tag_constants()?.copy_image))
198 }
199
200 pub fn share_image() -> Result<Self, VisionKitError> {
202 Ok(Self(live_text_menu_tag_constants()?.share_image))
203 }
204
205 pub fn copy_subject() -> Result<Self, VisionKitError> {
207 Ok(Self(live_text_menu_tag_constants()?.copy_subject))
208 }
209
210 pub fn share_subject() -> Result<Self, VisionKitError> {
212 Ok(Self(live_text_menu_tag_constants()?.share_subject))
213 }
214
215 pub fn lookup_item() -> Result<Self, VisionKitError> {
217 Ok(Self(live_text_menu_tag_constants()?.lookup_item))
218 }
219
220 pub fn recommended_app_items() -> Result<Self, VisionKitError> {
222 Ok(Self(live_text_menu_tag_constants()?.recommended_app_items))
223 }
224}
225
226#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
227#[serde(rename_all = "camelCase")]
228pub struct LiveTextMenuItem {
230 pub title: String,
232 pub tag: i64,
234 pub is_separator: bool,
236 pub is_enabled: bool,
238 pub is_hidden: bool,
240 pub state: i64,
242 pub submenu: Option<Box<LiveTextMenu>>,
244}
245
246#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
247#[serde(rename_all = "camelCase")]
248pub struct LiveTextMenu {
250 pub title: String,
252 pub items: Vec<LiveTextMenuItem>,
254}
255
256#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
257#[serde(rename_all = "camelCase")]
258pub struct LiveTextEventInfo {
260 pub type_name: String,
262 pub location_in_window: Point,
264 pub modifier_flags: u64,
266 pub key_code: u16,
268 pub characters: Option<String>,
270 pub characters_ignoring_modifiers: Option<String>,
272 pub click_count: i64,
274}
275
276#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
277#[serde(rename_all = "camelCase")]
278pub struct LiveTextDelegateEvent {
280 pub kind: String,
282 pub point: Option<Point>,
284 pub analysis_type_raw: Option<u64>,
286 pub decision: Option<bool>,
288 pub rect: Option<Rect>,
290 pub event: Option<LiveTextEventInfo>,
292 pub menu: Option<LiveTextMenu>,
294 pub menu_item: Option<LiveTextMenuItem>,
296 pub visible: Option<bool>,
298 pub highlighted: Option<bool>,
300 pub has_content_view: Option<bool>,
302}
303
304#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
305#[serde(rename_all = "camelCase")]
306pub struct LiveTextFont {
308 pub name: String,
310 pub point_size: f64,
312}
313
314#[derive(Debug, Clone, PartialEq)]
315pub struct LiveTextImageData {
317 pub size: Size,
319 pub png_data: Vec<u8>,
321}
322
323impl LiveTextImageData {
324 #[must_use]
325 pub fn is_empty(&self) -> bool {
327 self.size.is_empty() || self.png_data.is_empty()
328 }
329}
330
331#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
332#[serde(rename_all = "camelCase")]
333struct LiveTextMenuTagConstants {
334 copy_image: i64,
335 share_image: i64,
336 copy_subject: i64,
337 share_subject: i64,
338 lookup_item: i64,
339 recommended_app_items: i64,
340}
341
342static LIVE_TEXT_MENU_TAGS: OnceLock<Result<LiveTextMenuTagConstants, VisionKitError>> =
343 OnceLock::new();
344
345#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
346#[serde(rename_all = "camelCase")]
347struct LiveTextInteractionDelegateConfigPayload {
348 should_begin: bool,
349 contents_rect: Option<Rect>,
350 should_handle_key_down_event: bool,
351 should_show_menu_for_event: bool,
352 updated_menu: Option<LiveTextMenu>,
353}
354
355impl Default for LiveTextInteractionDelegateConfigPayload {
356 fn default() -> Self {
357 Self {
358 should_begin: true,
359 contents_rect: None,
360 should_handle_key_down_event: true,
361 should_show_menu_for_event: true,
362 updated_menu: None,
363 }
364 }
365}
366
367#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
368pub struct LiveTextInteractionTypes(u64);
370
371impl LiveTextInteractionTypes {
372 pub const NONE: Self = Self(0);
374 pub const AUTOMATIC: Self = Self(1);
376 pub const TEXT_SELECTION: Self = Self(2);
378 pub const DATA_DETECTORS: Self = Self(4);
380 pub const IMAGE_SUBJECT: Self = Self(8);
382 pub const VISUAL_LOOK_UP: Self = Self(16);
384 pub const AUTOMATIC_TEXT_ONLY: Self = Self(32);
386
387 #[must_use]
388 pub const fn new(raw: u64) -> Self {
390 Self(raw)
391 }
392
393 #[must_use]
394 pub const fn bits(self) -> u64 {
396 self.0
397 }
398
399 #[must_use]
400 pub const fn contains(self, other: Self) -> bool {
402 (self.0 & other.0) == other.0
403 }
404}
405
406impl BitOr for LiveTextInteractionTypes {
407 type Output = Self;
408
409 fn bitor(self, rhs: Self) -> Self::Output {
410 Self(self.0 | rhs.0)
411 }
412}
413
414impl BitOrAssign for LiveTextInteractionTypes {
415 fn bitor_assign(&mut self, rhs: Self) {
416 self.0 |= rhs.0;
417 }
418}
419
420impl Default for LiveTextInteractionTypes {
421 fn default() -> Self {
422 Self::NONE
423 }
424}
425
426pub struct LiveTextContentView {
428 token: *mut c_void,
429}
430
431impl Drop for LiveTextContentView {
432 fn drop(&mut self) {
433 if !self.token.is_null() {
434 unsafe { ffi::live_text_interaction::vk_live_text_content_view_release(self.token) };
435 self.token = ptr::null_mut();
436 }
437 }
438}
439
440impl LiveTextContentView {
441 pub fn new() -> Result<Self, VisionKitError> {
443 construct_token(|out_token, out_error_message| unsafe {
444 ffi::live_text_interaction::vk_live_text_content_view_new(out_token, out_error_message)
445 })
446 .map(Self::from_token)
447 }
448
449 pub fn frame(&self) -> Result<Rect, VisionKitError> {
451 query_rect_call(
452 "live text content view frame",
453 |out_x, out_y, out_width, out_height, out_error_message| unsafe {
454 ffi::live_text_interaction::vk_live_text_content_view_frame(
455 self.token,
456 out_x,
457 out_y,
458 out_width,
459 out_height,
460 out_error_message,
461 )
462 },
463 )
464 }
465
466 pub fn set_frame(&self, frame: Rect) -> Result<(), VisionKitError> {
468 let mut err_msg: *mut c_char = ptr::null_mut();
469 let status = unsafe {
470 ffi::live_text_interaction::vk_live_text_content_view_set_frame(
471 self.token,
472 frame.x,
473 frame.y,
474 frame.width,
475 frame.height,
476 &raw mut err_msg,
477 )
478 };
479 status_to_unit(status, err_msg)
480 }
481
482 pub(crate) fn raw_token(&self) -> *mut c_void {
483 self.token
484 }
485
486 fn from_token(token: *mut c_void) -> Self {
487 Self { token }
488 }
489}
490
491pub struct LiveTextTrackingImageView {
493 token: *mut c_void,
494}
495
496impl Drop for LiveTextTrackingImageView {
497 fn drop(&mut self) {
498 if !self.token.is_null() {
499 unsafe {
500 ffi::live_text_interaction::vk_live_text_tracking_image_view_release(self.token);
501 }
502 self.token = ptr::null_mut();
503 }
504 }
505}
506
507impl LiveTextTrackingImageView {
508 pub fn new() -> Result<Self, VisionKitError> {
510 construct_token(|out_token, out_error_message| unsafe {
511 ffi::live_text_interaction::vk_live_text_tracking_image_view_new(
512 out_token,
513 out_error_message,
514 )
515 })
516 .map(Self::from_token)
517 }
518
519 pub fn frame(&self) -> Result<Rect, VisionKitError> {
521 query_rect_call(
522 "live text tracking image view frame",
523 |out_x, out_y, out_width, out_height, out_error_message| unsafe {
524 ffi::live_text_interaction::vk_live_text_tracking_image_view_frame(
525 self.token,
526 out_x,
527 out_y,
528 out_width,
529 out_height,
530 out_error_message,
531 )
532 },
533 )
534 }
535
536 pub fn set_frame(&self, frame: Rect) -> Result<(), VisionKitError> {
538 let mut err_msg: *mut c_char = ptr::null_mut();
539 let status = unsafe {
540 ffi::live_text_interaction::vk_live_text_tracking_image_view_set_frame(
541 self.token,
542 frame.x,
543 frame.y,
544 frame.width,
545 frame.height,
546 &raw mut err_msg,
547 )
548 };
549 status_to_unit(status, err_msg)
550 }
551
552 pub fn set_image_at_path<P: AsRef<Path>>(&self, path: P) -> Result<(), VisionKitError> {
554 let path = path_to_cstring(path.as_ref())?;
555 let mut err_msg: *mut c_char = ptr::null_mut();
556 let status = unsafe {
557 ffi::live_text_interaction::vk_live_text_tracking_image_view_set_image_at_path(
558 self.token,
559 path.as_ptr(),
560 &raw mut err_msg,
561 )
562 };
563 status_to_unit(status, err_msg)
564 }
565
566 pub fn image_size(&self) -> Result<Option<Size>, VisionKitError> {
568 let mut has_image = 0;
569 let mut width = 0.0;
570 let mut height = 0.0;
571 let mut err_msg: *mut c_char = ptr::null_mut();
572 let status = unsafe {
573 ffi::live_text_interaction::vk_live_text_tracking_image_view_image_size(
574 self.token,
575 &raw mut has_image,
576 &raw mut width,
577 &raw mut height,
578 &raw mut err_msg,
579 )
580 };
581 if status == ffi::status::OK {
582 Ok((has_image != 0).then_some(Size { width, height }))
583 } else {
584 Err(unsafe { error_from_status(status, err_msg) })
585 }
586 }
587
588 pub(crate) fn raw_token(&self) -> *mut c_void {
589 self.token
590 }
591
592 fn from_token(token: *mut c_void) -> Self {
593 Self { token }
594 }
595}
596
597pub struct LiveTextInteractionDelegate {
599 token: *mut c_void,
600}
601
602impl Drop for LiveTextInteractionDelegate {
603 fn drop(&mut self) {
604 if !self.token.is_null() {
605 unsafe {
606 ffi::live_text_interaction::vk_live_text_interaction_delegate_release(self.token);
607 }
608 self.token = ptr::null_mut();
609 }
610 }
611}
612
613impl LiveTextInteractionDelegate {
614 pub fn new() -> Result<Self, VisionKitError> {
616 construct_token(|out_token, out_error_message| unsafe {
617 ffi::live_text_interaction::vk_live_text_interaction_delegate_new(
618 out_token,
619 out_error_message,
620 )
621 })
622 .map(Self::from_token)
623 }
624
625 pub fn should_begin(&self) -> Result<bool, VisionKitError> {
627 Ok(self.config()?.should_begin)
628 }
629
630 pub fn set_should_begin(&self, value: bool) -> Result<(), VisionKitError> {
632 let mut config = self.config()?;
633 config.should_begin = value;
634 self.set_config(&config)
635 }
636
637 pub fn contents_rect_override(&self) -> Result<Option<Rect>, VisionKitError> {
639 Ok(self.config()?.contents_rect)
640 }
641
642 pub fn set_contents_rect_override(&self, value: Option<Rect>) -> Result<(), VisionKitError> {
644 let mut config = self.config()?;
645 config.contents_rect = value;
646 self.set_config(&config)
647 }
648
649 pub fn content_view(&self) -> Result<Option<LiveTextContentView>, VisionKitError> {
651 optional_token_call(|out_token, out_error_message| unsafe {
652 ffi::live_text_interaction::vk_live_text_interaction_delegate_content_view(
653 self.token,
654 out_token,
655 out_error_message,
656 )
657 })
658 .map(|token| token.map(LiveTextContentView::from_token))
659 }
660
661 pub fn set_content_view(
663 &self,
664 value: Option<&LiveTextContentView>,
665 ) -> Result<(), VisionKitError> {
666 let mut err_msg: *mut c_char = ptr::null_mut();
667 let status = unsafe {
668 ffi::live_text_interaction::vk_live_text_interaction_delegate_set_content_view(
669 self.token,
670 value.map_or(ptr::null_mut(), LiveTextContentView::raw_token),
671 &raw mut err_msg,
672 )
673 };
674 status_to_unit(status, err_msg)
675 }
676
677 pub fn should_handle_key_down_event(&self) -> Result<bool, VisionKitError> {
679 Ok(self.config()?.should_handle_key_down_event)
680 }
681
682 pub fn set_should_handle_key_down_event(&self, value: bool) -> Result<(), VisionKitError> {
684 let mut config = self.config()?;
685 config.should_handle_key_down_event = value;
686 self.set_config(&config)
687 }
688
689 pub fn should_show_menu_for_event(&self) -> Result<bool, VisionKitError> {
691 Ok(self.config()?.should_show_menu_for_event)
692 }
693
694 pub fn set_should_show_menu_for_event(&self, value: bool) -> Result<(), VisionKitError> {
696 let mut config = self.config()?;
697 config.should_show_menu_for_event = value;
698 self.set_config(&config)
699 }
700
701 pub fn updated_menu(&self) -> Result<Option<LiveTextMenu>, VisionKitError> {
703 Ok(self.config()?.updated_menu)
704 }
705
706 pub fn set_updated_menu(&self, value: Option<&LiveTextMenu>) -> Result<(), VisionKitError> {
708 let mut config = self.config()?;
709 config.updated_menu = value.cloned();
710 self.set_config(&config)
711 }
712
713 pub fn recorded_events(&self) -> Result<Vec<LiveTextDelegateEvent>, VisionKitError> {
715 parse_json_call(
716 |out_json, out_error_message| unsafe {
717 ffi::live_text_interaction::vk_live_text_interaction_delegate_recorded_events_json(
718 self.token,
719 out_json,
720 out_error_message,
721 )
722 },
723 "live text interaction delegate recorded events",
724 )
725 }
726
727 pub fn clear_recorded_events(&self) -> Result<(), VisionKitError> {
729 let mut err_msg: *mut c_char = ptr::null_mut();
730 let status = unsafe {
731 ffi::live_text_interaction::vk_live_text_interaction_delegate_clear_recorded_events(
732 self.token,
733 &raw mut err_msg,
734 )
735 };
736 status_to_unit(status, err_msg)
737 }
738
739 pub(crate) fn raw_token(&self) -> *mut c_void {
740 self.token
741 }
742
743 fn from_token(token: *mut c_void) -> Self {
744 Self { token }
745 }
746
747 fn config(&self) -> Result<LiveTextInteractionDelegateConfigPayload, VisionKitError> {
748 parse_json_call(
749 |out_json, out_error_message| unsafe {
750 ffi::live_text_interaction::vk_live_text_interaction_delegate_config_json(
751 self.token,
752 out_json,
753 out_error_message,
754 )
755 },
756 "live text interaction delegate config",
757 )
758 }
759
760 fn set_config(
761 &self,
762 config: &LiveTextInteractionDelegateConfigPayload,
763 ) -> Result<(), VisionKitError> {
764 let config_json = json_cstring(config)?;
765 let mut err_msg: *mut c_char = ptr::null_mut();
766 let status = unsafe {
767 ffi::live_text_interaction::vk_live_text_interaction_delegate_set_config_json(
768 self.token,
769 config_json.as_ptr(),
770 &raw mut err_msg,
771 )
772 };
773 status_to_unit(status, err_msg)
774 }
775}
776
777pub struct LiveTextSubject {
779 token: *mut c_void,
780}
781
782impl Drop for LiveTextSubject {
783 fn drop(&mut self) {
784 if !self.token.is_null() {
785 unsafe { ffi::live_text_interaction::vk_live_text_subject_release(self.token) };
786 self.token = ptr::null_mut();
787 }
788 }
789}
790
791impl LiveTextSubject {
792 pub fn bounds(&self) -> Result<Rect, VisionKitError> {
794 query_rect_call(
795 "live text subject bounds",
796 |out_x, out_y, out_width, out_height, out_error_message| unsafe {
797 ffi::live_text_interaction::vk_live_text_subject_bounds(
798 self.token,
799 out_x,
800 out_y,
801 out_width,
802 out_height,
803 out_error_message,
804 )
805 },
806 )
807 }
808
809 pub fn image(&self) -> Result<LiveTextImageData, VisionKitError> {
811 query_image_data_call(
812 |out_bytes, out_len, out_width, out_height, out_error_message| unsafe {
813 ffi::live_text_interaction::vk_live_text_subject_png_data(
814 self.token,
815 out_bytes,
816 out_len,
817 out_width,
818 out_height,
819 out_error_message,
820 )
821 },
822 "live text subject image",
823 )
824 }
825
826 pub(crate) fn raw_token(&self) -> *mut c_void {
827 self.token
828 }
829
830 fn from_token(token: *mut c_void) -> Self {
831 Self { token }
832 }
833}
834
835pub struct LiveTextInteraction {
837 token: *mut c_void,
838}
839
840impl Drop for LiveTextInteraction {
841 fn drop(&mut self) {
842 if !self.token.is_null() {
843 unsafe { ffi::live_text_interaction::vk_live_text_interaction_release(self.token) };
844 self.token = ptr::null_mut();
845 }
846 }
847}
848
849impl LiveTextInteraction {
850 pub fn new() -> Result<Self, VisionKitError> {
852 construct_token(|out_token, out_error_message| unsafe {
853 ffi::live_text_interaction::vk_live_text_interaction_new(out_token, out_error_message)
854 })
855 .map(|token| Self { token })
856 }
857
858 #[cfg(feature = "async")]
859 #[allow(dead_code, reason = "used by the optional async API surface")]
860 pub(crate) fn raw_token(&self) -> *mut c_void {
861 self.token
862 }
863
864 pub fn with_delegate(delegate: &LiveTextInteractionDelegate) -> Result<Self, VisionKitError> {
866 construct_token(|out_token, out_error_message| unsafe {
867 ffi::live_text_interaction::vk_live_text_interaction_new_with_delegate(
868 delegate.raw_token(),
869 out_token,
870 out_error_message,
871 )
872 })
873 .map(|token| Self { token })
874 }
875
876 pub fn set_analysis(&self, analysis: &ImageAnalysis) -> Result<(), VisionKitError> {
878 let mut err_msg: *mut c_char = ptr::null_mut();
879 let status = unsafe {
880 ffi::live_text_interaction::vk_live_text_interaction_set_analysis(
881 self.token,
882 analysis.raw_token(),
883 &raw mut err_msg,
884 )
885 };
886 status_to_unit(status, err_msg)
887 }
888
889 pub fn track_image_at_path<P: AsRef<Path>>(&self, path: P) -> Result<(), VisionKitError> {
891 let path = path_to_cstring(path.as_ref())?;
892 let mut err_msg: *mut c_char = ptr::null_mut();
893 let status = unsafe {
894 ffi::live_text_interaction::vk_live_text_interaction_track_image_at_path(
895 self.token,
896 path.as_ptr(),
897 &raw mut err_msg,
898 )
899 };
900 status_to_unit(status, err_msg)
901 }
902
903 pub fn delegate(&self) -> Result<Option<LiveTextInteractionDelegate>, VisionKitError> {
905 self.query_optional_token(ffi::live_text_interaction::vk_live_text_interaction_delegate)
906 .map(|token| token.map(LiveTextInteractionDelegate::from_token))
907 }
908
909 pub fn set_delegate(
911 &self,
912 delegate: Option<&LiveTextInteractionDelegate>,
913 ) -> Result<(), VisionKitError> {
914 let mut err_msg: *mut c_char = ptr::null_mut();
915 let status = unsafe {
916 ffi::live_text_interaction::vk_live_text_interaction_set_delegate(
917 self.token,
918 delegate.map_or(ptr::null_mut(), LiveTextInteractionDelegate::raw_token),
919 &raw mut err_msg,
920 )
921 };
922 status_to_unit(status, err_msg)
923 }
924
925 pub fn preferred_interaction_types(&self) -> Result<LiveTextInteractionTypes, VisionKitError> {
927 self.query_types(
928 ffi::live_text_interaction::vk_live_text_interaction_preferred_interaction_types,
929 )
930 }
931
932 pub fn set_preferred_interaction_types(
934 &self,
935 interaction_types: LiveTextInteractionTypes,
936 ) -> Result<(), VisionKitError> {
937 let mut err_msg: *mut c_char = ptr::null_mut();
938 let status = unsafe {
939 ffi::live_text_interaction::vk_live_text_interaction_set_preferred_interaction_types(
940 self.token,
941 interaction_types.bits(),
942 &raw mut err_msg,
943 )
944 };
945 status_to_unit(status, err_msg)
946 }
947
948 pub fn active_interaction_types(&self) -> Result<LiveTextInteractionTypes, VisionKitError> {
950 self.query_types(
951 ffi::live_text_interaction::vk_live_text_interaction_active_interaction_types,
952 )
953 }
954
955 pub fn selectable_items_highlighted(&self) -> Result<bool, VisionKitError> {
957 self.query_bool(
958 ffi::live_text_interaction::vk_live_text_interaction_selectable_items_highlighted,
959 )
960 }
961
962 pub fn set_selectable_items_highlighted(&self, value: bool) -> Result<(), VisionKitError> {
964 self.set_bool(
965 value,
966 ffi::live_text_interaction::vk_live_text_interaction_set_selectable_items_highlighted,
967 )
968 }
969
970 pub fn tracking_image_view(&self) -> Result<Option<LiveTextTrackingImageView>, VisionKitError> {
972 self.query_optional_token(
973 ffi::live_text_interaction::vk_live_text_interaction_tracking_image_view,
974 )
975 .map(|token| token.map(LiveTextTrackingImageView::from_token))
976 }
977
978 pub fn set_tracking_image_view(
980 &self,
981 view: Option<&LiveTextTrackingImageView>,
982 ) -> Result<(), VisionKitError> {
983 let mut err_msg: *mut c_char = ptr::null_mut();
984 let status = unsafe {
985 ffi::live_text_interaction::vk_live_text_interaction_set_tracking_image_view(
986 self.token,
987 view.map_or(ptr::null_mut(), LiveTextTrackingImageView::raw_token),
988 &raw mut err_msg,
989 )
990 };
991 status_to_unit(status, err_msg)
992 }
993
994 pub fn has_active_text_selection(&self) -> Result<bool, VisionKitError> {
996 self.query_bool(
997 ffi::live_text_interaction::vk_live_text_interaction_has_active_text_selection,
998 )
999 }
1000
1001 pub fn reset_selection(&self) -> Result<(), VisionKitError> {
1003 let mut err_msg: *mut c_char = ptr::null_mut();
1004 let status = unsafe {
1005 ffi::live_text_interaction::vk_live_text_interaction_reset_selection(
1006 self.token,
1007 &raw mut err_msg,
1008 )
1009 };
1010 status_to_unit(status, err_msg)
1011 }
1012
1013 pub fn text(&self) -> Result<String, VisionKitError> {
1015 self.query_string(ffi::live_text_interaction::vk_live_text_interaction_text)
1016 }
1017
1018 pub fn selected_text(&self) -> Result<String, VisionKitError> {
1020 self.query_string(ffi::live_text_interaction::vk_live_text_interaction_selected_text)
1021 }
1022
1023 pub fn selected_attributed_text(&self) -> Result<LiveTextAttributedText, VisionKitError> {
1025 self.query_json(
1026 ffi::live_text_interaction::vk_live_text_interaction_selected_attributed_text_json,
1027 "live text interaction selected attributed text",
1028 )
1029 }
1030
1031 pub fn selected_ranges(&self) -> Result<Vec<LiveTextTextRange>, VisionKitError> {
1033 self.query_json(
1034 ffi::live_text_interaction::vk_live_text_interaction_selected_ranges_json,
1035 "live text interaction selected ranges",
1036 )
1037 }
1038
1039 pub fn set_selected_ranges(&self, ranges: &[LiveTextTextRange]) -> Result<(), VisionKitError> {
1041 self.set_json(
1042 ranges,
1043 ffi::live_text_interaction::vk_live_text_interaction_set_selected_ranges_json,
1044 )
1045 }
1046
1047 pub fn contents_rect(&self) -> Result<Rect, VisionKitError> {
1049 self.query_rect(ffi::live_text_interaction::vk_live_text_interaction_contents_rect)
1050 }
1051
1052 pub fn set_contents_rect_needs_update(&self) -> Result<(), VisionKitError> {
1054 let mut err_msg: *mut c_char = ptr::null_mut();
1055 let status = unsafe {
1056 ffi::live_text_interaction::vk_live_text_interaction_set_contents_rect_needs_update(
1057 self.token,
1058 &raw mut err_msg,
1059 )
1060 };
1061 status_to_unit(status, err_msg)
1062 }
1063
1064 pub fn has_interactive_item_at_point(&self, x: f64, y: f64) -> Result<bool, VisionKitError> {
1066 self.query_point_bool(
1067 x,
1068 y,
1069 ffi::live_text_interaction::vk_live_text_interaction_has_interactive_item_at_point,
1070 )
1071 }
1072
1073 pub fn has_text_at_point(&self, x: f64, y: f64) -> Result<bool, VisionKitError> {
1075 self.query_point_bool(
1076 x,
1077 y,
1078 ffi::live_text_interaction::vk_live_text_interaction_has_text_at_point,
1079 )
1080 }
1081
1082 pub fn has_data_detector_at_point(&self, x: f64, y: f64) -> Result<bool, VisionKitError> {
1084 self.query_point_bool(
1085 x,
1086 y,
1087 ffi::live_text_interaction::vk_live_text_interaction_has_data_detector_at_point,
1088 )
1089 }
1090
1091 pub fn has_supplementary_interface_at_point(
1093 &self,
1094 x: f64,
1095 y: f64,
1096 ) -> Result<bool, VisionKitError> {
1097 self.query_point_bool(
1098 x,
1099 y,
1100 ffi::live_text_interaction::vk_live_text_interaction_has_supplementary_interface_at_point,
1101 )
1102 }
1103
1104 pub fn analysis_has_text_at_point(&self, x: f64, y: f64) -> Result<bool, VisionKitError> {
1106 self.query_point_bool(
1107 x,
1108 y,
1109 ffi::live_text_interaction::vk_live_text_interaction_analysis_has_text_at_point,
1110 )
1111 }
1112
1113 pub fn live_text_button_visible(&self) -> Result<bool, VisionKitError> {
1115 self.query_bool(
1116 ffi::live_text_interaction::vk_live_text_interaction_live_text_button_visible,
1117 )
1118 }
1119
1120 pub fn is_supplementary_interface_hidden(&self) -> Result<bool, VisionKitError> {
1122 self.query_bool(
1123 ffi::live_text_interaction::vk_live_text_interaction_is_supplementary_interface_hidden,
1124 )
1125 }
1126
1127 pub fn set_supplementary_interface_hidden(
1129 &self,
1130 hidden: bool,
1131 animated: bool,
1132 ) -> Result<(), VisionKitError> {
1133 let mut err_msg: *mut c_char = ptr::null_mut();
1134 let status = unsafe {
1135 ffi::live_text_interaction::vk_live_text_interaction_set_supplementary_interface_hidden(
1136 self.token,
1137 i32::from(hidden),
1138 i32::from(animated),
1139 &raw mut err_msg,
1140 )
1141 };
1142 status_to_unit(status, err_msg)
1143 }
1144
1145 pub fn supplementary_interface_content_insets(&self) -> Result<EdgeInsets, VisionKitError> {
1147 let rect = self.query_rect(
1148 ffi::live_text_interaction::vk_live_text_interaction_supplementary_interface_content_insets,
1149 )?;
1150 Ok(EdgeInsets {
1151 top: rect.x,
1152 left: rect.y,
1153 bottom: rect.width,
1154 right: rect.height,
1155 })
1156 }
1157
1158 pub fn set_supplementary_interface_content_insets(
1160 &self,
1161 insets: EdgeInsets,
1162 ) -> Result<(), VisionKitError> {
1163 let mut err_msg: *mut c_char = ptr::null_mut();
1164 let status = unsafe {
1165 ffi::live_text_interaction::vk_live_text_interaction_set_supplementary_interface_content_insets(
1166 self.token,
1167 insets.top,
1168 insets.left,
1169 insets.bottom,
1170 insets.right,
1171 &raw mut err_msg,
1172 )
1173 };
1174 status_to_unit(status, err_msg)
1175 }
1176
1177 pub fn supplementary_interface_font(&self) -> Result<Option<LiveTextFont>, VisionKitError> {
1179 self.query_json(
1180 ffi::live_text_interaction::vk_live_text_interaction_supplementary_interface_font_json,
1181 "live text interaction supplementary interface font",
1182 )
1183 }
1184
1185 pub fn set_supplementary_interface_font(
1187 &self,
1188 font: Option<&LiveTextFont>,
1189 ) -> Result<(), VisionKitError> {
1190 let font_json = json_cstring(&font)?;
1191 let mut err_msg: *mut c_char = ptr::null_mut();
1192 let status = unsafe {
1193 ffi::live_text_interaction::vk_live_text_interaction_set_supplementary_interface_font_json(
1194 self.token,
1195 font_json.as_ptr(),
1196 &raw mut err_msg,
1197 )
1198 };
1199 status_to_unit(status, err_msg)
1200 }
1201
1202 pub fn begin_subject_analysis_if_necessary(&self) -> Result<(), VisionKitError> {
1204 let mut err_msg: *mut c_char = ptr::null_mut();
1205 let status = unsafe {
1206 ffi::live_text_interaction::vk_live_text_interaction_begin_subject_analysis_if_necessary(
1207 self.token,
1208 &raw mut err_msg,
1209 )
1210 };
1211 status_to_unit(status, err_msg)
1212 }
1213
1214 pub fn subjects(&self) -> Result<Vec<LiveTextSubject>, VisionKitError> {
1216 self.query_subjects(ffi::live_text_interaction::vk_live_text_interaction_subjects_json)
1217 }
1218
1219 pub fn highlighted_subjects(&self) -> Result<Vec<LiveTextSubject>, VisionKitError> {
1221 self.query_subjects(
1222 ffi::live_text_interaction::vk_live_text_interaction_highlighted_subjects_json,
1223 )
1224 }
1225
1226 pub fn set_highlighted_subjects(
1228 &self,
1229 subjects: &[LiveTextSubject],
1230 ) -> Result<(), VisionKitError> {
1231 let subjects_json = json_cstring(&subject_tokens(subjects))?;
1232 let mut err_msg: *mut c_char = ptr::null_mut();
1233 let status = unsafe {
1234 ffi::live_text_interaction::vk_live_text_interaction_set_highlighted_subjects_json(
1235 self.token,
1236 subjects_json.as_ptr(),
1237 &raw mut err_msg,
1238 )
1239 };
1240 status_to_unit(status, err_msg)
1241 }
1242
1243 pub fn subject_at_point(
1245 &self,
1246 x: f64,
1247 y: f64,
1248 ) -> Result<Option<LiveTextSubject>, VisionKitError> {
1249 let mut subject_json: *mut c_char = ptr::null_mut();
1250 let mut err_msg: *mut c_char = ptr::null_mut();
1251 let status = unsafe {
1252 ffi::live_text_interaction::vk_live_text_interaction_subject_at_json(
1253 self.token,
1254 x,
1255 y,
1256 &raw mut subject_json,
1257 &raw mut err_msg,
1258 )
1259 };
1260 if status == ffi::status::OK {
1261 let token: Option<u64> =
1262 unsafe { parse_json_ptr(subject_json, "live text interaction subject lookup") }?;
1263 Ok(token.map(token_from_u64).map(LiveTextSubject::from_token))
1264 } else {
1265 Err(unsafe { error_from_status(status, err_msg) })
1266 }
1267 }
1268
1269 pub fn image_for_subjects(
1271 &self,
1272 subjects: &[LiveTextSubject],
1273 ) -> Result<LiveTextImageData, VisionKitError> {
1274 let subjects_json = json_cstring(&subject_tokens(subjects))?;
1275 let mut bytes: *mut c_void = ptr::null_mut();
1276 let mut len = 0;
1277 let mut width = 0.0;
1278 let mut height = 0.0;
1279 let mut err_msg: *mut c_char = ptr::null_mut();
1280 let status = unsafe {
1281 ffi::live_text_interaction::vk_live_text_interaction_image_for_subjects_png_data(
1282 self.token,
1283 subjects_json.as_ptr(),
1284 &raw mut bytes,
1285 &raw mut len,
1286 &raw mut width,
1287 &raw mut height,
1288 &raw mut err_msg,
1289 )
1290 };
1291 if status == ffi::status::OK {
1292 Ok(LiveTextImageData {
1293 size: Size { width, height },
1294 png_data: unsafe {
1295 vec_from_buffer_ptr(
1296 bytes.cast::<u8>(),
1297 u64_to_usize(len, "live text interaction subject image")?,
1298 "live text interaction subject image",
1299 )
1300 }?,
1301 })
1302 } else {
1303 Err(unsafe { error_from_status(status, err_msg) })
1304 }
1305 }
1306
1307 fn query_bool(&self, query: BoolQueryFn) -> Result<bool, VisionKitError> {
1308 let mut value = 0;
1309 let mut err_msg: *mut c_char = ptr::null_mut();
1310 let status = unsafe { query(self.token, &raw mut value, &raw mut err_msg) };
1311 if status == ffi::status::OK {
1312 Ok(value != 0)
1313 } else {
1314 Err(unsafe { error_from_status(status, err_msg) })
1315 }
1316 }
1317
1318 fn set_bool(&self, value: bool, setter: BoolSetterFn) -> Result<(), VisionKitError> {
1319 let mut err_msg: *mut c_char = ptr::null_mut();
1320 let status = unsafe { setter(self.token, i32::from(value), &raw mut err_msg) };
1321 status_to_unit(status, err_msg)
1322 }
1323
1324 fn query_types(&self, query: TypesQueryFn) -> Result<LiveTextInteractionTypes, VisionKitError> {
1325 let mut raw = 0;
1326 let mut err_msg: *mut c_char = ptr::null_mut();
1327 let status = unsafe { query(self.token, &raw mut raw, &raw mut err_msg) };
1328 if status == ffi::status::OK {
1329 Ok(LiveTextInteractionTypes::new(raw))
1330 } else {
1331 Err(unsafe { error_from_status(status, err_msg) })
1332 }
1333 }
1334
1335 fn query_string(
1336 &self,
1337 query: unsafe extern "C" fn(*mut c_void, *mut *mut c_char, *mut *mut c_char) -> i32,
1338 ) -> Result<String, VisionKitError> {
1339 let mut value: *mut c_char = ptr::null_mut();
1340 let mut err_msg: *mut c_char = ptr::null_mut();
1341 let status = unsafe { query(self.token, &raw mut value, &raw mut err_msg) };
1342 if status == ffi::status::OK {
1343 unsafe { string_from_ptr(value, "live text interaction string") }
1344 } else {
1345 Err(unsafe { error_from_status(status, err_msg) })
1346 }
1347 }
1348
1349 fn query_json<T>(&self, query: JsonQueryFn, context: &str) -> Result<T, VisionKitError>
1350 where
1351 T: DeserializeOwned,
1352 {
1353 let mut value: *mut c_char = ptr::null_mut();
1354 let mut err_msg: *mut c_char = ptr::null_mut();
1355 let status = unsafe { query(self.token, &raw mut value, &raw mut err_msg) };
1356 if status == ffi::status::OK {
1357 unsafe { parse_json_ptr(value, context) }
1358 } else {
1359 Err(unsafe { error_from_status(status, err_msg) })
1360 }
1361 }
1362
1363 fn set_json<T>(&self, value: &T, setter: JsonSetterFn) -> Result<(), VisionKitError>
1364 where
1365 T: Serialize + ?Sized,
1366 {
1367 let json = json_cstring(value)?;
1368 let mut err_msg: *mut c_char = ptr::null_mut();
1369 let status = unsafe { setter(self.token, json.as_ptr(), &raw mut err_msg) };
1370 status_to_unit(status, err_msg)
1371 }
1372
1373 fn query_rect(&self, query: RectQueryFn) -> Result<Rect, VisionKitError> {
1374 query_rect_call(
1375 "live text interaction rect",
1376 |out_x, out_y, out_width, out_height, out_error_message| unsafe {
1377 query(
1378 self.token,
1379 out_x,
1380 out_y,
1381 out_width,
1382 out_height,
1383 out_error_message,
1384 )
1385 },
1386 )
1387 }
1388
1389 fn query_point_bool(
1390 &self,
1391 x: f64,
1392 y: f64,
1393 query: PointBoolQueryFn,
1394 ) -> Result<bool, VisionKitError> {
1395 let mut value = 0;
1396 let mut err_msg: *mut c_char = ptr::null_mut();
1397 let status = unsafe { query(self.token, x, y, &raw mut value, &raw mut err_msg) };
1398 if status == ffi::status::OK {
1399 Ok(value != 0)
1400 } else {
1401 Err(unsafe { error_from_status(status, err_msg) })
1402 }
1403 }
1404
1405 fn query_optional_token(
1406 &self,
1407 query: OptionalTokenQueryFn,
1408 ) -> Result<Option<*mut c_void>, VisionKitError> {
1409 optional_token_call(|out_token, out_error_message| unsafe {
1410 query(self.token, out_token, out_error_message)
1411 })
1412 }
1413
1414 fn query_subjects(&self, query: JsonQueryFn) -> Result<Vec<LiveTextSubject>, VisionKitError> {
1415 let tokens: Vec<u64> = self.query_json(query, "live text interaction subjects")?;
1416 Ok(tokens
1417 .into_iter()
1418 .map(token_from_u64)
1419 .map(LiveTextSubject::from_token)
1420 .collect())
1421 }
1422}
1423
1424fn parse_json_call<T, F>(mut call: F, context: &str) -> Result<T, VisionKitError>
1425where
1426 T: DeserializeOwned,
1427 F: FnMut(*mut *mut c_char, *mut *mut c_char) -> i32,
1428{
1429 let mut json: *mut c_char = ptr::null_mut();
1430 let mut err_msg: *mut c_char = ptr::null_mut();
1431 let status = call(&raw mut json, &raw mut err_msg);
1432 if status == ffi::status::OK {
1433 unsafe { parse_json_ptr(json, context) }
1434 } else {
1435 Err(unsafe { error_from_status(status, err_msg) })
1436 }
1437}
1438
1439fn construct_token(
1440 make: impl FnOnce(*mut *mut c_void, *mut *mut c_char) -> i32,
1441) -> Result<*mut c_void, VisionKitError> {
1442 let mut token: *mut c_void = ptr::null_mut();
1443 let mut err_msg: *mut c_char = ptr::null_mut();
1444 let status = make(&raw mut token, &raw mut err_msg);
1445 if status != ffi::status::OK {
1446 return Err(unsafe { error_from_status(status, err_msg) });
1447 }
1448 if token.is_null() {
1449 return Err(VisionKitError::Unknown(
1450 "Swift bridge returned no object".to_owned(),
1451 ));
1452 }
1453 Ok(token)
1454}
1455
1456fn optional_token_call<F>(mut call: F) -> Result<Option<*mut c_void>, VisionKitError>
1457where
1458 F: FnMut(*mut *mut c_void, *mut *mut c_char) -> i32,
1459{
1460 let mut token: *mut c_void = ptr::null_mut();
1461 let mut err_msg: *mut c_char = ptr::null_mut();
1462 let status = call(&raw mut token, &raw mut err_msg);
1463 if status == ffi::status::OK {
1464 Ok((!token.is_null()).then_some(token))
1465 } else {
1466 Err(unsafe { error_from_status(status, err_msg) })
1467 }
1468}
1469
1470fn query_rect_call<F>(context: &str, mut call: F) -> Result<Rect, VisionKitError>
1471where
1472 F: FnMut(*mut f64, *mut f64, *mut f64, *mut f64, *mut *mut c_char) -> i32,
1473{
1474 let mut x = 0.0;
1475 let mut y = 0.0;
1476 let mut width = 0.0;
1477 let mut height = 0.0;
1478 let mut err_msg: *mut c_char = ptr::null_mut();
1479 let status = call(
1480 &raw mut x,
1481 &raw mut y,
1482 &raw mut width,
1483 &raw mut height,
1484 &raw mut err_msg,
1485 );
1486 if status == ffi::status::OK {
1487 Ok(Rect {
1488 x,
1489 y,
1490 width,
1491 height,
1492 })
1493 } else {
1494 let _ = context;
1495 Err(unsafe { error_from_status(status, err_msg) })
1496 }
1497}
1498
1499fn query_image_data_call<F>(mut call: F, context: &str) -> Result<LiveTextImageData, VisionKitError>
1500where
1501 F: FnMut(*mut *mut c_void, *mut u64, *mut f64, *mut f64, *mut *mut c_char) -> i32,
1502{
1503 let mut bytes: *mut c_void = ptr::null_mut();
1504 let mut len = 0;
1505 let mut width = 0.0;
1506 let mut height = 0.0;
1507 let mut err_msg: *mut c_char = ptr::null_mut();
1508 let status = call(
1509 &raw mut bytes,
1510 &raw mut len,
1511 &raw mut width,
1512 &raw mut height,
1513 &raw mut err_msg,
1514 );
1515 if status == ffi::status::OK {
1516 Ok(LiveTextImageData {
1517 size: Size { width, height },
1518 png_data: unsafe {
1519 vec_from_buffer_ptr(bytes.cast::<u8>(), u64_to_usize(len, context)?, context)
1520 }?,
1521 })
1522 } else {
1523 Err(unsafe { error_from_status(status, err_msg) })
1524 }
1525}
1526
1527fn live_text_menu_tag_constants() -> Result<LiveTextMenuTagConstants, VisionKitError> {
1528 LIVE_TEXT_MENU_TAGS
1529 .get_or_init(|| {
1530 parse_json_call(
1531 |out_json, out_error_message| unsafe {
1532 ffi::live_text_interaction::vk_live_text_menu_tags_json(
1533 out_json,
1534 out_error_message,
1535 )
1536 },
1537 "live text menu tags",
1538 )
1539 })
1540 .clone()
1541}
1542
1543fn status_to_unit(status: i32, err_msg: *mut c_char) -> Result<(), VisionKitError> {
1544 if status == ffi::status::OK {
1545 Ok(())
1546 } else {
1547 Err(unsafe { error_from_status(status, err_msg) })
1548 }
1549}
1550
1551fn subject_tokens(subjects: &[LiveTextSubject]) -> Vec<u64> {
1552 subjects
1553 .iter()
1554 .map(|subject| token_to_u64(subject.raw_token()))
1555 .collect()
1556}
1557
1558fn token_to_u64(token: *mut c_void) -> u64 {
1559 token as usize as u64
1560}
1561
1562fn token_from_u64(token: u64) -> *mut c_void {
1563 usize::try_from(token).map_or(ptr::null_mut(), |value| value as *mut c_void)
1564}
1565
1566fn u64_to_usize(value: u64, context: &str) -> Result<usize, VisionKitError> {
1567 usize::try_from(value).map_err(|_| {
1568 VisionKitError::Unknown(format!(
1569 "{context} length exceeded this platform's address width"
1570 ))
1571 })
1572}