ferroui-base 0.3.0

The base library of FerroUI: the property system, layout, input, styling, media, text, animation, data binding and the compositor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
// @generated by scripts/generate_composition.py — do not edit

//! `CompositionBrush`.

use bitflags::bitflags;
use crate::RelativePoint;
use crate::media::ITransform;
use crate::rendering::composition::ICompositionObjectHost;
use crate::rendering::composition::animations::AnimationInstanceFactory;
use crate::rendering::composition::animations::ICompositionAnimation;
use crate::rendering::composition::expressions::ExpressionVariant;
use crate::rendering::composition::server::AsServerRenderResource;
use crate::rendering::composition::server::CompositionProperty;
use crate::rendering::composition::server::CompositionPropertyOf;
use crate::rendering::composition::server::IServerAnimatedPropertyHost;
use crate::rendering::composition::server::ServerPropertyValue;
use crate::rendering::composition::server::ServerResourceRef;
use crate::rendering::composition::server::ServerValueChange;
use crate::rendering::composition::server::props_of;
use crate::rendering::composition::server::read_resource;
use crate::rendering::composition::transport::BatchResource;
use crate::rendering::composition::transport::BatchStreamReader;
use crate::rendering::composition::transport::BatchStreamWriter;
use crate::rendering::composition::transport::BatchValue;
use crate::rendering::composition::transport::BatchValueReader;
use std::any::Any;
use std::any::TypeId;
use std::cell::Cell;
use std::cell::RefCell;
use std::sync::OnceLock;
use std::time::Duration;

bitflags! {
    /// The fields of `CompositionBrush` that changed since its last serialization.
    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
    pub struct CompositionBrushChangedFields: u8 {
        const OPACITY = 1;
        const OPACITY_ANIMATED = 2;
        const TRANSFORM_ORIGIN = 4;
        const TRANSFORM = 8;
        const RELATIVE_TRANSFORM = 16;
    }
}

impl BatchValue for CompositionBrushChangedFields {
    #[inline]
    fn write_to(&self, out: &mut Vec<u8>) {
        self.bits().write_to(out);
    }

    #[inline]
    fn read_from(input: &mut BatchValueReader<'_>) -> Self {
        CompositionBrushChangedFields::from_bits_retain(u8::read_from(input))
    }
}

/// The partial methods of `CompositionBrush`: implemented by the class that embeds
/// [`CompositionBrushProps`]. Every hook defaults to doing nothing.
pub trait CompositionBrushHooks: ICompositionObjectHost {
    fn initialize_defaults_extra(&self) {}

    fn validate_opacity_change(&self, _old_value: f64, _new_value: f64) {}
    fn on_opacity_changed(&self) {}
    fn on_opacity_changing(&self) {}

    fn validate_transform_origin_change(&self, _old_value: RelativePoint, _new_value: RelativePoint) {}
    fn on_transform_origin_changed(&self) {}
    fn on_transform_origin_changing(&self) {}

    fn validate_transform_change(&self, _old_value: &Option<BatchResource<dyn ITransform>>, _new_value: &Option<BatchResource<dyn ITransform>>) {}
    fn on_transform_changed(&self) {}
    fn on_transform_changing(&self) {}

    fn validate_relative_transform_change(&self, _old_value: &Option<BatchResource<dyn ITransform>>, _new_value: &Option<BatchResource<dyn ITransform>>) {}
    fn on_relative_transform_changed(&self) {}
    fn on_relative_transform_changing(&self) {}
}

/// The UI-thread properties of `CompositionBrush`.
pub struct CompositionBrushProps {
    changed_fields_of_composition_brush: Cell<CompositionBrushChangedFields>,
    opacity: Cell<f64>,
    transform_origin: Cell<RelativePoint>,
    transform: RefCell<Option<BatchResource<dyn ITransform>>>,
    relative_transform: RefCell<Option<BatchResource<dyn ITransform>>>,
}

impl Default for CompositionBrushProps {
    fn default() -> Self {
        Self::new()
    }
}

impl CompositionBrushProps {
    /// Creates the properties with every field at the default of its type.
    /// The defaults of the schema are applied by
    /// [`initialize_defaults`](Self::initialize_defaults).
    pub fn new() -> Self {
        Self {
            changed_fields_of_composition_brush: Cell::new(CompositionBrushChangedFields::empty()),
            opacity: Cell::new(Default::default()),
            transform_origin: Cell::new(Default::default()),
            transform: RefCell::new(None),
            relative_transform: RefCell::new(None),
        }
    }

