visionkit/async_api.rs
1//! Async API for `VisionKit`
2//!
3//! Enabled with the `async` Cargo feature. Every type here is an executor-agnostic
4//! [`Future`] backed by a C callback fired from a Swift `Task { … }` thunk.
5//!
6//! ## Available types
7//!
8//! | Type | Wraps |
9//! |---|---|
10//! | [`AsyncImageAnalyzer`] | `ImageAnalyzer.analyze(imageAt:orientation:configuration:) async throws` |
11//! | [`AsyncOverlaySubjects`] | `ImageAnalysisOverlayView.subjects async` and `.subject(at:) async` |
12//!
13//! ## Platform notes
14//!
15//! On macOS the subject APIs (`subjects`, `subject(at:)`) live on
16//! `ImageAnalysisOverlayView` (Rust: [`LiveTextInteraction`]), not on
17//! `ImageAnalysis` as on iOS. [`AsyncOverlaySubjects`] wraps this macOS surface.
18//!
19//! `DataScannerViewController` is an **iOS-only** API and is not available on
20//! macOS. Its multi-delegate live-scan surface is a Tier-2 (Stream) concern in
21//! any case. No wrappers are provided here.
22//!
23//! ## Design
24//!
25//! * Each async Swift API gets a `@_cdecl` thunk that accepts a C callback
26//! `(result, error, ctx)` and a `ctx` opaque pointer. The thunk spawns a
27//! Swift `Task`, awaits the Apple API, then fires the callback.
28//! * The Rust side wraps that in a typed `Future` newtype backed by
29//! [`AsyncCompletionFuture<T>`](doom_fish_utils::completion::AsyncCompletionFuture)
30//! and maps the `String` error to [`VisionKitError`].
31//! * Works with any async executor (`pollster`, Tokio, async-std, …).
32//!
33//! ## Example
34//!
35//! ```rust,no_run
36//! use visionkit::async_api::AsyncImageAnalyzer;
37//! use visionkit::{ImageAnalysisTypes, ImageAnalyzerConfiguration, ImageOrientation};
38//!
39//! # pollster::block_on(async {
40//! let cfg = ImageAnalyzerConfiguration::new(ImageAnalysisTypes::TEXT);
41//! let analysis = AsyncImageAnalyzer::new()?
42//! .analyze_image_at_path("/path/to/image.png", ImageOrientation::Up, &cfg)?
43//! .await?;
44//! println!("transcript: {}", analysis.transcript()?);
45//! # Ok::<_, Box<dyn std::error::Error>>(())
46//! # });
47//! ```
48
49use std::ffi::{c_void, CStr};
50use std::future::Future;
51use std::pin::Pin;
52use std::sync::Arc;
53use std::task::{Context, Poll, Wake, Waker};
54
55use doom_fish_utils::completion::{error_from_cstr, AsyncCompletion, AsyncCompletionFuture};
56use doom_fish_utils::panic_safe::catch_user_panic;
57use serde::Deserialize;
58
59use crate::error::VisionKitError;
60use crate::ffi;
61use crate::image_analysis::ImageAnalysis;
62use crate::image_analyzer::{ImageAnalyzerConfiguration, ImageOrientation};
63use crate::live_text_interaction::LiveTextInteraction;
64use crate::private::{json_cstring, path_to_cstring};
65
66// ============================================================================
67// AnalysisSubjectBounds
68// ============================================================================
69
70/// Bounds rectangle for an `ImageAnalysisOverlayView.Subject` (macOS) or
71/// `ImageAnalysisInteraction.Subject` (iOS).
72///
73/// The coordinate space matches what VisionKit reports for the analysis
74/// resolution. `x` and `y` are the origin (top-left corner).
75#[derive(Debug, Clone, PartialEq, Deserialize)]
76pub struct AnalysisSubjectBounds {
77 /// X coordinate of the origin.
78 pub x: f64,
79 /// Y coordinate of the origin.
80 pub y: f64,
81 /// Width of the bounding rectangle.
82 pub width: f64,
83 /// Height of the bounding rectangle.
84 pub height: f64,
85}
86
87// ============================================================================
88// Helpers
89// ============================================================================
90
91/// Copy a non-null C-string result pointer (reinterpreted as `*const i8`) to a `String`.
92///
93/// # Safety
94/// `ptr` must be a valid, null-terminated C string that remains valid for the
95/// duration of this call. The callback contract guarantees this: the Swift
96/// bridge passes a string from a `withCString` closure, so the pointer is live
97/// for the duration of the (synchronous) callback invocation.
98unsafe fn cstring_result_to_string(ptr: *const c_void) -> String {
99 CStr::from_ptr(ptr.cast::<i8>())
100 .to_str()
101 .map_or_else(|_| String::new(), str::to_owned)
102}
103
104// ============================================================================
105// AsyncImageAnalyzer
106// ============================================================================
107
108extern "C" fn analyze_cb(result: *const c_void, error: *const i8, ctx: *mut c_void) {
109 catch_user_panic("visionkit::analyze_cb", move || {
110 if !error.is_null() {
111 let msg = unsafe { error_from_cstr(error) };
112 unsafe { AsyncCompletion::<ImageAnalysis>::complete_err(ctx, msg) };
113 } else if !result.is_null() {
114 // result is a retained VKImageAnalysisBox pointer
115 let analysis = ImageAnalysis::from_token(result.cast_mut());
116 unsafe { AsyncCompletion::complete_ok(ctx, analysis) };
117 } else {
118 unsafe {
119 AsyncCompletion::<ImageAnalysis>::complete_err(ctx, "Unknown error".into());
120 };
121 }
122 });
123}
124
125/// Future returned by [`AsyncImageAnalyzer::analyze_image_at_path`].
126#[must_use = "futures do nothing unless polled"]
127pub struct AnalyzeImageFuture {
128 inner: AsyncCompletionFuture<ImageAnalysis>,
129}
130
131impl std::fmt::Debug for AnalyzeImageFuture {
132 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133 f.debug_struct("AnalyzeImageFuture").finish_non_exhaustive()
134 }
135}
136
137impl Future for AnalyzeImageFuture {
138 type Output = Result<ImageAnalysis, VisionKitError>;
139
140 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
141 Pin::new(&mut self.inner)
142 .poll(cx)
143 .map(|r| r.map_err(VisionKitError::Unknown))
144 }
145}
146
147/// True-async entry point for `ImageAnalyzer.analyze(imageAt:orientation:configuration:)`.
148///
149/// Requires macOS 13+. The returned [`AnalyzeImageFuture`] resolves to an
150/// [`ImageAnalysis`] that can then be inspected synchronously via its existing
151/// methods or have its subjects queried via [`AsyncOverlaySubjects`].
152pub struct AsyncImageAnalyzer {
153 token: *mut c_void,
154}
155
156// SAFETY: the underlying VKImageAnalyzerBox is reference-counted by Swift ARC
157// and the callback fires exactly once. The callback carries a reference to the
158// token across threads, and since the token is ARC-counted by Swift, it remains
159// valid regardless of which thread completes the async operation. Sync is safe
160// because VKImageAnalyzerBox is thread-safe (it's an immutable system framework
161// class with no thread-local state).
162unsafe impl Send for AsyncImageAnalyzer {}
163unsafe impl Sync for AsyncImageAnalyzer {}
164
165impl Drop for AsyncImageAnalyzer {
166 fn drop(&mut self) {
167 if !self.token.is_null() {
168 unsafe { ffi::image_analyzer::vk_image_analyzer_release(self.token) };
169 }
170 }
171}
172
173impl AsyncImageAnalyzer {
174 /// Create a new `AsyncImageAnalyzer`.
175 ///
176 /// # Errors
177 ///
178 /// Returns [`VisionKitError::UnavailableOnThisMacOS`] if the device does
179 /// not run macOS 13 or later.
180 pub fn new() -> Result<Self, VisionKitError> {
181 let token = unsafe { ffi::image_analyzer::vk_image_analyzer_new() };
182 if token.is_null() {
183 return Err(VisionKitError::UnavailableOnThisMacOS(
184 "ImageAnalyzer requires macOS 13+".to_owned(),
185 ));
186 }
187 Ok(Self { token })
188 }
189
190 /// Returns `true` when the current Mac supports `ImageAnalyzer`.
191 #[must_use]
192 pub fn is_supported() -> bool {
193 unsafe { ffi::image_analyzer::vk_image_analyzer_is_supported() != 0 }
194 }
195
196 /// Asynchronously analyze the image at `path` and return an [`ImageAnalysis`].
197 ///
198 /// This is a true async wrapper: the Swift bridge spawns a
199 /// `Task { @MainActor … }`, calls
200 /// `await analyzer.analyze(imageAt:orientation:configuration:)`, and fires
201 /// a C callback when done. The returned [`AnalyzeImageFuture`] resolves
202 /// when that callback fires.
203 ///
204 /// # Errors
205 ///
206 /// Returns [`VisionKitError`] if the path cannot be represented as a C
207 /// string, if the configuration cannot be serialized, or if VisionKit
208 /// reports an analysis error.
209 pub fn analyze_image_at_path<P: AsRef<std::path::Path>>(
210 &self,
211 path: P,
212 orientation: ImageOrientation,
213 configuration: &ImageAnalyzerConfiguration,
214 ) -> Result<AnalyzeImageFuture, VisionKitError> {
215 let path_cs = path_to_cstring(path.as_ref())?;
216 let cfg_cs = json_cstring(configuration)?;
217 let (future, ctx) = AsyncCompletion::create();
218 unsafe {
219 ffi::image_analyzer::vk_image_analyzer_analyze_image_async(
220 self.token,
221 path_cs.as_ptr(),
222 orientation.raw_value(),
223 cfg_cs.as_ptr(),
224 analyze_cb,
225 ctx,
226 );
227 }
228 Ok(AnalyzeImageFuture { inner: future })
229 }
230}
231
232// ============================================================================
233// AsyncOverlaySubjects
234// ============================================================================
235
236extern "C" fn subjects_cb(result: *const c_void, error: *const i8, ctx: *mut c_void) {
237 catch_user_panic("visionkit::subjects_cb", move || {
238 if !error.is_null() {
239 let msg = unsafe { error_from_cstr(error) };
240 unsafe { AsyncCompletion::<String>::complete_err(ctx, msg) };
241 } else if !result.is_null() {
242 let json = unsafe { cstring_result_to_string(result) };
243 unsafe { AsyncCompletion::complete_ok(ctx, json) };
244 } else {
245 unsafe { AsyncCompletion::<String>::complete_err(ctx, "Unknown error".into()) };
246 }
247 });
248}
249
250extern "C" fn subject_at_cb(result: *const c_void, error: *const i8, ctx: *mut c_void) {
251 catch_user_panic("visionkit::subject_at_cb", move || {
252 if !error.is_null() {
253 let msg = unsafe { error_from_cstr(error) };
254 unsafe { AsyncCompletion::<String>::complete_err(ctx, msg) };
255 } else if !result.is_null() {
256 let json = unsafe { cstring_result_to_string(result) };
257 unsafe { AsyncCompletion::complete_ok(ctx, json) };
258 } else {
259 unsafe { AsyncCompletion::<String>::complete_err(ctx, "Unknown error".into()) };
260 }
261 });
262}
263
264/// Future returned by [`AsyncOverlaySubjects::subjects`].
265#[must_use = "futures do nothing unless polled"]
266pub struct SubjectsFuture {
267 inner: AsyncCompletionFuture<String>,
268}
269
270impl std::fmt::Debug for SubjectsFuture {
271 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
272 f.debug_struct("SubjectsFuture").finish_non_exhaustive()
273 }
274}
275
276impl Future for SubjectsFuture {
277 type Output = Result<Vec<AnalysisSubjectBounds>, VisionKitError>;
278
279 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
280 Pin::new(&mut self.inner).poll(cx).map(|r| {
281 r.map_err(VisionKitError::Unknown).and_then(|json| {
282 serde_json::from_str::<Vec<AnalysisSubjectBounds>>(&json).map_err(|e| {
283 VisionKitError::Unknown(format!(
284 "failed to decode subjects JSON from Swift bridge: {e}"
285 ))
286 })
287 })
288 })
289 }
290}
291
292/// Future returned by [`AsyncOverlaySubjects::subject_at`].
293#[must_use = "futures do nothing unless polled"]
294pub struct SubjectAtFuture {
295 inner: AsyncCompletionFuture<String>,
296}
297
298impl std::fmt::Debug for SubjectAtFuture {
299 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
300 f.debug_struct("SubjectAtFuture").finish_non_exhaustive()
301 }
302}
303
304impl Future for SubjectAtFuture {
305 type Output = Result<Option<AnalysisSubjectBounds>, VisionKitError>;
306
307 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
308 Pin::new(&mut self.inner).poll(cx).map(|r| {
309 r.map_err(VisionKitError::Unknown).and_then(|json| {
310 serde_json::from_str::<Option<AnalysisSubjectBounds>>(&json).map_err(|e| {
311 VisionKitError::Unknown(format!(
312 "failed to decode subject-at JSON from Swift bridge: {e}"
313 ))
314 })
315 })
316 })
317 }
318}
319
320/// True-async entry point for `ImageAnalysisOverlayView.subjects` and
321/// `ImageAnalysisOverlayView.subject(at:)` (macOS).
322///
323/// On macOS the subject APIs live on `ImageAnalysisOverlayView`
324/// (Rust: [`LiveTextInteraction`]), not directly on `ImageAnalysis`.
325/// Both require macOS 13+ and the [`crate::ImageAnalysisTypes::VISUAL_LOOK_UP`]
326/// analysis type in the configuration used when the analysis was performed.
327///
328/// # Note on subject bounds coordinate space
329///
330/// Bounds are in the same coordinate space that VisionKit uses when populating
331/// the overlay view. That is, they are relative to the view's bounds as
332/// configured via `setPreferredInteractionTypes` and `setAnalysis(_:)`.
333pub struct AsyncOverlaySubjects {
334 // Raw token of the underlying VKLiveTextInteractionBox.
335 // Caller must ensure the LiveTextInteraction outlives the returned futures.
336 token: *mut c_void,
337}
338
339// SAFETY: the underlying VKLiveTextInteractionBox is ARC-counted and the callback
340// fires exactly once. The callback carries a reference to the token across threads,
341// and since the token is ARC-counted by Swift, it remains valid regardless of which
342// thread completes the async operation. Sync is NOT implemented because the
343// underlying ImageAnalysisOverlayView is a UI component that must be accessed from
344// the main thread.
345unsafe impl Send for AsyncOverlaySubjects {}
346
347impl AsyncOverlaySubjects {
348 /// Wrap a [`LiveTextInteraction`] for async subject queries.
349 ///
350 /// The `interaction` must remain alive for as long as the returned
351 /// futures are pending.
352 #[must_use]
353 pub fn new(interaction: &LiveTextInteraction) -> Self {
354 Self {
355 token: interaction.raw_token(),
356 }
357 }
358
359 /// Asynchronously retrieve all subjects as their bounds rectangles.
360 ///
361 /// Internally calls `await overlayView.subjects` on the Swift side
362 /// (requires `@MainActor`). Each subject's `bounds` is accessed
363 /// synchronously within that actor context.
364 ///
365 /// Returns an empty `Vec` when no subjects are found or when the analysis
366 /// did not include [`crate::ImageAnalysisTypes::VISUAL_LOOK_UP`].
367 #[must_use = "returns a future that must be awaited"]
368 pub fn subjects(&self) -> SubjectsFuture {
369 let (future, ctx) = AsyncCompletion::create();
370 unsafe {
371 ffi::live_text_interaction::vk_live_text_overlay_subjects_async(
372 self.token,
373 subjects_cb,
374 ctx,
375 );
376 }
377 SubjectsFuture { inner: future }
378 }
379
380 /// Asynchronously find the subject at the given overlay-coordinate point.
381 ///
382 /// Returns `Ok(None)` when no subject is present at `(x, y)`.
383 #[must_use = "returns a future that must be awaited"]
384 pub fn subject_at(&self, x: f64, y: f64) -> SubjectAtFuture {
385 let (future, ctx) = AsyncCompletion::create();
386 unsafe {
387 ffi::live_text_interaction::vk_live_text_overlay_subject_at_async(
388 self.token,
389 x,
390 y,
391 subject_at_cb,
392 ctx,
393 );
394 }
395 SubjectAtFuture { inner: future }
396 }
397}
398
399// ============================================================================
400// block_on — run-loop-aware executor
401// ============================================================================
402
403struct NoopWake;
404impl Wake for NoopWake {
405 fn wake(self: Arc<Self>) {}
406 fn wake_by_ref(self: &Arc<Self>) {}
407}
408
409/// Drive a VisionKit async future to completion while pumping the Obj-C main
410/// run loop between polls.
411///
412/// **Must be called from the main thread.** VisionKit Swift `Task { @MainActor
413/// in }` thunks dispatch work to the main actor; without run-loop pumping the
414/// calling thread would deadlock when the main run loop is not free (e.g.
415/// inside `pollster::block_on`).
416///
417/// # Example
418///
419/// ```rust,no_run
420/// use visionkit::async_api::{AsyncImageAnalyzer, block_on};
421/// use visionkit::{ImageAnalysisTypes, ImageAnalyzerConfiguration, ImageOrientation};
422///
423/// let cfg = ImageAnalyzerConfiguration::new(ImageAnalysisTypes::TEXT);
424/// let analysis = block_on(async {
425/// AsyncImageAnalyzer::new()?
426/// .analyze_image_at_path("/path/to/image.png", ImageOrientation::Up, &cfg)?
427/// .await
428/// });
429/// ```
430pub fn block_on<F: Future>(future: F) -> F::Output {
431 let waker = Waker::from(Arc::new(NoopWake));
432 let cx = &mut Context::from_waker(&waker);
433 let mut future = std::pin::pin!(future);
434 loop {
435 match future.as_mut().poll(cx) {
436 Poll::Ready(val) => return val,
437 Poll::Pending => {
438 // Pump Obj-C RunLoop.main for 10 ms so Swift @MainActor Tasks
439 // can make progress before the next poll.
440 unsafe { ffi::image_analyzer::vk_pump_main_run_loop(10) };
441 }
442 }
443 }
444}