gdnative_async/
rt.rs

1use std::fmt::Display;
2use std::marker::PhantomData;
3
4use func_state::FuncState;
5use gdnative_bindings::Object;
6use gdnative_core::core_types::{GodotError, Variant};
7use gdnative_core::init::InitHandle;
8use gdnative_core::object::{Instance, SubClass, TInstance, TRef};
9
10use crate::future;
11
12mod bridge;
13mod func_state;
14
15/// Context for creating `yield`-like futures in async methods.
16pub struct Context {
17    func_state: Instance<FuncState>,
18    /// Remove Send and Sync
19    _marker: PhantomData<*const ()>,
20}
21
22impl Context {
23    pub(crate) fn new() -> Self {
24        Context {
25            func_state: FuncState::new().into_shared(),
26            _marker: PhantomData,
27        }
28    }
29
30    pub(crate) fn func_state(&self) -> Instance<FuncState> {
31        self.func_state.clone()
32    }
33
34    fn safe_func_state(&self) -> TInstance<'_, FuncState> {
35        // SAFETY: FuncState objects are bound to their origin threads in Rust, and
36        // Context is !Send, so this is safe to call within this type.
37        // Non-Rust code is expected to be following the official guidelines as per
38        // the global safety assumptions. Since a reference of `FuncState` is held by
39        // Rust, it voids the assumption to send the reference to any thread aside from
40        // the one where it's created.
41        unsafe { self.func_state.assume_safe() }
42    }
43
44    pub(crate) fn resolve(&self, value: Variant) {
45        func_state::resolve(self.safe_func_state(), value);
46    }
47
48    /// Returns a future that waits until the corresponding `FunctionState` object
49    /// is manually resumed from GDScript, and yields the argument to `resume` or `Nil`
50    /// if nothing is passed.
51    ///
52    /// Calling this function will put the associated `FunctionState`-like object in
53    /// resumable state, and will make it emit a `resumable` signal if it isn't in that
54    /// state already.
55    ///
56    /// Only the most recent future created from this `Context` is guaranteed to resolve
57    /// upon a `resume` call. If any previous futures weren't `await`ed to completion, they
58    /// are no longer guaranteed to resolve, and have unspecified, but safe behavior
59    /// when polled.
60    pub fn until_resume(&self) -> future::Yield<Variant> {
61        let (future, resume) = future::make();
62        func_state::make_resumable(self.safe_func_state(), resume);
63        future
64    }
65
66    /// Returns a future that waits until the specified signal is emitted, if connection succeeds.
67    /// Yields any arguments emitted with the signal.
68    ///
69    /// Only the most recent future created from this `Context` is guaranteed to resolve
70    /// when the signal is emitted. If any previous futures weren't `await`ed to completion, they
71    /// are no longer guaranteed to resolve, and have unspecified, but safe behavior
72    /// when polled.
73    ///
74    /// # Errors
75    ///
76    /// If connection to the signal failed.
77    pub fn signal<C>(
78        &self,
79        obj: TRef<'_, C>,
80        signal: &str,
81    ) -> Result<future::Yield<Vec<Variant>>, GodotError>
82    where
83        C: SubClass<Object>,
84    {
85        let (future, resume) = future::make();
86        bridge::SignalBridge::connect(obj.upcast(), signal, resume)?;
87        Ok(future)
88    }
89}
90
91/// Adds required supporting NativeScript classes to `handle`. This must be called once and
92/// only once per initialization.
93///
94/// This registers the internal types under an unspecified prefix, with the intention to avoid
95/// collision with user types. Users may provide a custom prefix using
96/// [`register_runtime_with_prefix`], should it be necessary to name these types.
97pub fn register_runtime(handle: &InitHandle) {
98    register_runtime_with_prefix(handle, "__GDNATIVE_ASYNC_INTERNAL__")
99}
100
101/// Adds required supporting NativeScript classes to `handle`. This must be called once and
102/// only once per initialization.
103///
104/// The user should ensure that no other NativeScript types is registered under the
105/// provided prefix.
106pub fn register_runtime_with_prefix<S>(handle: &InitHandle, prefix: S)
107where
108    S: Display,
109{
110    handle.add_class_as::<bridge::SignalBridge>(format!("{prefix}SignalBridge"));
111    handle.add_class_as::<func_state::FuncState>(format!("{prefix}FuncState"));
112}
113
114/// Releases all observers still in use. This should be called in the
115/// `godot_gdnative_terminate` callback.
116pub fn terminate_runtime() {
117    bridge::terminate();
118}