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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
use std::ops::{
    Deref,
    DerefMut,
};

use freya_common::{
    CompositorDirtyNodes,
    Layers,
};
use freya_native_core::{
    prelude::NodeImmutable,
    NodeId,
};
use itertools::sorted;
use rustc_hash::FxHashMap;
use torin::prelude::{
    Area,
    LayoutNode,
    Torin,
};

use crate::{
    dom::DioxusNode,
    prelude::{
        DioxusDOM,
        ElementUtils,
        ElementUtilsResolver,
        ElementWithUtils,
    },
};

/// Text-like elements with shadows are the only type of elements
/// whose drawing area
///     1. Can affect other nodes
///     2. Are not part of their layout
///
/// Therefore a special cache is needed to be able to mark as dirty the previous area
/// where the shadow of the text was.
#[derive(Clone, Default, Debug)]
pub struct CompositorCache(FxHashMap<NodeId, Area>);

impl Deref for CompositorCache {
    type Target = FxHashMap<NodeId, Area>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for CompositorCache {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

#[derive(Clone, Default, Debug)]
pub struct CompositorDirtyArea(Option<Area>);

impl CompositorDirtyArea {
    /// Take the area, leaving nothing behind.
    pub fn take(&mut self) -> Option<Area> {
        self.0.take()
    }

    /// Unite the area or insert it if none is yet present.
    pub fn unite_or_insert(&mut self, other: &Area) {
        if let Some(dirty_area) = &mut self.0 {
            *dirty_area = dirty_area.union(other);
        } else {
            self.0 = Some(*other);
        }
    }

    /// Round the dirty area to the out bounds to prevent float pixel issues.
    pub fn round_out(&mut self) {
        if let Some(dirty_area) = &mut self.0 {
            *dirty_area = dirty_area.round_out();
        }
    }

    /// Checks if the area (in case of being any) interesects with another area.
    pub fn intersects(&self, other: &Area) -> bool {
        self.0
            .map(|dirty_area| dirty_area.intersects(other))
            .unwrap_or_default()
    }
}

impl Deref for CompositorDirtyArea {
    type Target = Option<Area>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

#[derive(Debug)]
pub struct Compositor {
    full_render: bool,
}

impl Default for Compositor {
    fn default() -> Self {
        Self { full_render: true }
    }
}

impl Compositor {
    #[inline]
    pub fn get_drawing_area(
        node_id: NodeId,
        layout: &Torin<NodeId>,
        rdom: &DioxusDOM,
        scale_factor: f32,
    ) -> Option<Area> {
        let layout_node = layout.get(node_id)?;
        let node = rdom.get(node_id)?;
        let utils = node.node_type().tag()?.utils()?;

        utils.drawing_area_with_viewports(layout_node, &node, layout, scale_factor)
    }

    #[inline]
    pub fn with_utils<T>(
        node_id: NodeId,
        layout: &Torin<NodeId>,
        rdom: &DioxusDOM,
        run: impl FnOnce(DioxusNode, ElementWithUtils, &LayoutNode) -> T,
    ) -> Option<T> {
        let layout_node = layout.get(node_id)?;
        let node = rdom.get(node_id)?;
        let utils = node.node_type().tag()?.utils()?;

        Some(run(node, utils, layout_node))
    }

    /// The compositor runs from the bottom layers to the top and viceversa to check what Nodes might be affected by the
    /// dirty area. How a Node is checked is by calculating its drawing area which consists of its layout area plus any possible
    /// outer effect such as shadows and borders.
    /// Calculating the drawing area might get expensive so we cache them in the `cached_areas` map to make the second layers run faster
    /// (top to bottom).
    /// In addition to that, nodes that have already been united to the dirty area are removed from the `running_layers` to avoid being checked again
    /// at the second layers (top to bottom).
    #[allow(clippy::too_many_arguments)]
    pub fn run<'a>(
        &mut self,
        dirty_nodes: &mut CompositorDirtyNodes,
        dirty_area: &mut CompositorDirtyArea,
        cache: &mut CompositorCache,
        layers: &'a Layers,
        dirty_layers: &'a mut Layers,
        layout: &Torin<NodeId>,
        rdom: &DioxusDOM,
        scale_factor: f32,
    ) -> &'a Layers {
        if self.full_render {
            for nodes in layers.values() {
                for node_id in nodes {
                    Self::with_utils(*node_id, layout, rdom, |node_ref, utils, layout_node| {
                        if utils.needs_cached_area(&node_ref) {
                            let area = utils.drawing_area(layout_node, &node_ref, scale_factor);
                            // Cache the drawing area so it can be invalidated in the next frame
                            cache.insert(*node_id, area);
                        }
                    });
                }
            }
            self.full_render = false;
            return layers;
        }
        let mut running_layers = layers.clone();

        loop {
            let mut any_marked = false;

            for (layer_n, layer) in sorted(running_layers.iter_mut()).rev() {
                layer.retain(|node_id| {
                    Self::with_utils(*node_id, layout, rdom, |node_ref, utils, layout_node| {
                        // Use the cached area to invalidate the previous frame area if necessary
                        let cached_area = cache.get(node_id);
                        let needs_cached_area = utils.needs_cached_area(&node_ref);

                        let Some(area) = utils.drawing_area_with_viewports(
                            layout_node,
                            &node_ref,
                            layout,
                            scale_factor,
                        ) else {
                            return false;
                        };

                        let is_dirty = dirty_nodes.remove(node_id);
                        let cached_area_is_invalidated = cached_area
                            .map(|cached_area| {
                                if is_dirty {
                                    true
                                } else {
                                    dirty_area.intersects(cached_area)
                                }
                            })
                            .unwrap_or_default();

                        let is_invalidated =
                            is_dirty || cached_area_is_invalidated || dirty_area.intersects(&area);

                        if is_invalidated {
                            // Save this node to the layer it corresponds for rendering
                            dirty_layers.insert_node_in_layer(*node_id, *layer_n);

                            // Expand the dirty area with the cached area so it gets cleaned up
                            if is_dirty && cached_area_is_invalidated {
                                dirty_area.unite_or_insert(cached_area.unwrap());
                                any_marked = true;
                            }

                            // Cache the drawing area so it can be invalidated in the next frame
                            if needs_cached_area {
                                cache.insert(*node_id, area);
                            }

                            // Expand the dirty area with only nodes who have actually changed
                            if is_dirty {
                                dirty_area.unite_or_insert(&area);
                                any_marked = true;
                            }
                        }

                        !is_invalidated
                    })
                    .unwrap_or_default()
                })
            }

            if !any_marked {
                break;
            }
        }

        dirty_nodes.drain();

        dirty_layers
    }

    /// Reset the compositor, thus causing a full render in the next frame.
    pub fn reset(&mut self) {
        self.full_render = true;
    }
}

#[cfg(test)]
mod test {
    use freya::{
        common::*,
        prelude::*,
    };
    use freya_testing::prelude::*;
    use itertools::sorted;

