1
#[allow(unused_imports)]
2
pub use super::*;
3
#[cfg(test)]
4
#[allow(clippy::float_cmp)] // GPU cache values must round-trip bit-exactly, not "approximately"
5
mod autotest_generated {
6
    use azul_css::css::Css;
7

            
8
    use super::*;
9
    use crate::dom::Dom;
10

            
11
    /// A `StyledDom` with exactly one node (the body) and no CSS at all:
12
    /// compact cache present, `has_transform` unset, opacity == `OPACITY_SENTINEL`.
13
    fn plain_styled_dom() -> StyledDom {
14
        let mut dom = Dom::create_body();
15
        StyledDom::create(&mut dom, Css::empty())
16
    }
17

            
18
    /// body > div.<class>, styled by `css_src`.
19
    fn styled_dom_from_css(css_src: &str, class: &str) -> StyledDom {
20
        let css = azul_css::parser2::new_from_str(css_src).0;
21
        let mut dom = Dom::create_body()
22
            .with_children(vec![Dom::create_div().with_class(class.to_string().into())].into());
23
        StyledDom::create(&mut dom, css)
24
    }
25

            
26
    /// A matrix stuffed with every hostile f32 the transform math can produce.
27
    fn hostile_matrix() -> ComputedTransform3D {
28
        ComputedTransform3D::new(
29
            f32::NAN,
30
            f32::INFINITY,
31
            f32::NEG_INFINITY,
32
            f32::MIN,
33
            f32::MAX,
34
            0.0,
35
            -0.0,
36
            f32::EPSILON,
37
            1.0,
38
            2.0,
39
            3.0,
40
            4.0,
41
            5.0,
42
            6.0,
43
            7.0,
44
            8.0,
45
        )
46
    }
47

            
48
    fn scale_matrix(s: f32) -> ComputedTransform3D {
49
        ComputedTransform3D::new(
50
            s, 0.0, 0.0, 0.0, 0.0, s, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
51
        )
52
    }
53

            
54
    // ---------------------------------------------------------------------
55
    // constructors / neutral elements
56
    // ---------------------------------------------------------------------
57

            
58
    #[test]
59
    fn gpu_value_cache_empty_holds_no_keys_and_no_values() {
60
        let cache = GpuValueCache::empty();
61
        assert!(cache.transform_keys.is_empty());
62
        assert!(cache.current_transform_values.is_empty());
63
        assert!(cache.h_transform_keys.is_empty());
64
        assert!(cache.h_current_transform_values.is_empty());
65
        assert!(cache.css_transform_keys.is_empty());
66
        assert!(cache.css_current_transform_values.is_empty());
67
        assert!(cache.opacity_keys.is_empty());
68
        assert!(cache.current_opacity_values.is_empty());
69
        assert!(cache.scrollbar_v_opacity_keys.is_empty());
70
        assert!(cache.scrollbar_h_opacity_keys.is_empty());
71
        assert!(cache.scrollbar_v_opacity_values.is_empty());
72
        assert!(cache.scrollbar_h_opacity_values.is_empty());
73
    }
74

            
75
    #[test]
76
    fn gpu_event_changes_empty_equals_default_and_is_empty() {
77
        let changes = GpuEventChanges::empty();
78
        assert_eq!(changes, GpuEventChanges::default());
79
        assert!(changes.is_empty());
80
        assert_eq!(changes.transform_key_changes.len(), 0);
81
        assert_eq!(changes.opacity_key_changes.len(), 0);
82
        assert_eq!(changes.scrollbar_opacity_changes.len(), 0);
83
    }
84

            
85
    // ---------------------------------------------------------------------
86
    // GpuEventChanges::is_empty (predicate)
87
    // ---------------------------------------------------------------------
88

            
89
    #[test]
90
    fn is_empty_is_false_when_any_single_event_vec_is_populated() {
91
        let node = NodeId::ZERO;
92

            
93
        let mut only_transform = GpuEventChanges::empty();
94
        only_transform
95
            .transform_key_changes
96
            .push(GpuTransformKeyEvent::Removed(node, TransformKey::unique()));
97
        assert!(!only_transform.is_empty());
98

            
99
        let mut only_opacity = GpuEventChanges::empty();
100
        only_opacity
101
            .opacity_key_changes
102
            .push(GpuOpacityKeyEvent::Removed(node, OpacityKey::unique()));
103
        assert!(!only_opacity.is_empty());
104

            
105
        // scrollbar changes alone must also flip the predicate — is_empty() has to
106
        // check all three vecs, not just the two the CSS passes fill.
107
        let mut only_scrollbar = GpuEventChanges::empty();
108
        only_scrollbar
109
            .scrollbar_opacity_changes
110
            .push(GpuScrollbarOpacityEvent::VerticalRemoved(
111
                DomId::ROOT_ID,
112
                node,
113
                OpacityKey::unique(),
114
            ));
115
        assert!(!only_scrollbar.is_empty());
116
    }
117

            
118
    // ---------------------------------------------------------------------
119
    // GpuEventChanges::merge
120
    // ---------------------------------------------------------------------
121

            
122
    #[test]
123
    fn merge_moves_every_event_and_drains_the_source() {
124
        let node = NodeId::new(7);
125

            
126
        let mut target = GpuEventChanges::empty();
127
        target
128
            .transform_key_changes
129
            .push(GpuTransformKeyEvent::Added(
130
                node,
131
                TransformKey::unique(),
132
                ComputedTransform3D::IDENTITY,
133
            ));
134

            
135
        let mut source = GpuEventChanges::empty();
136
        source
137
            .transform_key_changes
138
            .push(GpuTransformKeyEvent::Removed(node, TransformKey::unique()));
139
        source.opacity_key_changes.push(GpuOpacityKeyEvent::Added(
140
            node,
141
            OpacityKey::unique(),
142
            0.25,
143
        ));
144
        source
145
            .scrollbar_opacity_changes
146
            .push(GpuScrollbarOpacityEvent::HorizontalAdded(
147
                DomId::ROOT_ID,
148
                node,
149
                OpacityKey::unique(),
150
                1.0,
151
            ));
152

            
153
        target.merge(&mut source);
154

            
155
        assert!(source.is_empty(), "merge must consume the source");
156
        assert_eq!(target.transform_key_changes.len(), 2);
157
        assert_eq!(target.opacity_key_changes.len(), 1);
158
        assert_eq!(target.scrollbar_opacity_changes.len(), 1);
159
        // append semantics: self's events keep their position, other's are pushed after.
160
        assert!(matches!(
161
            target.transform_key_changes[0],
162
            GpuTransformKeyEvent::Added(..)
163
        ));
164
        assert!(matches!(
165
            target.transform_key_changes[1],
166
            GpuTransformKeyEvent::Removed(..)
167
        ));
168
    }
169

            
170
    #[test]
171
    fn merge_with_an_empty_set_is_the_identity_in_both_directions() {
172
        let node = NodeId::new(1);
173
        let mut populated = GpuEventChanges::empty();
174
        populated
175
            .opacity_key_changes
176
            .push(GpuOpacityKeyEvent::Added(node, OpacityKey::unique(), 0.5));
177
        let snapshot = populated.clone();
178

            
179
        // x.merge(empty) == x
180
        let mut empty = GpuEventChanges::empty();
181
        populated.merge(&mut empty);
182
        assert_eq!(populated, snapshot);
183
        assert!(empty.is_empty());
184

            
185
        // empty.merge(x) == x
186
        let mut target = GpuEventChanges::empty();
187
        let mut source = snapshot.clone();
188
        target.merge(&mut source);
189
        assert_eq!(target, snapshot);
190
        assert!(source.is_empty());
191
    }
192

            
193
    #[test]
194
    fn merging_large_event_vectors_does_not_panic_and_is_idempotent_when_drained() {
195
        let mut target = GpuEventChanges::empty();
196
        let mut source = GpuEventChanges::empty();
197
        for i in 0..10_000usize {
198
            target.opacity_key_changes.push(GpuOpacityKeyEvent::Removed(
199
                NodeId::new(i),
200
                OpacityKey::unique(),
201
            ));
202
            source.opacity_key_changes.push(GpuOpacityKeyEvent::Removed(
203
                NodeId::new(i),
204
                OpacityKey::unique(),
205
            ));
206
        }
207

            
208
        target.merge(&mut source);
209
        assert_eq!(target.opacity_key_changes.len(), 20_000);
210
        assert!(source.is_empty());
211

            
212
        // merging an already-drained source a second time must be a no-op, not a duplicate
213
        target.merge(&mut source);
214
        assert_eq!(target.opacity_key_changes.len(), 20_000);
215
    }
216

            
217
    // ---------------------------------------------------------------------
218
    // apply_transform_events (private)
219
    // ---------------------------------------------------------------------
220

            
221
    #[test]
222
    fn apply_transform_events_on_an_empty_slice_is_a_noop() {
223
        let mut cache = GpuValueCache::empty();
224
        cache.apply_transform_events(&[]);
225
        assert!(cache.css_transform_keys.is_empty());
226
        assert!(cache.css_current_transform_values.is_empty());
227
    }
228

            
229
    #[test]
230
    fn apply_transform_events_keeps_keys_and_values_in_lockstep() {
231
        let node = NodeId::new(3);
232
        let key = TransformKey::unique();
233
        let mut cache = GpuValueCache::empty();
234

            
235
        cache.apply_transform_events(&[GpuTransformKeyEvent::Added(
236
            node,
237
            key,
238
            ComputedTransform3D::IDENTITY,
239
        )]);
240
        assert_eq!(cache.css_transform_keys.get(&node), Some(&key));
241
        assert_eq!(
242
            cache.css_current_transform_values.get(&node),
243
            Some(&ComputedTransform3D::IDENTITY)
244
        );
245

            
246
        // Changed must swap the value and *keep* the existing key (a new key here
247
        // would orphan the old one on the GPU).
248
        let scaled = scale_matrix(2.0);
249
        cache.apply_transform_events(&[GpuTransformKeyEvent::Changed(
250
            node,
251
            key,
252
            ComputedTransform3D::IDENTITY,
253
            scaled,
254
        )]);
255
        assert_eq!(cache.css_transform_keys.get(&node), Some(&key));
256
        assert_eq!(cache.css_current_transform_values.get(&node), Some(&scaled));
257

            
258
        cache.apply_transform_events(&[GpuTransformKeyEvent::Removed(node, key)]);
259
        assert!(cache.css_transform_keys.is_empty());
260
        assert!(cache.css_current_transform_values.is_empty());
261
    }
262

            
263
    #[test]
264
    fn removing_an_uncached_or_out_of_range_node_does_not_panic() {
265
        let mut cache = GpuValueCache::empty();
266
        // NodeId::new(usize::MAX) is never a valid DOM index — apply_* only hashes it,
267
        // so it must be tolerated rather than used as an array index.
268
        cache.apply_transform_events(&[
269
            GpuTransformKeyEvent::Removed(NodeId::new(usize::MAX), TransformKey::unique()),
270
            GpuTransformKeyEvent::Removed(NodeId::ZERO, TransformKey::unique()),
271
        ]);
272
        cache.apply_opacity_events(&[GpuOpacityKeyEvent::Removed(
273
            NodeId::new(usize::MAX),
274
            OpacityKey::unique(),
275
        )]);
276
        assert!(cache.css_transform_keys.is_empty());
277
        assert!(cache.css_current_transform_values.is_empty());
278
        assert!(cache.opacity_keys.is_empty());
279
        assert!(cache.current_opacity_values.is_empty());
280
    }
281

            
282
    #[test]
283
    fn transform_events_are_applied_in_slice_order_within_one_batch() {
284
        let node = NodeId::new(2);
285
        let first = TransformKey::unique();
286
        let second = TransformKey::unique();
287

            
288
        // Added -> Removed inside one batch must end up removed.
289
        let mut cache = GpuValueCache::empty();
290
        cache.apply_transform_events(&[
291
            GpuTransformKeyEvent::Added(node, first, ComputedTransform3D::IDENTITY),
292
            GpuTransformKeyEvent::Removed(node, first),
293
        ]);
294
        assert!(cache.css_transform_keys.is_empty());
295
        assert!(cache.css_current_transform_values.is_empty());
296

            
297
        // Removed -> Added inside one batch must end up added.
298
        let mut cache = GpuValueCache::empty();
299
        cache.apply_transform_events(&[
300
            GpuTransformKeyEvent::Removed(node, first),
301
            GpuTransformKeyEvent::Added(node, second, ComputedTransform3D::IDENTITY),
302
        ]);
303
        assert_eq!(cache.css_transform_keys.get(&node), Some(&second));
304
    }
305

            
306
    #[test]
307
    fn two_added_events_for_one_node_keep_only_the_last_key() {
308
        let node = NodeId::ZERO;
309
        let first = TransformKey::unique();
310
        let second = TransformKey::unique();
311
        assert_ne!(
312
            first, second,
313
            "TransformKey::unique() must never hand out the same id twice"
314
        );
315

            
316
        let mut cache = GpuValueCache::empty();
317
        cache.apply_transform_events(&[
318
            GpuTransformKeyEvent::Added(node, first, ComputedTransform3D::IDENTITY),
319
            GpuTransformKeyEvent::Added(node, second, scale_matrix(3.0)),
320
        ]);
321
        assert_eq!(cache.css_transform_keys.len(), 1);
322
        assert_eq!(cache.css_transform_keys.get(&node), Some(&second));
323
        assert_eq!(
324
            cache.css_current_transform_values.get(&node),
325
            Some(&scale_matrix(3.0))
326
        );
327
    }
328

            
329
    #[test]
330
    fn a_changed_event_for_an_uncached_node_inserts_a_value_but_no_key() {
331
        // compute_transform_events can never emit this (it `?`s on an existing key),
332
        // but apply_transform_events takes an arbitrary slice and must not panic.
333
        let node = NodeId::new(5);
334
        let mut cache = GpuValueCache::empty();
335
        cache.apply_transform_events(&[GpuTransformKeyEvent::Changed(
336
            node,
337
            TransformKey::unique(),
338
            ComputedTransform3D::IDENTITY,
339
            scale_matrix(2.0),
340
        )]);
341
        assert_eq!(
342
            cache.css_current_transform_values.get(&node),
343
            Some(&scale_matrix(2.0))
344
        );
345
        assert!(
346
            cache.css_transform_keys.is_empty(),
347
            "Changed only writes the value map; the key map stays untouched"
348
        );
349
    }
350

            
351
    #[test]
352
    fn non_finite_matrices_are_stored_verbatim_and_never_compare_equal() {
353
        let node = NodeId::new(1);
354
        let mut cache = GpuValueCache::empty();
355
        cache.apply_transform_events(&[GpuTransformKeyEvent::Added(
356
            node,
357
            TransformKey::unique(),
358
            hostile_matrix(),
359
        )]);
360

            
361
        let stored = cache
362
            .css_current_transform_values
363
            .get(&node)
364
            .copied()
365
            .expect("the matrix must be cached even when it is full of NaN/Inf");
366
        assert!(stored.m[0][0].is_nan());
367
        assert!(stored.m[0][1].is_infinite() && stored.m[0][1].is_sign_positive());
368
        assert!(stored.m[0][2].is_infinite() && stored.m[0][2].is_sign_negative());
369
        assert_eq!(stored.m[0][3], f32::MIN);
370
        assert_eq!(stored.m[1][0], f32::MAX);
371

            
372
        // Consequence worth pinning: a NaN matrix is not PartialEq-equal to itself, so
373
        // no caller may use `old == new` to suppress a redundant GPU update.
374
        let a = hostile_matrix();
375
        let b = hostile_matrix();
376
        assert_ne!(a, b);
377
    }
378

            
379
    // ---------------------------------------------------------------------
380
    // apply_opacity_events (private)
381
    // ---------------------------------------------------------------------
382

            
383
    #[test]
384
    fn apply_opacity_events_add_change_remove_round_trip() {
385
        let node = NodeId::new(4);
386
        let key = OpacityKey::unique();
387
        let mut cache = GpuValueCache::empty();
388

            
389
        cache.apply_opacity_events(&[GpuOpacityKeyEvent::Added(node, key, 0.25)]);
390
        assert_eq!(cache.opacity_keys.get(&node), Some(&key));
391
        assert_eq!(cache.current_opacity_values.get(&node), Some(&0.25));
392

            
393
        cache.apply_opacity_events(&[GpuOpacityKeyEvent::Changed(node, key, 0.25, 0.75)]);
394
        assert_eq!(cache.opacity_keys.get(&node), Some(&key));
395
        assert_eq!(cache.current_opacity_values.get(&node), Some(&0.75));
396

            
397
        cache.apply_opacity_events(&[GpuOpacityKeyEvent::Removed(node, key)]);
398
        assert!(cache.opacity_keys.is_empty());
399
        assert!(cache.current_opacity_values.is_empty());
400

            
401
        // a second Removed for the same node is a no-op, not a panic
402
        cache.apply_opacity_events(&[GpuOpacityKeyEvent::Removed(node, key)]);
403
        assert!(cache.opacity_keys.is_empty());
404
    }
405

            
406
    #[test]
407
    fn apply_opacity_events_stores_out_of_range_values_verbatim() {
408
        // The cache does no clamping of its own — pin that, so a future "helpful"
409
        // clamp shows up as a test change rather than a silent behaviour change.
410
        let cases = [
411
            f32::NAN,
412
            f32::INFINITY,
413
            f32::NEG_INFINITY,
414
            -1.0,
415
            2.0,
416
            1e30,
417
            -0.0,
418
        ];
419
        let mut cache = GpuValueCache::empty();
420
        for (i, value) in cases.iter().enumerate() {
421
            cache.apply_opacity_events(&[GpuOpacityKeyEvent::Added(
422
                NodeId::new(i),
423
                OpacityKey::unique(),
424
                *value,
425
            )]);
426
        }
427

            
428
        assert_eq!(cache.current_opacity_values.len(), cases.len());
429
        assert_eq!(cache.opacity_keys.len(), cache.current_opacity_values.len());
430
        assert!(cache.current_opacity_values[&NodeId::new(0)].is_nan());
431
        assert!(cache.current_opacity_values[&NodeId::new(1)].is_infinite());
432
        assert_eq!(cache.current_opacity_values[&NodeId::new(3)], -1.0);
433
        assert_eq!(cache.current_opacity_values[&NodeId::new(4)], 2.0);
434
        assert_eq!(cache.current_opacity_values[&NodeId::new(5)], 1e30);
435
    }
436

            
437
    // ---------------------------------------------------------------------
438
    // init_simd_features (private)
439
    // ---------------------------------------------------------------------
440

            
441
    #[test]
442
    fn init_simd_features_is_idempotent() {
443
        GpuValueCache::init_simd_features();
444
        GpuValueCache::init_simd_features();
445

            
446
        #[cfg(target_arch = "x86_64")]
447
        {
448
            assert!(
449
                INITIALIZED.load(AtomicOrdering::SeqCst),
450
                "the one-time init flag must be set after the first call"
451
            );
452
            let sse = USE_SSE.load(AtomicOrdering::SeqCst);
453
            let avx = USE_AVX.load(AtomicOrdering::SeqCst);
454
            GpuValueCache::init_simd_features();
455
            assert_eq!(sse, USE_SSE.load(AtomicOrdering::SeqCst));
456
            assert_eq!(avx, USE_AVX.load(AtomicOrdering::SeqCst));
457
        }
458
    }
459

            
460
    // ---------------------------------------------------------------------
461
    // synchronize / compute_* (against a real StyledDom)
462
    // ---------------------------------------------------------------------
463

            
464
    #[test]
465
    fn synchronize_on_a_transform_and_opacity_free_dom_emits_nothing() {
466
        let styled = plain_styled_dom();
467
        let mut cache = GpuValueCache::empty();
468

            
469
        let changes = cache.synchronize(&styled);
470

            
471
        assert!(changes.is_empty());
472
        assert!(cache.css_transform_keys.is_empty());
473
        assert!(cache.opacity_keys.is_empty());
474
    }
475

            
476
    #[test]
477
    fn synchronize_never_fills_scrollbar_opacity_changes() {
478
        // Documented contract: scrollbar opacity is filled by a *separate* pass, so
479
        // synchronize() must leave that vec empty (and not touch the scrollbar maps).
480
        let styled = plain_styled_dom();
481
        let mut cache = GpuValueCache::empty();
482
        cache
483
            .scrollbar_v_opacity_keys
484
            .insert((DomId::ROOT_ID, NodeId::ZERO), OpacityKey::unique());
485
        cache
486
            .scrollbar_v_opacity_values
487
            .insert((DomId::ROOT_ID, NodeId::ZERO), 0.5);
488

            
489
        let changes = cache.synchronize(&styled);
490

            
491
        assert!(changes.scrollbar_opacity_changes.is_empty());
492
        assert_eq!(cache.scrollbar_v_opacity_keys.len(), 1);
493
        assert_eq!(cache.scrollbar_v_opacity_values.len(), 1);
494
    }
495

            
496
    #[test]
497
    fn opacity_round_trips_from_css_through_the_compact_cache_quantizer() {
498
        // compact.rs encodes opacity as `(o * 254.0).round() as u8`; gpu.rs decodes it
499
        // as `raw / 254.0`. Every value must survive that round-trip within one step,
500
        // and must never leave [0, 1] (which WebRender would reject).
501
        const STEP: f32 = 1.0 / 254.0;
502
        for (css_value, expected) in [
503
            ("0", 0.0f32),
504
            ("0.25", 0.25),
505
            ("0.5", 0.5),
506
            ("1", 1.0),
507
            ("50%", 0.5),
508
            ("100%", 1.0),
509
        ] {
510
            let styled = styled_dom_from_css(&format!(".fade {{ opacity: {css_value}; }}"), "fade");
511
            let mut cache = GpuValueCache::empty();
512

            
513
            let changes = cache.synchronize(&styled);
514

            
515
            let decoded = changes
516
                .opacity_key_changes
517
                .iter()
518
                .find_map(|e| match e {
519
                    GpuOpacityKeyEvent::Added(_, _, v) => Some(*v),
520
                    _ => None,
521
                })
522
                .unwrap_or_else(|| panic!("`opacity: {css_value}` produced no Added event"));
523

            
524
            assert!(
525
                (decoded - expected).abs() <= STEP,
526
                "`opacity: {css_value}` decoded as {decoded}, expected ~{expected}"
527
            );
528
            assert!(
529
                (0.0..=1.0).contains(&decoded),
530
                "`opacity: {css_value}` decoded to {decoded}, outside [0, 1]"
531
            );
532
        }
533
    }
534

            
535
    #[test]
536
    fn re_synchronizing_an_unchanged_dom_never_mints_a_second_key() {
537
        let styled = styled_dom_from_css(".fade { opacity: 0.5; }", "fade");
538
        let mut cache = GpuValueCache::empty();
539

            
540
        let first = cache.synchronize(&styled);
541
        let added_first = first
542
            .opacity_key_changes
543
            .iter()
544
            .filter(|e| matches!(e, GpuOpacityKeyEvent::Added(..)))
545
            .count();
546
        assert_eq!(
547
            added_first, 1,
548
            "the .fade div must get exactly one opacity key"
549
        );
550
        let keys_after_first = cache.opacity_keys.clone();
551

            
552
        let second = cache.synchronize(&styled);
553

            
554
        assert!(
555
            !second
556
                .opacity_key_changes
557
                .iter()
558
                .any(|e| matches!(e, GpuOpacityKeyEvent::Added(..))),
559
            "re-syncing an unchanged DOM must not allocate a new OpacityKey (GPU key leak)"
560
        );
561
        assert_eq!(
562
            cache.opacity_keys, keys_after_first,
563
            "the OpacityKey of a node must be stable across syncs"
564
        );
565
    }
566

            
567
    #[test]
568
    fn synchronize_evicts_cached_keys_for_nodes_that_no_longer_exist() {
569
        // Structural shrink: the DOM got smaller, so cached keys for now-missing nodes
570
        // are never visited by the per-node loop and would leak on the GPU.
571
        let styled = plain_styled_dom();
572
        assert_eq!(styled.node_data.len(), 1);
573

            
574
        let ghost_a = NodeId::new(9_999);
575
        let ghost_b = NodeId::new(usize::MAX); // must be "out of range", not an overflow
576
        let mut cache = GpuValueCache::empty();
577
        for ghost in [ghost_a, ghost_b] {
578
            cache
579
                .css_transform_keys
580
                .insert(ghost, TransformKey::unique());
581
            cache
582
                .css_current_transform_values
583
                .insert(ghost, ComputedTransform3D::IDENTITY);
584
            cache.opacity_keys.insert(ghost, OpacityKey::unique());
585
            cache.current_opacity_values.insert(ghost, 0.5);
586
        }
587

            
588
        let changes = cache.synchronize(&styled);
589

            
590
        assert_eq!(changes.transform_key_changes.len(), 2);
591
        assert_eq!(changes.opacity_key_changes.len(), 2);
592
        assert!(changes
593
            .transform_key_changes
594
            .iter()
595
            .all(|e| matches!(e, GpuTransformKeyEvent::Removed(..))));
596
        assert!(changes
597
            .opacity_key_changes
598
            .iter()
599
            .all(|e| matches!(e, GpuOpacityKeyEvent::Removed(..))));
600
        assert!(cache.css_transform_keys.is_empty());
601
        assert!(cache.css_current_transform_values.is_empty());
602
        assert!(cache.opacity_keys.is_empty());
603
        assert!(cache.current_opacity_values.is_empty());
604
    }
605

            
606
    #[test]
607
    fn a_cached_opacity_is_evicted_when_the_node_loses_its_opacity() {
608
        // Node still exists, but the DOM no longer sets `opacity` on it: the
609
        // (Some(old), None) arm must fire a Removed so the OpacityKey is freed.
610
        let styled = plain_styled_dom();
611
        let node = NodeId::ZERO;
612
        let key = OpacityKey::unique();
613

            
614
        let mut cache = GpuValueCache::empty();
615
        cache.opacity_keys.insert(node, key);
616
        cache.current_opacity_values.insert(node, 0.5);
617

            
618
        let changes = cache.synchronize(&styled);
619

            
620
        assert_eq!(
621
            changes.opacity_key_changes,
622
            vec![GpuOpacityKeyEvent::Removed(node, key)]
623
        );
624
        assert!(cache.opacity_keys.is_empty());
625
        assert!(cache.current_opacity_values.is_empty());
626
    }
627

            
628
    #[test]
629
    fn a_cached_transform_is_evicted_when_the_node_loses_its_transform() {
630
        // Same scenario as the opacity test above, for transforms: the node is still in
631
        // the DOM but no longer carries a `transform` property (e.g. its class was
632
        // dropped between frames). The (Some(old), None) arm of compute_transform_events
633
        // must fire a Removed — otherwise the TransformKey leaks on the GPU and the
634
        // cache keeps serving a stale matrix forever.
635
        let styled = plain_styled_dom();
636
        let node = NodeId::ZERO;
637
        let key = TransformKey::unique();
638

            
639
        let mut cache = GpuValueCache::empty();
640
        cache.css_transform_keys.insert(node, key);
641
        cache
642
            .css_current_transform_values
643
            .insert(node, ComputedTransform3D::IDENTITY);
644

            
645
        let changes = cache.synchronize(&styled);
646

            
647
        assert_eq!(
648
            changes.transform_key_changes,
649
            vec![GpuTransformKeyEvent::Removed(node, key)]
650
        );
651
        assert!(
652
            cache.css_transform_keys.is_empty(),
653
            "a stale CSS transform key was not evicted"
654
        );
655
        assert!(
656
            cache.css_current_transform_values.is_empty(),
657
            "a stale CSS transform value was not evicted"
658
        );
659
    }
660

            
661
    #[test]
662
    fn synchronize_survives_malformed_and_unicode_css() {
663
        for css_src in [
664
            "",
665
            ".fade { opacity: ; }",
666
            ".fade { opacity: 🦀; }",
667
            ".fade { opacity: -1; }",
668
            ".fade { opacity: 99999999999; }",
669
            ".fade { opacity: NaN; }",
670
            ".fade { transform: }",
671
            ".fade { transform: rotate(NaN); }",
672
            ".fade { transform: rotate(1e400deg); }",
673
            ".fade { transform: rotate(); }",
674
        ] {
675
            let styled = styled_dom_from_css(css_src, "fade");
676
            let mut cache = GpuValueCache::empty();
677

            
678
            let _ = cache.synchronize(&styled);
679

            
680
            // Whatever the parser salvaged, the cache invariants must survive it.
681
            assert_eq!(
682
                cache.css_transform_keys.len(),
683
                cache.css_current_transform_values.len(),
684
                "transform key/value maps drifted apart (css: {css_src:?})"
685
            );
686
            assert_eq!(
687
                cache.opacity_keys.len(),
688
                cache.current_opacity_values.len(),
689
                "opacity key/value maps drifted apart (css: {css_src:?})"
690
            );
691
            for value in cache.current_opacity_values.values() {
692
                assert!(
693
                    !value.is_nan(),
694
                    "a NaN opacity reached the GPU cache (css: {css_src:?})"
695
                );
696
                assert!(
697
                    (0.0..=1.0).contains(value),
698
                    "an out-of-range opacity ({value}) reached the GPU cache (css: {css_src:?})"
699
                );
700
            }
701
        }
702
    }
703

            
704
    #[test]
705
    fn synchronize_on_a_500_node_dom_keeps_every_key_in_range() {
706
        let css = azul_css::parser2::new_from_str(
707
            ".t { transform: rotate(45deg); } .o { opacity: 0.25; }",
708
        )
709
        .0;
710
        let children = (0..500usize)
711
            .map(|i| {
712
                let class = if i % 2 == 0 { "t" } else { "o" };
713
                Dom::create_div().with_class(class.to_string().into())
714
            })
715
            .collect::<Vec<Dom>>();
716
        let mut dom = Dom::create_body().with_children(children.into());
717
        let styled = StyledDom::create(&mut dom, css);
718

            
719
        let mut cache = GpuValueCache::empty();
720
        let changes = cache.synchronize(&styled);
721

            
722
        // On a fresh cache every event has to be an Added, so the event count and the
723
        // resulting key count must agree exactly.
724
        assert_eq!(
725
            changes.transform_key_changes.len(),
726
            cache.css_transform_keys.len()
727
        );
728
        assert_eq!(changes.opacity_key_changes.len(), cache.opacity_keys.len());
729
        assert_eq!(
730
            cache.css_transform_keys.len(),
731
            cache.css_current_transform_values.len()
732
        );
733
        assert_eq!(cache.opacity_keys.len(), cache.current_opacity_values.len());
734

            
735
        // No cached key may point outside the DOM.
736
        let node_count = styled.node_data.len();
737
        assert!(cache
738
            .css_transform_keys
739
            .keys()
740
            .all(|n| n.index() < node_count));
741
        assert!(cache.opacity_keys.keys().all(|n| n.index() < node_count));
742
    }
743
}