    /// The `InitializeDefaults` calls of the constructor chain: the base
    /// classes first, then this class.
    pub fn initialize_defaults(&self, host: &dyn CompositionBrushHooks) {
        self.initialize_own_defaults(host);
    }

    /// `InitializeDefaults` of this class alone.
    pub fn initialize_own_defaults(&self, host: &dyn CompositionBrushHooks) {
        CompositionBrushHooks::initialize_defaults_extra(host);
        self.set_opacity(host, 1.0);
    }

    /// `Opacity` (animated, default `1.0`).
    pub fn opacity(&self) -> f64 {
        self.opacity.get()
    }

    /// Sets `Opacity` (animated, default `1.0`).
    pub fn set_opacity(&self, host: &dyn CompositionBrushHooks, value: f64) {
        let mut changed = false;
        let old_value = self.opacity.get();
        if old_value.differs(&value) {
            CompositionBrushHooks::validate_opacity_change(host, old_value, value);
            CompositionBrushHooks::on_opacity_changing(host);
            changed = true;
            // Update the backing value
            self.opacity.set(value);
            // Register object for serialization in the next batch
            self.changed_fields_of_composition_brush.set(self.changed_fields_of_composition_brush.get() | CompositionBrushChangedFields::OPACITY);
            host.register_for_serialization();
            // Reset previous animation if any
            host.pending_animations().remove(ServerCompositionBrushProps::id_of_opacity_property().base());
            self.changed_fields_of_composition_brush.set(self.changed_fields_of_composition_brush.get() & !CompositionBrushChangedFields::OPACITY_ANIMATED);
            // Check for implicit animations
            if let Some(animation) = host.implicit_animation("Opacity") {
                // Animation affects only current property
                if let Some(a) = animation.as_composition_animation() {
                    self.changed_fields_of_composition_brush.set(self.changed_fields_of_composition_brush.get() | CompositionBrushChangedFields::OPACITY_ANIMATED);
                    host.pending_animations().set(
                        ServerCompositionBrushProps::id_of_opacity_property().base(),
                        a.create_instance(host.server(), Some(ExpressionVariant::create(value))),
                    );
                }
                // Animation is triggered by the current field, but does not necessary affects it
                host.start_animation_group(&animation, "Opacity", ExpressionVariant::create(value));
            }
        }
        self.opacity.set(value);
        if changed {
            CompositionBrushHooks::on_opacity_changed(host);
        }
    }

    /// `TransformOrigin`.
    pub fn transform_origin(&self) -> RelativePoint {
        self.transform_origin.get()
    }

    /// Sets `TransformOrigin`.
    pub fn set_transform_origin(&self, host: &dyn CompositionBrushHooks, value: RelativePoint) {
        let mut changed = false;
        let old_value = self.transform_origin.get();
        if old_value.differs(&value) {
            CompositionBrushHooks::validate_transform_origin_change(host, old_value, value);
            CompositionBrushHooks::on_transform_origin_changing(host);
            changed = true;
            // Update the backing value
            self.transform_origin.set(value);
            // Register object for serialization in the next batch
            self.changed_fields_of_composition_brush.set(self.changed_fields_of_composition_brush.get() | CompositionBrushChangedFields::TRANSFORM_ORIGIN);
            host.register_for_serialization();
        }
        self.transform_origin.set(value);
        if changed {
            CompositionBrushHooks::on_transform_origin_changed(host);
        }
    }

    /// `Transform`.
    pub fn transform(&self) -> Option<BatchResource<dyn ITransform>> {
        self.transform.borrow().clone()
    }

    /// Sets `Transform`.
    pub fn set_transform(&self, host: &dyn CompositionBrushHooks, value: Option<BatchResource<dyn ITransform>>) {
        let mut changed = false;
        let old_value = self.transform.borrow().clone();
        if old_value.differs(&value) {
            CompositionBrushHooks::validate_transform_change(host, &old_value, &value);
            CompositionBrushHooks::on_transform_changing(host);
            changed = true;
            // Update the backing value
            *self.transform.borrow_mut() = value.clone();
            // Register object for serialization in the next batch
            self.changed_fields_of_composition_brush.set(self.changed_fields_of_composition_brush.get() | CompositionBrushChangedFields::TRANSFORM);
            host.register_for_serialization();
        }
        *self.transform.borrow_mut() = value;
        if changed {
            CompositionBrushHooks::on_transform_changed(host);
        }
    }