    fn run_compositor(
        utils: &TestingHandler<()>,
        compositor: &mut Compositor,
    ) -> (Layers, Layers, usize) {
        let sdom = utils.sdom();
        let fdom = sdom.get();
        let layout = fdom.layout();
        let layers = fdom.layers();
        let rdom = fdom.rdom();
        let mut compositor_dirty_area = fdom.compositor_dirty_area();
        let mut compositor_dirty_nodes = fdom.compositor_dirty_nodes();
        let mut compositor_cache = fdom.compositor_cache();

        let mut dirty_layers = Layers::default();

        // Process what nodes need to be rendered
        let rendering_layers = compositor.run(
            &mut *compositor_dirty_nodes,
            &mut *compositor_dirty_area,
            &mut compositor_cache,
            &*layers,
            &mut dirty_layers,
            &layout,
            rdom,
            1.0f32,
        );

        compositor_dirty_area.take();
        compositor_dirty_nodes.clear();

        let mut painted_nodes = 0;
        for (_, nodes) in sorted(rendering_layers.iter()) {
            for node_id in nodes {
                if layout.get(*node_id).is_some() {
                    painted_nodes += 1;
                }
            }
        }

        (layers.clone(), rendering_layers.clone(), painted_nodes)
    }

    #[tokio::test]
    pub async fn button_drawing() {
        fn compositor_app() -> Element {
            let mut count = use_signal(|| 0);

            rsx!(
                rect {
                    height: "50%",
                    width: "100%",
                    main_align: "center",
                    cross_align: "center",
                    background: "rgb(0, 119, 182)",
                    color: "white",
                    shadow: "0 4 20 5 rgb(0, 0, 0, 80)",
                    label {
                        font_size: "75",
                        font_weight: "bold",
                        "{count}"
                    }
                }
                rect {
                    height: "50%",
                    width: "100%",
                    main_align: "center",
                    cross_align: "center",
                    direction: "horizontal",
                    Button {
                        onclick: move |_| count += 1,
                        label { "Increase" }
                    }
                }
            )
        }

        let mut compositor = Compositor::default();
        let mut utils = launch_test(compositor_app);
        let root = utils.root();
        let label = root.get(0).get(0);
        utils.wait_for_update().await;

        assert_eq!(label.get(0).text(), Some("0"));

        let (layers, rendering_layers, _) = run_compositor(&utils, &mut compositor);
        // First render is always a full render
        assert_eq!(layers, rendering_layers);

        utils.move_cursor((275., 375.)).await;

        let (_, _, painted_nodes) = run_compositor(&utils, &mut compositor);

        // Root + Second rect + Button's internal rect + Button's label
        assert_eq!(painted_nodes, 4);

        utils.click_cursor((275., 375.)).await;

        assert_eq!(label.get(0).text(), Some("1"));
    }

