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
use super::animations::{ICompositionAnimation, ICompositionAnimationBase};
use super::container_visual::HIT_TEST_AABB_TREE_THRESHOLD;
use super::expressions::ExpressionVariant;
use super::generated::{CompositionTargetHooks, CompositionTargetProps, ServerCompositionTargetProps};
use super::hit_testing::{is_hit, ICompositionHitTester};
use super::server::{CompositionProperty, RenderSurfaces, ServerCompositionTarget, ServerObjectId};
use super::transport::{BatchStreamWriter, IRegisterForSerialization};
use super::{
    AsCompositionObject, CompositionObject, CompositionTransparencyLevel, ICompositionObjectAnimations, CompositionVisual, Compositor, ICompositionObject,
    ICompositionObjectHost, ICompositionTargetDebugEvents, ICompositorSerializable, PendingAnimations,
};
use crate::media::IntersectionResult;
use crate::rendering::{LayoutPassTiming, RendererDebugOverlays};
use crate::Size;
use std::any::Any;
use std::cell::RefCell;
use std::sync::Arc;
use std::rc::{Rc, Weak};
use std::sync::atomic::{AtomicI64, Ordering};

static NEXT_ID: AtomicI64 = AtomicI64::new(1);

type VisualFilter<'a> = Option<&'a dyn Fn(&Rc<CompositionVisual>) -> bool>;

/// The root of a composition visual tree: what a renderer draws to a
/// render target.
pub struct CompositionTarget {
    this: Weak<CompositionTarget>,
    object: CompositionObject,
    props: CompositionTargetProps,
    id: i64,
    hit_test_child_candidates: RefCell<Vec<Rc<CompositionVisual>>>,
}

impl CompositionTarget {
    pub(crate) fn new(compositor: &Rc<Compositor>, surfaces: RenderSurfaces) -> Rc<CompositionTarget> {
        let id = NEXT_ID.fetch_add(1, Ordering::SeqCst) + 1;
        // The render interface may have been registered after the compositor
        // was created. It is looked up here, on the thread that has the
        // services, before a frame of the render thread needs it.
        compositor.with_server(|server| {
            server.render_interface().capture_platform_render_interface();
        });
        let server =
            compositor.create_server_object(move |compositor, _| ServerCompositionTarget::new(compositor, surfaces, id));
        let target = Rc::new_cyclic(|this: &Weak<CompositionTarget>| CompositionTarget {
            this: this.clone(),
            object: CompositionObject::new(compositor, Some(server)),
            props: CompositionTargetProps::new(),
            id,
            hit_test_child_candidates: RefCell::new(Vec::new()),
        });
        target.props.initialize_defaults(&*target);
        target
    }

    pub fn compositor(&self) -> &Rc<Compositor> {
        self.object.compositor()
    }

    /// The id of the server-side target.
    pub fn server(&self) -> ServerObjectId {
        self.object.required_server()
    }

    /// The identity of the target, shared with its server side.
    pub fn id(&self) -> i64 {
        self.id
    }

    pub fn is_disposed(&self) -> bool {
        self.object.is_disposed()
    }

    pub fn dispose(&self) {
        self.object.dispose();
    }

    /// Marks the target disposed after its server side has been disposed
    /// out of band.
    pub(crate) fn mark_disposed_out_of_band(&self) {
        self.object.mark_disposed();
    }

    // --- generated properties -----------------------------------------------------

    pub fn root(&self) -> Option<Rc<CompositionVisual>> {
        self.props.root().and_then(|o| o.into_any_rc().downcast::<CompositionVisual>().ok())
    }

    pub fn set_root(&self, value: Option<Rc<CompositionVisual>>) {
        self.props.set_root(self, value.map(|v| v as Rc<dyn ICompositionObject>));
    }

    pub fn is_enabled(&self) -> bool {
        self.props.is_enabled()
    }

    pub fn set_is_enabled(&self, value: bool) {
        self.props.set_is_enabled(self, value);
    }

