1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
use std::{
boxed::Box,
future::Future,
mem, panic,
panic::{catch_unwind, AssertUnwindSafe},
pin::Pin,
rc::Rc,
sync::Arc,
task::{Context, Poll, Waker},
};
use super::application::{ApplicationHandle, HasAppHandle};
use crate::core::application::*;
/// The data that is sent to the GUI thread for `DelegateFuture`.
struct DelegateData<'a, 'b, H, R> {
handle: H,
result: &'a mut Option<Result<R, DelegateError>>,
func: Box<dyn FnOnce(H) -> R + Send + 'b>,
waker: Waker,
}
//unsafe impl<'a,H,R> Send for DelegateData<'a,H,R> {}
/// The data that is sent to the GUI thread for `DelegateFutureFuture`.
struct DelegateFutureData<'a, 'b, R>
where
R: Send,
{
inner: &'b mut DelegateFutureInner<'a, R>,
waker: Waker,
}
/// The error that occurs when you're delegating work to the GUI thread, but it
/// fails to finish and/or return a result.
#[derive(Debug)]
pub enum DelegateError {
/// The runtime has either not yet started or already ended.
/// This happens when the application has already exited for example.
RuntimeNotAvailable,
/// The delegated closure has panicked.
ClosurePanicked,
}
/// This future executes a closure on the GUI thread and returns the result.
pub struct DelegateFuture<'a, H, R>
where
R: Send,
{
handle: H,
func: Option<Box<dyn FnOnce(H) -> R + Send + 'a>>,
result: Option<Result<R, DelegateError>>,
started: bool,
}
impl<'a, H, R> Unpin for DelegateFuture<'a, H, R> where R: Send {}
/// # Safety
/// `DelegateFuture` by itself is not send.
/// This is because we keep a handle `H`, which is not necessarily `Send`.
/// However, because the closure only executes on the GUI thread,
/// and because the handle is only provided to the closure that will be
/// executed on the GUI thread, this should be fine.
unsafe impl<'a, H, R> Send for DelegateFuture<'a, H, R> where R: Send {}
/// This future runs a future on the GUI thread and returns its output.
pub struct DelegateFutureFuture<'a, R>
where
R: Send,
{
app_handle: ApplicationHandle,
inner: DelegateFutureInner<'a, R>,
started: bool,
}
/// # Safety
/// `DelegateFutureFuture` by itself is not send.
/// This is because of `ApplicationHandle`.
/// However, because the closure only executes on the GUI thread,
/// and because this handle that is provided to the closure is something that
/// will only be sent with the closure to the GUI thread, this should be fine.
unsafe impl<'a, R> Send for DelegateFutureFuture<'a, R> where R: Send {}
impl<'a, R> Unpin for DelegateFutureFuture<'a, R> where R: Send {}
/// This is not a future but the inner part that of `DelegateFutureFuture` that
/// needs to have mutable reference.
struct DelegateFutureInner<'a, R>
where
R: Send,
{
result: Option<Result<R, DelegateError>>,
future: Pin<Box<dyn Future<Output = R> + 'a>>,
}
// # Safety
// `DelegateFutureInner` is marked as `Send` so that `delegate_async` can pass a
// non-`Send` future into this future. The resulting future from the closure of
// `delegate_async` does not need to be `Send` because the future is obtained
// _and_ executed within the GUI thread. `delegate_async` puts a future obtained
// from an `async` block into `DelegateFutureFuture`, and therefor in
// `DelegateFutureInner`. However, because the future obtained from the closure
// is not necessarily `Send`, Rust makes the whole async block non-`Send`.
// Even though all parts of that `async` block are executed on the same thread
// in this scenario. This is therefor marked as `Send` on the condition that
// whenever `DelegateFutureFuture` is constructed, care should be taken to make
// sure that the future is safe to send to other threads.
unsafe impl<'a, R> Send for DelegateFutureInner<'a, R> where R: Send {}
impl<'a, H, R> DelegateFuture<'a, H, R>
where
R: Send,
{
pub(super) fn new<F>(handle: H, func: F) -> Self
where
F: FnOnce(H) -> R + Send + 'a,
R: Send,
{
Self {
handle,
func: Some(Box::new(func)),
result: None,
started: false,
}
}
}
#[cfg(feature = "threadsafe")]
impl<'a, H, R> Future for DelegateFuture<'a, H, R>
where
H: HasAppHandle + Clone + 'static,
R: Send + 'static,
{
type Output = Result<R, DelegateError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
if !self.started {
self.started = true;
let app_inner = self.handle.app_handle().inner;
// Move ownership from `DelegateFuture` to `DelegateData`
let mut func = None;
mem::swap(&mut self.func, &mut func);
// Data to provide for the dispatched c function
// This includes the closure to actually call,
// a pointer to set the output with,
// and a waker to finish our future with.
let data = DelegateData {
handle: self.handle.clone(),
func: func.unwrap(),
result: &mut self.result,
waker: cx.waker().clone(),
};
let succeeded = {
let data_ptr = Box::into_raw(Box::new(data));
app_inner.dispatch(delegate_handler::<H, R>, data_ptr as _)
};
// cbw_Application_dispatch fails when there is now runtime that is running
if !succeeded {
return Poll::Ready(Err(DelegateError::RuntimeNotAvailable));
}
Poll::Pending
} else {
if self.result.is_none() {
return Poll::Pending;
}
// Move ownership of output to temporary value so we can return it
let mut temp: Option<Result<R, DelegateError>> = None;
mem::swap(&mut self.result, &mut temp);
Poll::Ready(temp.unwrap())
}
}
}
#[cfg(feature = "threadsafe")]
impl<'a, R> DelegateFutureFuture<'a, R>
where
R: Send,
{
pub(super) fn new(app_handle: ApplicationHandle, future: impl Future<Output = R> + 'a) -> Self {
Self {
app_handle,
inner: DelegateFutureInner {
result: None,
future: Box::pin(future),
},
started: false,
}
}
}
#[cfg(feature = "threadsafe")]
impl<'a, R> Future for DelegateFutureFuture<'a, R>
where
R: Send,
{
type Output = Result<R, DelegateError>;
fn poll(mut self: Pin<&mut Self>, ctx: &mut Context) -> Poll<Self::Output> {
// While the result is not yet set, we can keep polling
if !self.started {
self.started = true;
let app_inner = self.app_handle.inner.clone();
let succeeded = unsafe {
let data_ptr = Box::into_raw(Box::new(DelegateFutureData {
inner: &mut self.inner,
waker: ctx.waker().clone(),
}));
app_inner.dispatch(delegate_async_handler::<R>, data_ptr as _)
};
// cbw_Application_dispatch fails when there is now runtime that is running
if !succeeded {
return Poll::Ready(Err(DelegateError::RuntimeNotAvailable));
}
Poll::Pending
} else {
// Move ownership of output to temporary value so we can return it
let mut temp: Option<Result<R, DelegateError>> = None;
mem::swap(&mut self.inner.result, &mut temp);
Poll::Ready(temp.unwrap())
}
}
}
fn delegate_handler<H, R>(app: ApplicationImpl, _data: *mut ())
where
H: Clone + 'static,
R: 'static,
{
let data_ptr = _data as *mut DelegateData<'static, 'static, H, R>;
let data = unsafe { Box::from_raw(data_ptr) }; // Take ownership of the data struct
match *data {
DelegateData {
handle,
func,
result,
waker,
} => {
// Catch Rust panics during execution of delegated function
match catch_unwind(AssertUnwindSafe(|| {
*result = Some(Ok(func(handle)));
waker.clone().wake();
})) {
Ok(()) => {}
Err(_) => {
*result = Some(Err(DelegateError::ClosurePanicked));
// Wake the future before exiting. This allows the calling thread to still
// receive the `DelegateError` before the application stops working.
waker.wake();
app.exit(-1);
}
}
}
}
}
#[cfg(feature = "threadsafe")]
fn delegate_async_handler<R>(app: ApplicationImpl, _data: *mut ())
where
R: Send,
{
let data_ptr = _data as *mut DelegateFutureData<R>;
let data = unsafe { Box::from_raw(data_ptr) }; // Take ownership of the data struct
match *data {
DelegateFutureData { inner, waker } => {
// Catch Rust panics
match panic::catch_unwind(AssertUnwindSafe(|| {
let mut ctx = Context::from_waker(&waker);
match inner.future.as_mut().poll(&mut ctx) {
Poll::Pending => {}
Poll::Ready(result) => {
// Set the result and wake our future so it gets returned
inner.result = Some(Ok(result));
waker.clone().wake();
}
}
})) {
Ok(()) => {}
Err(_) => {
inner.result = Some(Err(DelegateError::ClosurePanicked));
// Wake the future before exiting. This allows the calling thread to still
// receive the `DelegateError` before the application stops working.
waker.wake();
app.exit(-1);
}
}
}
}
}