    /// `RelativeTransform`.
    pub fn relative_transform(&self) -> Option<BatchResource<dyn ITransform>> {
        self.relative_transform.borrow().clone()
    }

    /// Sets `RelativeTransform`.
    pub fn set_relative_transform(&self, host: &dyn CompositionBrushHooks, value: Option<BatchResource<dyn ITransform>>) {
        let mut changed = false;
        let old_value = self.relative_transform.borrow().clone();
        if old_value.differs(&value) {
            CompositionBrushHooks::validate_relative_transform_change(host, &old_value, &value);
            CompositionBrushHooks::on_relative_transform_changing(host);
            changed = true;
            // Update the backing value
            *self.relative_transform.borrow_mut() = value.clone();
            // Register object for serialization in the next batch
            self.changed_fields_of_composition_brush.set(self.changed_fields_of_composition_brush.get() | CompositionBrushChangedFields::RELATIVE_TRANSFORM);
            host.register_for_serialization();
        }
        *self.relative_transform.borrow_mut() = value;
        if changed {
            CompositionBrushHooks::on_relative_transform_changed(host);
        }
    }

    /// Connects an animation with the named property. Returns `false` when
    /// neither this class nor its generated bases have an animated property
    /// of that name: the caller continues with its hand-written base.
    pub fn start_animation(
        &self,
        host: &dyn CompositionBrushHooks,
        property_name: &str,
        animation: &dyn ICompositionAnimation,
        final_value: Option<ExpressionVariant>,
    ) -> bool {
        if property_name == "Opacity" {
            let server = animation.create_instance(host.server(), final_value);
            host.pending_animations().set(ServerCompositionBrushProps::id_of_opacity_property().base(), server);
            self.changed_fields_of_composition_brush.set(self.changed_fields_of_composition_brush.get() | CompositionBrushChangedFields::OPACITY_ANIMATED);
            host.register_for_serialization();
            return true;
        }
        false
    }

    /// Writes the changes of the object: the base class first, then the
    /// changed-fields mask and the changed members of this class.
    pub fn serialize_changes_core(&self, host: &dyn CompositionBrushHooks, writer: &mut BatchStreamWriter<'_>) {
        let changed = self.changed_fields_of_composition_brush.get();
        writer.write(changed);
        if changed.contains(CompositionBrushChangedFields::OPACITY_ANIMATED) {
            writer.write_value(host.pending_animations().get_and_remove(ServerCompositionBrushProps::id_of_opacity_property().base()));
        } else if changed.contains(CompositionBrushChangedFields::OPACITY) {
            writer.write(self.opacity.get());
        }
        if changed.contains(CompositionBrushChangedFields::TRANSFORM_ORIGIN) {
            writer.write(self.transform_origin.get());
        }
        if changed.contains(CompositionBrushChangedFields::TRANSFORM) {
            writer.write_resource(self.transform.borrow().clone());
        }
        if changed.contains(CompositionBrushChangedFields::RELATIVE_TRANSFORM) {
            writer.write_resource(self.relative_transform.borrow().clone());
        }
        self.changed_fields_of_composition_brush.set(CompositionBrushChangedFields::empty());
    }
}

/// The partial methods of `ServerCompositionBrush`: implemented by the class that embeds
/// [`ServerCompositionBrushProps`]. Every hook defaults to doing nothing.
pub trait ServerCompositionBrushHooks: IServerAnimatedPropertyHost {
    fn deserialize_changes_extra(&self, _reader: &mut BatchStreamReader<'_>) {}
    fn on_fields_deserialized(&self, _changed: CompositionBrushChangedFields) {}

    fn on_transform_origin_changed(&self) {}
    fn on_transform_origin_changing(&self) {}

    fn on_transform_changed(&self) {}
    fn on_transform_changing(&self) {}

    fn on_relative_transform_changed(&self) {}
    fn on_relative_transform_changing(&self) {}
}

/// The server-side properties of `ServerCompositionBrush`.
pub struct ServerCompositionBrushProps {
    opacity: Cell<f64>,
    transform_origin: Cell<RelativePoint>,
    transform: RefCell<Option<ServerResourceRef<dyn ITransform>>>,
    relative_transform: RefCell<Option<ServerResourceRef<dyn ITransform>>>,
}

impl Default for ServerCompositionBrushProps {
    fn default() -> Self {
        Self::new()
    }
}

impl ServerCompositionBrushProps {
    /// Creates the properties with every field at the default of its type; the
    /// values of the UI thread arrive with the first batch.
    pub fn new() -> Self {
        Self {
            opacity: Cell::new(Default::default()),
            transform_origin: Cell::new(Default::default()),
            transform: RefCell::new(None),
            relative_transform: RefCell::new(None),
        }
    }

