visionkit-rs 0.3.3

Safe Rust bindings for VisionKit.framework — image analysis, Live Text, and availability-aware area coverage on macOS
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
use core::ffi::{c_char, c_void};
use core::ops::{BitOr, BitOrAssign};
use core::ptr;
use std::path::Path;
use std::sync::OnceLock;

use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};

use crate::error::VisionKitError;
use crate::ffi;
use crate::image_analysis::ImageAnalysis;
use crate::private::{
    error_from_status, json_cstring, parse_json_ptr, path_to_cstring, string_from_ptr,
    vec_from_buffer_ptr,
};

type BoolQueryFn = unsafe extern "C" fn(
    token: *mut c_void,
    out_value: *mut i32,
    out_error_message: *mut *mut c_char,
) -> i32;
type TypesQueryFn = unsafe extern "C" fn(
    token: *mut c_void,
    out_types_raw: *mut u64,
    out_error_message: *mut *mut c_char,
) -> i32;
type BoolSetterFn = unsafe extern "C" fn(
    token: *mut c_void,
    value: i32,
    out_error_message: *mut *mut c_char,
) -> i32;
type PointBoolQueryFn = unsafe extern "C" fn(
    token: *mut c_void,
    x: f64,
    y: f64,
    out_value: *mut i32,
    out_error_message: *mut *mut c_char,
) -> i32;
type RectQueryFn = unsafe extern "C" fn(
    token: *mut c_void,
    out_x: *mut f64,
    out_y: *mut f64,
    out_width: *mut f64,
    out_height: *mut f64,
    out_error_message: *mut *mut c_char,
) -> i32;
type JsonQueryFn = unsafe extern "C" fn(
    token: *mut c_void,
    out_json: *mut *mut c_char,
    out_error_message: *mut *mut c_char,
) -> i32;
type JsonSetterFn = unsafe extern "C" fn(
    token: *mut c_void,
    json: *const c_char,
    out_error_message: *mut *mut c_char,
) -> i32;
type OptionalTokenQueryFn = unsafe extern "C" fn(
    token: *mut c_void,
    out_token: *mut *mut c_void,
    out_error_message: *mut *mut c_char,
) -> i32;
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
/// Represents a point exchanged with VisionKit.
pub struct Point {
    /// Stores the VisionKit x value.
    pub x: f64,
    /// Stores the VisionKit y value.
    pub y: f64,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
/// Represents a rectangle exchanged with VisionKit.
pub struct Rect {
    /// Stores the VisionKit x value.
    pub x: f64,
    /// Stores the VisionKit y value.
    pub y: f64,
    /// Stores the VisionKit width value.
    pub width: f64,
    /// Stores the VisionKit height value.
    pub height: f64,
}

impl Rect {
    #[must_use]
    /// Returns whether this VisionKit `Rect` value is empty.
    pub fn is_empty(self) -> bool {
        self.width <= 0.0 || self.height <= 0.0
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
/// Represents a size reported by VisionKit.
pub struct Size {
    /// Stores the VisionKit width value.
    pub width: f64,
    /// Stores the VisionKit height value.
    pub height: f64,
}

impl Size {
    #[must_use]
    /// Returns whether this VisionKit `Size` value is empty.
    pub fn is_empty(self) -> bool {
        self.width <= 0.0 || self.height <= 0.0
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
/// Represents edge insets used by VisionKit.
pub struct EdgeInsets {
    /// Stores the VisionKit top value.
    pub top: f64,
    /// Stores the VisionKit left value.
    pub left: f64,
    /// Stores the VisionKit bottom value.
    pub bottom: f64,
    /// Stores the VisionKit right value.
    pub right: f64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
/// Represents a text range reported by VisionKit.
pub struct LiveTextTextRange {
    /// Stores the VisionKit location value.
    pub location: usize,
    /// Stores the VisionKit length value.
    pub length: usize,
}

impl LiveTextTextRange {
    #[must_use]
    /// Creates the VisionKit `LiveTextTextRange` wrapper.
    pub const fn new(location: usize, length: usize) -> Self {
        Self { location, length }
    }

    #[must_use]
    /// Returns the end offset derived from the VisionKit text range.
    pub const fn end(self) -> usize {
        self.location.saturating_add(self.length)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
/// Represents a VisionKit attributed-text attribute.
pub struct LiveTextAttributedTextAttribute {
    /// Stores the VisionKit name value.
    pub name: String,
    /// Stores the VisionKit value value.
    pub value: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
/// Represents a VisionKit attributed-text run.
pub struct LiveTextAttributedTextRun {
    /// Stores the VisionKit range value.
    pub range: LiveTextTextRange,
    /// Stores the VisionKit attributes value.
    pub attributes: Vec<LiveTextAttributedTextAttribute>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
/// Represents VisionKit selected attributed text.
pub struct LiveTextAttributedText {
    /// Stores the VisionKit text value.
    pub text: String,
    /// Stores the VisionKit runs value.
    pub runs: Vec<LiveTextAttributedTextRun>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
/// Wraps a VisionKit live text menu tag.
pub struct LiveTextMenuTag(i64);

impl LiveTextMenuTag {
    #[must_use]
    /// Creates the VisionKit `LiveTextMenuTag` wrapper.
    pub const fn new(raw_value: i64) -> Self {
        Self(raw_value)
    }

    #[must_use]
    /// Returns the raw VisionKit menu-tag value.
    pub const fn raw_value(self) -> i64 {
        self.0
    }

    /// Returns the VisionKit menu tag for copying an image.
    pub fn copy_image() -> Result<Self, VisionKitError> {
        Ok(Self(live_text_menu_tag_constants()?.copy_image))
    }

    /// Returns the VisionKit menu tag for sharing an image.
    pub fn share_image() -> Result<Self, VisionKitError> {
        Ok(Self(live_text_menu_tag_constants()?.share_image))
    }

    /// Returns the VisionKit menu tag for copying a subject.
    pub fn copy_subject() -> Result<Self, VisionKitError> {
        Ok(Self(live_text_menu_tag_constants()?.copy_subject))
    }

    /// Returns the VisionKit menu tag for sharing a subject.
    pub fn share_subject() -> Result<Self, VisionKitError> {
        Ok(Self(live_text_menu_tag_constants()?.share_subject))
    }

    /// Returns the VisionKit menu tag for looking up an item.
    pub fn lookup_item() -> Result<Self, VisionKitError> {
        Ok(Self(live_text_menu_tag_constants()?.lookup_item))
    }

    /// Returns the VisionKit menu tag for recommended app items.
    pub fn recommended_app_items() -> Result<Self, VisionKitError> {
        Ok(Self(live_text_menu_tag_constants()?.recommended_app_items))
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
/// Represents a VisionKit live text menu item.
pub struct LiveTextMenuItem {
    /// Stores the VisionKit title value.
    pub title: String,
    /// Stores the VisionKit tag value.
    pub tag: i64,
    /// Indicates whether VisionKit reports this value is separator.
    pub is_separator: bool,
    /// Indicates whether VisionKit reports this value is enabled.
    pub is_enabled: bool,
    /// Indicates whether VisionKit reports this value is hidden.
    pub is_hidden: bool,
    /// Stores the VisionKit state value.
    pub state: i64,
    /// Stores the VisionKit submenu value.
    pub submenu: Option<Box<LiveTextMenu>>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
/// Represents a VisionKit live text menu.
pub struct LiveTextMenu {
    /// Stores the VisionKit title value.
    pub title: String,
    /// Stores the VisionKit items value.
    pub items: Vec<LiveTextMenuItem>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
/// Represents VisionKit event details captured by the live text delegate.
pub struct LiveTextEventInfo {
    /// Stores the VisionKit type name value.
    pub type_name: String,
    /// Stores the VisionKit location in window value.
    pub location_in_window: Point,
    /// Stores the VisionKit modifier flags value.
    pub modifier_flags: u64,
    /// Stores the VisionKit key code value.
    pub key_code: u16,
    /// Stores the VisionKit characters value.
    pub characters: Option<String>,
    /// Stores the VisionKit characters ignoring modifiers value.
    pub characters_ignoring_modifiers: Option<String>,
    /// Stores the VisionKit click count value.
    pub click_count: i64,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
/// Represents a VisionKit live text delegate callback event.
pub struct LiveTextDelegateEvent {
    /// Stores the VisionKit kind value.
    pub kind: String,
    /// Stores the VisionKit point value.
    pub point: Option<Point>,
    /// Stores the VisionKit analysis type raw value.
    pub analysis_type_raw: Option<u64>,
    /// Stores the VisionKit decision value.
    pub decision: Option<bool>,
    /// Stores the VisionKit rect value.
    pub rect: Option<Rect>,
    /// Stores the VisionKit event value.
    pub event: Option<LiveTextEventInfo>,
    /// Stores the VisionKit menu value.
    pub menu: Option<LiveTextMenu>,
    /// Stores the VisionKit menu item value.
    pub menu_item: Option<LiveTextMenuItem>,
    /// Stores the VisionKit visible value.
    pub visible: Option<bool>,
    /// Stores the VisionKit highlighted value.
    pub highlighted: Option<bool>,
    /// Indicates whether VisionKit reports this value has content view.
    pub has_content_view: Option<bool>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
/// Represents a VisionKit font value.
pub struct LiveTextFont {
    /// Stores the VisionKit name value.
    pub name: String,
    /// Stores the VisionKit point size value.
    pub point_size: f64,
}

#[derive(Debug, Clone, PartialEq)]
/// Represents image data returned by VisionKit.
pub struct LiveTextImageData {
    /// Stores the VisionKit size value.
    pub size: Size,
    /// Stores the VisionKit png data value.
    pub png_data: Vec<u8>,
}

impl LiveTextImageData {
    #[must_use]
    /// Returns whether this VisionKit `LiveTextImageData` value is empty.
    pub fn is_empty(&self) -> bool {
        self.size.is_empty() || self.png_data.is_empty()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct LiveTextMenuTagConstants {
    copy_image: i64,
    share_image: i64,
    copy_subject: i64,
    share_subject: i64,
    lookup_item: i64,
    recommended_app_items: i64,
}

static LIVE_TEXT_MENU_TAGS: OnceLock<Result<LiveTextMenuTagConstants, VisionKitError>> =
    OnceLock::new();

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct LiveTextInteractionDelegateConfigPayload {
    should_begin: bool,
    contents_rect: Option<Rect>,
    should_handle_key_down_event: bool,
    should_show_menu_for_event: bool,
    updated_menu: Option<LiveTextMenu>,
}

impl Default for LiveTextInteractionDelegateConfigPayload {
    fn default() -> Self {
        Self {
            should_begin: true,
            contents_rect: None,
            should_handle_key_down_event: true,
            should_show_menu_for_event: true,
            updated_menu: None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
/// Wraps VisionKit live text interaction type flags.
pub struct LiveTextInteractionTypes(u64);

impl LiveTextInteractionTypes {
    /// Matches the empty VisionKit `LiveTextInteractionTypes` flag set.
    pub const NONE: Self = Self(0);
    /// Matches the VisionKit `AUTOMATIC` flag.
    pub const AUTOMATIC: Self = Self(1);
    /// Matches the VisionKit `TEXT_SELECTION` flag.
    pub const TEXT_SELECTION: Self = Self(2);
    /// Matches the VisionKit `DATA_DETECTORS` flag.
    pub const DATA_DETECTORS: Self = Self(4);
    /// Matches the VisionKit `IMAGE_SUBJECT` flag.
    pub const IMAGE_SUBJECT: Self = Self(8);
    /// Matches the VisionKit `VISUAL_LOOK_UP` flag.
    pub const VISUAL_LOOK_UP: Self = Self(16);
    /// Matches the VisionKit `AUTOMATIC_TEXT_ONLY` flag.
    pub const AUTOMATIC_TEXT_ONLY: Self = Self(32);

    #[must_use]
    /// Creates the VisionKit `LiveTextInteractionTypes` wrapper.
    pub const fn new(raw: u64) -> Self {
        Self(raw)
    }

    #[must_use]
    /// Returns the raw VisionKit `LiveTextInteractionTypes` value.
    pub const fn bits(self) -> u64 {
        self.0
    }

    #[must_use]
    /// Returns whether this VisionKit `LiveTextInteractionTypes` value contains `other`.
    pub const fn contains(self, other: Self) -> bool {
        (self.0 & other.0) == other.0
    }
}

impl BitOr for LiveTextInteractionTypes {
    type Output = Self;

    fn bitor(self, rhs: Self) -> Self::Output {
        Self(self.0 | rhs.0)
    }
}

impl BitOrAssign for LiveTextInteractionTypes {
    fn bitor_assign(&mut self, rhs: Self) {
        self.0 |= rhs.0;
    }
}

impl Default for LiveTextInteractionTypes {
    fn default() -> Self {
        Self::NONE
    }
}

/// Wraps the VisionKit content view counterpart used with live text.
pub struct LiveTextContentView {
    token: *mut c_void,
}

impl Drop for LiveTextContentView {
    fn drop(&mut self) {
        if !self.token.is_null() {
            unsafe { ffi::live_text_interaction::vk_live_text_content_view_release(self.token) };
            self.token = ptr::null_mut();
        }
    }
}

impl LiveTextContentView {
    /// Creates the VisionKit `LiveTextContentView` wrapper.
    pub fn new() -> Result<Self, VisionKitError> {
        let token = unsafe { ffi::live_text_interaction::vk_live_text_content_view_new() };
        if token.is_null() {
            return Err(VisionKitError::Unknown(
                "failed to allocate LiveTextContentView".to_owned(),
            ));
        }
        Ok(Self { token })
    }

    /// Returns the VisionKit frame value.
    pub fn frame(&self) -> Result<Rect, VisionKitError> {
        query_rect_call(
            "live text content view frame",
            |out_x, out_y, out_width, out_height, out_error_message| unsafe {
                ffi::live_text_interaction::vk_live_text_content_view_frame(
                    self.token,
                    out_x,
                    out_y,
                    out_width,
                    out_height,
                    out_error_message,
                )
            },
        )
    }

    /// Sets the VisionKit frame value.
    pub fn set_frame(&self, frame: Rect) -> Result<(), VisionKitError> {
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe {
            ffi::live_text_interaction::vk_live_text_content_view_set_frame(
                self.token,
                frame.x,
                frame.y,
                frame.width,
                frame.height,
                &mut err_msg,
            )
        };
        status_to_unit(status, err_msg)
    }

    pub(crate) fn raw_token(&self) -> *mut c_void {
        self.token
    }

    fn from_token(token: *mut c_void) -> Self {
        Self { token }
    }
}

/// Wraps the VisionKit tracking image view counterpart.
pub struct LiveTextTrackingImageView {
    token: *mut c_void,
}

impl Drop for LiveTextTrackingImageView {
    fn drop(&mut self) {
        if !self.token.is_null() {
            unsafe {
                ffi::live_text_interaction::vk_live_text_tracking_image_view_release(self.token);
            }
            self.token = ptr::null_mut();
        }
    }
}

impl LiveTextTrackingImageView {
    /// Creates the VisionKit `LiveTextTrackingImageView` wrapper.
    pub fn new() -> Result<Self, VisionKitError> {
        let token = unsafe { ffi::live_text_interaction::vk_live_text_tracking_image_view_new() };
        if token.is_null() {
            return Err(VisionKitError::Unknown(
                "failed to allocate LiveTextTrackingImageView".to_owned(),
            ));
        }
        Ok(Self { token })
    }

    /// Returns the VisionKit frame value.
    pub fn frame(&self) -> Result<Rect, VisionKitError> {
        query_rect_call(
            "live text tracking image view frame",
            |out_x, out_y, out_width, out_height, out_error_message| unsafe {
                ffi::live_text_interaction::vk_live_text_tracking_image_view_frame(
                    self.token,
                    out_x,
                    out_y,
                    out_width,
                    out_height,
                    out_error_message,
                )
            },
        )
    }

    /// Sets the VisionKit frame value.
    pub fn set_frame(&self, frame: Rect) -> Result<(), VisionKitError> {
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe {
            ffi::live_text_interaction::vk_live_text_tracking_image_view_set_frame(
                self.token,
                frame.x,
                frame.y,
                frame.width,
                frame.height,
                &mut err_msg,
            )
        };
        status_to_unit(status, err_msg)
    }

    /// Sets the VisionKit image at path value.
    pub fn set_image_at_path<P: AsRef<Path>>(&self, path: P) -> Result<(), VisionKitError> {
        let path = path_to_cstring(path.as_ref())?;
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe {
            ffi::live_text_interaction::vk_live_text_tracking_image_view_set_image_at_path(
                self.token,
                path.as_ptr(),
                &mut err_msg,
            )
        };
        status_to_unit(status, err_msg)
    }

    /// Returns the VisionKit image size value.
    pub fn image_size(&self) -> Result<Option<Size>, VisionKitError> {
        let mut has_image = 0;
        let mut width = 0.0;
        let mut height = 0.0;
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe {
            ffi::live_text_interaction::vk_live_text_tracking_image_view_image_size(
                self.token,
                &mut has_image,
                &mut width,
                &mut height,
                &mut err_msg,
            )
        };
        if status == ffi::status::OK {
            Ok((has_image != 0).then_some(Size { width, height }))
        } else {
            Err(unsafe { error_from_status(status, err_msg) })
        }
    }

    pub(crate) fn raw_token(&self) -> *mut c_void {
        self.token
    }

    fn from_token(token: *mut c_void) -> Self {
        Self { token }
    }
}

/// Wraps the VisionKit live text interaction delegate counterpart.
pub struct LiveTextInteractionDelegate {
    token: *mut c_void,
}

impl Drop for LiveTextInteractionDelegate {
    fn drop(&mut self) {
        if !self.token.is_null() {
            unsafe {
                ffi::live_text_interaction::vk_live_text_interaction_delegate_release(self.token);
            }
            self.token = ptr::null_mut();
        }
    }
}

impl LiveTextInteractionDelegate {
    /// Creates the VisionKit `LiveTextInteractionDelegate` wrapper.
    pub fn new() -> Result<Self, VisionKitError> {
        let token = unsafe { ffi::live_text_interaction::vk_live_text_interaction_delegate_new() };
        if token.is_null() {
            return Err(VisionKitError::UnavailableOnThisMacOS(
                "LiveTextInteractionDelegate requires macOS 13+".to_owned(),
            ));
        }
        Ok(Self { token })
    }

    /// Returns whether VisionKit should begin.
    pub fn should_begin(&self) -> Result<bool, VisionKitError> {
        Ok(self.config()?.should_begin)
    }

    /// Sets the VisionKit should begin value.
    pub fn set_should_begin(&self, value: bool) -> Result<(), VisionKitError> {
        let mut config = self.config()?;
        config.should_begin = value;
        self.set_config(&config)
    }

    /// Returns the VisionKit contents rect override value.
    pub fn contents_rect_override(&self) -> Result<Option<Rect>, VisionKitError> {
        Ok(self.config()?.contents_rect)
    }

    /// Sets the VisionKit contents rect override value.
    pub fn set_contents_rect_override(&self, value: Option<Rect>) -> Result<(), VisionKitError> {
        let mut config = self.config()?;
        config.contents_rect = value;
        self.set_config(&config)
    }

    /// Returns the VisionKit content view value.
    pub fn content_view(&self) -> Result<Option<LiveTextContentView>, VisionKitError> {
        optional_token_call(|out_token, out_error_message| unsafe {
            ffi::live_text_interaction::vk_live_text_interaction_delegate_content_view(
                self.token,
                out_token,
                out_error_message,
            )
        })
        .map(|token| token.map(LiveTextContentView::from_token))
    }

    /// Sets the VisionKit content view value.
    pub fn set_content_view(
        &self,
        value: Option<&LiveTextContentView>,
    ) -> Result<(), VisionKitError> {
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe {
            ffi::live_text_interaction::vk_live_text_interaction_delegate_set_content_view(
                self.token,
                value.map_or(ptr::null_mut(), LiveTextContentView::raw_token),
                &mut err_msg,
            )
        };
        status_to_unit(status, err_msg)
    }

    /// Returns whether VisionKit should handle key down event.
    pub fn should_handle_key_down_event(&self) -> Result<bool, VisionKitError> {
        Ok(self.config()?.should_handle_key_down_event)
    }

    /// Sets the VisionKit should handle key down event value.
    pub fn set_should_handle_key_down_event(&self, value: bool) -> Result<(), VisionKitError> {
        let mut config = self.config()?;
        config.should_handle_key_down_event = value;
        self.set_config(&config)
    }

    /// Returns whether VisionKit should show menu for event.
    pub fn should_show_menu_for_event(&self) -> Result<bool, VisionKitError> {
        Ok(self.config()?.should_show_menu_for_event)
    }

    /// Sets the VisionKit should show menu for event value.
    pub fn set_should_show_menu_for_event(&self, value: bool) -> Result<(), VisionKitError> {
        let mut config = self.config()?;
        config.should_show_menu_for_event = value;
        self.set_config(&config)
    }

    /// Returns the VisionKit updated menu value.
    pub fn updated_menu(&self) -> Result<Option<LiveTextMenu>, VisionKitError> {
        Ok(self.config()?.updated_menu)
    }

    /// Sets the VisionKit updated menu value.
    pub fn set_updated_menu(&self, value: Option<&LiveTextMenu>) -> Result<(), VisionKitError> {
        let mut config = self.config()?;
        config.updated_menu = value.cloned();
        self.set_config(&config)
    }

    /// Returns the VisionKit delegate events recorded by this wrapper.
    pub fn recorded_events(&self) -> Result<Vec<LiveTextDelegateEvent>, VisionKitError> {
        parse_json_call(
            |out_json, out_error_message| unsafe {
                ffi::live_text_interaction::vk_live_text_interaction_delegate_recorded_events_json(
                    self.token,
                    out_json,
                    out_error_message,
                )
            },
            "live text interaction delegate recorded events",
        )
    }

    /// Clears the recorded VisionKit delegate events.
    pub fn clear_recorded_events(&self) -> Result<(), VisionKitError> {
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe {
            ffi::live_text_interaction::vk_live_text_interaction_delegate_clear_recorded_events(
                self.token,
                &mut err_msg,
            )
        };
        status_to_unit(status, err_msg)
    }

    pub(crate) fn raw_token(&self) -> *mut c_void {
        self.token
    }

    fn from_token(token: *mut c_void) -> Self {
        Self { token }
    }

    fn config(&self) -> Result<LiveTextInteractionDelegateConfigPayload, VisionKitError> {
        parse_json_call(
            |out_json, out_error_message| unsafe {
                ffi::live_text_interaction::vk_live_text_interaction_delegate_config_json(
                    self.token,
                    out_json,
                    out_error_message,
                )
            },
            "live text interaction delegate config",
        )
    }

    fn set_config(
        &self,
        config: &LiveTextInteractionDelegateConfigPayload,
    ) -> Result<(), VisionKitError> {
        let config_json = json_cstring(config)?;
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe {
            ffi::live_text_interaction::vk_live_text_interaction_delegate_set_config_json(
                self.token,
                config_json.as_ptr(),
                &mut err_msg,
            )
        };
        status_to_unit(status, err_msg)
    }
}

/// Wraps a VisionKit image subject.
pub struct LiveTextSubject {
    token: *mut c_void,
}

impl Drop for LiveTextSubject {
    fn drop(&mut self) {
        if !self.token.is_null() {
            unsafe { ffi::live_text_interaction::vk_live_text_subject_release(self.token) };
            self.token = ptr::null_mut();
        }
    }
}

impl LiveTextSubject {
    /// Returns the VisionKit bounds value.
    pub fn bounds(&self) -> Result<Rect, VisionKitError> {
        query_rect_call(
            "live text subject bounds",
            |out_x, out_y, out_width, out_height, out_error_message| unsafe {
                ffi::live_text_interaction::vk_live_text_subject_bounds(
                    self.token,
                    out_x,
                    out_y,
                    out_width,
                    out_height,
                    out_error_message,
                )
            },
        )
    }

    /// Returns the VisionKit image value.
    pub fn image(&self) -> Result<LiveTextImageData, VisionKitError> {
        query_image_data_call(
            |out_bytes, out_len, out_width, out_height, out_error_message| unsafe {
                ffi::live_text_interaction::vk_live_text_subject_png_data(
                    self.token,
                    out_bytes,
                    out_len,
                    out_width,
                    out_height,
                    out_error_message,
                )
            },
            "live text subject image",
        )
    }

    pub(crate) fn raw_token(&self) -> *mut c_void {
        self.token
    }

    fn from_token(token: *mut c_void) -> Self {
        Self { token }
    }
}

/// Wraps the VisionKit image analysis overlay view counterpart.
pub struct LiveTextInteraction {
    token: *mut c_void,
}

impl Drop for LiveTextInteraction {
    fn drop(&mut self) {
        if !self.token.is_null() {
            unsafe { ffi::live_text_interaction::vk_live_text_interaction_release(self.token) };
            self.token = ptr::null_mut();
        }
    }
}

impl LiveTextInteraction {
    /// Creates the VisionKit `LiveTextInteraction` wrapper.
    pub fn new() -> Result<Self, VisionKitError> {
        let token = unsafe { ffi::live_text_interaction::vk_live_text_interaction_new() };
        if token.is_null() {
            return Err(VisionKitError::UnavailableOnThisMacOS(
                "LiveTextInteraction requires macOS 13+".to_owned(),
            ));
        }
        Ok(Self { token })
    }

    pub(crate) fn raw_token(&self) -> *mut c_void {
        self.token
    }

    /// Creates the VisionKit live text interaction wrapper with the provided delegate.
    pub fn with_delegate(delegate: &LiveTextInteractionDelegate) -> Result<Self, VisionKitError> {
        let token = unsafe {
            ffi::live_text_interaction::vk_live_text_interaction_new_with_delegate(
                delegate.raw_token(),
            )
        };
        if token.is_null() {
            return Err(VisionKitError::UnavailableOnThisMacOS(
                "LiveTextInteraction requires macOS 13+".to_owned(),
            ));
        }
        Ok(Self { token })
    }

    /// Sets the VisionKit analysis value.
    pub fn set_analysis(&self, analysis: &ImageAnalysis) -> Result<(), VisionKitError> {
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe {
            ffi::live_text_interaction::vk_live_text_interaction_set_analysis(
                self.token,
                analysis.raw_token(),
                &mut err_msg,
            )
        };
        status_to_unit(status, err_msg)
    }

    /// Tracks the image at `path` for the VisionKit live text interaction.
    pub fn track_image_at_path<P: AsRef<Path>>(&self, path: P) -> Result<(), VisionKitError> {
        let path = path_to_cstring(path.as_ref())?;
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe {
            ffi::live_text_interaction::vk_live_text_interaction_track_image_at_path(
                self.token,
                path.as_ptr(),
                &mut err_msg,
            )
        };
        status_to_unit(status, err_msg)
    }

    /// Returns the VisionKit delegate value.
    pub fn delegate(&self) -> Result<Option<LiveTextInteractionDelegate>, VisionKitError> {
        self.query_optional_token(ffi::live_text_interaction::vk_live_text_interaction_delegate)
            .map(|token| token.map(LiveTextInteractionDelegate::from_token))
    }

    /// Sets the VisionKit delegate value.
    pub fn set_delegate(
        &self,
        delegate: Option<&LiveTextInteractionDelegate>,
    ) -> Result<(), VisionKitError> {
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe {
            ffi::live_text_interaction::vk_live_text_interaction_set_delegate(
                self.token,
                delegate.map_or(ptr::null_mut(), LiveTextInteractionDelegate::raw_token),
                &mut err_msg,
            )
        };
        status_to_unit(status, err_msg)
    }

    /// Returns the VisionKit preferred interaction types value.
    pub fn preferred_interaction_types(&self) -> Result<LiveTextInteractionTypes, VisionKitError> {
        self.query_types(
            ffi::live_text_interaction::vk_live_text_interaction_preferred_interaction_types,
        )
    }

    /// Sets the VisionKit preferred interaction types value.
    pub fn set_preferred_interaction_types(
        &self,
        interaction_types: LiveTextInteractionTypes,
    ) -> Result<(), VisionKitError> {
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe {
            ffi::live_text_interaction::vk_live_text_interaction_set_preferred_interaction_types(
                self.token,
                interaction_types.bits(),
                &mut err_msg,
            )
        };
        status_to_unit(status, err_msg)
    }

    /// Returns the VisionKit active interaction types value.
    pub fn active_interaction_types(&self) -> Result<LiveTextInteractionTypes, VisionKitError> {
        self.query_types(
            ffi::live_text_interaction::vk_live_text_interaction_active_interaction_types,
        )
    }

    /// Returns the VisionKit selectable items highlighted value.
    pub fn selectable_items_highlighted(&self) -> Result<bool, VisionKitError> {
        self.query_bool(
            ffi::live_text_interaction::vk_live_text_interaction_selectable_items_highlighted,
        )
    }

    /// Sets the VisionKit selectable items highlighted value.
    pub fn set_selectable_items_highlighted(&self, value: bool) -> Result<(), VisionKitError> {
        self.set_bool(
            value,
            ffi::live_text_interaction::vk_live_text_interaction_set_selectable_items_highlighted,
        )
    }

    /// Returns the VisionKit tracking image view value.
    pub fn tracking_image_view(&self) -> Result<Option<LiveTextTrackingImageView>, VisionKitError> {
        self.query_optional_token(
            ffi::live_text_interaction::vk_live_text_interaction_tracking_image_view,
        )
        .map(|token| token.map(LiveTextTrackingImageView::from_token))
    }

    /// Sets the VisionKit tracking image view value.
    pub fn set_tracking_image_view(
        &self,
        view: Option<&LiveTextTrackingImageView>,
    ) -> Result<(), VisionKitError> {
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe {
            ffi::live_text_interaction::vk_live_text_interaction_set_tracking_image_view(
                self.token,
                view.map_or(ptr::null_mut(), LiveTextTrackingImageView::raw_token),
                &mut err_msg,
            )
        };
        status_to_unit(status, err_msg)
    }

    /// Returns whether VisionKit reports active text selection.
    pub fn has_active_text_selection(&self) -> Result<bool, VisionKitError> {
        self.query_bool(
            ffi::live_text_interaction::vk_live_text_interaction_has_active_text_selection,
        )
    }

    /// Resets the VisionKit selection state.
    pub fn reset_selection(&self) -> Result<(), VisionKitError> {
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe {
            ffi::live_text_interaction::vk_live_text_interaction_reset_selection(
                self.token,
                &mut err_msg,
            )
        };
        status_to_unit(status, err_msg)
    }

    /// Returns the VisionKit text value.
    pub fn text(&self) -> Result<String, VisionKitError> {
        self.query_string(ffi::live_text_interaction::vk_live_text_interaction_text)
    }

    /// Returns the VisionKit selected text value.
    pub fn selected_text(&self) -> Result<String, VisionKitError> {
        self.query_string(ffi::live_text_interaction::vk_live_text_interaction_selected_text)
    }

    /// Returns the VisionKit selected attributed text value.
    pub fn selected_attributed_text(&self) -> Result<LiveTextAttributedText, VisionKitError> {
        self.query_json(
            ffi::live_text_interaction::vk_live_text_interaction_selected_attributed_text_json,
            "live text interaction selected attributed text",
        )
    }

    /// Returns the VisionKit selected ranges value.
    pub fn selected_ranges(&self) -> Result<Vec<LiveTextTextRange>, VisionKitError> {
        self.query_json(
            ffi::live_text_interaction::vk_live_text_interaction_selected_ranges_json,
            "live text interaction selected ranges",
        )
    }

    /// Sets the VisionKit selected ranges value.
    pub fn set_selected_ranges(&self, ranges: &[LiveTextTextRange]) -> Result<(), VisionKitError> {
        self.set_json(
            ranges,
            ffi::live_text_interaction::vk_live_text_interaction_set_selected_ranges_json,
        )
    }

    /// Returns the VisionKit contents rect value.
    pub fn contents_rect(&self) -> Result<Rect, VisionKitError> {
        self.query_rect(ffi::live_text_interaction::vk_live_text_interaction_contents_rect)
    }

    /// Marks the VisionKit contents rectangle as needing an update.
    pub fn set_contents_rect_needs_update(&self) -> Result<(), VisionKitError> {
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe {
            ffi::live_text_interaction::vk_live_text_interaction_set_contents_rect_needs_update(
                self.token,
                &mut err_msg,
            )
        };
        status_to_unit(status, err_msg)
    }

    /// Returns whether VisionKit reports interactive item at point.
    pub fn has_interactive_item_at_point(&self, x: f64, y: f64) -> Result<bool, VisionKitError> {
        self.query_point_bool(
            x,
            y,
            ffi::live_text_interaction::vk_live_text_interaction_has_interactive_item_at_point,
        )
    }

    /// Returns whether VisionKit reports text at point.
    pub fn has_text_at_point(&self, x: f64, y: f64) -> Result<bool, VisionKitError> {
        self.query_point_bool(
            x,
            y,
            ffi::live_text_interaction::vk_live_text_interaction_has_text_at_point,
        )
    }

    /// Returns whether VisionKit reports data detector at point.
    pub fn has_data_detector_at_point(&self, x: f64, y: f64) -> Result<bool, VisionKitError> {
        self.query_point_bool(
            x,
            y,
            ffi::live_text_interaction::vk_live_text_interaction_has_data_detector_at_point,
        )
    }

    /// Returns whether VisionKit reports supplementary interface at point.
    pub fn has_supplementary_interface_at_point(
        &self,
        x: f64,
        y: f64,
    ) -> Result<bool, VisionKitError> {
        self.query_point_bool(
            x,
            y,
            ffi::live_text_interaction::vk_live_text_interaction_has_supplementary_interface_at_point,
        )
    }

    /// Returns the VisionKit analysis has text at point value.
    pub fn analysis_has_text_at_point(&self, x: f64, y: f64) -> Result<bool, VisionKitError> {
        self.query_point_bool(
            x,
            y,
            ffi::live_text_interaction::vk_live_text_interaction_analysis_has_text_at_point,
        )
    }

    /// Returns the VisionKit live text button visible value.
    pub fn live_text_button_visible(&self) -> Result<bool, VisionKitError> {
        self.query_bool(
            ffi::live_text_interaction::vk_live_text_interaction_live_text_button_visible,
        )
    }

    /// Returns whether VisionKit reports supplementary interface hidden.
    pub fn is_supplementary_interface_hidden(&self) -> Result<bool, VisionKitError> {
        self.query_bool(
            ffi::live_text_interaction::vk_live_text_interaction_is_supplementary_interface_hidden,
        )
    }

    /// Sets the VisionKit supplementary interface hidden value.
    pub fn set_supplementary_interface_hidden(
        &self,
        hidden: bool,
        animated: bool,
    ) -> Result<(), VisionKitError> {
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe {
            ffi::live_text_interaction::vk_live_text_interaction_set_supplementary_interface_hidden(
                self.token,
                i32::from(hidden),
                i32::from(animated),
                &mut err_msg,
            )
        };
        status_to_unit(status, err_msg)
    }

    /// Returns the VisionKit supplementary interface content insets value.
    pub fn supplementary_interface_content_insets(&self) -> Result<EdgeInsets, VisionKitError> {
        let rect = self.query_rect(
            ffi::live_text_interaction::vk_live_text_interaction_supplementary_interface_content_insets,
        )?;
        Ok(EdgeInsets {
            top: rect.x,
            left: rect.y,
            bottom: rect.width,
            right: rect.height,
        })
    }

    /// Sets the VisionKit supplementary interface content insets value.
    pub fn set_supplementary_interface_content_insets(
        &self,
        insets: EdgeInsets,
    ) -> Result<(), VisionKitError> {
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe {
            ffi::live_text_interaction::vk_live_text_interaction_set_supplementary_interface_content_insets(
                self.token,
                insets.top,
                insets.left,
                insets.bottom,
                insets.right,
                &mut err_msg,
            )
        };
        status_to_unit(status, err_msg)
    }

    /// Returns the VisionKit supplementary interface font value.
    pub fn supplementary_interface_font(&self) -> Result<Option<LiveTextFont>, VisionKitError> {
        self.query_json(
            ffi::live_text_interaction::vk_live_text_interaction_supplementary_interface_font_json,
            "live text interaction supplementary interface font",
        )
    }

    /// Sets the VisionKit supplementary interface font value.
    pub fn set_supplementary_interface_font(
        &self,
        font: Option<&LiveTextFont>,
    ) -> Result<(), VisionKitError> {
        let font_json = json_cstring(&font)?;
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe {
            ffi::live_text_interaction::vk_live_text_interaction_set_supplementary_interface_font_json(
                self.token,
                font_json.as_ptr(),
                &mut err_msg,
            )
        };
        status_to_unit(status, err_msg)
    }

    /// Begins VisionKit subject analysis when the overlay requires it.
    pub fn begin_subject_analysis_if_necessary(&self) -> Result<(), VisionKitError> {
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe {
            ffi::live_text_interaction::vk_live_text_interaction_begin_subject_analysis_if_necessary(
                self.token,
                &mut err_msg,
            )
        };
        status_to_unit(status, err_msg)
    }

    /// Returns the VisionKit subjects value.
    pub fn subjects(&self) -> Result<Vec<LiveTextSubject>, VisionKitError> {
        self.query_subjects(ffi::live_text_interaction::vk_live_text_interaction_subjects_json)
    }

    /// Returns the VisionKit highlighted subjects value.
    pub fn highlighted_subjects(&self) -> Result<Vec<LiveTextSubject>, VisionKitError> {
        self.query_subjects(
            ffi::live_text_interaction::vk_live_text_interaction_highlighted_subjects_json,
        )
    }

    /// Sets the VisionKit highlighted subjects value.
    pub fn set_highlighted_subjects(
        &self,
        subjects: &[LiveTextSubject],
    ) -> Result<(), VisionKitError> {
        let subjects_json = json_cstring(&subject_tokens(subjects))?;
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe {
            ffi::live_text_interaction::vk_live_text_interaction_set_highlighted_subjects_json(
                self.token,
                subjects_json.as_ptr(),
                &mut err_msg,
            )
        };
        status_to_unit(status, err_msg)
    }

    /// Returns the VisionKit subject at point value.
    pub fn subject_at_point(
        &self,
        x: f64,
        y: f64,
    ) -> Result<Option<LiveTextSubject>, VisionKitError> {
        let mut subject_json: *mut c_char = ptr::null_mut();
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe {
            ffi::live_text_interaction::vk_live_text_interaction_subject_at_json(
                self.token,
                x,
                y,
                &mut subject_json,
                &mut err_msg,
            )
        };
        if status == ffi::status::OK {
            let token: Option<u64> =
                unsafe { parse_json_ptr(subject_json, "live text interaction subject lookup") }?;
            Ok(token.map(token_from_u64).map(LiveTextSubject::from_token))
        } else {
            Err(unsafe { error_from_status(status, err_msg) })
        }
    }

    /// Returns the VisionKit image extracted for the provided subjects.
    pub fn image_for_subjects(
        &self,
        subjects: &[LiveTextSubject],
    ) -> Result<LiveTextImageData, VisionKitError> {
        let subjects_json = json_cstring(&subject_tokens(subjects))?;
        let mut bytes: *mut c_void = ptr::null_mut();
        let mut len = 0;
        let mut width = 0.0;
        let mut height = 0.0;
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe {
            ffi::live_text_interaction::vk_live_text_interaction_image_for_subjects_png_data(
                self.token,
                subjects_json.as_ptr(),
                &mut bytes,
                &mut len,
                &mut width,
                &mut height,
                &mut err_msg,
            )
        };
        if status == ffi::status::OK {
            Ok(LiveTextImageData {
                size: Size { width, height },
                png_data: unsafe {
                    vec_from_buffer_ptr(
                        bytes.cast::<u8>(),
                        u64_to_usize(len, "live text interaction subject image")?,
                        "live text interaction subject image",
                    )
                }?,
            })
        } else {
            Err(unsafe { error_from_status(status, err_msg) })
        }
    }

    fn query_bool(&self, query: BoolQueryFn) -> Result<bool, VisionKitError> {
        let mut value = 0;
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe { query(self.token, &mut value, &mut err_msg) };
        if status == ffi::status::OK {
            Ok(value != 0)
        } else {
            Err(unsafe { error_from_status(status, err_msg) })
        }
    }

    fn set_bool(&self, value: bool, setter: BoolSetterFn) -> Result<(), VisionKitError> {
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe { setter(self.token, i32::from(value), &mut err_msg) };
        status_to_unit(status, err_msg)
    }

    fn query_types(&self, query: TypesQueryFn) -> Result<LiveTextInteractionTypes, VisionKitError> {
        let mut raw = 0;
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe { query(self.token, &mut raw, &mut err_msg) };
        if status == ffi::status::OK {
            Ok(LiveTextInteractionTypes::new(raw))
        } else {
            Err(unsafe { error_from_status(status, err_msg) })
        }
    }

    fn query_string(
        &self,
        query: unsafe extern "C" fn(*mut c_void, *mut *mut c_char, *mut *mut c_char) -> i32,
    ) -> Result<String, VisionKitError> {
        let mut value: *mut c_char = ptr::null_mut();
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe { query(self.token, &mut value, &mut err_msg) };
        if status == ffi::status::OK {
            unsafe { string_from_ptr(value, "live text interaction string") }
        } else {
            Err(unsafe { error_from_status(status, err_msg) })
        }
    }

    fn query_json<T>(&self, query: JsonQueryFn, context: &str) -> Result<T, VisionKitError>
    where
        T: DeserializeOwned,
    {
        let mut value: *mut c_char = ptr::null_mut();
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe { query(self.token, &mut value, &mut err_msg) };
        if status == ffi::status::OK {
            unsafe { parse_json_ptr(value, context) }
        } else {
            Err(unsafe { error_from_status(status, err_msg) })
        }
    }

    fn set_json<T>(&self, value: &T, setter: JsonSetterFn) -> Result<(), VisionKitError>
    where
        T: Serialize + ?Sized,
    {
        let json = json_cstring(value)?;
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe { setter(self.token, json.as_ptr(), &mut err_msg) };
        status_to_unit(status, err_msg)
    }

    fn query_rect(&self, query: RectQueryFn) -> Result<Rect, VisionKitError> {
        query_rect_call(
            "live text interaction rect",
            |out_x, out_y, out_width, out_height, out_error_message| unsafe {
                query(
                    self.token,
                    out_x,
                    out_y,
                    out_width,
                    out_height,
                    out_error_message,
                )
            },
        )
    }

    fn query_point_bool(
        &self,
        x: f64,
        y: f64,
        query: PointBoolQueryFn,
    ) -> Result<bool, VisionKitError> {
        let mut value = 0;
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe { query(self.token, x, y, &mut value, &mut err_msg) };
        if status == ffi::status::OK {
            Ok(value != 0)
        } else {
            Err(unsafe { error_from_status(status, err_msg) })
        }
    }

    fn query_optional_token(
        &self,
        query: OptionalTokenQueryFn,
    ) -> Result<Option<*mut c_void>, VisionKitError> {
        optional_token_call(|out_token, out_error_message| unsafe {
            query(self.token, out_token, out_error_message)
        })
    }

    fn query_subjects(&self, query: JsonQueryFn) -> Result<Vec<LiveTextSubject>, VisionKitError> {
        let tokens: Vec<u64> = self.query_json(query, "live text interaction subjects")?;
        Ok(tokens
            .into_iter()
            .map(token_from_u64)
            .map(LiveTextSubject::from_token)
            .collect())
    }
}

fn parse_json_call<T, F>(mut call: F, context: &str) -> Result<T, VisionKitError>
where
    T: DeserializeOwned,
    F: FnMut(*mut *mut c_char, *mut *mut c_char) -> i32,
{
    let mut json: *mut c_char = ptr::null_mut();
    let mut err_msg: *mut c_char = ptr::null_mut();
    let status = call(&mut json, &mut err_msg);
    if status == ffi::status::OK {
        unsafe { parse_json_ptr(json, context) }
    } else {
        Err(unsafe { error_from_status(status, err_msg) })
    }
}

fn optional_token_call<F>(mut call: F) -> Result<Option<*mut c_void>, VisionKitError>
where
    F: FnMut(*mut *mut c_void, *mut *mut c_char) -> i32,
{
    let mut token: *mut c_void = ptr::null_mut();
    let mut err_msg: *mut c_char = ptr::null_mut();
    let status = call(&mut token, &mut err_msg);
    if status == ffi::status::OK {
        Ok((!token.is_null()).then_some(token))
    } else {
        Err(unsafe { error_from_status(status, err_msg) })
    }
}

fn query_rect_call<F>(context: &str, mut call: F) -> Result<Rect, VisionKitError>
where
    F: FnMut(*mut f64, *mut f64, *mut f64, *mut f64, *mut *mut c_char) -> i32,
{
    let mut x = 0.0;
    let mut y = 0.0;
    let mut width = 0.0;
    let mut height = 0.0;
    let mut err_msg: *mut c_char = ptr::null_mut();
    let status = call(&mut x, &mut y, &mut width, &mut height, &mut err_msg);
    if status == ffi::status::OK {
        Ok(Rect {
            x,
            y,
            width,
            height,
        })
    } else {
        let _ = context;
        Err(unsafe { error_from_status(status, err_msg) })
    }
}

fn query_image_data_call<F>(mut call: F, context: &str) -> Result<LiveTextImageData, VisionKitError>
where
    F: FnMut(*mut *mut c_void, *mut u64, *mut f64, *mut f64, *mut *mut c_char) -> i32,
{
    let mut bytes: *mut c_void = ptr::null_mut();
    let mut len = 0;
    let mut width = 0.0;
    let mut height = 0.0;
    let mut err_msg: *mut c_char = ptr::null_mut();
    let status = call(&mut bytes, &mut len, &mut width, &mut height, &mut err_msg);
    if status == ffi::status::OK {
        Ok(LiveTextImageData {
            size: Size { width, height },
            png_data: unsafe {
                vec_from_buffer_ptr(bytes.cast::<u8>(), u64_to_usize(len, context)?, context)
            }?,
        })
    } else {
        Err(unsafe { error_from_status(status, err_msg) })
    }
}

fn live_text_menu_tag_constants() -> Result<LiveTextMenuTagConstants, VisionKitError> {
    LIVE_TEXT_MENU_TAGS
        .get_or_init(|| {
            parse_json_call(
                |out_json, out_error_message| unsafe {
                    ffi::live_text_interaction::vk_live_text_menu_tags_json(
                        out_json,
                        out_error_message,
                    )
                },
                "live text menu tags",
            )
        })
        .clone()
}

fn status_to_unit(status: i32, err_msg: *mut c_char) -> Result<(), VisionKitError> {
    if status == ffi::status::OK {
        Ok(())
    } else {
        Err(unsafe { error_from_status(status, err_msg) })
    }
}

fn subject_tokens(subjects: &[LiveTextSubject]) -> Vec<u64> {
    subjects
        .iter()
        .map(|subject| token_to_u64(subject.raw_token()))
        .collect()
}

fn token_to_u64(token: *mut c_void) -> u64 {
    token as usize as u64
}

fn token_from_u64(token: u64) -> *mut c_void {
    usize::try_from(token).map_or(ptr::null_mut(), |value| value as *mut c_void)
}

fn u64_to_usize(value: u64, context: &str) -> Result<usize, VisionKitError> {
    usize::try_from(value).map_err(|_| {
        VisionKitError::Unknown(format!(
            "{context} length exceeded this platform's address width"
        ))
    })
}