Skip to main content

libobs_wrapper/
macros.rs

1#[macro_export]
2macro_rules! run_with_obs_impl {
3    ($runtime:expr, $operation:expr) => {
4        $crate::run_with_obs_impl!($runtime, (), $operation)
5    };
6    ($runtime:expr, ($($var:ident),* $(,)*), $operation:expr) => {{
7        $(let $var = $var.clone();)*
8        $runtime.run_with_obs_result(move || {
9            $(let $var = $var;)*
10            let inner_obs_run = { $operation };
11            inner_obs_run()
12        })
13    }};
14}
15
16/// Execute work on the OBS actor while preserving the runtime's structured error.
17#[macro_export]
18macro_rules! run_with_obs {
19    ($runtime:expr, $operation:expr) => {{
20        $crate::run_with_obs_impl!($runtime, $operation)
21    }};
22    ($runtime:expr, ($($var:ident),* $(,)*), $operation:expr) => {{
23        $crate::run_with_obs_impl!($runtime, ($($var),*), $operation)
24    }};
25}
26
27/// Implement a non-panicking native cleanup guard.
28///
29/// Cleanup is enqueued on the runtime's dedicated cleanup queue, so destructors do
30/// not synchronously execute libobs calls or require a Tokio runtime.
31#[macro_export]
32macro_rules! impl_obs_drop {
33    ($struct_name: ident, $operation:expr) => {
34        $crate::impl_obs_drop!($struct_name, (), $operation);
35    };
36    ($struct_name: ident, ($($var:ident),* $(,)*), $operation:expr) => {
37        // Deferred cleanup always executes on the OBS owner thread.
38        #[allow(unknown_lints)]
39        #[allow(ensure_obs_call_in_runtime)]
40        impl Drop for $struct_name {
41            fn drop(&mut self) {
42                log::trace!("Dropping {}...", stringify!($struct_name));
43                $(let $var = self.$var.clone();)*
44                // Move one Send tuple rather than accessing wrapper fields across the
45                // closure boundary. This defeats precise field capture of raw pointers
46                // without introducing a generic "make anything Send" adapter.
47                let cleanup_payload = ($($var,)*);
48                // Deferred cleanup always runs on the OBS owner thread (queued to the actor, or
49                // inline when already there), so the operation is called directly. Capturing a
50                // runtime clone here would let the final runtime handle drop on the actor itself,
51                // where shutdown cannot be awaited and the process may exit while OBS still runs.
52                self.runtime.defer_obs_cleanup(move || {
53                    // Rebind the whole tuple first so Rust's precise closure capture cannot
54                    // extract a raw pointer field from it.
55                    let cleanup_payload = cleanup_payload;
56                    let ($($var,)*) = cleanup_payload;
57                    let inner_obs_drop = { $operation };
58                    inner_obs_drop()
59                });
60            }
61        }
62    };
63}
64
65/// Implements PartialEq, Eq and Hash für a struct by comparing the inner pointer given by `as_ptr()`.
66macro_rules! impl_eq_of_ptr {
67    ($struct: ty) => {
68        impl PartialEq for $struct {
69            fn eq(&self, other: &Self) -> bool {
70                self.as_ptr().native_id() == other.as_ptr().native_id()
71            }
72        }
73
74        impl Eq for $struct {}
75
76        impl std::hash::Hash for $struct {
77            fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
78                self.as_ptr().native_id().hash(state);
79            }
80        }
81    };
82}
83
84/// Implements PartialEq, Eq and Hash for a managed OBS object using its opaque ID.
85macro_rules! impl_eq_of_obs_object {
86    ($struct: ty) => {
87        impl PartialEq for $struct {
88            fn eq(&self, other: &Self) -> bool {
89                crate::data::object::ObsObjectTrait::object_id(self)
90                    == crate::data::object::ObsObjectTrait::object_id(other)
91            }
92        }
93
94        impl Eq for $struct {}
95
96        impl std::hash::Hash for $struct {
97            fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
98                crate::data::object::ObsObjectTrait::object_id(self).hash(state);
99            }
100        }
101    };
102}
103
104#[cfg(windows)]
105macro_rules! enum_from_number {
106    ($var: ident, $numb: expr) => {{
107        use num_traits::FromPrimitive;
108        $var::from_i32($numb)
109    }};
110}
111
112#[cfg(not(windows))]
113macro_rules! enum_from_number {
114    ($var: ident, $numb: expr) => {{
115        use num_traits::FromPrimitive;
116        $var::from_u32($numb)
117    }};
118}
119
120/// Defines a trait that conditionally includes Send + Sync bounds when the enable_runtime feature is enabled.
121/// This avoids duplicating trait definitions for runtime vs non-runtime scenarios.
122///
123/// # Example
124/// ```ignore
125/// trait_with_optional_send_sync! {
126///     #[doc(hidden)]
127///     pub trait MyTrait: Debug {
128///         fn my_method(&self);
129///     }
130/// }
131/// ```
132/// This expands to two trait definitions:
133/// - With enable_runtime: `pub trait MyTrait: Debug + Send + Sync { ... }`
134/// - Without enable_runtime: `pub trait MyTrait: Debug { ... }`
135macro_rules! trait_with_optional_send_sync {
136    (
137        $(#[$meta:meta])*
138        $vis:vis trait $trait_name:ident: $base_bound:path {
139            $($body:tt)*
140        }
141    ) => {
142        #[cfg(feature="enable_runtime")]
143        $(#[$meta])*
144        $vis trait $trait_name: $base_bound + Send + Sync {
145            $($body)*
146        }
147
148        #[cfg(not(feature="enable_runtime"))]
149        $(#[$meta])*
150        $vis trait $trait_name: $base_bound {
151            $($body)*
152        }
153    };
154}
155
156pub(crate) use enum_from_number;
157pub(crate) use impl_eq_of_obs_object;
158pub(crate) use impl_eq_of_ptr;
159pub(crate) use trait_with_optional_send_sync;