ferroui-base 0.5.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
527
528
529
530
531
532
533
534
535
536
537
538
539
use super::walker::{walk, IServerTreeVisitor, TreeWalkContext};
use super::ServerCompositionVisual;
use crate::media::{RenderOptions, TextOptions};
use crate::platform::{IDrawingContextImpl, LtrbRect};
use crate::rendering::composition::effects::{pop_custom_effect_graph_with, push_custom_effect_graph_with};
use crate::rendering::composition::server::{
    render_scope, CompositorPools, IDirtyRectTracker, LitContent, ServerDrawItems, ServerVisualRenderContext,
};
use crate::{Matrix, Vector};
use std::rc::Rc;

pub(super) struct RenderContext<'a> {
    pub(super) canvas: &'a mut dyn IDrawingContextImpl,
    dirty_rects: Option<Rc<dyn IDirtyRectTracker>>,
    pub(super) pools: &'a CompositorPools,
    render_children: bool,
    walk_context: TreeWalkContext,
    opacity_stack: Vec<f64>,
    opacity: f64,
    full_skip: bool,
    used_cache: bool,
    rendered_visuals: i32,
    visited_visuals: i32,
    pub(super) root_visual: Rc<ServerCompositionVisual>,
    skip_next_visual_transform: bool,
    rendering_to_bitmap_cache: bool,
    pub(super) adorner_pushed_clip_stack: Option<Vec<i32>>,
    pub(super) current_adorner_layer: Option<Rc<ServerCompositionVisual>>,
    /// The visual the render stops at (a backdrop render): it and
    /// everything after it in paint order are not drawn.
    stop_at: Option<*const ServerCompositionVisual>,
    /// Whether the render reached `stop_at`.
    stopped: bool,
    /// Whether the compositor has lights at all, asked once for the walk
    /// (not from upstream): without lights no visual looks for its light map.
    lights_registered: bool,
}

impl<'a> RenderContext<'a> {
    #[allow(clippy::too_many_arguments)]
    fn new(
        root_visual: Rc<ServerCompositionVisual>,
        canvas: &'a mut dyn IDrawingContextImpl,
        mut dirty_rects: Option<Rc<dyn IDirtyRectTracker>>,
        pools: &'a CompositorPools,
        matrix: Matrix,
        mut clip: LtrbRect,
        render_children: bool,
        skip_root_visual_transform: bool,
        rendering_to_bitmap_cache: bool,
    ) -> Self {
        if let Some(tracker) = &dirty_rects {
            let dirty_clip = tracker.combined_rect();
            let is_single = tracker.is_single_dirty_rect_tracker();
            if is_single {
                dirty_rects = None;
            }
            clip = clip.intersect_or_empty(dirty_clip);
        }

        let lights_registered = root_visual.compositor().is_some_and(|compositor| compositor.has_registered_lights());

        Self {
            canvas,
            dirty_rects,
            pools,
            render_children,
            root_visual,
            lights_registered,
            walk_context: TreeWalkContext::new(pools, matrix, clip),
            opacity: 1.0,
            opacity_stack: pools.double_stack_pool.rent(),
            full_skip: false,
            used_cache: false,
            rendered_visuals: 0,
            visited_visuals: 0,
            skip_next_visual_transform: skip_root_visual_transform,
            rendering_to_bitmap_cache,
            adorner_pushed_clip_stack: None,
            current_adorner_layer: None,
            stop_at: None,
            stopped: false,
        }
    }

