1use 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#[derive(Debug, Clone, PartialEq, Deserialize)]
79pub struct AnalysisSubjectBounds {
80 pub x: f64,
82 pub y: f64,
84 pub width: f64,
86 pub height: f64,
88}
89
90unsafe 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
116struct 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#[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
183pub struct AsyncImageAnalyzer {
189 token: *mut c_void,
190}
191
192unsafe 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 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 #[must_use]
228 pub fn is_supported() -> bool {
229 unsafe { ffi::image_analyzer::vk_image_analyzer_is_supported() != 0 }
230 }
231
232 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
311type 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#[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#[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
391pub struct AsyncOverlaySubjects<'a> {
405 interaction: &'a LiveTextInteraction,
406}
407
408impl<'a> AsyncOverlaySubjects<'a> {
409 #[must_use]
414 pub const fn new(interaction: &'a LiveTextInteraction) -> Self {
415 Self { interaction }
416 }
417
418 #[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 #[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
458struct 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
482pub 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}