    #[tokio::test]
    pub async fn after_shadow_drawing() {
        fn compositor_app() -> Element {
            let mut height = use_signal(|| 200);
            let mut shadow = use_signal(|| 20);

            rsx!(
                rect {
                    height: "100",
                    width: "200",
                    background: "red",
                    onclick: move |_| height += 10,
                }
                rect {
                    height: "{height}",
                    width: "200",
                    background: "green",
                    shadow: "0 {shadow} 8 0 rgb(0, 0, 0, 0.5)",
                    onclick: move |_| height -= 10,
                }
                rect {
                    height: "100",
                    width: "200",
                    background: "blue",
                    onclick: move |_| shadow.set(-20),
                }
            )
        }

        let mut compositor = Compositor::default();
        let mut utils = launch_test(compositor_app);
        utils.wait_for_update().await;

        let (layers, rendering_layers, _) = run_compositor(&utils, &mut compositor);
        // First render is always a full render
        assert_eq!(layers, rendering_layers);

        utils.click_cursor((5., 5.)).await;

        let (_, _, painted_nodes) = run_compositor(&utils, &mut compositor);

        // Root + Second rect + Third rect
        assert_eq!(painted_nodes, 3);

        utils.click_cursor((5., 150.)).await;

        let (_, _, painted_nodes) = run_compositor(&utils, &mut compositor);

        // Root + Second rect + Third rect
        assert_eq!(painted_nodes, 3);

        utils.click_cursor((5., 350.)).await;

        let (_, _, painted_nodes) = run_compositor(&utils, &mut compositor);

        // Root + First rect + Second rect + Third Rect
        assert_eq!(painted_nodes, 4);

        utils.click_cursor((5., 150.)).await;

        let (_, _, painted_nodes) = run_compositor(&utils, &mut compositor);

        // Root + First + Second rect + Third rect
        assert_eq!(painted_nodes, 4);
    }

