use std::ffi::{c_char, c_int, c_void, CStr};
use std::future::Future;
use std::mem::ManuallyDrop;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
use std::thread::{self, Thread};
use doom_fish_utils::completion::{AsyncCompletion, AsyncCompletionFuture};
use doom_fish_utils::panic_safe::catch_user_panic;
use serde::Deserialize;
use crate::error::VisionKitError;
use crate::ffi;
use crate::image_analysis::ImageAnalysis;
use crate::image_analyzer::{ImageAnalyzerConfiguration, ImageOrientation};
use crate::live_text_interaction::LiveTextInteraction;
use crate::private::{error_for_status, json_cstring, path_to_cstring};
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct AnalysisSubjectBounds {
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
}
unsafe fn cstring_result_to_string(ptr: *const c_void) -> String {
CStr::from_ptr(ptr.cast::<i8>())
.to_str()
.map_or_else(|_| String::new(), str::to_owned)
}
unsafe fn async_error(status: i32, error: *const c_char) -> VisionKitError {
let message = if error.is_null() {
format!("Swift bridge call failed with status code {status}")
} else {
CStr::from_ptr(error).to_string_lossy().into_owned()
};
error_for_status(status, message)
}
struct AnalysisToken(*mut c_void);
unsafe impl Send for AnalysisToken {}
impl AnalysisToken {
fn into_analysis(self) -> ImageAnalysis {
let token = ManuallyDrop::new(self);
ImageAnalysis::from_token(token.0)
}
}
impl Drop for AnalysisToken {
fn drop(&mut self) {
unsafe { ffi::image_analysis::vk_image_analysis_release(self.0) };
}
}
type AnalysisOutcome = Result<AnalysisToken, VisionKitError>;
unsafe extern "C" fn analyze_cb(
result: *const c_void,
status: i32,
error: *const c_char,
ctx: *mut c_void,
) {
catch_user_panic("visionkit::analyze_cb", move || {
let outcome: AnalysisOutcome = if status != ffi::status::OK {
Err(unsafe { async_error(status, error) })
} else if result.is_null() {
Err(VisionKitError::Unknown(
"Swift bridge returned no image analysis".to_owned(),
))
} else {
Ok(AnalysisToken(result.cast_mut()))
};
unsafe { AsyncCompletion::complete_ok(ctx, outcome) };
});
}
#[must_use = "futures do nothing unless polled"]
pub struct AnalyzeImageFuture {
inner: AsyncCompletionFuture<AnalysisOutcome>,
}
impl std::fmt::Debug for AnalyzeImageFuture {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AnalyzeImageFuture").finish_non_exhaustive()
}
}
impl Future for AnalyzeImageFuture {
type Output = Result<ImageAnalysis, VisionKitError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Pin::new(&mut self.inner).poll(cx).map(|result| {
result
.map_err(VisionKitError::Unknown)
.and_then(|outcome| outcome.map(AnalysisToken::into_analysis))
})
}
}
pub struct AsyncImageAnalyzer {
token: *mut c_void,
}
unsafe impl Send for AsyncImageAnalyzer {}
unsafe impl Sync for AsyncImageAnalyzer {}
impl Drop for AsyncImageAnalyzer {
fn drop(&mut self) {
if !self.token.is_null() {
unsafe { ffi::image_analyzer::vk_image_analyzer_release(self.token) };
}
}
}
impl AsyncImageAnalyzer {
pub fn new() -> Result<Self, VisionKitError> {
let token = unsafe { ffi::image_analyzer::vk_image_analyzer_new() };
if token.is_null() {
return Err(VisionKitError::UnavailableOnThisMacOS(
"ImageAnalyzer requires macOS 13+".to_owned(),
));
}
Ok(Self { token })
}
#[must_use]
pub fn is_supported() -> bool {
unsafe { ffi::image_analyzer::vk_image_analyzer_is_supported() != 0 }
}
pub fn analyze_image_at_path<P: AsRef<std::path::Path>>(
&self,
path: P,
orientation: ImageOrientation,
configuration: &ImageAnalyzerConfiguration,
) -> Result<AnalyzeImageFuture, VisionKitError> {
let path_cs = path_to_cstring(path.as_ref())?;
let cfg_cs = json_cstring(configuration)?;
let (future, ctx) = AsyncCompletion::create();
unsafe {
ffi::image_analyzer::vk_image_analyzer_analyze_image_async(
self.token,
path_cs.as_ptr(),
orientation.raw_value(),
cfg_cs.as_ptr(),
analyze_cb,
ctx,
);
}
Ok(AnalyzeImageFuture { inner: future })
}
#[cfg(feature = "apple-cf")]
pub fn analyze_cg_image(
&self,
image: &apple_cf::cg::CGImage,
orientation: ImageOrientation,
configuration: &ImageAnalyzerConfiguration,
) -> Result<AnalyzeImageFuture, VisionKitError> {
let cfg_cs = json_cstring(configuration)?;
let (future, ctx) = AsyncCompletion::create();
unsafe {
ffi::image_analyzer::vk_image_analyzer_analyze_cg_image_async(
self.token,
image.as_ptr(),
orientation.raw_value(),
cfg_cs.as_ptr(),
analyze_cb,
ctx,
);
}
Ok(AnalyzeImageFuture { inner: future })
}
#[cfg(feature = "apple-cf")]
pub fn analyze_pixel_buffer(
&self,
pixel_buffer: &apple_cf::cv::CVPixelBuffer,
orientation: ImageOrientation,
configuration: &ImageAnalyzerConfiguration,
) -> Result<AnalyzeImageFuture, VisionKitError> {
let cfg_cs = json_cstring(configuration)?;
let (future, ctx) = AsyncCompletion::create();
unsafe {
ffi::image_analyzer::vk_image_analyzer_analyze_pixel_buffer_async(
self.token,
pixel_buffer.as_ptr(),
orientation.raw_value(),
cfg_cs.as_ptr(),
analyze_cb,
ctx,
);
}
Ok(AnalyzeImageFuture { inner: future })
}
}
type JsonOutcome = Result<String, VisionKitError>;
unsafe extern "C" fn subject_json_cb(
result: *const c_void,
status: i32,
error: *const c_char,
ctx: *mut c_void,
) {
catch_user_panic("visionkit::subject_json_cb", move || {
let outcome: JsonOutcome = if status != ffi::status::OK {
Err(unsafe { async_error(status, error) })
} else if result.is_null() {
Err(VisionKitError::Unknown(
"Swift bridge returned no subject payload".to_owned(),
))
} else {
Ok(unsafe { cstring_result_to_string(result) })
};
unsafe { AsyncCompletion::complete_ok(ctx, outcome) };
});
}
#[must_use = "futures do nothing unless polled"]
pub struct SubjectsFuture {
inner: AsyncCompletionFuture<JsonOutcome>,
}
impl std::fmt::Debug for SubjectsFuture {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SubjectsFuture").finish_non_exhaustive()
}
}
impl Future for SubjectsFuture {
type Output = Result<Vec<AnalysisSubjectBounds>, VisionKitError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Pin::new(&mut self.inner).poll(cx).map(|r| {
let json = r.map_err(VisionKitError::Unknown)??;
serde_json::from_str::<Vec<AnalysisSubjectBounds>>(&json).map_err(|e| {
VisionKitError::Unknown(format!(
"failed to decode subjects JSON from Swift bridge: {e}"
))
})
})
}
}
#[must_use = "futures do nothing unless polled"]
pub struct SubjectAtFuture {
inner: AsyncCompletionFuture<JsonOutcome>,
}
impl std::fmt::Debug for SubjectAtFuture {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SubjectAtFuture").finish_non_exhaustive()
}
}
impl Future for SubjectAtFuture {
type Output = Result<Option<AnalysisSubjectBounds>, VisionKitError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Pin::new(&mut self.inner).poll(cx).map(|r| {
let json = r.map_err(VisionKitError::Unknown)??;
serde_json::from_str::<Option<AnalysisSubjectBounds>>(&json).map_err(|e| {
VisionKitError::Unknown(format!(
"failed to decode subject-at JSON from Swift bridge: {e}"
))
})
})
}
}
pub struct AsyncOverlaySubjects<'a> {
interaction: &'a LiveTextInteraction,
}
impl<'a> AsyncOverlaySubjects<'a> {
#[must_use]
pub const fn new(interaction: &'a LiveTextInteraction) -> Self {
Self { interaction }
}
#[must_use = "returns a future that must be awaited"]
pub fn subjects(&self) -> SubjectsFuture {
let (future, ctx) = AsyncCompletion::create();
unsafe {
ffi::live_text_interaction::vk_live_text_overlay_subjects_async(
self.interaction.raw_token(),
subject_json_cb,
ctx,
);
}
SubjectsFuture { inner: future }
}
#[must_use = "returns a future that must be awaited"]
pub fn subject_at(&self, x: f64, y: f64) -> SubjectAtFuture {
let (future, ctx) = AsyncCompletion::create();
unsafe {
ffi::live_text_interaction::vk_live_text_overlay_subject_at_async(
self.interaction.raw_token(),
x,
y,
subject_json_cb,
ctx,
);
}
SubjectAtFuture { inner: future }
}
}
struct ThreadWaker {
thread: Thread,
woken: AtomicBool,
}
impl Wake for ThreadWaker {
fn wake(self: Arc<Self>) {
self.wake_by_ref();
}
fn wake_by_ref(self: &Arc<Self>) {
self.woken.store(true, Ordering::Release);
self.thread.unpark();
}
}
extern "C" {
fn pthread_main_np() -> c_int;
}
pub fn block_on<F: Future>(future: F) -> F::Output {
let on_main_thread = unsafe { pthread_main_np() } != 0;
let state = Arc::new(ThreadWaker {
thread: thread::current(),
woken: AtomicBool::new(false),
});
let waker = Waker::from(Arc::clone(&state));
let mut cx = Context::from_waker(&waker);
let mut future = std::pin::pin!(future);
loop {
if let Poll::Ready(output) = future.as_mut().poll(&mut cx) {
return output;
}
while !state.woken.swap(false, Ordering::Acquire) {
if on_main_thread {
unsafe { ffi::image_analyzer::vk_pump_main_run_loop(10) };
} else {
thread::park();
}
}
}
}