|
| 1 | +use std::future::Future; |
| 2 | +use std::marker::PhantomData; |
| 3 | +use std::sync::Arc; |
| 4 | + |
| 5 | +use futures_task::{LocalFutureObj, LocalSpawn, SpawnError}; |
| 6 | + |
| 7 | +use gdnative_core::core_types::{ToVariant, Variant}; |
| 8 | +use gdnative_core::log::{self, Site}; |
| 9 | +use gdnative_core::nativescript::export::{Method, Varargs}; |
| 10 | +use gdnative_core::nativescript::{NativeClass, RefInstance}; |
| 11 | +use gdnative_core::object::ownership::Shared; |
| 12 | + |
| 13 | +use crate::rt::Context; |
| 14 | + |
| 15 | +/// Trait for async methods. When exported, such methods return `FunctionState`-like |
| 16 | +/// objects that can be manually resumed or yielded to completion. |
| 17 | +/// |
| 18 | +/// Async methods are always spawned locally on the thread where they were created, |
| 19 | +/// and never sent to another thread. This is so that we can ensure the safety of |
| 20 | +/// emitting signals from the `FunctionState`-like object. If you need to off-load |
| 21 | +/// some task to another thread, consider using something like |
| 22 | +/// `futures::future::Remote` to spawn it remotely on a thread pool. |
| 23 | +pub trait AsyncMethod<C: NativeClass>: Send + Sync + 'static { |
| 24 | + /// Spawns the future for result of this method with `spawner`. This is done so |
| 25 | + /// that implementors of this trait do not have to name their future types. |
| 26 | + /// |
| 27 | + /// If the `spawner` object is not used, the Godot side of the call will fail, output an |
| 28 | + /// error, and return a `Nil` variant. |
| 29 | + fn spawn_with(&self, spawner: Spawner<'_, C>); |
| 30 | + |
| 31 | + /// Returns an optional site where this method is defined. Used for logging errors in FFI wrappers. |
| 32 | + /// |
| 33 | + /// Default implementation returns `None`. |
| 34 | + #[inline] |
| 35 | + fn site() -> Option<Site<'static>> { |
| 36 | + None |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +/// A helper structure for working around naming future types. See [`Spawner::spawn`]. |
| 41 | +pub struct Spawner<'a, C: NativeClass> { |
| 42 | + sp: &'static dyn LocalSpawn, |
| 43 | + ctx: Context, |
| 44 | + this: RefInstance<'a, C, Shared>, |
| 45 | + args: Varargs<'a>, |
| 46 | + result: &'a mut Option<Result<(), SpawnError>>, |
| 47 | + /// Remove Send and Sync |
| 48 | + _marker: PhantomData<*const ()>, |
| 49 | +} |
| 50 | + |
| 51 | +impl<'a, C: NativeClass> Spawner<'a, C> { |
| 52 | + /// Consumes this `Spawner` and spawns a future returned by the closure. This indirection |
| 53 | + /// is necessary so that implementors of the `AsyncMethod` trait do not have to name their |
| 54 | + /// future types. |
| 55 | + pub fn spawn<F, R>(self, f: F) |
| 56 | + where |
| 57 | + F: FnOnce(Arc<Context>, RefInstance<'_, C, Shared>, Varargs<'_>) -> R, |
| 58 | + R: Future<Output = Variant> + 'static, |
| 59 | + { |
| 60 | + let ctx = Arc::new(self.ctx); |
| 61 | + let future = f(Arc::clone(&ctx), self.this, self.args); |
| 62 | + *self.result = Some( |
| 63 | + self.sp |
| 64 | + .spawn_local_obj(LocalFutureObj::new(Box::new(async move { |
| 65 | + let value = future.await; |
| 66 | + ctx.resolve(value); |
| 67 | + }))), |
| 68 | + ); |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +/// Adapter for async methods that implements `Method` and can be registered. |
| 73 | +#[derive(Clone, Copy, Default, Debug)] |
| 74 | +pub struct Async<F> { |
| 75 | + f: F, |
| 76 | +} |
| 77 | + |
| 78 | +impl<F> Async<F> { |
| 79 | + /// Wrap `f` in an adapter that implements `Method`. |
| 80 | + #[inline] |
| 81 | + pub fn new(f: F) -> Self { |
| 82 | + Async { f } |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +impl<C: NativeClass, F: AsyncMethod<C>> Method<C> for Async<F> { |
| 87 | + fn call(&self, this: RefInstance<'_, C, Shared>, args: Varargs<'_>) -> Variant { |
| 88 | + if let Some(sp) = crate::executor::local_spawn() { |
| 89 | + let ctx = Context::new(); |
| 90 | + let func_state = ctx.func_state(); |
| 91 | + |
| 92 | + let mut result = None; |
| 93 | + self.f.spawn_with(Spawner { |
| 94 | + sp, |
| 95 | + ctx, |
| 96 | + this, |
| 97 | + args, |
| 98 | + result: &mut result, |
| 99 | + _marker: PhantomData, |
| 100 | + }); |
| 101 | + |
| 102 | + match result { |
| 103 | + Some(Ok(())) => func_state.to_variant(), |
| 104 | + Some(Err(err)) => { |
| 105 | + log::error( |
| 106 | + Self::site().unwrap_or_default(), |
| 107 | + format_args!("unable to spawn future: {}", err), |
| 108 | + ); |
| 109 | + Variant::new() |
| 110 | + } |
| 111 | + None => { |
| 112 | + log::error( |
| 113 | + Self::site().unwrap_or_default(), |
| 114 | + format_args!("implementation did not spawn a future"), |
| 115 | + ); |
| 116 | + Variant::new() |
| 117 | + } |
| 118 | + } |
| 119 | + } else { |
| 120 | + log::error( |
| 121 | + Self::site().unwrap_or_default(), |
| 122 | + "a global executor must be set before any async methods can be called on this thread", |
| 123 | + ); |
| 124 | + Variant::new() |
| 125 | + } |
| 126 | + } |
| 127 | +} |
0 commit comments