    fn handle_pre_graph_transform_clip_opacity(&mut self, visual: &ServerCompositionVisual) -> bool {
        let Some(transformed_sub_tree_bounds) = visual.transformed_sub_tree_bounds.get() else { return false };
        if !visual.visible() {
            return false;
        }
        let visual_opacity = visual.opacity() as f64;
        let effective_opacity = visual_opacity * self.opacity;
        if effective_opacity <= 0.003 {
            return false;
        }

        let mut effective_new_transform = self.walk_context.transform;
        if let Some(own_transform) = visual.own_transform.get() {
            if !self.skip_next_visual_transform {
                effective_new_transform = own_transform * self.walk_context.transform;
            }
        }
        self.skip_next_visual_transform = false;

        let mut effective_clip = self.walk_context.clip;
        if let Some(own_clip) = visual.own_clip_rect.get() {
            effective_clip = effective_clip.intersect_or_empty(own_clip.transform_to_aabb(effective_new_transform));
        }

        let world_bounds = transformed_sub_tree_bounds.transform_to_aabb(self.walk_context.transform);
        if !effective_clip.intersects(world_bounds)
            || self.dirty_rects.as_ref().is_some_and(|d| !d.intersects(world_bounds))
        {
            return false;
        }

        self.rendered_visuals += 1;

        // We are still in parent's coordinate space here

        if visual_opacity != 1.0 {
            self.opacity_stack.push(self.opacity);
            self.opacity = effective_opacity;
            crate::perf_count!(RenderVisualOpacitiesPushed);
            self.canvas.push_opacity(visual_opacity, Some(transformed_sub_tree_bounds.to_rect()));
        }

        // Switch coordinate space to this visual's space

        if visual.own_transform.get().is_some() {
            self.walk_context.push_set_transform(effective_new_transform); // Reuse one computed before
            crate::perf_count!(RenderVisualTransformsSet);
            self.canvas.set_transform(effective_new_transform);
        }

        if visual.own_clip_rect.get().is_some() {
            self.walk_context.push_clip(effective_clip);
        }

        if visual.clip_to_bounds() {
            crate::perf_count!(RenderVisualClipsPushed);
            visual.content.push_clip_to_bounds(visual, self.canvas);
        }

        if let Some(clip) = visual.clip() {
            self.canvas.push_geometry_clip(&*clip);
        }

        // The WinUI clip object (not from upstream), in the space of the
        // visual.
        if let Some(shape) = visual.composition_clip_shape() {
            shape.push(self.canvas);
        }

        true
    }

    /// Draws the drawing items `range` of `holder`, in its space (section 9.42).
    fn render_draw_items(
        &mut self,
        holder: &Rc<ServerCompositionVisual>,
        items: &ServerDrawItems,
        range: std::ops::Range<usize>,
    ) {
        if range.is_empty() {
            return;
        }
        let transform = self.walk_context.transform;
        let clip = self.walk_context.clip;
        // The lights that reach the content reach its items.
        let lit = if self.lights_registered { LitContent::begin(holder, self.canvas) } else { None };
        let canvas = &mut *self.canvas;
        let dirty_rects = self.dirty_rects.as_deref();
        let moved = render_scope::with_painting_visual(holder, || {
            items.render(range, canvas, transform, clip, dirty_rects)
        });
        if moved {
            crate::perf_count!(RenderVisualTransformsSet);
            self.canvas.set_transform(transform);
        }
        if let Some(lit) = lit {
            lit.end(self.canvas);
        }
    }

    fn dispose(mut self) {
        let pools = self.pools;
        self.adorner_helper_dispose();
        pools.double_stack_pool.return_stack(self.opacity_stack);
        self.walk_context.dispose(pools);
    }
}

/// The part `from..to` of the world on one axis in the space of a walk whose transform has `scale`
/// and `offset` on that axis, wider by more than the arithmetic of the two directions can differ.
/// `None` for one that is no part of the axis.
fn span_in_walk_space(from: f64, to: f64, scale: f64, offset: f64) -> Option<(f64, f64)> {
    let end = |value: f64| -> Option<(f64, f64)> {
        let at = (value - offset) / scale;
        if at.is_nan() {
            return None;
        }
        if at.is_infinite() {
            return Some((at, at));
        }
        let off = ((value.abs() + offset.abs() + 1.0) / scale.abs() * 1e-9).max(at.abs() * 1e-12);
        Some((at - off, at + off))
    };
    let (from, to) = (end(from)?, end(to)?);
    Some((from.0.min(to.0), from.1.max(to.1)))
}

