Skip to main content

ferroui_base/rendering/composition/server/
server_object.rs

1use super::{
2    CompositionProperty, IServerAnimatedPropertyHost, IServerRenderResource, ServerCompositor, ServerObjectAnimations,
3    ServerValueChange,
4};
5use crate::rendering::composition::animations::IAnimationInstance;
6use crate::rendering::composition::expressions::{ExpressionObjectKey, ExpressionVariant, IExpressionObject};
7use crate::media::{IBrush, IGradientStop, IPen, ITransform};
8use crate::rendering::composition::drawing::IRenderDataGeometry;
9use crate::rendering::composition::transport::BatchStreamReader;
10use std::any::{Any, TypeId};
11use std::cell::{Cell, RefCell};
12use std::rc::{Rc, Weak};
13use std::time::Duration;
14
15/// Identifies a server-side object within its server compositor.
16///
17/// UI-thread objects never hold a server object; they hold its id, and the
18/// batch that creates, changes or disposes the object refers to it by id.
19/// The id is a plain value that can cross threads.
20#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
21pub struct ServerObjectId(pub(crate) u32);
22
23impl ServerObjectId {
24    /// The slot index of the object.
25    #[inline]
26    pub fn index(self) -> usize {
27        self.0 as usize
28    }
29}
30
31/// The base contract of every server-side object (upstream
32/// `SimpleServerObject`).
33pub trait IServerObject: 'static {
34    /// Reads the changes of the object from a batch.
35    fn deserialize_changes_core(&self, _reader: &mut BatchStreamReader<'_>, _committed_at: Duration) {}
36
37    /// Called after a group of values of the object changed.
38    fn values_invalidated(&self) {}
39
40    /// Applies the changes of the object from a batch.
41    fn deserialize_changes(&self, reader: &mut BatchStreamReader<'_>, committed_at: Duration) {
42        self.deserialize_changes_core(reader, committed_at);
43        self.values_invalidated();
44    }
45
46    /// Releases the object: it has been disposed on the UI thread.
47    fn dispose(&self) {}
48
49    /// The object as a render resource, if it is one.
50    fn as_render_resource(self: Rc<Self>) -> Option<Rc<dyn IServerRenderResource>> {
51        None
52    }
53
54    /// The object as a brush, if it is a server-side brush.
55    fn as_brush(self: Rc<Self>) -> Option<Rc<dyn IBrush>> {
56        None
57    }
58
59    /// The object as a pen, if it is a server-side pen.
60    fn as_pen(self: Rc<Self>) -> Option<Rc<dyn IPen>> {
61        None
62    }
63
64    /// The object as a geometry usable by render data, if it is a
65    /// server-side geometry.
66    fn as_render_data_geometry(self: Rc<Self>) -> Option<Rc<dyn IRenderDataGeometry>> {
67        None
68    }
69
70    /// The object as a transform, if it is a server-side transform.
71    fn as_transform(self: Rc<Self>) -> Option<Rc<dyn ITransform>> {
72        None
73    }
74
75    /// The object as a gradient stop, if it is a server-side gradient stop.
76    fn as_gradient_stop(self: Rc<Self>) -> Option<Rc<dyn IGradientStop>> {
77        None
78    }
79
80    /// The object as a composition surface, if it is one.
81    fn as_surface(self: Rc<Self>) -> Option<Rc<dyn super::IServerCompositionSurface>> {
82        None
83    }
84
85    /// The object as an animatable object, if it is one.
86    fn as_animated(self: Rc<Self>) -> Option<Rc<dyn IAnimatedServerObject>> {
87        None
88    }
89
90    /// The generated property block of the given type embedded in the
91    /// object, if it has one. A class that embeds generated properties
92    /// forwards to their `find_props`; composition properties locate their
93    /// fields through it.
94    fn get_props(&self, _type_id: TypeId) -> Option<&dyn Any> {
95        None
96    }
97
98    fn as_any(&self) -> &dyn Any;
99
100    fn into_any_rc(self: Rc<Self>) -> Rc<dyn Any>;
101}
102
103/// A server object that supports animated properties: what upstream's
104/// abstract `ServerObject` is to its subclasses.
105///
106/// A class "derives" from `ServerObject` by embedding a [`ServerObject`]
107/// and implementing this trait; the embedded part reaches the class through
108/// it.
109pub trait IAnimatedServerObject: IServerObject + IServerAnimatedPropertyHost {
110    /// The embedded `ServerObject` part.
111    fn server_object(&self) -> &ServerObject;
112
113    /// The composition property with the given name, if the class has one.
114    fn get_composition_property(&self, _field_name: &str) -> Option<&'static CompositionProperty> {
115        None
116    }
117
118    /// The object as the base contract (an explicit upcast).
119    fn as_server_object_dyn(&self) -> &dyn IServerObject;
120}
121
122/// An animatable server object as an expression reads it: the target of an
123/// animation, or an object an animation refers to through a reference
124/// parameter (upstream passes the `ServerObject` itself, which implements
125/// `IExpressionObject`).
126#[derive(Clone)]
127pub struct ServerExpressionObject(pub Rc<dyn IAnimatedServerObject>);
128
129impl IExpressionObject for ServerExpressionObject {
130    fn get_property(&self, name: &str) -> ExpressionVariant {
131        self.0.server_object().get_property(name)
132    }
133
134    fn key(&self) -> ExpressionObjectKey {
135        ExpressionObjectKey(Rc::as_ptr(&self.0) as *const () as usize)
136    }
137}
138
139/// Server-side `CompositionObject` counterpart. Is responsible for
140/// animation activation and invalidation.
141pub struct ServerObject {
142    compositor: Weak<ServerCompositor>,
143    owner: Weak<dyn IAnimatedServerObject>,
144    activation_count: Cell<u32>,
145    animations: RefCell<Option<Rc<ServerObjectAnimations>>>,
146}
147
148impl ServerObject {
149    /// `owner` is the object that embeds this part.
150    pub fn new(compositor: &Rc<ServerCompositor>, owner: Weak<dyn IAnimatedServerObject>) -> Self {
151        Self {
152            compositor: Rc::downgrade(compositor),
153            owner,
154            activation_count: Cell::new(0),
155            animations: RefCell::new(None),
156        }
157    }
158
159    /// The compositor of the object, while it is alive.
160    pub fn compositor(&self) -> Option<Rc<ServerCompositor>> {
161        self.compositor.upgrade()
162    }
163
164    pub fn animations(&self) -> Option<Rc<ServerObjectAnimations>> {
165        self.animations.borrow().clone()
166    }
167
168    pub fn get_or_create_animations(&self) -> Rc<ServerObjectAnimations> {
169        self.animations
170            .borrow_mut()
171            .get_or_insert_with(|| Rc::new(ServerObjectAnimations::new(self.owner.clone(), self.compositor.clone())))
172            .clone()
173    }
174
175    pub fn is_active(&self) -> bool {
176        self.activation_count.get() != 0
177    }
178
179    pub fn activate(&self) {
180        self.activation_count.set(self.activation_count.get() + 1);
181        if self.activation_count.get() == 1 {
182            self.activated();
183        }
184    }
185
186    pub fn deactivate(&self) {
187        if cfg!(debug_assertions) && self.activation_count.get() == 0 {
188            panic!("the server object is not active");
189        }
190        self.activation_count.set(self.activation_count.get().saturating_sub(1));
191        if self.activation_count.get() == 0 {
192            self.deactivated();
193        }
194    }
195
196    fn activated(&self) {
197        if let Some(animations) = self.animations() {
198            animations.activated();
199        }
200    }
201
202    fn deactivated(&self) {
203        if let Some(animations) = self.animations() {
204            animations.deactivated();
205        }
206    }
207
208    /// `SetValue(prop, ref field, value)` of an animatable object: assigns
209    /// and invalidates the subscriptions of the property.
210    pub fn set_value(&self, property: &'static CompositionProperty, change: ServerValueChange<'_>) {
211        (change.assign)();
212        if let Some(animations) = self.animations() {
213            animations.on_set_direct_value(property);
214        }
215    }
216
217    /// `SetAnimatedValue(prop, ref field, committedAt, animation)`.
218    pub fn set_animated_value(
219        &self,
220        property: &'static CompositionProperty,
221        current_value: ExpressionVariant,
222        committed_at: Duration,
223        animation: Rc<dyn IAnimationInstance>,
224    ) {
225        self.get_or_create_animations().on_set_animated_value(property, current_value, committed_at, animation);
226    }
227
228    /// The tail of `SetAnimatedValue(prop, out field, value)`.
229    pub fn remove_animation_for_property(&self, property: &'static CompositionProperty) {
230        if let Some(animations) = self.animations() {
231            animations.remove_animation_for_property(property);
232        }
233    }
234
235    /// `IExpressionObject.GetProperty` of the owner.
236    pub fn get_property(&self, name: &str) -> ExpressionVariant {
237        match self.animations() {
238            None => {
239                let Some(owner) = self.owner.upgrade() else { return ExpressionVariant::default() };
240                owner
241                    .get_composition_property(name)
242                    .and_then(|property| property.get_variant())
243                    .map(|get| get(owner.as_server_object_dyn()))
244                    .unwrap_or_default()
245            }
246            Some(animations) => animations.get_property_for_animation(name),
247        }
248    }
249}
250
251/// Implements the property-host and animation contracts of a class that
252/// embeds a [`ServerObject`] in the field `$object` and a
253/// `Weak<ServerCompositor>` in the field `compositor`: what deriving from
254/// upstream's `ServerObject` provides.
255#[doc(hidden)]
256#[macro_export]
257macro_rules! __impl_animated_server_object {
258    ($ty:ty, $object:ident $(, composition_property: $get:expr)?) => {
259        impl $crate::rendering::composition::server::IServerPropertyHost for $ty {
260            fn server_compositor(
261                &self,
262            ) -> Option<::std::rc::Rc<$crate::rendering::composition::server::ServerCompositor>> {
263                self.$object.compositor()
264            }
265
266            fn set_value(
267                &self,
268                property: &'static $crate::rendering::composition::server::CompositionProperty,
269                change: $crate::rendering::composition::server::ServerValueChange<'_>,
270            ) {
271                self.$object.set_value(property, change);
272            }
273        }
274
275        impl $crate::rendering::composition::server::IServerAnimatedPropertyHost for $ty {
276            fn set_animated_value(
277                &self,
278                property: &'static $crate::rendering::composition::server::CompositionProperty,
279                current_value: $crate::rendering::composition::expressions::ExpressionVariant,
280                committed_at: ::std::time::Duration,
281                animation: ::std::rc::Rc<dyn $crate::rendering::composition::animations::IAnimationInstance>,
282            ) {
283                self.$object.set_animated_value(property, current_value, committed_at, animation);
284            }
285
286            fn remove_animation_for_property(
287                &self,
288                property: &'static $crate::rendering::composition::server::CompositionProperty,
289            ) {
290                self.$object.remove_animation_for_property(property);
291            }
292
293            fn notify_animated_value_changed(
294                &self,
295                _property: &'static $crate::rendering::composition::server::CompositionProperty,
296            ) {
297                $crate::rendering::composition::server::IServerObject::values_invalidated(self);
298            }
299        }
300
301        impl $crate::rendering::composition::server::IAnimatedServerObject for $ty {
302            fn server_object(&self) -> &$crate::rendering::composition::server::ServerObject {
303                &self.$object
304            }
305
306            $(fn get_composition_property(
307                &self,
308                field_name: &str,
309            ) -> Option<&'static $crate::rendering::composition::server::CompositionProperty> {
310                ($get)(field_name)
311            })?
312
313            fn as_server_object_dyn(&self) -> &dyn $crate::rendering::composition::server::IServerObject {
314                self
315            }
316        }
317    };
318}
319
320pub use crate::__impl_animated_server_object as impl_animated_server_object;