1use std::{future, pin::Pin, ptr};
4
5use glib::{GString, translate::*};
6
7use crate::{Drop, ffi, prelude::*};
8
9impl Drop {
10 #[doc(alias = "gdk_drop_read_async")]
23 pub fn read_async<Q: FnOnce(Result<(gio::InputStream, GString), glib::Error>) + 'static>(
24 &self,
25 mime_types: &[&str],
26 io_priority: glib::Priority,
27 cancellable: Option<&impl IsA<gio::Cancellable>>,
28 callback: Q,
29 ) {
30 let main_context = glib::MainContext::ref_thread_default();
31 let is_main_context_owner = main_context.is_owner();
32 let has_acquired_main_context = (!is_main_context_owner)
33 .then(|| main_context.acquire().ok())
34 .flatten();
35 assert!(
36 is_main_context_owner || has_acquired_main_context.is_some(),
37 "Async operations only allowed if the thread is owning the MainContext"
38 );
39
40 let user_data: Box<glib::thread_guard::ThreadGuard<Q>> =
41 Box::new(glib::thread_guard::ThreadGuard::new(callback));
42 unsafe extern "C" fn read_async_trampoline<
43 Q: FnOnce(Result<(gio::InputStream, GString), glib::Error>) + 'static,
44 >(
45 _source_object: *mut glib::gobject_ffi::GObject,
46 res: *mut gio::ffi::GAsyncResult,
47 user_data: glib::ffi::gpointer,
48 ) {
49 unsafe {
50 let mut error = ptr::null_mut();
51 let mut out_mime_type = ptr::null();
52 let ret = ffi::gdk_drop_read_finish(
53 _source_object as *mut _,
54 res,
55 &mut out_mime_type,
56 &mut error,
57 );
58 let result = if error.is_null() {
59 Ok((from_glib_full(ret), from_glib_none(out_mime_type)))
60 } else {
61 Err(from_glib_full(error))
62 };
63 let callback: Box<glib::thread_guard::ThreadGuard<Q>> =
64 Box::from_raw(user_data as *mut _);
65 let callback = callback.into_inner();
66 callback(result);
67 }
68 }
69 let callback = read_async_trampoline::<Q>;
70 unsafe {
71 ffi::gdk_drop_read_async(
72 self.to_glib_none().0,
73 mime_types.to_glib_none().0,
74 io_priority.into_glib(),
75 cancellable.map(|p| p.as_ref()).to_glib_none().0,
76 Some(callback),
77 Box::into_raw(user_data) as *mut _,
78 );
79 }
80 }
81
82 #[allow(clippy::type_complexity)]
83 pub fn read_future(
84 &self,
85 mime_types: &[&str],
86 io_priority: glib::Priority,
87 ) -> Pin<
88 Box<
89 dyn future::Future<Output = Result<(gio::InputStream, GString), glib::Error>> + 'static,
90 >,
91 > {
92 let mime_types = mime_types
93 .iter()
94 .copied()
95 .map(String::from)
96 .collect::<Vec<_>>();
97 Box::pin(gio::GioFuture::new(self, move |obj, cancellable, send| {
98 let mime_types = mime_types.iter().map(|s| s.as_str()).collect::<Vec<_>>();
99 obj.read_async(&mime_types, io_priority, Some(cancellable), move |res| {
100 send.resolve(res);
101 });
102 }))
103 }
104}