godot_core/obj/traits.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 godot_ffi as sys;
9
10use crate::builder::ClassBuilder;
11use crate::builtin::GString;
12use crate::init::InitLevel;
13use crate::meta::ClassId;
14use crate::meta::inspect::EnumConstant;
15use crate::obj::{Base, BaseMut, BaseRef, BorrowedGd, Bounds, Gd, bounds};
16use crate::signal::SignalObject;
17use crate::storage::Storage;
18
19/// Makes `T` eligible to be managed by Godot and stored in [`Gd<T>`][crate::obj::Gd] pointers.
20///
21/// The behavior of types implementing this trait is influenced by the associated types; check their documentation for information.
22///
23/// Normally, you don't need to implement this trait yourself; use [`#[derive(GodotClass)]`](../register/derive.GodotClass.html) instead.
24// Above intra-doc link to the derive-macro only works as HTML, not as symbol link.
25#[diagnostic::on_unimplemented(
26 message = "only classes registered with Godot are allowed in this context",
27 note = "you can use `#[derive(GodotClass)]` to register your own structs with Godot",
28 note = "see also: https://godot-rust.github.io/book/register/classes.html"
29)]
30pub trait GodotClass: Bounds + 'static
31where
32 Self: Sized,
33{
34 /// The immediate superclass of `T`. This is always a Godot engine class.
35 type Base: GodotClass; // not EngineClass because it can be ()
36
37 /// Globally unique class ID, linked to the name under which the class is registered in Godot.
38 ///
39 /// The name may deviate from the Rust struct name: `HttpRequest::class_id().to_cow_str() == "HTTPRequest"`.
40 fn class_id() -> ClassId;
41
42 /// Initialization level, during which this class should be initialized with Godot.
43 ///
44 /// The default is a good choice in most cases; override only if you have very specific initialization requirements.
45 /// It must not be less than `Base::INIT_LEVEL`.
46 const INIT_LEVEL: InitLevel = <Self::Base as GodotClass>::INIT_LEVEL;
47
48 /// Returns whether `Self` inherits from `Base`.
49 ///
50 /// This is reflexive, i.e `Self` inherits from itself.
51 ///
52 /// See also [`Inherits`] for a trait bound.
53 fn inherits<Base: GodotClass>() -> bool {
54 if Self::class_id() == Base::class_id() {
55 true
56 } else if Self::Base::class_id() == <NoBase>::class_id() {
57 false
58 } else {
59 Self::Base::inherits::<Base>()
60 }
61 }
62}
63
64/// Type representing the absence of a base class, at the root of the hierarchy.
65///
66/// `NoBase` is used as the base class for exactly one class: [`Object`][crate::classes::Object].
67///
68/// This is an enum without any variants, as we should never construct an instance of this class.
69pub enum NoBase {}
70
71impl GodotClass for NoBase {
72 type Base = NoBase;
73
74 fn class_id() -> ClassId {
75 ClassId::none()
76 }
77
78 const INIT_LEVEL: InitLevel = InitLevel::Core; // arbitrary; never read.
79}
80
81unsafe impl Bounds for NoBase {
82 type Memory = bounds::MemManual;
83 type DynMemory = bounds::MemManual;
84 type Declarer = bounds::DeclEngine;
85 type Exportable = bounds::No;
86}
87
88/// Non-strict inheritance relationship in the Godot class hierarchy.
89///
90/// `Derived: Inherits<Base>` means that either `Derived` is a subclass of `Base`, or the class `Base` itself (hence "non-strict").
91///
92/// This trait is automatically implemented for all Godot engine classes and user-defined classes that derive [`GodotClass`].
93/// It has `GodotClass` as a supertrait, allowing your code to have bounds solely on `Derived: Inherits<Base>` rather than
94/// `Derived: Inherits<Base> + GodotClass`.
95///
96/// Inheritance is transitive across indirect base classes: `Node3D` implements `Inherits<Node>` and `Inherits<Object>`.
97///
98/// The trait is also reflexive: `T` always implements `Inherits<T>`.
99///
100/// # Usage
101///
102/// The primary use case for this trait is polymorphism: you write a function that accepts anything that derives from a certain class
103/// (including the class itself):
104/// ```no_run
105/// # use godot::prelude::*;
106/// fn print_node<T>(node: Gd<T>)
107/// where
108/// T: Inherits<Node>,
109/// {
110/// let up = node.upcast(); // type Gd<Node> inferred
111/// println!("Node #{} with name {}", up.instance_id(), up.get_name());
112/// up.free();
113/// }
114///
115/// // Call with different types
116/// print_node(Node::new_alloc()); // works on T=Node as well
117/// print_node(Node2D::new_alloc()); // or derived classes
118/// print_node(Node3D::new_alloc());
119/// ```
120///
121/// A variation of the above pattern works without `Inherits` or generics, if you move the `upcast()` into the call site:
122/// ```no_run
123/// # use godot::prelude::*;
124/// fn print_node(node: Gd<Node>) { /* ... */ }
125///
126/// // Call with different types
127/// print_node(Node::new_alloc()); // no upcast needed
128/// print_node(Node2D::new_alloc().upcast());
129/// print_node(Node3D::new_alloc().upcast());
130/// ```
131///
132/// # Safety
133///
134/// This trait must only be implemented for subclasses of `Base`.
135///
136/// Importantly, this means it is always safe to upcast a value of type `Gd<Self>` to `Gd<Base>`.
137pub unsafe trait Inherits<Base: GodotClass>: GodotClass {
138 /// True iff `Self == Base`.
139 ///
140 /// Exists because something like C++'s [`std::is_same`](https://en.cppreference.com/w/cpp/types/is_same.html) is notoriously difficult
141 /// in stable Rust, due to lack of specialization.
142 const IS_SAME_CLASS: bool = false;
143}
144
145// SAFETY: Every class is a subclass of itself.
146unsafe impl<T: GodotClass> Inherits<T> for T {
147 const IS_SAME_CLASS: bool = true;
148}
149
150/// Trait that defines a `T` -> `dyn Trait` relation for use in [`DynGd`][crate::obj::DynGd].
151///
152/// You should typically not implement this manually, but use the [`#[godot_dyn]`](../register/attr.godot_dyn.html) macro.
153#[diagnostic::on_unimplemented(
154 message = "`{Trait}` needs to be a trait object linked with class `{Self}` in the library",
155 note = "you can use `#[godot_dyn]` on `impl Trait for Class` to auto-generate `impl Implements<dyn Trait> for Class`"
156)]
157// Note: technically, `Trait` doesn't _have to_ implement `Self`. The Rust type system provides no way to verify that a) D is a trait object,
158// and b) that the trait behind it is implemented for the class. Thus, users could any another reference type, such as `&str` pointing to a field.
159// This should be safe, since lifetimes are checked throughout and the class instance remains in place (pinned) inside a DynGd.
160pub trait AsDyn<Trait>: GodotClass
161where
162 Trait: ?Sized + 'static,
163{
164 fn dyn_upcast(&self) -> &Trait;
165 fn dyn_upcast_mut(&mut self) -> &mut Trait;
166}
167
168/// Implemented for all user-defined classes, providing extensions on the raw object to interact with `Gd`.
169#[doc(hidden)]
170pub trait UserClass: Bounds<Declarer = bounds::DeclUser> {
171 #[doc(hidden)]
172 fn __config() -> crate::private::ClassConfig;
173
174 #[doc(hidden)]
175 fn __before_ready(&mut self);
176
177 #[doc(hidden)]
178 fn __default_virtual_call(
179 _method_name: &str,
180 #[cfg(since_api = "4.4")] _hash: u32,
181 ) -> sys::GDExtensionClassCallVirtual {
182 None
183 }
184}
185
186/// Auto-implemented for all engine-provided enums.
187///
188/// # Future direction: `GodotEnum` unification
189/// Currently engine enums implement this trait with `all_constants()` returning `&[EnumConstant<Self>]`, while user enums provide
190/// metadata through `GodotShape::Enum` with `&[EnumeratorShape]`. A future `GodotEnum` trait could unify both, providing a single
191/// interface for enumerator introspection, constant registration via `classdb_register_extension_class_integer_constant` (which
192/// also accepts `p_is_bitfield`), and shared `GodotShape` construction. This would let user enums opt-in to the same capabilities
193/// as engine enums (GDScript name resolution, editor integration).
194pub trait EngineEnum: Copy + 'static {
195 fn try_from_ord(ord: i32) -> Option<Self>;
196
197 /// Ordinal value of the enumerator, as specified in Godot.
198 /// This is not necessarily unique.
199 fn ord(self) -> i32;
200
201 fn from_ord(ord: i32) -> Self {
202 Self::try_from_ord(ord)
203 .unwrap_or_else(|| panic!("ordinal {ord} does not map to any enumerator"))
204 }
205
206 /// The name of the enumerator, as it appears in Rust.
207 ///
208 /// Note that **this may not match the Rust constant name.** In case of multiple constants with the same ordinal value, this method returns
209 /// the first one in the order of definition. For example, [`LayoutDirection::LOCALE.as_str()`][crate::classes::window::LayoutDirection::LOCALE]
210 /// (ord 1) returns `"APPLICATION_LOCALE"`, because that happens to be the first constant with ordinal `1`.
211 /// See [`all_constants()`][Self::all_constants] for a more robust and general approach to introspection of enum constants.
212 ///
213 /// If the value does not match one of the known enumerators, the empty string is returned.
214 fn as_str(&self) -> &'static str;
215
216 /// Returns a slice of distinct enum values.
217 ///
218 /// This excludes `MAX` constants at the end (existing only to express the number of enumerators) and deduplicates aliases,
219 /// providing only meaningful enum values. See [`all_constants()`][Self::all_constants] for a complete list of all constants.
220 ///
221 /// Enables iteration over distinct enum variants:
222 /// ```no_run
223 /// use godot::classes::window;
224 /// use godot::obj::EngineEnum;
225 ///
226 /// for mode in window::Mode::values() {
227 /// println!("* {}: {}", mode.as_str(), mode.ord());
228 /// }
229 /// ```
230 fn values() -> &'static [Self];
231
232 /// Returns metadata for all enum constants.
233 ///
234 /// This includes all constants as they appear in the enum definition, including duplicates and `MAX` constants.
235 /// For a list of useful, distinct values, use [`values()`][Self::values].
236 ///
237 /// Enables introspection of available constants:
238 /// ```no_run
239 /// use godot::classes::window;
240 /// use godot::obj::EngineEnum;
241 ///
242 /// for constant in window::Mode::all_constants() {
243 /// println!("* window::Mode.{} (original {}) has ordinal value {}.",
244 /// constant.rust_name(),
245 /// constant.godot_name(),
246 /// constant.value().ord()
247 /// );
248 /// }
249 /// ```
250 fn all_constants() -> &'static [EnumConstant<Self>];
251}
252
253/// Auto-implemented for all engine-provided bitfields.
254pub trait EngineBitfield: Copy + 'static {
255 fn try_from_ord(ord: u64) -> Option<Self>;
256
257 /// Ordinal value of the bit flag, as specified in Godot.
258 fn ord(self) -> u64;
259
260 fn from_ord(ord: u64) -> Self {
261 Self::try_from_ord(ord)
262 .unwrap_or_else(|| panic!("ordinal {ord} does not map to any valid bit flag"))
263 }
264
265 // TODO consolidate API: named methods vs. | & ! etc.
266 fn is_set(self, flag: Self) -> bool {
267 self.ord() & flag.ord() != 0
268 }
269
270 /// Returns metadata for all bitfield constants.
271 ///
272 /// This includes all constants as they appear in the bitfield definition.
273 ///
274 /// Enables introspection of available constants:
275 /// ```no_run
276 /// use godot::global::KeyModifierMask;
277 /// use godot::obj::EngineBitfield;
278 ///
279 /// for constant in KeyModifierMask::all_constants() {
280 /// println!("* KeyModifierMask.{} (original {}) has ordinal value {}.",
281 /// constant.rust_name(),
282 /// constant.godot_name(),
283 /// constant.value().ord()
284 /// );
285 /// }
286 /// ```
287 fn all_constants() -> &'static [EnumConstant<Self>];
288}
289
290/// Trait for enums that can be used as indices in arrays.
291///
292/// The conditions for a Godot enum to be "index-like" are:
293/// - Contains an enumerator ending in `_MAX`, which has the highest ordinal (denotes the size).
294/// - All other enumerators are consecutive integers inside `0..max` (no negative ordinals, no gaps).
295///
296/// Duplicates are explicitly allowed, to allow for renamings/deprecations. The order in which Godot exposes
297/// the enumerators in the JSON is irrelevant.
298pub trait IndexEnum: EngineEnum {
299 /// Number of **distinct** enumerators in the enum.
300 ///
301 /// All enumerators are guaranteed to be in the range `0..ENUMERATOR_COUNT`, so you can use them
302 /// as indices in an array of size `ENUMERATOR_COUNT`.
303 ///
304 /// Keep in mind that two enumerators with the same ordinal are only counted once.
305 const ENUMERATOR_COUNT: usize;
306
307 /// Converts the enumerator to `usize`, which can be used as an array index.
308 ///
309 /// Note that two enumerators may have the same index, if they have the same ordinal.
310 fn to_index(self) -> usize {
311 self.ord() as usize
312 }
313}
314
315/// Trait that is automatically implemented for user classes containing a `Base<T>` field.
316///
317/// Gives direct access to the containing `Gd<Self>` from `self`.
318///
319/// # Usage as a bound
320///
321/// In order to call `base()` or `base_mut()` within a function or on a type you define, you need a `WithBaseField<Base = T>` bound,
322/// where `T` is the base class of your type.
323///
324/// ```no_run
325/// # use godot::prelude::*;
326/// # use godot::obj::WithBaseField;
327/// fn some_fn<T>(value: &T)
328/// where
329/// T: WithBaseField<Base = Node3D>,
330/// {
331/// let base = value.base();
332/// let pos = base.get_position();
333/// }
334/// ```
335///
336// Possible alternative for builder APIs, although even less ergonomic: Base<T> could be Base<T, Self> and return Gd<Self>.
337#[diagnostic::on_unimplemented(
338 message = "Class `{Self}` requires a `Base<T>` field",
339 label = "missing field `_base: Base<...>` in struct declaration",
340 note = "a base field is required to access the base from within `self`, as well as for #[signal], #[rpc] and #[func(virtual)]",
341 note = "see also: https://godot-rust.github.io/book/register/classes.html#the-base-field"
342)]
343pub trait WithBaseField: GodotClass + Bounds<Declarer = bounds::DeclUser> {
344 /// Returns the `Gd` pointer containing this object.
345 ///
346 /// This is intended to be stored or passed to engine methods. You cannot call `bind()` or `bind_mut()` on it, while the method
347 /// calling `to_gd()` is still running; that would lead to a double borrow panic.
348 ///
349 /// # Panics
350 /// If called during initialization (the `init()` function or `Gd::from_init_fn()`). Use [`Base::to_init_gd()`] instead.
351 fn to_gd(&self) -> Gd<Self>;
352
353 /// Returns a reference to the `Base` stored by this object.
354 #[doc(hidden)]
355 fn base_field(&self) -> &Base<Self::Base>;
356
357 /// Returns a shared reference guard, suitable for calling `&self` engine methods on this object.
358 ///
359 /// Holding a shared guard prevents other code paths from obtaining a _mutable_ reference to `self`, as such it is recommended to drop the
360 /// guard as soon as you no longer need it.
361 ///
362 /// # Examples
363 ///
364 /// ```no_run
365 /// use godot::prelude::*;
366 ///
367 /// #[derive(GodotClass)]
368 /// #[class(init, base=Node)]
369 /// struct MyClass {
370 /// base: Base<Node>,
371 /// }
372 ///
373 /// #[godot_api]
374 /// impl INode for MyClass {
375 /// fn process(&mut self, _delta: f32) {
376 /// let name = self.base().get_name();
377 /// godot_print!("name is {name}");
378 /// }
379 /// }
380 /// ```
381 ///
382 /// However, we cannot call methods that require `&mut Base`, such as
383 /// [`Node::add_child()`](crate::classes::Node::add_child).
384 ///
385 /// ```compile_fail
386 /// use godot::prelude::*;
387 ///
388 /// #[derive(GodotClass)]
389 /// #[class(init, base = Node)]
390 /// struct MyClass {
391 /// /// base: Base<Node>,
392 /// }
393 ///
394 /// #[godot_api]
395 /// impl INode for MyClass {
396 /// fn process(&mut self, _delta: f32) {
397 /// let node = Node::new_alloc();
398 /// // fails because `add_child` requires a mutable reference.
399 /// self.base().add_child(&node);
400 /// }
401 /// }
402 ///
403 /// # pub struct Test;
404 ///
405 /// # #[gdextension]
406 /// # unsafe impl ExtensionLibrary for Test {}
407 /// ```
408 ///
409 /// For this, use [`base_mut()`](WithBaseField::base_mut()) instead.
410 fn base(&self) -> BaseRef<'_, Self> {
411 BaseRef::new(self.base_field().constructed_borrowed())
412 }
413
414 /// Returns an exclusive reference guard, suitable for calling `&self`/`&mut self` engine methods on this object.
415 ///
416 /// This method will allow you to call back into the same object from Godot -- something that [`to_gd()`][Self::to_gd] does not allow.
417 /// You have to keep the `BaseMut` guard bound for the entire duration the engine might re-enter a function of your class. The guard
418 /// temporarily absorbs the `&mut self` reference, which allows for an additional exclusive (mutable) reference to be acquired.
419 ///
420 /// Holding an exclusive guard prevents other code paths from obtaining _any_ reference to `self`, as such it is recommended to drop the
421 /// guard as soon as you no longer need it.
422 ///
423 /// # Examples
424 ///
425 /// ```no_run
426 /// # use godot::prelude::*;
427 /// #[derive(GodotClass)]
428 /// #[class(init, base = Node)]
429 /// struct MyClass {
430 /// base: Base<Node>,
431 /// }
432 ///
433 /// #[godot_api]
434 /// impl INode for MyClass {
435 /// fn process(&mut self, _delta: f32) {
436 /// let node = Node::new_alloc();
437 /// self.base_mut().add_child(&node);
438 /// }
439 /// }
440 ///
441 /// # pub struct Test;
442 ///
443 /// # #[gdextension]
444 /// # unsafe impl ExtensionLibrary for Test {}
445 /// ```
446 ///
447 /// We can call back into `self` through Godot:
448 ///
449 /// ```no_run
450 /// # use godot::prelude::*;
451 /// #[derive(GodotClass)]
452 /// #[class(init, base=Node)]
453 /// struct MyClass {
454 /// base: Base<Node>,
455 /// }
456 ///
457 /// #[godot_api]
458 /// impl INode for MyClass {
459 /// fn process(&mut self, _delta: f32) {
460 /// self.base_mut().call("other_method", &[]);
461 /// }
462 /// }
463 ///
464 /// #[godot_api]
465 /// impl MyClass {
466 /// #[func]
467 /// fn other_method(&mut self) {}
468 /// }
469 /// ```
470 ///
471 /// Rust's borrow checking rules are enforced if you try to overlap `base_mut()` calls:
472 /// ```compile_fail
473 /// # use godot::prelude::*;
474 /// # #[derive(GodotClass)]
475 /// # #[class(init)]
476 /// # struct MyStruct {
477 /// # base: Base<RefCounted>,
478 /// # }
479 /// # impl MyStruct {
480 /// // error[E0499]: cannot borrow `*self` as mutable more than once at a time
481 ///
482 /// fn method(&mut self) {
483 /// let mut a = self.base_mut();
484 /// // ---- first mutable borrow occurs here
485 /// let mut b = self.base_mut();
486 /// // ^^^^ second mutable borrow occurs here
487 /// }
488 /// # }
489 /// ```
490 #[allow(clippy::let_unit_value)]
491 fn base_mut(&mut self) -> BaseMut<'_, Self> {
492 // We need to acquire this first, as the mut-borrow below will block all other access. A raw pointer (not a BorrowedGd tied to
493 // &self) is needed, since any shared borrow of self would conflict with that mut-borrow.
494 let base_ptr = self.base_field().constructed_obj_sys();
495
496 let gd = self.to_gd();
497
498 // SAFETY:
499 // - We have a `Gd<Self>` so, provided that `storage_unbounded` succeeds, the associated instance
500 // storage has been created.
501 //
502 // - Since we can get a `&'a Base<Self::Base>` from `&'a self`, that must mean we have a Rust object
503 // somewhere that has this base object. The only way to have such a base object is by being the
504 // Rust object referenced by that base object. I.e. this storage's user-instance is that Rust
505 // object. That means this storage cannot be destroyed for the lifetime of that Rust object. And
506 // since we have a reference to the base object derived from that Rust object, then that Rust
507 // object must outlive `'a`. And so the storage cannot be destroyed during the lifetime `'a`.
508 let storage = unsafe {
509 gd.raw
510 .storage_unbounded()
511 .expect("we have Gd<Self>; its RawGd should not be null")
512 };
513
514 let guard = storage.get_inaccessible(self);
515
516 // SAFETY: `base_ptr` is the base object of this instance, and BaseMut::new() unifies the BorrowedGd's lifetime with `guard`'s
517 // borrow of the instance -- which keeps the object alive for that entire lifetime.
518 let borrowed_gd = unsafe { BorrowedGd::from_obj_sys(base_ptr) };
519
520 BaseMut::new(borrowed_gd, guard)
521 }
522
523 /// Defers the given closure to run during [idle time](https://docs.godotengine.org/en/stable/classes/class_object.html#class-object-method-call-deferred).
524 ///
525 /// This is a type-safe alternative to [`Object::call_deferred()`][crate::classes::Object::call_deferred]. The closure receives
526 /// `&mut Self` allowing direct access to Rust fields and methods.
527 ///
528 /// See also [`Gd::run_deferred()`] to defer logic outside of `self`.
529 ///
530 /// # Panics
531 /// If called outside the main thread.
532 fn run_deferred<F>(&mut self, mut_self_method: F)
533 where
534 F: FnOnce(&mut Self) + 'static,
535 {
536 // We need to copy the Gd, because the lifetime of `&mut self` does not extend throughout the closure, which will only be called
537 // deferred. It might even be freed in-between, causing panic on bind_mut().
538 self.to_gd().run_deferred(mut_self_method)
539 }
540
541 /// Defers the given closure to run during [idle time](https://docs.godotengine.org/en/stable/classes/class_object.html#class-object-method-call-deferred).
542 ///
543 /// This is a type-safe alternative to [`Object::call_deferred()`][crate::classes::Object::call_deferred]. The closure receives
544 /// `Gd<Self>`, which can be used to call engine methods or [`bind()`][Gd::bind]/[`bind_mut()`][Gd::bind_mut] to access the Rust object.
545 ///
546 /// See also [`Gd::run_deferred_gd()`] to defer logic outside of `self`.
547 ///
548 /// # Panics
549 /// If called outside the main thread.
550 fn run_deferred_gd<F>(&mut self, gd_function: F)
551 where
552 F: FnOnce(Gd<Self>) + 'static,
553 {
554 self.to_gd().run_deferred_gd(gd_function)
555 }
556}
557
558/// Implemented for all classes with registered signals, both engine- and user-declared.
559///
560/// This trait enables the [`Gd::signals()`] method.
561///
562/// User-defined classes with `#[signal]` additionally implement [`WithUserSignals`].
563// Inherits bound makes some up/downcasting in signals impl easier.
564pub trait WithSignals: Inherits<crate::classes::Object> {
565 /// The associated struct listing all signals of this class.
566 ///
567 /// Parameters:
568 /// - `'c` denotes the lifetime during which the class instance is borrowed and its signals can be modified.
569 /// - `C` is the concrete class on which the signals are provided. This can be different than `Self` in case of derived classes
570 /// (e.g. a user-defined node) connecting/emitting signals of a base class (e.g. `Node`).
571 type SignalCollection<'c, C>
572 where
573 C: WithSignals;
574
575 /// Whether the representation needs to be able to hold just `Gd` (for engine classes) or `UserSignalObject` (for user classes).
576 // Note: this cannot be in Declarer (Engine/UserDecl) as associated type `type SignalObjectType<'c, T: WithSignals>`,
577 // because the user impl has the additional requirement T: WithUserSignals.
578 #[doc(hidden)]
579 type __SignalObj<'c>: SignalObject<'c>;
580 // type __SignalObj<'c, C>: SignalObject<'c>
581 // where
582 // C: WithSignals + 'c;
583
584 /// Create from existing `Gd`, to enable `Gd::signals()`.
585 ///
586 /// Only used for constructing from a concrete class, so `C = Self` in the return type.
587 ///
588 /// Takes by reference and not value, to retain lifetime chain.
589 #[doc(hidden)]
590 fn __signals_from_external(external: &Gd<Self>) -> Self::SignalCollection<'_, Self>;
591}
592
593/// Implemented for user-defined classes with at least one `#[signal]` declaration.
594///
595/// Allows to access signals from within the class, as `self.signals()`. This requires a `Base<T>` field.
596pub trait WithUserSignals: WithSignals + WithBaseField {
597 /// Access user-defined signals of the current object `self`.
598 ///
599 /// For classes that have at least one `#[signal]` defined, returns a collection of signal names. Each returned signal has a specialized
600 /// API for connecting and emitting signals in a type-safe way. If you need to access signals from outside (given a `Gd` pointer), use
601 /// [`Gd::signals()`] instead.
602 ///
603 /// If you haven't already, read the [book chapter about signals](https://godot-rust.github.io/book/register/signals.html) for a
604 /// walkthrough.
605 ///
606 /// # Provided API
607 /// The returned collection provides a method for each signal, with the same name as the corresponding `#[signal]`. \
608 /// For example, if you have...
609 /// ```ignore
610 /// #[signal]
611 /// fn damage_taken(&mut self, amount: i32);
612 /// ```
613 /// ...then you can access the signal as `self.signals().damage_taken()`, which returns an object with the following API:
614 /// ```ignore
615 /// // Connects global or associated function, or a closure.
616 /// fn connect(f: impl FnMut(i32));
617 ///
618 /// // Connects a &mut self method or closure on the emitter object.
619 /// fn connect_self(f: impl FnMut(&mut Self, i32));
620 ///
621 /// // Connects a &mut self method or closure on another object.
622 /// fn connect_other<C>(f: impl FnMut(&mut C, i32));
623 ///
624 /// // Emits the signal with the given arguments.
625 /// fn emit(amount: i32);
626 /// ```
627 ///
628 /// See [`TypedSignal`][crate::signal::TypedSignal] for more information.
629 fn signals(&mut self) -> Self::SignalCollection<'_, Self>;
630}
631
632/// Implemented for user-defined classes with at least one `#[rpc]` declaration.
633///
634/// Allows accessing type-safe RPCs from within the class, as `self.rpcs()`. This requires a `Base<T>` field and a `Node`-derived class.
635/// To access RPCs from outside (given a `Gd` pointer), use [`Gd::rpcs()`] instead.
636// `Inherits<Node>` supertrait makes the up-casting to `Node` in the RPC implementation possible, and avoids repeating the bound in
637// generic user code. There is no scenario where user-defined RPCs can be used if the class isn't `Node`-based.
638pub trait WithUserRpcs: WithBaseField + Inherits<crate::classes::Node> {
639 /// The associated struct listing all RPCs of this class.
640 ///
641 /// `'c` denotes the lifetime during which the class instance is borrowed and its RPCs can be called.
642 type RpcCollection<'c>;
643
644 /// Access type-safe RPCs of the current object `self`.
645 ///
646 /// For classes that have at least one `#[rpc]` defined, returns a collection with one method per RPC. If you need to access RPCs from
647 /// outside (given a `Gd` pointer), use [`Gd::rpcs()`] instead.
648 ///
649 /// # Provided API
650 /// The returned collection provides a method for each RPC, with the same name as the corresponding `#[rpc]`. \
651 /// For example, the following RPC:
652 ///
653 /// ```ignore
654 /// #[rpc]
655 /// fn say_hello_to(&mut self, to: String) {
656 /// godot_print!("hello, {to}");
657 /// }
658 /// ```
659 ///
660 /// can be called with:
661 ///
662 /// ```ignore
663 /// my_node.rpcs().say_hello_to("world".to_string()).call();
664 /// my_node.rpcs().say_hello_to("world".to_string()).call_id(1); // call RPC on specific peer
665 /// ```
666 fn rpcs(&mut self) -> Self::RpcCollection<'_>;
667
668 /// Create from existing `Gd`, to enable [`Gd::rpcs()`].
669 ///
670 /// Only used for constructing from a concrete class, so `C = Self`. Takes by reference to retain the lifetime chain.
671 #[doc(hidden)]
672 fn __rpcs_from_external(external: &Gd<Self>) -> Self::RpcCollection<'_>;
673}
674
675/// Extension trait for all reference-counted classes.
676pub trait NewGd: GodotClass {
677 /// Return a new, ref-counted `Gd` containing a default-constructed instance.
678 ///
679 /// `MyClass::new_gd()` is equivalent to `Gd::<MyClass>::default()`.
680 ///
681 /// # Panics
682 /// If `Self` is user-defined and its default constructor `init()` panics, that panic is propagated.
683 fn new_gd() -> Gd<Self>;
684}
685
686impl<T> NewGd for T
687where
688 T: cap::GodotDefault + Bounds<Memory = bounds::MemRefCounted>,
689{
690 fn new_gd() -> Gd<Self> {
691 Gd::default()
692 }
693}
694
695/// Extension trait for all manually managed classes.
696pub trait NewAlloc: GodotClass {
697 /// Return a new, manually-managed `Gd` containing a default-constructed instance.
698 ///
699 /// The result must be manually managed, e.g. by attaching it to the scene tree or calling `free()` after usage.
700 /// Failure to do so will result in memory leaks.
701 ///
702 /// # Panics
703 /// If `Self` is user-defined and its default constructor `init()` panics, that panic is propagated to the caller.
704 #[must_use]
705 fn new_alloc() -> Gd<Self>;
706}
707
708/// Trait for singleton classes in Godot.
709///
710/// There is only one instance of each singleton class in the engine, accessible through [`singleton()`][Self::singleton].
711pub trait Singleton: GodotClass {
712 // Note: we cannot return &'static mut Self, as this would be very easy to mutably alias. Returning &'static Self is possible, but we'd
713 // lose the whole mutability information (even if that is best-effort and not strict Rust mutability, it makes the API much more usable).
714 // As long as the user has multiple Gd smart pointers to the same singletons, only the internal raw pointers are aliased.
715 // See also Deref/DerefMut impl for Gd.
716
717 /// Returns the singleton instance.
718 ///
719 /// # Panics
720 /// If called during global init/deinit of godot-rust, and the singleton in question is not yet available.
721 /// You can check this with [`init::is_singleton_available::<Self>()`][crate::init::is_singleton_available].
722 /// See also [`ExtensionLibrary`](../init/trait.ExtensionLibrary.html#availability-of-godot-apis-during-init-and-deinit).
723 fn singleton() -> Gd<Self>;
724}
725
726/// Trait for user-defined singleton classes in Godot.
727///
728/// Implementing this trait allows accessing a registered singleton instance through [`singleton()`][Singleton::singleton].
729/// User singletons should be registered under their class name – otherwise some Godot components (for example GDScript before 4.4) might have trouble handling them,
730/// and the editor might crash when using `T::singleton()`.
731///
732/// There should be only one instance of a given singleton class in the engine, valid as long as the library is loaded.
733/// Therefore, user singletons are limited to classes with manual memory management (ones not inheriting from `RefCounted`).
734///
735/// # Registration
736///
737/// godot-rust provides a way to register given class as an Engine Singleton with [`#[class(singleton)]`](../prelude/derive.GodotClass.html#user-engine-singletons).
738///
739/// Alternatively, a user singleton can be registered manually:
740///
741/// ```no_run
742/// # use godot::prelude::*;
743/// # use godot::classes::Engine;
744/// #[derive(GodotClass)]
745/// #[class(init, base = Object)]
746/// struct MyEngineSingleton {}
747///
748/// // Provides blanket implementation allowing to use MyEngineSingleton::singleton().
749/// // Ensures that `MyEngineSingleton` is a valid singleton (i.e., a non-refcounted GodotClass).
750/// impl UserSingleton for MyEngineSingleton {}
751///
752/// struct MyExtension;
753///
754/// #[gdextension]
755/// unsafe impl ExtensionLibrary for MyExtension {
756/// fn on_stage_init(stage: InitStage) {
757/// // Singleton should be registered before the MainLoop startup – otherwise it won't be recognized by the GDScriptParser.
758/// if stage == InitStage::Scene {
759/// let obj = MyEngineSingleton::new_alloc();
760/// Engine::singleton()
761/// .register_singleton(&MyEngineSingleton::class_id().to_string_name(), &obj);
762/// }
763/// }
764///
765/// fn on_stage_deinit(stage: InitStage) {
766/// if stage == InitStage::Scene {
767/// let obj = MyEngineSingleton::singleton();
768/// Engine::singleton()
769/// .unregister_singleton(&MyEngineSingleton::class_id().to_string_name());
770/// obj.free();
771/// }
772/// }
773/// }
774/// ```
775// For now exists mostly as a marker trait and a way to provide blanket implementation for `Singleton` trait.
776pub trait UserSingleton:
777 GodotClass + Bounds<Declarer = bounds::DeclUser, Memory = bounds::MemManual>
778{
779}
780
781impl<T> Singleton for T
782where
783 T: UserSingleton + Inherits<crate::classes::Object>,
784{
785 fn singleton() -> Gd<T> {
786 // Note: Under any safeguards level `singleton_unchecked_type` will panic if Singleton can't be retrieved.
787
788 let class_name = <T as GodotClass>::class_id().to_string_name();
789 // SAFETY: The caller must ensure that `class_name` corresponds to the actual class name of type `T`.
790 // This is always true for `#[class(singleton)]`.
791 unsafe { crate::classes::singleton_unchecked_type(&class_name) }
792 }
793}
794
795impl<T> NewAlloc for T
796where
797 T: cap::GodotDefault + Bounds<Memory = bounds::MemManual>,
798{
799 fn new_alloc() -> Gd<Self> {
800 use crate::obj::bounds::Declarer as _;
801
802 <Self as Bounds>::Declarer::create_gd()
803 }
804}
805
806// ----------------------------------------------------------------------------------------------------------------------------------------------
807
808/// Capability traits, providing dedicated functionalities for Godot classes
809pub mod cap {
810 use std::any::Any;
811
812 use super::*;
813 use crate::builtin::{StringName, Variant};
814 use crate::obj::{Base, Gd};
815 use crate::registry::info::PropertyInfo;
816 use crate::storage::{IntoVirtualMethodReceiver, VirtualMethodReceiver};
817
818 /// Trait for all classes that are default-constructible from the Godot engine.
819 ///
820 /// Enables the `MyClass.new()` syntax in GDScript, and allows the type to be used by the editor, which often default-constructs objects.
821 ///
822 /// This trait is automatically implemented for the following classes:
823 /// - User defined classes if either:
824 /// - they override an `init()` method
825 /// - they have `#[class(init)]` attribute
826 /// - Engine classes if:
827 /// - they are reference-counted and constructible (i.e. provide a `new()` method).
828 ///
829 /// This trait is not manually implemented, and you cannot call any methods. You can use it as a bound, but typically you'd use
830 /// it indirectly through [`Gd::default()`][crate::obj::Gd::default()]. Note that `Gd::default()` has an additional requirement on
831 /// being reference-counted, meaning not every `GodotDefault` class can automatically be used with `Gd::default()`.
832 #[diagnostic::on_unimplemented(
833 message = "Class `{Self}` requires either an `init` constructor, or explicit opt-out",
834 label = "needs `init`",
835 note = "to provide a default constructor, use `#[class(init)]` or implement an `init` method",
836 note = "to opt out, use `#[class(no_init)]`",
837 note = "see also: https://godot-rust.github.io/book/register/constructors.html"
838 )]
839 pub trait GodotDefault: GodotClass {
840 /// Provides a default smart pointer instance.
841 ///
842 /// Semantics:
843 /// - For user-defined classes, this calls `T::init()` or the generated init-constructor.
844 /// - For engine classes, this calls `T::new()`.
845 #[doc(hidden)]
846 fn __godot_default() -> Gd<Self> {
847 // This is a bit hackish, but the alternatives are:
848 // 1. Separate trait `GodotUserDefault` for user classes, which then proliferates through all APIs and makes abstraction harder.
849 // 2. Repeatedly implementing __godot_default() that forwards to something like Gd::default_user_instance(). Possible, but this
850 // will make the step toward builder APIs more difficult, as users would need to re-implement this as well.
851 sys::strict_assert_eq!(
852 std::any::TypeId::of::<<Self as Bounds>::Declarer>(),
853 std::any::TypeId::of::<bounds::DeclUser>(),
854 "__godot_default() called on engine class; must be overridden for engine classes"
855 );
856
857 Gd::default_instance()
858 }
859
860 /// Only provided for user classes.
861 #[doc(hidden)]
862 fn __godot_user_init(_base: Base<Self::Base>) -> Self {
863 unreachable!(
864 "__godot_user_init() called on engine class; must be overridden for user classes"
865 )
866 }
867 }
868
869 // TODO Evaluate whether we want this public or not
870 #[doc(hidden)]
871 pub trait GodotToString: GodotClass {
872 #[doc(hidden)]
873 type Recv: IntoVirtualMethodReceiver<Self>;
874
875 #[doc(hidden)]
876 fn __godot_to_string(this: VirtualMethodReceiver<Self>) -> GString;
877 }
878
879 // TODO Evaluate whether we want this public or not
880 #[doc(hidden)]
881 pub trait GodotNotification: GodotClass {
882 #[doc(hidden)]
883 fn __godot_notification(&mut self, what: i32);
884 }
885
886 // TODO Evaluate whether we want this public or not
887 #[doc(hidden)]
888 pub trait GodotRegisterClass: GodotClass {
889 #[doc(hidden)]
890 fn __godot_register_class(builder: &mut ClassBuilder<Self>);
891 }
892
893 #[doc(hidden)]
894 pub trait GodotGet: GodotClass {
895 #[doc(hidden)]
896 type Recv: IntoVirtualMethodReceiver<Self>;
897
898 #[doc(hidden)]
899 fn __godot_get_property(
900 this: VirtualMethodReceiver<Self>,
901 property: StringName,
902 ) -> Option<Variant>;
903 }
904
905 #[doc(hidden)]
906 pub trait GodotSet: GodotClass {
907 #[doc(hidden)]
908 type Recv: IntoVirtualMethodReceiver<Self>;
909
910 #[doc(hidden)]
911 fn __godot_set_property(
912 this: VirtualMethodReceiver<Self>,
913 property: StringName,
914 value: Variant,
915 ) -> bool;
916 }
917
918 #[doc(hidden)]
919 pub trait GodotGetPropertyList: GodotClass {
920 #[doc(hidden)]
921 type Recv: IntoVirtualMethodReceiver<Self>;
922
923 #[doc(hidden)]
924 fn __godot_get_property_list(
925 this: VirtualMethodReceiver<Self>,
926 ) -> Vec<crate::registry::info::PropertyInfo>;
927 }
928
929 #[doc(hidden)]
930 pub trait GodotPropertyGetRevert: GodotClass {
931 #[doc(hidden)]
932 type Recv: IntoVirtualMethodReceiver<Self>;
933
934 #[doc(hidden)]
935 fn __godot_property_get_revert(
936 this: VirtualMethodReceiver<Self>,
937 property: StringName,
938 ) -> Option<Variant>;
939 }
940
941 #[doc(hidden)]
942 pub trait GodotValidateProperty: GodotClass {
943 #[doc(hidden)]
944 type Recv: IntoVirtualMethodReceiver<Self>;
945
946 #[doc(hidden)]
947 fn __godot_validate_property(
948 this: VirtualMethodReceiver<Self>,
949 property: &mut PropertyInfo,
950 );
951 }
952
953 /// Auto-implemented for `#[godot_api] impl MyClass` blocks
954 pub trait ImplementsGodotApi: GodotClass {
955 #[doc(hidden)]
956 fn __register_methods();
957 #[doc(hidden)]
958 fn __register_constants();
959 #[doc(hidden)]
960 fn __register_rpcs(_: &mut dyn Any) {}
961 }
962
963 pub trait ImplementsGodotExports: GodotClass {
964 #[doc(hidden)]
965 fn __register_exports();
966 }
967
968 /// Auto-implemented for `#[godot_api] impl XyVirtual for MyClass` blocks
969 pub trait ImplementsGodotVirtual: GodotClass {
970 // Cannot use #[cfg(since_api = "4.4")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.4")))] on the `hash` parameter, because the doc-postprocessing generates #[doc(cfg)],
971 // which isn't valid in parameter position.
972
973 #[cfg(before_api = "4.4")] #[cfg_attr(published_docs, doc(cfg(before_api = "4.4")))]
974 #[doc(hidden)]
975 fn __virtual_call(name: &str) -> sys::GDExtensionClassCallVirtual;
976
977 #[cfg(since_api = "4.4")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.4")))]
978 #[doc(hidden)]
979 fn __virtual_call(name: &str, hash: u32) -> sys::GDExtensionClassCallVirtual;
980 }
981}