godot_core/obj/
call_deferred.rs

1/*
2 * Copyright (c) godot-rust; Bromeon and contributors.
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
6 */
7
8use std::ops::DerefMut;
9
10use godot_ffi::is_main_thread;
11
12use crate::builtin::{Callable, Variant};
13use crate::meta::UniformObjectDeref;
14use crate::obj::bounds::Declarer;
15use crate::obj::GodotClass;
16#[cfg(since_api = "4.2")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.2")))]
17use crate::registry::signal::ToSignalObj;
18
19// Dummy traits to still allow bounds and imports.
20#[cfg(before_api = "4.2")] #[cfg_attr(published_docs, doc(cfg(before_api = "4.2")))]
21pub trait WithDeferredCall<T: GodotClass> {}
22
23// TODO(v0.4): seal this and similar traits.
24
25/// Enables `Gd::apply_deferred()` for type-safe deferred calls.
26///
27/// The trait is automatically available for all engine-defined Godot classes and user classes containing a `Base<T>` field.
28///
29/// # Usage
30///
31/// ```no_run
32/// # use godot::prelude::*;
33/// # use std::f32::consts::PI;
34/// fn some_fn(mut node: Gd<Node2D>) {
35///     node.apply_deferred(|n: &mut Node2D| n.rotate(PI))
36/// }
37/// ```
38#[cfg(since_api = "4.2")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.2")))]
39pub trait WithDeferredCall<T: GodotClass> {
40    /// Defers the given closure to run during [idle time](https://docs.godotengine.org/en/stable/classes/class_object.html#class-object-method-call-deferred).
41    ///
42    /// This is a type-safe alternative to [`Object::call_deferred()`][crate::classes::Object::call_deferred].
43    ///
44    /// # Panics
45    /// If called outside the main thread.
46    fn apply_deferred<F>(&mut self, rust_function: F)
47    where
48        F: FnOnce(&mut T) + 'static;
49}
50
51#[cfg(since_api = "4.2")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.2")))]
52impl<T, S, D> WithDeferredCall<T> for S
53where
54    T: UniformObjectDeref<D, Declarer = D>,
55    S: ToSignalObj<T>,
56    D: Declarer,
57{
58    fn apply_deferred<'a, F>(&mut self, rust_function: F)
59    where
60        F: FnOnce(&mut T) + 'static,
61    {
62        assert!(
63            is_main_thread(),
64            "`apply_deferred` must be called on the main thread"
65        );
66
67        let mut this = self.to_signal_obj().clone();
68        let callable = Callable::from_once_fn("apply_deferred", move |_| {
69            let mut this_mut = T::object_as_mut(&mut this);
70            rust_function(this_mut.deref_mut());
71            Ok(Variant::nil())
72        });
73        callable.call_deferred(&[]);
74    }
75}