    #[tokio::test]
    pub async fn paragraph_drawing() {
        fn compositor_app() -> Element {
            let mut msg_state = use_signal(|| true);
            let mut shadow_state = use_signal(|| true);

            let msg = if msg_state() { "12" } else { "23" };
            let shadow = if shadow_state() {
                "-40 0 20 black"
            } else {
                "none"
            };

            rsx!(
                rect {
                    height: "200",
                    width: "200",
                    direction: "horizontal",
                    rect {
                        onclick: move |_| msg_state.toggle(),
                        height: "200",
                        width: "200",
                        background: "red"
                    }
                    paragraph {
                        onclick: move |_| shadow_state.toggle(),
                        text {
                            font_size: "75",
                            font_weight: "bold",
                            text_shadow: "{shadow}",
                            "{msg}"
                        }
                    }
                }
            )
        }

        let mut compositor = Compositor::default();
        let mut utils = launch_test(compositor_app);
        let root = utils.root();
        utils.wait_for_update().await;

        assert_eq!(root.get(0).get(1).get(0).get(0).text(), Some("12"));

        let (layers, rendering_layers, _) = run_compositor(&utils, &mut compositor);
        // First render is always a full render
        assert_eq!(layers, rendering_layers);

        utils.click_cursor((5., 5.)).await;

        let (_, _, painted_nodes) = run_compositor(&utils, &mut compositor);

        // Root + First rect + Paragraph + Second rect
        assert_eq!(painted_nodes, 4);

        utils.click_cursor((205., 5.)).await;

        let (_, _, painted_nodes) = run_compositor(&utils, &mut compositor);

        // Root + First rect + Paragraph + Second rect
        assert_eq!(painted_nodes, 4);

        utils.click_cursor((5., 5.)).await;

        let (_, _, painted_nodes) = run_compositor(&utils, &mut compositor);

        // Root + First rect + Paragraph
        assert_eq!(painted_nodes, 2);
    }

    #[tokio::test]
    pub async fn rotated_drawing() {
        fn compositor_app() -> Element {
            let mut rotate = use_signal(|| 0);

            rsx!(
                rect {
                    height: "50%",
                    width: "100%",
                    main_align: "center",
                    cross_align: "center",
                    background: "rgb(0, 119, 182)",
                    color: "white",
                    shadow: "0 4 20 5 rgb(0, 0, 0, 80)",
                    label {
                        rotate: "{rotate}deg",
                        "Hello"
                    }
                    label {
                        "World"
                    }
                }
                rect {
                    height: "50%",
                    width: "100%",
                    main_align: "center",
                    cross_align: "center",
                    direction: "horizontal",
                    Button {
                        onclick: move |_| rotate += 1,
                        label { "Rotate" }
                    }
                }
            )
        }

        let mut compositor = Compositor::default();
        let mut utils = launch_test(compositor_app);
        utils.wait_for_update().await;

        let (layers, rendering_layers, _) = run_compositor(&utils, &mut compositor);
        // First render is always a full render
        assert_eq!(layers, rendering_layers);

        utils.click_cursor((275., 375.)).await;

        let (_, _, painted_nodes) = run_compositor(&utils, &mut compositor);

        // Root + First rect + First Label + Second Label
        assert_eq!(painted_nodes, 4);
    }

    #[tokio::test]
    pub async fn rotated_shadow_drawing() {
        fn compositor_app() -> Element {
            let mut rotate = use_signal(|| 0);

            rsx!(
                rect {
                    height: "50%",
                    width: "100%",
                    main_align: "center",
                    cross_align: "center",
                    background: "rgb(0, 119, 182)",
                    color: "white",
                    shadow: "0 4 20 5 rgb(0, 0, 0, 80)",
                    label {
                        rotate: "{rotate}deg",
                        text_shadow: "0 180 12 rgb(0, 0, 0, 240)",
                        "Hello"
                    }
                    label {
                        "World"
                    }
                }
                rect {
                    height: "50%",
                    width: "100%",
                    main_align: "center",
                    cross_align: "center",
                    direction: "horizontal",
                    Button {
                        onclick: move |_| rotate += 1,
                        label { "Rotate" }
                    }
                }
            )
        }

        let mut compositor = Compositor::default();
        let mut utils = launch_test(compositor_app);
        utils.wait_for_update().await;

        let (layers, rendering_layers, _) = run_compositor(&utils, &mut compositor);
        // First render is always a full render
        assert_eq!(layers, rendering_layers);

        utils.click_cursor((275., 375.)).await;

        let (_, _, painted_nodes) = run_compositor(&utils, &mut compositor);

        // Everything
        assert_eq!(painted_nodes, 7);
    }
}