impl RenderContext<'_> {
    /// The clip of the walk and the origin of the world, in the space the walk is in and each a
    /// little larger than it is (section 9.48). `None` with a transform that turns or skews: the
    /// bounds of a child in the world are then not those of its bounds here.
    fn clip_and_origin_in_walk_space(&self) -> Option<(LtrbRect, LtrbRect)> {
        let m = self.walk_context.transform;
        let straight = m.m12 == 0.0 && m.m21 == 0.0 && !m.contains_perspective();
        if !straight || m.m11 == 0.0 || m.m22 == 0.0 || !(m.m11 + m.m22 + m.m31 + m.m32).is_finite() {
            return None;
        }
        let clip = self.walk_context.clip;
        let (left, right) = span_in_walk_space(clip.left, clip.right, m.m11, m.m31)?;
        let (top, bottom) = span_in_walk_space(clip.top, clip.bottom, m.m22, m.m32)?;
        let (origin_left, origin_right) = span_in_walk_space(0.0, 0.0, m.m11, m.m31)?;
        let (origin_top, origin_bottom) = span_in_walk_space(0.0, 0.0, m.m22, m.m32)?;
        Some((
            LtrbRect::new(left, top, right, bottom),
            LtrbRect::new(origin_left, origin_top, origin_right, origin_bottom),
        ))
    }
}