    pub fn debug_overlays(&self) -> RendererDebugOverlays {
        self.props.debug_overlays()
    }

    pub fn set_debug_overlays(&self, value: RendererDebugOverlays) {
        if !value.is_empty() {
            // The text of the overlays is made from the default typeface,
            // on this thread; the frames that draw it may run on another.
            self.compositor().with_server(|server| {
                server.diagnostic_text_renderer();
            });
        }
        self.props.set_debug_overlays(self, value);
    }

    pub fn last_layout_pass_timing(&self) -> LayoutPassTiming {
        self.props.last_layout_pass_timing()
    }

    pub fn set_last_layout_pass_timing(&self, value: LayoutPassTiming) {
        self.props.set_last_layout_pass_timing(self, value);
    }

    pub fn scaling(&self) -> f64 {
        self.props.scaling()
    }

    pub fn set_scaling(&self, value: f64) {
        self.props.set_scaling(self, value);
    }

    pub fn size(&self) -> Size {
        self.props.size()
    }

    pub fn set_size(&self, value: Size) {
        self.props.set_size(self, value);
    }

    pub fn transparency_level(&self) -> CompositionTransparencyLevel {
        self.props.transparency_level()
    }

    pub fn set_transparency_level(&self, value: CompositionTransparencyLevel) {
        self.props.set_transparency_level(self, value);
    }

    pub fn platform_specific_scene_info(&self) -> Option<std::sync::Arc<dyn Any + Send + Sync>> {
        self.props.platform_specific_scene_info()
    }

    pub fn set_platform_specific_scene_info(&self, value: Option<std::sync::Arc<dyn Any + Send + Sync>>) {
        self.props.set_platform_specific_scene_info(self, value);
    }

    /// Sets the receiver of the debug events of the server-side target.
    /// It is handed over with the next batch.
    pub fn set_debug_events(&self, events: Option<Arc<dyn ICompositionTargetDebugEvents>>) {
        let server = self.server();
        self.compositor().post_server_job(
            move |compositor| {
                if let Some(target) = compositor.get::<ServerCompositionTarget>(server) {
                    target.set_debug_events(events);
                }
            },
            false,
        );
    }

    // --- hit testing --------------------------------------------------------------

    /// Collects the visuals hit by `input` (in the coordinates of `root`,
    /// or of the root of the target), topmost first, with how they are
    /// hit. `None` when the tree has not been rendered yet.
    pub fn try_hit_test<H: ICompositionHitTester>(
        &self,
        input: &H::Input,
        root: Option<&Rc<CompositionVisual>>,
        filter: VisualFilter<'_>,
    ) -> Option<Vec<(IntersectionResult, Rc<CompositionVisual>)>> {
        self.compositor().readback().next_read();
        let root = match root {
            Some(root) => root.clone(),
            None => self.root()?,
        };

        // Need to convert transform the point using visual's readback since HitTestCore will use its inverse matrix
        // NOTE: it can technically break hit-testing of the root visual itself if it has a non-identity transform,
        // need to investigate that possibility later. We might want a separate mode for root hit-testing.
        let readback = root.try_get_valid_readback()?;
        let parent_input = H::transform(input, readback.matrix);

        let mut res = Vec::new();
        self.hit_test_core::<H>(&root, &parent_input, &mut res, filter);
        Some(res)
    }

    fn hit_test_core<H: ICompositionHitTester>(
        &self,
        visual: &Rc<CompositionVisual>,
        parent_input: &H::Input,
        result: &mut Vec<(IntersectionResult, Rc<CompositionVisual>)>,
        filter: VisualFilter<'_>,
    ) {
        let Some(input) = Self::hit_test_visual::<H>(visual, parent_input, filter) else { return };

        // Inspect children
        self.hit_test_children::<H>(visual, &input, result, filter);

        // Hit-test the current node
        let intersection_result = H::hit_test(visual, &input);
        if is_hit(intersection_result) {
            result.push((intersection_result, visual.clone()));
        }
    }

