Skip to main content

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_char, c_int, c_void, CStr};
50use std::future::Future;
51use std::mem::ManuallyDrop;
52use std::pin::Pin;
53use std::sync::atomic::{AtomicBool, Ordering};
54use std::sync::Arc;
55use std::task::{Context, Poll, Wake, Waker};
56use std::thread::{self, Thread};
57
58use doom_fish_utils::completion::{AsyncCompletion, AsyncCompletionFuture};
59use doom_fish_utils::panic_safe::catch_user_panic;
60use serde::Deserialize;
61
62use crate::error::VisionKitError;
63use crate::ffi;
64use crate::image_analysis::ImageAnalysis;
65use crate::image_analyzer::{ImageAnalyzerConfiguration, ImageOrientation};
66use crate::live_text_interaction::LiveTextInteraction;
67use crate::private::{error_for_status, json_cstring, path_to_cstring};
68
69// ============================================================================
70// AnalysisSubjectBounds
71// ============================================================================
72
73/// Bounds rectangle for an `ImageAnalysisOverlayView.Subject` (macOS) or
74/// `ImageAnalysisInteraction.Subject` (iOS).
75///
76/// The coordinate space matches what VisionKit reports for the analysis
77/// resolution. `x` and `y` are the origin (top-left corner).
78#[derive(Debug, Clone, PartialEq, Deserialize)]
79pub struct AnalysisSubjectBounds {
80    /// X coordinate of the origin.
81    pub x: f64,
82    /// Y coordinate of the origin.
83    pub y: f64,
84    /// Width of the bounding rectangle.
85    pub width: f64,
86    /// Height of the bounding rectangle.
87    pub height: f64,
88}
89
90// ============================================================================
91// Helpers
92// ============================================================================
93
94/// Copy a non-null C-string result pointer (reinterpreted as `*const i8`) to a `String`.
95///
96/// # Safety
97/// `ptr` must be a valid, null-terminated C string that remains valid for the
98/// duration of this call.  The callback contract guarantees this: the Swift
99/// bridge passes a string from a `withCString` closure, so the pointer is live
100/// for the duration of the (synchronous) callback invocation.
101unsafe fn cstring_result_to_string(ptr: *const c_void) -> String {
102    CStr::from_ptr(ptr.cast::<i8>())
103        .to_str()
104        .map_or_else(|_| String::new(), str::to_owned)
105}
106
107unsafe fn async_error(status: i32, error: *const c_char) -> VisionKitError {
108    let message = if error.is_null() {
109        format!("Swift bridge call failed with status code {status}")
110    } else {
111        CStr::from_ptr(error).to_string_lossy().into_owned()
112    };
113    error_for_status(status, message)
114}
115
116// ============================================================================
117// AsyncImageAnalyzer
118// ============================================================================
119
120struct AnalysisToken(*mut c_void);
121
122unsafe impl Send for AnalysisToken {}
123
124impl AnalysisToken {
125    fn into_analysis(self) -> ImageAnalysis {
126        let token = ManuallyDrop::new(self);
127        ImageAnalysis::from_token(token.0)
128    }
129}
130
131impl Drop for AnalysisToken {
132    fn drop(&mut self) {
133        unsafe { ffi::image_analysis::vk_image_analysis_release(self.0) };
134    }
135}
136
137type AnalysisOutcome = Result<AnalysisToken, VisionKitError>;
138
139unsafe extern "C" fn analyze_cb(
140    result: *const c_void,
141    status: i32,
142    error: *const c_char,
143    ctx: *mut c_void,
144) {
145    catch_user_panic("visionkit::analyze_cb", move || {
146        let outcome: AnalysisOutcome = if status != ffi::status::OK {
147            Err(unsafe { async_error(status, error) })
148        } else if result.is_null() {
149            Err(VisionKitError::Unknown(
150                "Swift bridge returned no image analysis".to_owned(),
151            ))
152        } else {
153            Ok(AnalysisToken(result.cast_mut()))
154        };
155        unsafe { AsyncCompletion::complete_ok(ctx, outcome) };
156    });
157}
158
159/// Future returned by [`AsyncImageAnalyzer::analyze_image_at_path`].
160#[must_use = "futures do nothing unless polled"]
161pub struct AnalyzeImageFuture {
162    inner: AsyncCompletionFuture<AnalysisOutcome>,
163}
164
165impl std::fmt::Debug for AnalyzeImageFuture {
166    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
167        f.debug_struct("AnalyzeImageFuture").finish_non_exhaustive()
168    }
169}
170
171impl Future for AnalyzeImageFuture {
172    type Output = Result<ImageAnalysis, VisionKitError>;
173
174    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
175        Pin::new(&mut self.inner).poll(cx).map(|result| {
176            result
177                .map_err(VisionKitError::Unknown)
178                .and_then(|outcome| outcome.map(AnalysisToken::into_analysis))
179        })
180    }
181}
182
183/// True-async entry point for `ImageAnalyzer.analyze(imageAt:orientation:configuration:)`.
184///
185/// Requires macOS 13+.  The returned [`AnalyzeImageFuture`] resolves to an
186/// [`ImageAnalysis`] that can then be inspected synchronously via its existing
187/// methods or have its subjects queried via [`AsyncOverlaySubjects`].
188pub struct AsyncImageAnalyzer {
189    token: *mut c_void,
190}
191
192// SAFETY: the underlying VKImageAnalyzerBox is reference-counted by Swift ARC
193// and the callback fires exactly once. The callback carries a reference to the
194// token across threads, and since the token is ARC-counted by Swift, it remains
195// valid regardless of which thread completes the async operation. Sync is safe
196// because VKImageAnalyzerBox is thread-safe (it's an immutable system framework
197// class with no thread-local state).
198unsafe impl Send for AsyncImageAnalyzer {}
199unsafe impl Sync for AsyncImageAnalyzer {}
200
201impl Drop for AsyncImageAnalyzer {
202    fn drop(&mut self) {
203        if !self.token.is_null() {
204            unsafe { ffi::image_analyzer::vk_image_analyzer_release(self.token) };
205        }
206    }
207}
208
209impl AsyncImageAnalyzer {
210    /// Create a new `AsyncImageAnalyzer`.
211    ///
212    /// # Errors
213    ///
214    /// Returns [`VisionKitError::UnavailableOnThisMacOS`] if the device does
215    /// not run macOS 13 or later.
216    pub fn new() -> Result<Self, VisionKitError> {
217        let token = unsafe { ffi::image_analyzer::vk_image_analyzer_new() };
218        if token.is_null() {
219            return Err(VisionKitError::UnavailableOnThisMacOS(
220                "ImageAnalyzer requires macOS 13+".to_owned(),
221            ));
222        }
223        Ok(Self { token })
224    }
225
226    /// Returns `true` when the current Mac supports `ImageAnalyzer`.
227    #[must_use]
228    pub fn is_supported() -> bool {
229        unsafe { ffi::image_analyzer::vk_image_analyzer_is_supported() != 0 }
230    }
231
232    /// Asynchronously analyze the image at `path` and return an [`ImageAnalysis`].
233    ///
234    /// This is a true async wrapper: the Swift bridge spawns a `Task`, calls
235    /// `await analyzer.analyze(imageAt:orientation:configuration:)`, and fires
236    /// a C callback when done.  The returned [`AnalyzeImageFuture`] resolves
237    /// when that callback fires.
238    ///
239    /// # Errors
240    ///
241    /// Returns [`VisionKitError`] if the path cannot be represented as a C
242    /// string, if the configuration cannot be serialized, or if VisionKit
243    /// reports an analysis error.
244    pub fn analyze_image_at_path<P: AsRef<std::path::Path>>(
245        &self,
246        path: P,
247        orientation: ImageOrientation,
248        configuration: &ImageAnalyzerConfiguration,
249    ) -> Result<AnalyzeImageFuture, VisionKitError> {
250        let path_cs = path_to_cstring(path.as_ref())?;
251        let cfg_cs = json_cstring(configuration)?;
252        let (future, ctx) = AsyncCompletion::create();
253        unsafe {
254            ffi::image_analyzer::vk_image_analyzer_analyze_image_async(
255                self.token,
256                path_cs.as_ptr(),
257                orientation.raw_value(),
258                cfg_cs.as_ptr(),
259                analyze_cb,
260                ctx,
261            );
262        }
263        Ok(AnalyzeImageFuture { inner: future })
264    }
265
266    #[cfg(feature = "apple-cf")]
267    pub fn analyze_cg_image(
268        &self,
269        image: &apple_cf::cg::CGImage,
270        orientation: ImageOrientation,
271        configuration: &ImageAnalyzerConfiguration,
272    ) -> Result<AnalyzeImageFuture, VisionKitError> {
273        let cfg_cs = json_cstring(configuration)?;
274        let (future, ctx) = AsyncCompletion::create();
275        unsafe {
276            ffi::image_analyzer::vk_image_analyzer_analyze_cg_image_async(
277                self.token,
278                image.as_ptr(),
279                orientation.raw_value(),
280                cfg_cs.as_ptr(),
281                analyze_cb,
282                ctx,
283            );
284        }
285        Ok(AnalyzeImageFuture { inner: future })
286    }
287
288    #[cfg(feature = "apple-cf")]
289    pub fn analyze_pixel_buffer(
290        &self,
291        pixel_buffer: &apple_cf::cv::CVPixelBuffer,
292        orientation: ImageOrientation,
293        configuration: &ImageAnalyzerConfiguration,
294    ) -> Result<AnalyzeImageFuture, VisionKitError> {
295        let cfg_cs = json_cstring(configuration)?;
296        let (future, ctx) = AsyncCompletion::create();
297        unsafe {
298            ffi::image_analyzer::vk_image_analyzer_analyze_pixel_buffer_async(
299                self.token,
300                pixel_buffer.as_ptr(),
301                orientation.raw_value(),
302                cfg_cs.as_ptr(),
303                analyze_cb,
304                ctx,
305            );
306        }
307        Ok(AnalyzeImageFuture { inner: future })
308    }
309}
310
311// ============================================================================
312// AsyncOverlaySubjects
313// ============================================================================
314
315type JsonOutcome = Result<String, VisionKitError>;
316
317unsafe extern "C" fn subject_json_cb(
318    result: *const c_void,
319    status: i32,
320    error: *const c_char,
321    ctx: *mut c_void,
322) {
323    catch_user_panic("visionkit::subject_json_cb", move || {
324        let outcome: JsonOutcome = if status != ffi::status::OK {
325            Err(unsafe { async_error(status, error) })
326        } else if result.is_null() {
327            Err(VisionKitError::Unknown(
328                "Swift bridge returned no subject payload".to_owned(),
329            ))
330        } else {
331            Ok(unsafe { cstring_result_to_string(result) })
332        };
333        unsafe { AsyncCompletion::complete_ok(ctx, outcome) };
334    });
335}
336
337/// Future returned by [`AsyncOverlaySubjects::subjects`].
338#[must_use = "futures do nothing unless polled"]
339pub struct SubjectsFuture {
340    inner: AsyncCompletionFuture<JsonOutcome>,
341}
342
343impl std::fmt::Debug for SubjectsFuture {
344    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
345        f.debug_struct("SubjectsFuture").finish_non_exhaustive()
346    }
347}
348
349impl Future for SubjectsFuture {
350    type Output = Result<Vec<AnalysisSubjectBounds>, VisionKitError>;
351
352    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
353        Pin::new(&mut self.inner).poll(cx).map(|r| {
354            let json = r.map_err(VisionKitError::Unknown)??;
355            serde_json::from_str::<Vec<AnalysisSubjectBounds>>(&json).map_err(|e| {
356                VisionKitError::Unknown(format!(
357                    "failed to decode subjects JSON from Swift bridge: {e}"
358                ))
359            })
360        })
361    }
362}
363
364/// Future returned by [`AsyncOverlaySubjects::subject_at`].
365#[must_use = "futures do nothing unless polled"]
366pub struct SubjectAtFuture {
367    inner: AsyncCompletionFuture<JsonOutcome>,
368}
369
370impl std::fmt::Debug for SubjectAtFuture {
371    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
372        f.debug_struct("SubjectAtFuture").finish_non_exhaustive()
373    }
374}
375
376impl Future for SubjectAtFuture {
377    type Output = Result<Option<AnalysisSubjectBounds>, VisionKitError>;
378
379    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
380        Pin::new(&mut self.inner).poll(cx).map(|r| {
381            let json = r.map_err(VisionKitError::Unknown)??;
382            serde_json::from_str::<Option<AnalysisSubjectBounds>>(&json).map_err(|e| {
383                VisionKitError::Unknown(format!(
384                    "failed to decode subject-at JSON from Swift bridge: {e}"
385                ))
386            })
387        })
388    }
389}
390
391/// True-async entry point for `ImageAnalysisOverlayView.subjects` and
392/// `ImageAnalysisOverlayView.subject(at:)` (macOS).
393///
394/// On macOS the subject APIs live on `ImageAnalysisOverlayView`
395/// (Rust: [`LiveTextInteraction`]), not directly on `ImageAnalysis`.
396/// Both require macOS 13+ and the [`crate::ImageAnalysisTypes::VISUAL_LOOK_UP`]
397/// analysis type in the configuration used when the analysis was performed.
398///
399/// # Note on subject bounds coordinate space
400///
401/// Bounds are in the same coordinate space that VisionKit uses when populating
402/// the overlay view.  That is, they are relative to the view's bounds as
403/// configured via `setPreferredInteractionTypes` and `setAnalysis(_:)`.
404pub struct AsyncOverlaySubjects<'a> {
405    interaction: &'a LiveTextInteraction,
406}
407
408impl<'a> AsyncOverlaySubjects<'a> {
409    /// Wrap a [`LiveTextInteraction`] for async subject queries.
410    ///
411    /// Each query takes its own reference to the overlay view before it
412    /// returns, so pending futures stay valid if the `interaction` is dropped.
413    #[must_use]
414    pub const fn new(interaction: &'a LiveTextInteraction) -> Self {
415        Self { interaction }
416    }
417
418    /// Asynchronously retrieve all subjects as their bounds rectangles.
419    ///
420    /// Internally calls `await overlayView.subjects` on the Swift side
421    /// (requires `@MainActor`). Each subject's `bounds` is accessed
422    /// synchronously within that actor context.
423    ///
424    /// Returns an empty `Vec` when no subjects are found or when the analysis
425    /// did not include [`crate::ImageAnalysisTypes::VISUAL_LOOK_UP`].
426    #[must_use = "returns a future that must be awaited"]
427    pub fn subjects(&self) -> SubjectsFuture {
428        let (future, ctx) = AsyncCompletion::create();
429        unsafe {
430            ffi::live_text_interaction::vk_live_text_overlay_subjects_async(
431                self.interaction.raw_token(),
432                subject_json_cb,
433                ctx,
434            );
435        }
436        SubjectsFuture { inner: future }
437    }
438
439    /// Asynchronously find the subject at the given overlay-coordinate point.
440    ///
441    /// Returns `Ok(None)` when no subject is present at `(x, y)`.
442    #[must_use = "returns a future that must be awaited"]
443    pub fn subject_at(&self, x: f64, y: f64) -> SubjectAtFuture {
444        let (future, ctx) = AsyncCompletion::create();
445        unsafe {
446            ffi::live_text_interaction::vk_live_text_overlay_subject_at_async(
447                self.interaction.raw_token(),
448                x,
449                y,
450                subject_json_cb,
451                ctx,
452            );
453        }
454        SubjectAtFuture { inner: future }
455    }
456}
457
458// ============================================================================
459// block_on — run-loop-aware executor
460// ============================================================================
461
462struct ThreadWaker {
463    thread: Thread,
464    woken: AtomicBool,
465}
466
467impl Wake for ThreadWaker {
468    fn wake(self: Arc<Self>) {
469        self.wake_by_ref();
470    }
471
472    fn wake_by_ref(self: &Arc<Self>) {
473        self.woken.store(true, Ordering::Release);
474        self.thread.unpark();
475    }
476}
477
478extern "C" {
479    fn pthread_main_np() -> c_int;
480}
481
482/// Drive a VisionKit async future to completion on the current thread.
483///
484/// On the main thread it pumps the Obj-C main run loop until the future is
485/// woken, because VisionKit completes its work through the main queue (and
486/// the overlay-subject queries run on the main actor). On any other thread it
487/// parks until woken; the futures then complete only while the main thread is
488/// running its run loop, as it does in an AppKit app.
489///
490/// # Example
491///
492/// ```rust,no_run
493/// use visionkit::async_api::{AsyncImageAnalyzer, block_on};
494/// use visionkit::{ImageAnalysisTypes, ImageAnalyzerConfiguration, ImageOrientation};
495///
496/// let cfg = ImageAnalyzerConfiguration::new(ImageAnalysisTypes::TEXT);
497/// let analysis = block_on(async {
498///     AsyncImageAnalyzer::new()?
499///         .analyze_image_at_path("/path/to/image.png", ImageOrientation::Up, &cfg)?
500///         .await
501/// });
502/// ```
503pub fn block_on<F: Future>(future: F) -> F::Output {
504    let on_main_thread = unsafe { pthread_main_np() } != 0;
505    let state = Arc::new(ThreadWaker {
506        thread: thread::current(),
507        woken: AtomicBool::new(false),
508    });
509    let waker = Waker::from(Arc::clone(&state));
510    let mut cx = Context::from_waker(&waker);
511    let mut future = std::pin::pin!(future);
512    loop {
513        if let Poll::Ready(output) = future.as_mut().poll(&mut cx) {
514            return output;
515        }
516        while !state.woken.swap(false, Ordering::Acquire) {
517            if on_main_thread {
518                unsafe { ffi::image_analyzer::vk_pump_main_run_loop(10) };
519            } else {
520                thread::park();
521            }
522        }
523    }
524}