impl IServerTreeVisitor for RenderContext<'_> {
    fn next_child(&mut self, container: &Rc<ServerCompositionVisual>, from: usize, _count: usize) -> usize {
        // A child whose bounds in the world do not meet the clip of the walk is counted and left
        // (`handle_pre_graph_transform_clip_opacity`): the clip of the child is within the clip
        // of the walk, or it is the empty rectangle at the origin of the world, which only bounds
        // around that origin meet. The table has the bounds of every child, and tells the
        // children that are left without a look at them. A render that stops at a visual, or
        // whose next visual is drawn without its transform, looks at every visual.
        if self.stop_at.is_some() || self.skip_next_visual_transform {
            return from;
        }
        let Some(children) = container.children() else { return from };
        let Some((clip, origin)) = self.clip_and_origin_in_walk_space() else { return from };
        let next = children.next_child_in(from, clip, origin);
        if next > from {
            self.visited_visuals += (next - from) as i32;
            if container.has_draw_items() {
                // The drawing items before a child that is left are drawn as before a child
                // that is visited.
                for index in from..next {
                    self.before_child(container, index);
                }
            }
        }
        next
    }

    fn before_child(&mut self, container: &Rc<ServerCompositionVisual>, index: usize) {
        if !container.has_draw_items() || self.stopped {
            return;
        }
        if let Some(items) = container.content.draw_items() {
            self.render_draw_items(container, items, items.range_before_child(index));
        }
    }

    fn pre_subgraph(&mut self, visual: &Rc<ServerCompositionVisual>) -> bool {
        // A backdrop render stops at the visual that paints the backdrop
        // (winui-materials.md).
        if let Some(stop_at) = self.stop_at {
            if self.stopped || std::ptr::eq(Rc::as_ptr(visual), stop_at) {
                self.stopped = true;
                self.full_skip = true;
                return false;
            }
        }
        self.visited_visuals += 1;
        let bitmap_cache_root = self.rendering_to_bitmap_cache && Rc::ptr_eq(visual, &self.root_visual);
        if !bitmap_cache_root {
            // Skip those for the root visual if we are rendering to bitmap cache
            // Push transform, clip, opacity and check if those make the visual effectively invisible
            if !self.handle_pre_graph_transform_clip_opacity(visual) {
                self.full_skip = true;
                return false;
            }

            // Push adorner clip
            if visual.adorned_visual().is_some() {
                self.adorner_helper_render_pre_graph_push_adorner_clip(visual);
            }

            // If caching is enabled, draw from cache and skip rendering
            if let Some(cache) = visual.cache() {
                crate::perf_count!(RenderCachedVisualsDrawn);
                let (visited, rendered) = cache.draw(self.canvas);
                self.visited_visuals += visited;
                self.rendered_visuals += rendered;
                self.used_cache = true;
                return false;
            }
        }

        if visual.render_options() != RenderOptions::default() {
            self.canvas.push_render_options(visual.render_options());
        }

        if visual.text_options() != TextOptions::default() {
            self.canvas.push_text_options(visual.text_options());
        }

        if let (Some(mask), Some(bounds)) = (visual.opacity_mask_brush(), visual.sub_tree_bounds.get()) {
            self.canvas.push_opacity_mask(&*mask, bounds.to_rect());
        }

        if let (Some(effect), Some(bounds)) = (visual.effect(), visual.sub_tree_bounds.get()) {
            // A custom effect that is an effect graph (#455) is drawn as its
            // graph around the content, as a layer visual draws its effect
            // brush around its children; any other effect is an effect of
            // the drawing context, a runtime shader effect (E4) among them,
            // which the backend draws with its program.
            let graph = effect.as_custom_effect().is_some_and(|custom| {
                push_custom_effect_graph_with(self.canvas, custom, bounds.to_rect(), visual.compositor())
            });
            if !graph {
                if let Some(effects) = self.canvas.as_drawing_context_impl_with_effects() {
                    effects.push_effect(Some(bounds.to_rect()), &*effect);
                }
            }
        }

        let clip = self.walk_context.clip;
        // The WinUI lights that reach the content (not from upstream): the
        // content is drawn into a layer and the light map over it.
        let lit = if self.lights_registered { LitContent::begin(visual, self.canvas) } else { None };
        // The brushes the content paints learn which visual paints them
        // (backdrops, scene lighting).
        let canvas = &mut *self.canvas;
        render_scope::with_painting_visual(visual, || {
            visual.render_core(&mut ServerVisualRenderContext::new(canvas), clip);
        });
        if let Some(lit) = lit {
            lit.end(self.canvas);
        }

        self.render_children
    }

    fn post_subgraph(&mut self, visual: &Rc<ServerCompositionVisual>) {
        if self.full_skip {
            self.full_skip = false;
            return;
        }

        let bitmap_cache_root = self.rendering_to_bitmap_cache && Rc::ptr_eq(visual, &self.root_visual);

        // If we've used cache, those never got pushed in PreSubgraph
        if !self.used_cache {
            // The drawing items after the last child (not from upstream; section 9.42): all
            // of them for a visual without children. A render without the children leaves
            // them out, as what is below the visual; one that stopped has drawn what it shows.
            if visual.has_draw_items() && self.render_children && !self.stopped {
                if let Some(items) = visual.content.draw_items() {
                    let children = visual.children().map_or(0, |children| children.count());
                    self.render_draw_items(visual, items, items.range_after_children(children));
                }
            }

            // What the content pushed for its children (not from upstream).
            let canvas = &mut *self.canvas;
            render_scope::with_painting_visual(visual, || {
                visual.content.render_after_children(visual, &mut ServerVisualRenderContext::new(canvas));
            });

            if let (Some(effect), Some(bounds)) = (visual.effect(), visual.sub_tree_bounds.get()) {
                let graph = effect.as_custom_effect().is_some_and(|custom| {
                    pop_custom_effect_graph_with(self.canvas, custom, bounds.to_rect(), visual.compositor())
                });
                if !graph {
                    if let Some(effects) = self.canvas.as_drawing_context_impl_with_effects() {
                        effects.pop_effect();
                    }
                }
            }

            if visual.opacity_mask_brush().is_some() && visual.sub_tree_bounds.get().is_some() {
                self.canvas.pop_opacity_mask();
            }

            if visual.text_options() != TextOptions::default() {
                self.canvas.pop_text_options();
            }

            if visual.render_options() != RenderOptions::default() {
                self.canvas.pop_render_options();
            }
        }

        // A cached visual is always a leaf in the walk (children are skipped), so its
        // PreSubgraph/PostSubgraph are adjacent. Reset here so the flag never leaks into a
        // later sibling and causes its effect/mask/options pushes to be left unpopped.
        self.used_cache = false;

        // If we are rendering to bitmap cache, PreSubgraph skipped those for the root visual
        if !bitmap_cache_root {
            if visual.adorned_visual().is_some() {
                self.adorner_helper_render_post_graph_push_adorner_clip(visual);
            }

            if let Some(shape) = visual.composition_clip_shape() {
                shape.pop(self.canvas);
            }

            if visual.clip().is_some() {
                self.canvas.pop_geometry_clip();
            }

            if visual.clip_to_bounds() {
                self.canvas.pop_clip();
            }

            if visual.own_clip_rect.get().is_some() {
                self.walk_context.pop_clip();
            }

            if visual.own_transform.get().is_some() {
                self.walk_context.pop_transform();
                crate::perf_count!(RenderVisualTransformsSet);
                self.canvas.set_transform(self.walk_context.transform);
            }

            if visual.opacity() != 1.0 {
                self.canvas.pop_opacity();
                self.opacity = self.opacity_stack.pop().expect("an opacity was pushed");
            }
        }
    }
}