    /// This block or the block of a base class, by type: what
    /// `IServerObject::get_props` of the embedding class returns.
    pub fn find_props(&self, type_id: TypeId) -> Option<&dyn Any> {
        if type_id == TypeId::of::<Self>() {
            return Some(self);
        }
        None
    }

    /// The composition property of `Opacity`.
    pub fn id_of_opacity_property() -> &'static CompositionPropertyOf<f64> {
        static PROPERTY: OnceLock<CompositionPropertyOf<f64>> = OnceLock::new();
        PROPERTY.get_or_init(|| {
            CompositionProperty::register::<ServerCompositionBrushProps, f64>(
                "Opacity",
                "ServerCompositionBrush",
                |obj| props_of::<ServerCompositionBrushProps>(obj).opacity.get(),
                |obj, v| props_of::<ServerCompositionBrushProps>(obj).opacity.set(v),
                Some(|obj| ExpressionVariant::create(props_of::<ServerCompositionBrushProps>(obj).opacity.get())),
                Some(|obj, v: ExpressionVariant| props_of::<ServerCompositionBrushProps>(obj).opacity.set(v.cast_or_default::<f64>())),
            )
        })
    }

    /// `Opacity` (animated).
    pub fn opacity(&self) -> f64 {
        self.opacity.get()
    }

    pub fn set_opacity(&self, host: &dyn ServerCompositionBrushHooks, value: f64) {
        self.opacity.set(value);
        host.remove_animation_for_property(Self::id_of_opacity_property().base());
    }

