Skip to main content

visionkit/
live_text_interaction.rs

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)]
64/// Represents a point exchanged with VisionKit.
65pub struct Point {
66    /// Stores the VisionKit x value.
67    pub x: f64,
68    /// Stores the VisionKit y value.
69    pub y: f64,
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
73/// Represents a rectangle exchanged with VisionKit.
74pub struct Rect {
75    /// Stores the VisionKit x value.
76    pub x: f64,
77    /// Stores the VisionKit y value.
78    pub y: f64,
79    /// Stores the VisionKit width value.
80    pub width: f64,
81    /// Stores the VisionKit height value.
82    pub height: f64,
83}
84
85impl Rect {
86    #[must_use]
87    /// Returns whether this VisionKit `Rect` value is empty.
88    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)]
94/// Represents a size reported by VisionKit.
95pub struct Size {
96    /// Stores the VisionKit width value.
97    pub width: f64,
98    /// Stores the VisionKit height value.
99    pub height: f64,
100}
101
102impl Size {
103    #[must_use]
104    /// Returns whether this VisionKit `Size` value is empty.
105    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)]
111/// Represents edge insets used by VisionKit.
112pub struct EdgeInsets {
113    /// Stores the VisionKit top value.
114    pub top: f64,
115    /// Stores the VisionKit left value.
116    pub left: f64,
117    /// Stores the VisionKit bottom value.
118    pub bottom: f64,
119    /// Stores the VisionKit right value.
120    pub right: f64,
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
124#[serde(rename_all = "camelCase")]
125/// Represents a text range reported by VisionKit.
126pub struct LiveTextTextRange {
127    /// Stores the VisionKit location value.
128    pub location: usize,
129    /// Stores the VisionKit length value.
130    pub length: usize,
131}
132
133impl LiveTextTextRange {
134    #[must_use]
135    /// Creates the VisionKit `LiveTextTextRange` wrapper.
136    pub const fn new(location: usize, length: usize) -> Self {
137        Self { location, length }
138    }
139
140    #[must_use]
141    /// Returns the end offset derived from the VisionKit text range.
142    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")]
149/// Represents a VisionKit attributed-text attribute.
150pub struct LiveTextAttributedTextAttribute {
151    /// Stores the VisionKit name value.
152    pub name: String,
153    /// Stores the VisionKit value value.
154    pub value: String,
155}
156
157#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
158#[serde(rename_all = "camelCase")]
159/// Represents a VisionKit attributed-text run.
160pub struct LiveTextAttributedTextRun {
161    /// Stores the VisionKit range value.
162    pub range: LiveTextTextRange,
163    /// Stores the VisionKit attributes value.
164    pub attributes: Vec<LiveTextAttributedTextAttribute>,
165}
166
167#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
168#[serde(rename_all = "camelCase")]
169/// Represents VisionKit selected attributed text.
170pub struct LiveTextAttributedText {
171    /// Stores the VisionKit text value.
172    pub text: String,
173    /// Stores the VisionKit runs value.
174    pub runs: Vec<LiveTextAttributedTextRun>,
175}
176
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
178#[serde(transparent)]
179/// Wraps a VisionKit live text menu tag.
180pub struct LiveTextMenuTag(i64);
181
182impl LiveTextMenuTag {
183    #[must_use]
184    /// Creates the VisionKit `LiveTextMenuTag` wrapper.
185    pub const fn new(raw_value: i64) -> Self {
186        Self(raw_value)
187    }
188
189    #[must_use]
190    /// Returns the raw VisionKit menu-tag value.
191    pub const fn raw_value(self) -> i64 {
192        self.0
193    }
194
195    /// Returns the VisionKit menu tag for copying an image.
196    pub fn copy_image() -> Result<Self, VisionKitError> {
197        Ok(Self(live_text_menu_tag_constants()?.copy_image))
198    }
199
200    /// Returns the VisionKit menu tag for sharing an image.
201    pub fn share_image() -> Result<Self, VisionKitError> {
202        Ok(Self(live_text_menu_tag_constants()?.share_image))
203    }
204
205    /// Returns the VisionKit menu tag for copying a subject.
206    pub fn copy_subject() -> Result<Self, VisionKitError> {
207        Ok(Self(live_text_menu_tag_constants()?.copy_subject))
208    }
209
210    /// Returns the VisionKit menu tag for sharing a subject.
211    pub fn share_subject() -> Result<Self, VisionKitError> {
212        Ok(Self(live_text_menu_tag_constants()?.share_subject))
213    }
214
215    /// Returns the VisionKit menu tag for looking up an item.
216    pub fn lookup_item() -> Result<Self, VisionKitError> {
217        Ok(Self(live_text_menu_tag_constants()?.lookup_item))
218    }
219
220    /// Returns the VisionKit menu tag for recommended app items.
221    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")]
228/// Represents a VisionKit live text menu item.
229pub struct LiveTextMenuItem {
230    /// Stores the VisionKit title value.
231    pub title: String,
232    /// Stores the VisionKit tag value.
233    pub tag: i64,
234    /// Indicates whether VisionKit reports this value is separator.
235    pub is_separator: bool,
236    /// Indicates whether VisionKit reports this value is enabled.
237    pub is_enabled: bool,
238    /// Indicates whether VisionKit reports this value is hidden.
239    pub is_hidden: bool,
240    /// Stores the VisionKit state value.
241    pub state: i64,
242    /// Stores the VisionKit submenu value.
243    pub submenu: Option<Box<LiveTextMenu>>,
244}
245
246#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
247#[serde(rename_all = "camelCase")]
248/// Represents a VisionKit live text menu.
249pub struct LiveTextMenu {
250    /// Stores the VisionKit title value.
251    pub title: String,
252    /// Stores the VisionKit items value.
253    pub items: Vec<LiveTextMenuItem>,
254}
255
256#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
257#[serde(rename_all = "camelCase")]
258/// Represents VisionKit event details captured by the live text delegate.
259pub struct LiveTextEventInfo {
260    /// Stores the VisionKit type name value.
261    pub type_name: String,
262    /// Stores the VisionKit location in window value.
263    pub location_in_window: Point,
264    /// Stores the VisionKit modifier flags value.
265    pub modifier_flags: u64,
266    /// Stores the VisionKit key code value.
267    pub key_code: u16,
268    /// Stores the VisionKit characters value.
269    pub characters: Option<String>,
270    /// Stores the VisionKit characters ignoring modifiers value.
271    pub characters_ignoring_modifiers: Option<String>,
272    /// Stores the VisionKit click count value.
273    pub click_count: i64,
274}
275
276#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
277#[serde(rename_all = "camelCase")]
278/// Represents a VisionKit live text delegate callback event.
279pub struct LiveTextDelegateEvent {
280    /// Stores the VisionKit kind value.
281    pub kind: String,
282    /// Stores the VisionKit point value.
283    pub point: Option<Point>,
284    /// Stores the VisionKit analysis type raw value.
285    pub analysis_type_raw: Option<u64>,
286    /// Stores the VisionKit decision value.
287    pub decision: Option<bool>,
288    /// Stores the VisionKit rect value.
289    pub rect: Option<Rect>,
290    /// Stores the VisionKit event value.
291    pub event: Option<LiveTextEventInfo>,
292    /// Stores the VisionKit menu value.
293    pub menu: Option<LiveTextMenu>,
294    /// Stores the VisionKit menu item value.
295    pub menu_item: Option<LiveTextMenuItem>,
296    /// Stores the VisionKit visible value.
297    pub visible: Option<bool>,
298    /// Stores the VisionKit highlighted value.
299    pub highlighted: Option<bool>,
300    /// Indicates whether VisionKit reports this value has content view.
301    pub has_content_view: Option<bool>,
302}
303
304#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
305#[serde(rename_all = "camelCase")]
306/// Represents a VisionKit font value.
307pub struct LiveTextFont {
308    /// Stores the VisionKit name value.
309    pub name: String,
310    /// Stores the VisionKit point size value.
311    pub point_size: f64,
312}
313
314#[derive(Debug, Clone, PartialEq)]
315/// Represents image data returned by VisionKit.
316pub struct LiveTextImageData {
317    /// Stores the VisionKit size value.
318    pub size: Size,
319    /// Stores the VisionKit png data value.
320    pub png_data: Vec<u8>,
321}
322
323impl LiveTextImageData {
324    #[must_use]
325    /// Returns whether this VisionKit `LiveTextImageData` value is empty.
326    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)]
368/// Wraps VisionKit live text interaction type flags.
369pub struct LiveTextInteractionTypes(u64);
370
371impl LiveTextInteractionTypes {
372    /// Matches the empty VisionKit `LiveTextInteractionTypes` flag set.
373    pub const NONE: Self = Self(0);
374    /// Matches the VisionKit `AUTOMATIC` flag.
375    pub const AUTOMATIC: Self = Self(1);
376    /// Matches the VisionKit `TEXT_SELECTION` flag.
377    pub const TEXT_SELECTION: Self = Self(2);
378    /// Matches the VisionKit `DATA_DETECTORS` flag.
379    pub const DATA_DETECTORS: Self = Self(4);
380    /// Matches the VisionKit `IMAGE_SUBJECT` flag.
381    pub const IMAGE_SUBJECT: Self = Self(8);
382    /// Matches the VisionKit `VISUAL_LOOK_UP` flag.
383    pub const VISUAL_LOOK_UP: Self = Self(16);
384    /// Matches the VisionKit `AUTOMATIC_TEXT_ONLY` flag.
385    pub const AUTOMATIC_TEXT_ONLY: Self = Self(32);
386
387    #[must_use]
388    /// Creates the VisionKit `LiveTextInteractionTypes` wrapper.
389    pub const fn new(raw: u64) -> Self {
390        Self(raw)
391    }
392
393    #[must_use]
394    /// Returns the raw VisionKit `LiveTextInteractionTypes` value.
395    pub const fn bits(self) -> u64 {
396        self.0
397    }
398
399    #[must_use]
400    /// Returns whether this VisionKit `LiveTextInteractionTypes` value contains `other`.
401    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
426/// Wraps the VisionKit content view counterpart used with live text.
427pub 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    /// Creates the VisionKit `LiveTextContentView` wrapper.
442    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    /// Returns the VisionKit frame value.
450    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    /// Sets the VisionKit frame value.
467    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
491/// Wraps the VisionKit tracking image view counterpart.
492pub 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    /// Creates the VisionKit `LiveTextTrackingImageView` wrapper.
509    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    /// Returns the VisionKit frame value.
520    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    /// Sets the VisionKit frame value.
537    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    /// Sets the VisionKit image at path value.
553    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    /// Returns the VisionKit image size value.
567    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
597/// Wraps the VisionKit live text interaction delegate counterpart.
598pub 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    /// Creates the VisionKit `LiveTextInteractionDelegate` wrapper.
615    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    /// Returns whether VisionKit should begin.
626    pub fn should_begin(&self) -> Result<bool, VisionKitError> {
627        Ok(self.config()?.should_begin)
628    }
629
630    /// Sets the VisionKit should begin value.
631    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    /// Returns the VisionKit contents rect override value.
638    pub fn contents_rect_override(&self) -> Result<Option<Rect>, VisionKitError> {
639        Ok(self.config()?.contents_rect)
640    }
641
642    /// Sets the VisionKit contents rect override value.
643    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    /// Returns the VisionKit content view value.
650    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    /// Sets the VisionKit content view value.
662    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    /// Returns whether VisionKit should handle key down event.
678    pub fn should_handle_key_down_event(&self) -> Result<bool, VisionKitError> {
679        Ok(self.config()?.should_handle_key_down_event)
680    }
681
682    /// Sets the VisionKit should handle key down event value.
683    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    /// Returns whether VisionKit should show menu for event.
690    pub fn should_show_menu_for_event(&self) -> Result<bool, VisionKitError> {
691        Ok(self.config()?.should_show_menu_for_event)
692    }
693
694    /// Sets the VisionKit should show menu for event value.
695    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    /// Returns the VisionKit updated menu value.
702    pub fn updated_menu(&self) -> Result<Option<LiveTextMenu>, VisionKitError> {
703        Ok(self.config()?.updated_menu)
704    }
705
706    /// Sets the VisionKit updated menu value.
707    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    /// Returns the VisionKit delegate events recorded by this wrapper.
714    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    /// Clears the recorded VisionKit delegate events.
728    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
777/// Wraps a VisionKit image subject.
778pub 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    /// Returns the VisionKit bounds value.
793    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    /// Returns the VisionKit image value.
810    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
835/// Wraps the VisionKit image analysis overlay view counterpart.
836pub 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    /// Creates the VisionKit `LiveTextInteraction` wrapper.
851    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    /// Creates the VisionKit live text interaction wrapper with the provided delegate.
865    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    /// Sets the VisionKit analysis value.
877    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    /// Tracks the image at `path` for the VisionKit live text interaction.
890    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    /// Returns the VisionKit delegate value.
904    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    /// Sets the VisionKit delegate value.
910    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    /// Returns the VisionKit preferred interaction types value.
926    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    /// Sets the VisionKit preferred interaction types value.
933    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    /// Returns the VisionKit active interaction types value.
949    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    /// Returns the VisionKit selectable items highlighted value.
956    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    /// Sets the VisionKit selectable items highlighted value.
963    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    /// Returns the VisionKit tracking image view value.
971    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    /// Sets the VisionKit tracking image view value.
979    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    /// Returns whether VisionKit reports active text selection.
995    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    /// Resets the VisionKit selection state.
1002    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    /// Returns the VisionKit text value.
1014    pub fn text(&self) -> Result<String, VisionKitError> {
1015        self.query_string(ffi::live_text_interaction::vk_live_text_interaction_text)
1016    }
1017
1018    /// Returns the VisionKit selected text value.
1019    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    /// Returns the VisionKit selected attributed text value.
1024    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    /// Returns the VisionKit selected ranges value.
1032    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    /// Sets the VisionKit selected ranges value.
1040    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    /// Returns the VisionKit contents rect value.
1048    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    /// Marks the VisionKit contents rectangle as needing an update.
1053    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    /// Returns whether VisionKit reports interactive item at point.
1065    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    /// Returns whether VisionKit reports text at point.
1074    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    /// Returns whether VisionKit reports data detector at point.
1083    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    /// Returns whether VisionKit reports supplementary interface at point.
1092    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    /// Returns the VisionKit analysis has text at point value.
1105    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    /// Returns the VisionKit live text button visible value.
1114    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    /// Returns whether VisionKit reports supplementary interface hidden.
1121    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    /// Sets the VisionKit supplementary interface hidden value.
1128    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    /// Returns the VisionKit supplementary interface content insets value.
1146    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    /// Sets the VisionKit supplementary interface content insets value.
1159    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    /// Returns the VisionKit supplementary interface font value.
1178    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    /// Sets the VisionKit supplementary interface font value.
1186    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    /// Begins VisionKit subject analysis when the overlay requires it.
1203    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    /// Returns the VisionKit subjects value.
1215    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    /// Returns the VisionKit highlighted subjects value.
1220    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    /// Sets the VisionKit highlighted subjects value.
1227    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    /// Returns the VisionKit subject at point value.
1244    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    /// Returns the VisionKit image extracted for the provided subjects.
1270    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}