impl ServerCompositionVisual {
    /// Renders the visual and, with `render_children`, its subtree onto
    /// `canvas`. Returns the numbers of visited and rendered visuals.
    pub fn render(
        self: &Rc<Self>,
        canvas: &mut dyn IDrawingContextImpl,
        clip: LtrbRect,
        dirty_rects: Option<Rc<dyn IDirtyRectTracker>>,
        render_children: bool,
        skip_root_visual_transform: bool,
        rendering_to_bitmap_cache: bool,
    ) -> (i32, i32) {
        self.render_with_stop(
            canvas,
            clip,
            dirty_rects,
            render_children,
            skip_root_visual_transform,
            rendering_to_bitmap_cache,
            None,
            Vector::ZERO,
        )
    }

    /// Renders the subtree of the visual onto `canvas` up to `stop_at`: the
    /// visuals before it in paint order, not it and not those after it
    /// (the backdrop of `stop_at`, winui-materials.md). The transform of the
    /// canvas is that of the render the backdrop belongs to.
    pub(crate) fn render_up_to(
        self: &Rc<Self>,
        canvas: &mut dyn IDrawingContextImpl,
        clip: LtrbRect,
        stop_at: &Rc<ServerCompositionVisual>,
        skip_root_visual_transform: bool,
        rendering_to_bitmap_cache: bool,
        device_origin: Vector,
    ) {
        self.render_with_stop(
            canvas,
            clip,
            None,
            true,
            skip_root_visual_transform,
            rendering_to_bitmap_cache,
            Some(Rc::as_ptr(stop_at)),
            device_origin,
        );
    }

    #[allow(clippy::too_many_arguments)]
    fn render_with_stop(
        self: &Rc<Self>,
        canvas: &mut dyn IDrawingContextImpl,
        clip: LtrbRect,
        dirty_rects: Option<Rc<dyn IDirtyRectTracker>>,
        render_children: bool,
        skip_root_visual_transform: bool,
        rendering_to_bitmap_cache: bool,
        stop_at: Option<*const ServerCompositionVisual>,
        device_origin: Vector,
    ) -> (i32, i32) {
        let Some(compositor) = self.compositor() else { return (0, 0) };
        let pools = compositor.pools();
        let transform = canvas.transform();
        let root = render_scope::RenderRoot {
            visual: self.clone(),
            transform,
            clip,
            device_origin,
            skip_root_visual_transform,
            rendering_to_bitmap_cache,
        };
        render_scope::with_render_root(root, || {
            let mut render_context = RenderContext::new(
                self.clone(),
                canvas,
                dirty_rects,
                pools,
                transform,
                clip,
                render_children,
                skip_root_visual_transform,
                rendering_to_bitmap_cache,
            );
            render_context.stop_at = stop_at;
            walk(&mut render_context, self, pools);
            let result = (render_context.visited_visuals, render_context.rendered_visuals);
            {
                use crate::diagnostics::perf_counters::{add, PerfCounter};
                add(PerfCounter::RenderVisualsVisited, result.0.max(0) as u64);
                add(PerfCounter::RenderVisualsRendered, result.1.max(0) as u64);
            }
            render_context.dispose();
            result
        })
    }
}