    /// The composition property of `TransformOrigin`.
    pub fn id_of_transform_origin_property() -> &'static CompositionPropertyOf<RelativePoint> {
        static PROPERTY: OnceLock<CompositionPropertyOf<RelativePoint>> = OnceLock::new();
        PROPERTY.get_or_init(|| {
            CompositionProperty::register::<ServerCompositionBrushProps, RelativePoint>(
                "TransformOrigin",
                "ServerCompositionBrush",
                |obj| props_of::<ServerCompositionBrushProps>(obj).transform_origin.get(),
                |obj, v| props_of::<ServerCompositionBrushProps>(obj).transform_origin.set(v),
                None,
                None,
            )
        })
    }

    /// `TransformOrigin`.
    pub fn transform_origin(&self) -> RelativePoint {
        self.transform_origin.get()
    }

    pub fn set_transform_origin(&self, host: &dyn ServerCompositionBrushHooks, value: RelativePoint) {
        let old_value = self.transform_origin.get();
        let mut changed = false;
        if old_value.differs(&value) {
            ServerCompositionBrushHooks::on_transform_origin_changing(host);
            changed = true;
        }
        host.set_value(
            Self::id_of_transform_origin_property().base(),
            ServerValueChange {
                equal: old_value.default_equals(&value),
                old_resource: None,
                new_resource: None,
                assign: &mut || self.transform_origin.set(value),
            },
        );
        if changed {
            ServerCompositionBrushHooks::on_transform_origin_changed(host);
        }
    }

    /// The composition property of `Transform`.
    pub fn id_of_transform_property() -> &'static CompositionPropertyOf<Option<ServerResourceRef<dyn ITransform>>> {
        static PROPERTY: OnceLock<CompositionPropertyOf<Option<ServerResourceRef<dyn ITransform>>>> = OnceLock::new();
        PROPERTY.get_or_init(|| {
            CompositionProperty::register::<ServerCompositionBrushProps, Option<ServerResourceRef<dyn ITransform>>>(
                "Transform",
                "ServerCompositionBrush",
                |obj| props_of::<ServerCompositionBrushProps>(obj).transform.borrow().clone(),
                |obj, v| *props_of::<ServerCompositionBrushProps>(obj).transform.borrow_mut() = v,
                None,
                None,
            )
        })
    }

    /// `Transform`.
    pub fn transform(&self) -> Option<ServerResourceRef<dyn ITransform>> {
        self.transform.borrow().clone()
    }

    pub fn set_transform(&self, host: &dyn ServerCompositionBrushHooks, value: Option<ServerResourceRef<dyn ITransform>>) {
        let old_value = self.transform.borrow().clone();
        let mut changed = false;
        if old_value.differs(&value) {
            ServerCompositionBrushHooks::on_transform_changing(host);
            changed = true;
        }
        host.set_value(
            Self::id_of_transform_property().base(),
            ServerValueChange {
                equal: old_value.default_equals(&value),
                old_resource: old_value.as_server_render_resource(),
                new_resource: value.as_server_render_resource(),
                assign: &mut || *self.transform.borrow_mut() = value.clone(),
            },
        );
        if changed {
            ServerCompositionBrushHooks::on_transform_changed(host);
        }
    }

    /// The composition property of `RelativeTransform`.
    pub fn id_of_relative_transform_property() -> &'static CompositionPropertyOf<Option<ServerResourceRef<dyn ITransform>>> {
        static PROPERTY: OnceLock<CompositionPropertyOf<Option<ServerResourceRef<dyn ITransform>>>> = OnceLock::new();
        PROPERTY.get_or_init(|| {
            CompositionProperty::register::<ServerCompositionBrushProps, Option<ServerResourceRef<dyn ITransform>>>(
                "RelativeTransform",
                "ServerCompositionBrush",
                |obj| props_of::<ServerCompositionBrushProps>(obj).relative_transform.borrow().clone(),
                |obj, v| *props_of::<ServerCompositionBrushProps>(obj).relative_transform.borrow_mut() = v,
                None,
                None,
            )
        })
    }

    /// `RelativeTransform`.
    pub fn relative_transform(&self) -> Option<ServerResourceRef<dyn ITransform>> {
        self.relative_transform.borrow().clone()
    }

    pub fn set_relative_transform(&self, host: &dyn ServerCompositionBrushHooks, value: Option<ServerResourceRef<dyn ITransform>>) {
        let old_value = self.relative_transform.borrow().clone();
        let mut changed = false;
        if old_value.differs(&value) {
            ServerCompositionBrushHooks::on_relative_transform_changing(host);
            changed = true;
        }
        host.set_value(
            Self::id_of_relative_transform_property().base(),
            ServerValueChange {
                equal: old_value.default_equals(&value),
                old_resource: old_value.as_server_render_resource(),
                new_resource: value.as_server_render_resource(),
                assign: &mut || *self.relative_transform.borrow_mut() = value.clone(),
            },
        );
        if changed {
            ServerCompositionBrushHooks::on_relative_transform_changed(host);
        }
    }

    /// Reads the changes of the object: the base class first, then the
    /// changed-fields mask and the changed members of this class.
    pub fn deserialize_changes_core(
        &self,
        host: &dyn ServerCompositionBrushHooks,
        reader: &mut BatchStreamReader<'_>,
        committed_at: Duration,
    ) {
        let compositor = host.server_compositor();
        ServerCompositionBrushHooks::deserialize_changes_extra(host, reader);
        let changed = reader.read::<CompositionBrushChangedFields>();
        if changed.contains(CompositionBrushChangedFields::OPACITY_ANIMATED) {
            let Some(animation) = reader.read_value::<AnimationInstanceFactory>().map(AnimationInstanceFactory::create) else {
                panic!("a batch starts an animation of `Opacity` without an animation instance");
            };
            host.set_animated_value(
                Self::id_of_opacity_property().base(),
                ExpressionVariant::create(self.opacity.get()),
                committed_at,
                animation,
            );
        } else if changed.contains(CompositionBrushChangedFields::OPACITY) {
            let value = reader.read::<f64>();
            self.set_opacity(host, value);
        }
        if changed.contains(CompositionBrushChangedFields::TRANSFORM_ORIGIN) {
            let value = reader.read::<RelativePoint>();
            self.set_transform_origin(host, value);
        }
        if changed.contains(CompositionBrushChangedFields::TRANSFORM) {
            let value = read_resource(reader, compositor.as_ref(), |o| o.as_transform());
            self.set_transform(host, value);
        }
        if changed.contains(CompositionBrushChangedFields::RELATIVE_TRANSFORM) {
            let value = read_resource(reader, compositor.as_ref(), |o| o.as_transform());
            self.set_relative_transform(host, value);
        }
        ServerCompositionBrushHooks::on_fields_deserialized(host, changed);
    }

    /// The composition property with the given name, among the properties
    /// of this class and of its generated bases that have a variant form.
    pub fn get_composition_property(name: &str) -> Option<&'static CompositionProperty> {
        if name == "Opacity" {
            return Some(Self::id_of_opacity_property().base());
        }
        None
    }
}