    fn hit_test_children<H: ICompositionHitTester>(
        &self,
        visual: &Rc<CompositionVisual>,
        input: &H::Input,
        result: &mut Vec<(IntersectionResult, Rc<CompositionVisual>)>,
        filter: VisualFilter<'_>,
    ) {
        if visual.children().count() >= HIT_TEST_AABB_TREE_THRESHOLD {
            // The candidate list of the target is reused unless a query is
            // already running (a nested container).
            let mut candidates = match self.hit_test_child_candidates.try_borrow_mut() {
                Ok(mut pooled) => std::mem::take(&mut *pooled),
                Err(_) => Vec::new(),
            };
            candidates.clear();
            let queried = visual.try_query_hit_test_children::<H>(input, &mut candidates);
            if queried {
                for child in &candidates {
                    self.hit_test_core::<H>(child, input, result, filter);
                }
            }
            candidates.clear();
            if let Ok(mut pooled) = self.hit_test_child_candidates.try_borrow_mut() {
                if pooled.capacity() < candidates.capacity() {
                    *pooled = candidates;
                }
            }
            if queried {
                return;
            }
        }

        // By index, from the last child, as the original: no copy of the
        // children of every visual the hit test enters.
        let children = visual.children();
        let mut index = children.count();
        while index > 0 {
            index -= 1;
            self.hit_test_core::<H>(&children.get(index), input, result, filter);
        }
    }

    fn hit_test_visual<H: ICompositionHitTester>(
        visual: &Rc<CompositionVisual>,
        parent_input: &H::Input,
        filter: VisualFilter<'_>,
    ) -> Option<H::Input> {
        if !visual.visible() {
            return None;
        }

        if let Some(filter) = filter {
            if !filter(visual) {
                return None;
            }
        }

        let readback = visual.try_get_valid_readback()?;

        if !visual.disable_sub_tree_bounds_hit_test_optimization() {
            let transformed_subtree_bounds = readback.transformed_subtree_bounds?;
            if !H::transformed_sub_tree_bounds_match(transformed_subtree_bounds, parent_input) {
                return None;
            }
        }

        let inv_matrix = readback.matrix.try_invert()?;

        let input = H::transform(parent_input, inv_matrix);

        if visual.clip_to_bounds() && !H::clipped_bounds_match(visual, &input) {
            return None;
        }

        if let Some(clip) = visual.clip() {
            if !H::clip_matches(&*clip, &input) {
                return None;
            }
        }

        Some(input)
    }

    /// Finds the topmost visual hit by `input` that passes `result_filter`
    /// and returns it with how it is hit.
    pub fn try_hit_test_first<H: ICompositionHitTester>(
        &self,
        input: &H::Input,
        root: Option<&Rc<CompositionVisual>>,
        filter: VisualFilter<'_>,
        result_filter: VisualFilter<'_>,
    ) -> (Option<Rc<CompositionVisual>>, IntersectionResult) {
        self.compositor().readback().next_read();
        let none = (None, IntersectionResult::NotCalculated);
        let root = match root {
            Some(root) => root.clone(),
            None => match self.root() {
                Some(root) => root,
                None => return none,
            },
        };

        // Need to convert transform the point using visual's readback since HitTestCore will use its inverse matrix
        // NOTE: it can technically break hit-testing of the root visual itself if it has a non-identity transform,
        // need to investigate that possibility later. We might want a separate mode for root hit-testing.
        let Some(readback) = root.try_get_valid_readback() else { return none };
        let parent_input = H::transform(input, readback.matrix);

        self.hit_test_first_core::<H>(&root, &parent_input, filter, result_filter)
    }

    pub(crate) fn hit_test_first_core<H: ICompositionHitTester>(
        &self,
        visual: &Rc<CompositionVisual>,
        parent_input: &H::Input,
        filter: VisualFilter<'_>,
        result_filter: VisualFilter<'_>,
    ) -> (Option<Rc<CompositionVisual>>, IntersectionResult) {
        let Some(input) = Self::hit_test_visual::<H>(visual, parent_input, filter) else {
            return (None, IntersectionResult::NotCalculated);
        };

        let mut queried_indexed_children = false;
        if visual.children().count() >= HIT_TEST_AABB_TREE_THRESHOLD {
            if let Some((hit, intersection_result)) =
                visual.try_query_first_hit_test_child::<H>(self, &input, filter, result_filter)
            {
                queried_indexed_children = true;
                if hit.is_some() {
                    return (hit, intersection_result);
                }
            }
        }

        if !queried_indexed_children {
            // By index, from the last child, as the original: no copy of the
            // children of every visual the hit test enters.
            let children = visual.children();
            let mut index = children.count();
            while index > 0 {
                index -= 1;
                let child = children.get(index);
                let (hit, intersection_result) = self.hit_test_first_core::<H>(&child, &input, filter, result_filter);
                if hit.is_some() {
                    return (hit, intersection_result);
                }
            }
        }

        let intersection_result = H::hit_test(visual, &input);
        let hit = is_hit(intersection_result) && result_filter.is_none_or(|result_filter| result_filter(visual));
        (hit.then(|| visual.clone()), intersection_result)
    }

    pub fn request_redraw(&self) {
        self.register_for_serialization();
    }
}

impl CompositionTargetHooks for CompositionTarget {
    fn on_root_changed(&self) {
        if let Some(root) = self.root() {
            root.set_root(self.this.upgrade());
        }
    }

    fn on_root_changing(&self) {
        if let Some(root) = self.root() {
            root.set_root(None);
        }
    }
}

impl IRegisterForSerialization for CompositionTarget {
    fn register_for_serialization(&self) {
        self.object
            .register_for_serialization(|| self.this.upgrade().map(|this| this as Rc<dyn ICompositorSerializable>));
    }
}

impl ICompositionObjectHost for CompositionTarget {
    fn server(&self) -> ServerObjectId {
        self.object.required_server()
    }

    fn pending_animations(&self) -> &PendingAnimations {
        self.object.pending_animations()
    }

    fn implicit_animation(&self, property_name: &str) -> Option<Rc<dyn ICompositionAnimationBase>> {
        self.object.implicit_animation(property_name)
    }

    fn start_animation_group(
        &self,
        grp: &Rc<dyn ICompositionAnimationBase>,
        target: &str,
        final_value: ExpressionVariant,
    ) -> bool {
        self.start_animation_group_for(&**grp, target, final_value)
    }
}

/// The class has no animated property: upstream does not override
/// `StartAnimation`, whose base implementation rejects every property.
impl ICompositionObjectAnimations for CompositionTarget {
    fn try_start_animation(
        &self,
        _property_name: &str,
        _animation: &dyn ICompositionAnimation,
        _final_value: Option<ExpressionVariant>,
    ) -> bool {
        false
    }

    fn get_composition_property(&self, property_name: &str) -> Option<&'static CompositionProperty> {
        ServerCompositionTargetProps::get_composition_property(property_name)
    }

    fn composition_object(&self) -> &CompositionObject {
        &self.object
    }
}

impl AsCompositionObject for CompositionTarget {
    fn as_composition_object(&self) -> &CompositionObject {
        &self.object
    }

    fn composition_type_name(&self) -> &'static str {
        "CompositionTarget"
    }
}

impl ICompositionObject for CompositionTarget {
    fn server(&self) -> ServerObjectId {
        self.object.required_server()
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn into_any_rc(self: Rc<Self>) -> Rc<dyn Any> {
        self
    }
}

impl ICompositorSerializable for CompositionTarget {
    fn try_get_server(&self, c: &Compositor) -> Option<ServerObjectId> {
        self.object.try_get_server(c)
    }

    fn serialize_changes(&self, c: &Compositor, writer: &mut BatchStreamWriter<'_>) {
        self.object.begin_serialize_changes(c);
        self.props.serialize_changes_core(self, writer);
    }
}