1
//! Centralized GPU state management.
2
//!
3
//! This module provides management of GPU property keys
4
//! (opacity, transforms, etc.), fade-in/fade-out animations
5
//! for scrollbar opacity - as a single source of truth for
6
//! the GPU cache.
7

            
8
use alloc::collections::BTreeMap;
9
#[cfg(not(feature = "std"))]
10
use alloc::collections::BTreeMap as HashMap;
11
#[cfg(feature = "std")]
12
use std::collections::HashMap;
13

            
14
use azul_core::{
15
    dom::{DomId, NodeId, ScrollbarOrientation},
16
    geom::{LogicalPosition, LogicalRect, LogicalSize},
17
    gpu::{GpuEventChanges, GpuTransformKeyEvent, GpuValueCache},
18
    resources::TransformKey,
19
    task::{Duration, SystemTimeDiff},
20
    transform::ComputedTransform3D,
21
};
22

            
23
use crate::{
24
    managers::scroll_state::ScrollManager,
25
    solver3::{
26
        fc::DEFAULT_SCROLLBAR_WIDTH_PX,
27
        layout_tree::{LayoutNodeId, LayoutTree},
28
        scrollbar::compute_scrollbar_geometry_with_button_size,
29
    },
30
};
31

            
32
/// Default delay before scrollbars start fading out (500ms)
33
pub const DEFAULT_FADE_DELAY_MS: u64 = 500;
34
/// Default duration of scrollbar fade-out animation (200ms)
35
pub const DEFAULT_FADE_DURATION_MS: u64 = 200;
36

            
37
/// Manages GPU-accelerated properties across all DOMs.
38
///
39
/// The `GpuStateManager` maintains caches for transform and opacity keys
40
/// that are used by the GPU renderer. It handles:
41
///
42
/// - Scrollbar thumb position transforms (updated on scroll)
43
/// - Opacity fading for scrollbars (fade in on activity, fade out after delay)
44
/// - Per-DOM GPU value caches for efficient rendering
45
/// A tiny FNV-1a accumulator for "is this the same payload I sent last frame?".
46
///
47
/// Floats go in BITWISE (`to_bits`): a NaN opacity compares unequal to itself
48
/// and would reinstate the very redraw loop this exists to break.
49
#[derive(Debug, Copy, Clone)]
50
pub struct FrameDigest(u64);
51

            
52
impl Default for FrameDigest {
53
    fn default() -> Self {
54
        Self::new()
55
    }
56
}
57

            
58
impl FrameDigest {
59
    #[must_use]
60
17
    pub const fn new() -> Self {
61
17
        Self(0xcbf2_9ce4_8422_2325)
62
17
    }
63

            
64
209
    pub fn push_u64(&mut self, v: u64) {
65
1672
        for b in v.to_le_bytes() {
66
1672
            self.0 ^= u64::from(b);
67
1672
            self.0 = self.0.wrapping_mul(0x0000_0100_0000_01B3);
68
1672
        }
69
209
    }
70

            
71
140
    pub fn push_f32(&mut self, v: f32) {
72
140
        self.push_u64(u64::from(v.to_bits()));
73
140
    }
74

            
75
    #[must_use]
76
17
    pub const fn finish(&self) -> u64 {
77
17
        self.0
78
17
    }
79
}
80

            
81
/// Which of the renderer submissions [`GpuStateManager::submitted_digest_changed`]
82
/// is being asked about.
83
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
84
pub enum SubmittedDigest {
85
    /// Image keys registered / updated on the transaction.
86
    Images,
87
    /// Scroll offsets pushed to `WebRender`'s scroll frames.
88
    ScrollOffsets,
89
}
90

            
91
#[derive(Debug, Clone)]
92
pub struct GpuStateManager {
93
    /// GPU value caches indexed by DOM ID
94
    pub caches: BTreeMap<DomId, GpuValueCache>,
95
    /// Delay before scrollbars start fading out after last activity
96
    pub fade_delay: Duration,
97
    /// Duration of the fade-out animation
98
    pub fade_duration: Duration,
99
    /// Whether any scrollbar has non-zero opacity and needs continued frame
100
    /// generation. Set during both the `fade_delay` period (opacity == 1.0)
101
    /// and the active fade-out phase (0 < opacity < 1).
102
    /// Set by `LayoutWindow::synchronize_scrollbar_opacity`, read by the platform render loop.
103
    pub scrollbar_fade_active: bool,
104
    /// Digest of the dynamic properties (scrollbar opacities + transforms)
105
    /// last handed to the renderer, so an IDENTICAL set can be recognised and
106
    /// skipped. See [`GpuStateManager::gpu_values_changed`].
107
    pub last_gpu_value_digest: Option<u64>,
108
    /// Digest of the image registrations last handed to the renderer.
109
    /// See [`GpuStateManager::submitted_digest_changed`].
110
    pub last_image_digest: Option<u64>,
111
    /// Digest of the scroll offsets last handed to the renderer.
112
    /// See [`GpuStateManager::submitted_digest_changed`].
113
    pub last_scroll_digest: Option<u64>,
114
    /// GPU events produced during layout (CSS transform / opacity synchronization,
115
    /// scrollbar transform / opacity updates) that have not yet been pushed to
116
    /// the renderer. Drained by the platform render path when a transaction is
117
    /// built.
118
    pub pending_changes: GpuEventChanges,
119
}
120

            
121
impl Default for GpuStateManager {
122
42
    fn default() -> Self {
123
42
        Self::new(
124
42
            Duration::System(SystemTimeDiff::from_millis(DEFAULT_FADE_DELAY_MS)),
125
42
            Duration::System(SystemTimeDiff::from_millis(DEFAULT_FADE_DURATION_MS)),
126
        )
127
42
    }
128
}
129

            
130
impl GpuStateManager {
131
    /// Have the dynamic GPU properties changed since they were last submitted?
132
    ///
133
    /// THE IDLE REDRAW LOOP THIS EXISTS TO BREAK. The lightweight transaction
134
    /// path — taken precisely because nothing needs rebuilding — pushed these
135
    /// values and then asked `WebRender` for a frame unconditionally.
136
    /// `WebRender`
137
    /// built one, signalled `new_frame_ready`, the backend woke and presented,
138
    /// and the present ran the lightweight path again. Measured idle on
139
    /// `X11`/GPU: 1087 submissions, 1087 frame-ready signals, 1086 presents, all
140
    /// carrying the same two floats and two transforms — ~59 fps of full
141
    /// render+present for a window nobody was touching.
142
    ///
143
    /// Floats are compared BITWISE (`to_bits`), not by value: a NaN opacity
144
    /// compares unequal to itself and would reinstate the loop it is meant to
145
    /// prevent.
146
    ///
147
    /// Returns `true` the first time (nothing to compare against) and whenever
148
    /// the set genuinely differs — a changed value, a new key, or a lost one.
149
17
    pub fn gpu_values_changed(
150
17
        &mut self,
151
17
        floats: &[(u64, f32)],
152
17
        transforms: &[(u64, [f32; 16])],
153
17
    ) -> bool {
154
        // Sorted by key before digesting. The caller collects these out of
155
        // `HashMap`s, whose iteration order is not a promise; an order that
156
        // flapped while the values stayed the same would report a change on a
157
        // frame that changed nothing, and the loop would be back.
158
17
        let mut sorted_floats = floats.iter().collect::<Vec<_>>();
159
17
        sorted_floats.sort_unstable_by_key(|(k, _)| *k);
160
17
        let mut sorted_transforms = transforms.iter().collect::<Vec<_>>();
161
17
        sorted_transforms.sort_unstable_by_key(|(k, _)| *k);
162

            
163
17
        let mut h = FrameDigest::new();
164
17
        h.push_u64(floats.len() as u64);
165
45
        for (k, v) in sorted_floats {
166
28
            h.push_u64(*k);
167
28
            h.push_f32(*v);
168
28
        }
169
17
        h.push_u64(transforms.len() as u64);
170
24
        for (k, m) in sorted_transforms {
171
7
            h.push_u64(*k);
172
119
            for f in m {
173
112
                h.push_f32(*f);
174
112
            }
175
        }
176
17
        let digest = h.finish();
177

            
178
17
        if self.last_gpu_value_digest == Some(digest) {
179
7
            return false;
180
10
        }
181
10
        self.last_gpu_value_digest = Some(digest);
182
10
        true
183
17
    }
184

            
185
    /// Same idea as [`Self::gpu_values_changed`] for the other two things a
186
    /// "nothing was rebuilt" transaction carries: image registrations and
187
    /// scroll offsets. The caller digests its own payload (the types live in
188
    /// the renderer crate); this only owns the remembering.
189
    ///
190
    /// `slot` picks which of the two is meant.
191
10
    pub fn submitted_digest_changed(&mut self, slot: SubmittedDigest, digest: u64) -> bool {
192
10
        let stored = match slot {
193
5
            SubmittedDigest::Images => &mut self.last_image_digest,
194
5
            SubmittedDigest::ScrollOffsets => &mut self.last_scroll_digest,
195
        };
196
10
        if *stored == Some(digest) {
197
3
            return false;
198
7
        }
199
7
        *stored = Some(digest);
200
7
        true
201
10
    }
202

            
203
    /// Forget what was last submitted, so the next submission pushes
204
    /// everything again.
205
    ///
206
    /// The full-frame path MUST call this before it builds: a scene rebuild
207
    /// gives `WebRender` a new display list whose property bindings start from
208
    /// the values baked into the list, and "identical to what I sent last
209
    /// time" is then the wrong question — the values have to be re-pushed even
210
    /// though they did not change.
211
1
    pub const fn invalidate_submitted_digests(&mut self) {
212
1
        self.last_gpu_value_digest = None;
213
1
        self.last_image_digest = None;
214
1
        self.last_scroll_digest = None;
215
1
    }
216

            
217
    /// Creates a new GPU state manager with specified fade timing.
218
    #[must_use]
219
7626
    pub fn new(fade_delay: Duration, fade_duration: Duration) -> Self {
220
7626
        Self {
221
7626
            caches: BTreeMap::new(),
222
7626
            fade_delay,
223
7626
            fade_duration,
224
7626
            scrollbar_fade_active: false,
225
7626
            last_gpu_value_digest: None,
226
7626
            last_image_digest: None,
227
7626
            last_scroll_digest: None,
228
7626
            pending_changes: GpuEventChanges::empty(),
229
7626
        }
230
7626
    }
231

            
232
    /// Take any queued transform / opacity events that have been accumulated
233
    /// during layout. Clears the internal buffer.
234
8485
    pub fn take_pending_changes(&mut self) -> GpuEventChanges {
235
8485
        core::mem::take(&mut self.pending_changes)
236
8485
    }
237

            
238
    // NOTE: the per-frame scrollbar-fade interpolation lives in
239
    // `LayoutWindow::synchronize_scrollbar_opacity` (layout/src/window.rs),
240
    // which reads the last-activity time straight from the `ScrollManager` and
241
    // is the single source of truth for fade opacity. An earlier duplicate
242
    // tick-based subsystem here (`tick` / `record_scroll_activity` /
243
    // `calculate_fade_opacity` + a `fade_states` map) was never wired into any
244
    // render loop and has been removed.
245

            
246
    /// Gets or creates the GPU cache for a specific DOM.
247
    #[must_use]
248
17106
    pub fn get_cache(&self, dom_id: DomId) -> Option<&GpuValueCache> {
249
17106
        self.caches.get(&dom_id)
250
17106
    }
251

            
252
65014
    pub fn get_or_create_cache(&mut self, dom_id: DomId) -> &mut GpuValueCache {
253
65014
        self.caches.entry(dom_id).or_default()
254
65014
    }
255

            
256
    /// Updates scrollbar thumb transforms based on current scroll positions.
257
    ///
258
    /// Calculates the transform needed to position scrollbar thumbs correctly
259
    /// based on the scroll offset and content/container sizes. Returns the
260
    /// GPU event changes that need to be applied by the renderer.
261
25297
    pub fn update_scrollbar_transforms(
262
25297
        &mut self,
263
25297
        dom_id: DomId,
264
25297
        scroll_manager: &ScrollManager,
265
25297
        layout_tree: &LayoutTree,
266
25297
    ) -> GpuEventChanges {
267
25297
        let mut changes = GpuEventChanges::empty();
268
25297
        let gpu_cache = self.get_or_create_cache(dom_id);
269

            
270
454275
        for (node_idx, node) in layout_tree.nodes.iter().enumerate() {
271
454275
            let warm = layout_tree.warm(LayoutNodeId::new(node_idx));
272
            // The necessity flags are the layout pass's, amended after layout by
273
            // `cache::apply_virtual_scroll_necessity` (via `register_scroll_nodes`)
274
            // for a `VirtualView`, whose scrollable extent layout cannot see. This
275
            // path deliberately re-derives nothing: it reads the one stored answer,
276
            // so a bar that `paint_scrollbars` drew always gets its thumb moved.
277
454275
            let Some(scrollbar_info) = warm.and_then(|w| w.scrollbar_info.as_ref()) else {
278
94979
                continue;
279
            };
280
359296
            let Some(node_id) = node.dom_node_id else {
281
132
                continue;
282
            };
283

            
284
359164
            let scroll_offset = scroll_manager
285
359164
                .get_current_offset(dom_id, node_id)
286
359164
                .unwrap_or_default();
287

            
288
            // Compute inner_rect (padding-box) by subtracting borders from used_size
289
359164
            let border_box_size = node.used_size.unwrap_or_default();
290
359164
            let nbp = node.box_props.unpack();
291
359164
            let border = &nbp.border;
292
359164
            let inner_size = LogicalSize {
293
359164
                width: (border_box_size.width - border.left - border.right).max(0.0),
294
359164
                height: (border_box_size.height - border.top - border.bottom).max(0.0),
295
359164
            };
296
            // Use zero origin since we only need the geometry ratios, not absolute position
297
359164
            let inner_rect = LogicalRect {
298
359164
                origin: LogicalPosition::new(0.0, 0.0),
299
359164
                size: inner_size,
300
359164
            };
301

            
302
            // `display_list::paint_scrollbars` sizes the thumb from
303
            // `ScrollPosition::children_rect.size` — the `VirtualView` virtual size
304
            // when the callback reported one, else the laid-out content size. This
305
            // path OVERWRITES the transform key that path seeds, so it has to size
306
            // from the same number: a `VirtualView` is a replaced element with no
307
            // flow content, so `get_content_size` returns roughly the viewport and
308
            // the thumb would snap to the full track on the first live scroll.
309
359164
            let content_size = scroll_manager
310
359164
                .get_scroll_state(dom_id, node_id)
311
359164
                .and_then(|s| s.virtual_scroll_size)
312
359164
                .unwrap_or_else(|| layout_tree.get_content_size(LayoutNodeId::new(node_idx)));
313

            
314
359164
            if scrollbar_info.needs_vertical {
315
                // Use the visual width from the scrollbar style — same value used
316
                // by display_list.rs to paint the scrollbar. For overlay scrollbars,
317
                // visual_width_px is non-zero (e.g. 8.0) even though the layout-
318
                // reserved width (scrollbar_height) is 0.0.
319
17968
                let is_overlay = scrollbar_info.scrollbar_height == 0.0;
320
17968
                let scrollbar_width_px = if scrollbar_info.visual_width_px > 0.0 {
321
17966
                    scrollbar_info.visual_width_px
322
2
                } else if !is_overlay {
323
                    scrollbar_info.scrollbar_height
324
                } else {
325
2
                    DEFAULT_SCROLLBAR_WIDTH_PX
326
                };
327
                // Overlay scrollbars (macOS-style) have no arrow buttons
328
17968
                let button_size = if is_overlay { 0.0 } else { scrollbar_width_px };
329

            
330
17968
                let v_geom = compute_scrollbar_geometry_with_button_size(
331
17968
                    ScrollbarOrientation::Vertical,
332
17968
                    inner_rect,
333
17968
                    content_size,
334
17968
                    scroll_offset.y,
335
17968
                    scrollbar_width_px,
336
17968
                    scrollbar_info.needs_horizontal,
337
17968
                    button_size,
338
                );
339

            
340
                // Quantised to whole logical pixels: this value is the only
341
                // channel that can damage the bar, and a sub-pixel thumb move
342
                // repaints a gutter that did not visibly change. See
343
                // `quantize_thumb_offset` — `paint_scrollbars` bakes the
344
                // display list's initial value through the same rounding.
345
17968
                let transform = ComputedTransform3D::new_translation(
346
                    0.0,
347
17968
                    crate::solver3::scrollbar::quantize_thumb_offset(v_geom.thumb_offset),
348
                    0.0,
349
                );
350
17968
                update_scrollbar_transform_key(
351
17968
                    gpu_cache,
352
17968
                    &mut changes,
353
17968
                    node_id,
354
17968
                    transform,
355
17968
                    ScrollbarOrientation::Vertical,
356
                );
357
341196
            }
358

            
359
359164
            if scrollbar_info.needs_horizontal {
360
197
                let is_overlay = scrollbar_info.scrollbar_width == 0.0;
361
197
                let scrollbar_width_px = if scrollbar_info.visual_width_px > 0.0 {
362
166
                    scrollbar_info.visual_width_px
363
31
                } else if !is_overlay {
364
                    scrollbar_info.scrollbar_width
365
                } else {
366
31
                    DEFAULT_SCROLLBAR_WIDTH_PX
367
                };
368
197
                let button_size = if is_overlay { 0.0 } else { scrollbar_width_px };
369

            
370
197
                let h_geom = compute_scrollbar_geometry_with_button_size(
371
197
                    ScrollbarOrientation::Horizontal,
372
197
                    inner_rect,
373
197
                    content_size,
374
197
                    scroll_offset.x,
375
197
                    scrollbar_width_px,
376
197
                    scrollbar_info.needs_vertical,
377
197
                    button_size,
378
                );
379

            
380
197
                let transform = ComputedTransform3D::new_translation(
381
197
                    crate::solver3::scrollbar::quantize_thumb_offset(h_geom.thumb_offset),
382
                    0.0,
383
                    0.0,
384
                );
385
197
                update_scrollbar_transform_key(
386
197
                    gpu_cache,
387
197
                    &mut changes,
388
197
                    node_id,
389
197
                    transform,
390
197
                    ScrollbarOrientation::Horizontal,
391
                );
392
358967
            }
393
        }
394

            
395
25297
        changes
396
25297
    }
397
}
398

            
399
/// Updates or creates a scrollbar transform key in the GPU cache for the given orientation.
400
18189
fn update_scrollbar_transform_key(
401
18189
    gpu_cache: &mut GpuValueCache,
402
18189
    changes: &mut GpuEventChanges,
403
18189
    node_id: NodeId,
404
18189
    transform: ComputedTransform3D,
405
18189
    orientation: ScrollbarOrientation,
406
18189
) {
407
18189
    let (keys, values) = match orientation {
408
17991
        ScrollbarOrientation::Vertical => (
409
17991
            &mut gpu_cache.transform_keys,
410
17991
            &mut gpu_cache.current_transform_values,
411
17991
        ),
412
198
        ScrollbarOrientation::Horizontal => (
413
198
            &mut gpu_cache.h_transform_keys,
414
198
            &mut gpu_cache.h_current_transform_values,
415
198
        ),
416
    };
417

            
418
18189
    if let Some(existing_transform) = values.get(&node_id) {
419
17128
        if *existing_transform != transform {
420
44
            let Some(&transform_key) = keys.get(&node_id) else {
421
1
                return;
422
            };
423
43
            changes
424
43
                .transform_key_changes
425
43
                .push(GpuTransformKeyEvent::Changed(
426
43
                    node_id,
427
43
                    transform_key,
428
43
                    *existing_transform,
429
43
                    transform,
430
43
                ));
431
43
            values.insert(node_id, transform);
432
17084
        }
433
1061
    } else {
434
1061
        let transform_key = TransformKey::unique();
435
1061
        keys.insert(node_id, transform_key);
436
1061
        values.insert(node_id, transform);
437
1061
        changes
438
1061
            .transform_key_changes
439
1061
            .push(GpuTransformKeyEvent::Added(
440
1061
                node_id,
441
1061
                transform_key,
442
1061
                transform,
443
1061
            ));
444
1061
    }
445
18189
}
446

            
447
impl crate::managers::NodeIdRemap for GpuStateManager {
448
    /// Remap the per-node GPU caches (transform / opacity keys and values).
449
    ///
450
    /// Without this, a rebuild that shifts `NodeIds` left the scrollbar/CSS
451
    /// transform + opacity keys attached to the wrong node — the visible symptom
452
    /// being a scrollbar thumb (or an animated element) that keeps painting at a
453
    /// stale offset, plus `scrollbar_fade_active` never settling because the
454
    /// platform loop keeps generating frames for a node that is not the one
455
    /// actually scrolling.
456
450
    fn remap_node_ids(&mut self, dom: DomId, map: &crate::managers::NodeIdMap) {
457
450
        let Some(cache) = self.caches.get_mut(&dom) else {
458
1
            return;
459
        };
460

            
461
449
        remap_hashmap(&mut cache.transform_keys, map);
462
449
        remap_hashmap(&mut cache.current_transform_values, map);
463
449
        remap_hashmap(&mut cache.h_transform_keys, map);
464
449
        remap_hashmap(&mut cache.h_current_transform_values, map);
465
449
        remap_hashmap(&mut cache.css_transform_keys, map);
466
449
        remap_hashmap(&mut cache.css_current_transform_values, map);
467
449
        remap_hashmap(&mut cache.opacity_keys, map);
468
449
        remap_hashmap(&mut cache.current_opacity_values, map);
469
449
        remap_dom_hashmap(&mut cache.scrollbar_v_opacity_keys, dom, map);
470
449
        remap_dom_hashmap(&mut cache.scrollbar_h_opacity_keys, dom, map);
471
449
        remap_dom_hashmap(&mut cache.scrollbar_v_opacity_values, dom, map);
472
449
        remap_dom_hashmap(&mut cache.scrollbar_h_opacity_values, dom, map);
473
450
    }
474
}
475

            
476
/// Rewrite `NodeId` keys, dropping entries for unmounted nodes.
477
3597
fn remap_hashmap<V>(map: &mut HashMap<NodeId, V>, node_map: &crate::managers::NodeIdMap) {
478
3597
    let old = core::mem::take(map);
479
3629
    for (old_id, v) in old {
480
32
        if let Some(new_id) = node_map.resolve(old_id) {
481
24
            map.insert(new_id, v);
482
24
        }
483
    }
484
3597
}
485

            
486
/// Rewrite `(DomId, NodeId)` keys for `dom` only, dropping unmounted nodes.
487
1800
fn remap_dom_hashmap<V>(
488
1800
    map: &mut HashMap<(DomId, NodeId), V>,
489
1800
    dom: DomId,
490
1800
    node_map: &crate::managers::NodeIdMap,
491
1800
) {
492
1800
    let old = core::mem::take(map);
493
1818
    for ((d, old_id), v) in old {
494
18
        if d != dom {
495
3
            map.insert((d, old_id), v);
496
15
        } else if let Some(new_id) = node_map.resolve(old_id) {
497
11
            map.insert((d, new_id), v);
498
11
        }
499
    }
500
1800
}
501

            
502
#[cfg(test)]
503
mod redundant_frame_tests {
504
    use super::GpuStateManager;
505

            
506
    /// The idle redraw loop, in one invariant.
507
    ///
508
    /// `build_image_only_transaction` — the LIGHTWEIGHT path a backend takes
509
    /// precisely because nothing needs rebuilding — pushed the scrollbar
510
    /// opacities and transforms and then called `txn.generate_frame()`
511
    /// unconditionally. WebRender built a frame, signalled `new_frame_ready`,
512
    /// the backend woke and presented, and presenting ran the lightweight path
513
    /// again. Measured on X11/GPU, 2026-09-05, with the window completely idle:
514
    ///
515
    ///     1087 synchronize_gpu_values  ->  1087 new_frame_ready  ->  1086 presents
516
    ///     every one reporting the SAME payload: floats=2 transforms=2 colors=0
517
    ///
518
    /// ~59 fps of full render+present for a static window. All four backends
519
    /// (X11, Wayland, macOS, Windows) call that path, so this is shared, not
520
    /// X11-specific; X11 merely spins fastest because its present is driven by
521
    /// the frame-ready wake rather than a frame callback or CVDisplayLink.
522
    ///
523
    /// The rule: pushing the SAME values again is not a reason to draw.
524
    #[test]
525
1
    fn resubmitting_identical_gpu_values_is_not_a_reason_to_draw() {
526
1
        let mut m = GpuStateManager::default();
527

            
528
        // First push of a value set: genuinely new, so it must be sent.
529
1
        assert!(
530
1
            m.gpu_values_changed(&[(1, 1.0), (2, 0.0)], &[]),
531
            "the first submission has nothing to compare against and must go"
532
        );
533

            
534
        // The idle case: byte-identical values, over and over. None of these
535
        // may request a frame.
536
1
        assert!(!m.gpu_values_changed(&[(1, 1.0), (2, 0.0)], &[]));
537
1
        assert!(!m.gpu_values_changed(&[(1, 1.0), (2, 0.0)], &[]));
538

            
539
        // A real change (a scrollbar fading) must still get through.
540
1
        assert!(m.gpu_values_changed(&[(1, 0.5), (2, 0.0)], &[]));
541
1
        assert!(!m.gpu_values_changed(&[(1, 0.5), (2, 0.0)], &[]));
542

            
543
        // So must a transform change on its own.
544
1
        assert!(m.gpu_values_changed(&[(1, 0.5), (2, 0.0)], &[(7, [1.0; 16])]));
545
1
        assert!(!m.gpu_values_changed(&[(1, 0.5), (2, 0.0)], &[(7, [1.0; 16])]));
546

            
547
        // And losing a property is a change too - the set shrank.
548
1
        assert!(m.gpu_values_changed(&[(1, 0.5)], &[(7, [1.0; 16])]));
549
1
    }
550

            
551
    /// NaN must not make every frame look different from itself. Opacity is an
552
    /// f32 and a NaN compares unequal to itself, so a bitwise digest is what
553
    /// keeps a degenerate value from reinstating the very loop this prevents.
554
    #[test]
555
1
    fn a_nan_value_still_compares_equal_to_itself() {
556
1
        let mut m = GpuStateManager::default();
557
1
        assert!(m.gpu_values_changed(&[(1, f32::NAN)], &[]));
558
1
        assert!(
559
1
            !m.gpu_values_changed(&[(1, f32::NAN)], &[]),
560
            "NaN == NaN bitwise, or a NaN opacity spins the redraw loop forever"
561
        );
562
1
    }
563

            
564
    /// The other two payloads a lightweight transaction carries - image
565
    /// registrations and scroll offsets - answer the same question, through the
566
    /// same remembering.
567
    #[test]
568
1
    fn image_and_scroll_digests_are_independent() {
569
        use super::SubmittedDigest;
570

            
571
1
        let mut m = GpuStateManager::default();
572

            
573
1
        assert!(m.submitted_digest_changed(SubmittedDigest::Images, 42));
574
1
        assert!(!m.submitted_digest_changed(SubmittedDigest::Images, 42));
575

            
576
        // A scroll offset that happens to digest to the same number is still a
577
        // first submission for ITS slot: the two must not share a memory.
578
1
        assert!(m.submitted_digest_changed(SubmittedDigest::ScrollOffsets, 42));
579
1
        assert!(!m.submitted_digest_changed(SubmittedDigest::ScrollOffsets, 42));
580

            
581
1
        assert!(m.submitted_digest_changed(SubmittedDigest::Images, 43));
582
1
        assert!(!m.submitted_digest_changed(SubmittedDigest::ScrollOffsets, 42));
583
1
    }
584

            
585
    /// A full frame rebuilds the scene. The values then have to be pushed again
586
    /// even though they did not change, so the full path invalidates first.
587
    #[test]
588
1
    fn a_scene_rebuild_forgets_what_was_submitted() {
589
        use super::SubmittedDigest;
590

            
591
1
        let mut m = GpuStateManager::default();
592
1
        assert!(m.gpu_values_changed(&[(1, 1.0)], &[]));
593
1
        assert!(m.submitted_digest_changed(SubmittedDigest::Images, 7));
594
1
        assert!(m.submitted_digest_changed(SubmittedDigest::ScrollOffsets, 9));
595

            
596
1
        assert!(!m.gpu_values_changed(&[(1, 1.0)], &[]));
597

            
598
1
        m.invalidate_submitted_digests();
599

            
600
1
        assert!(
601
1
            m.gpu_values_changed(&[(1, 1.0)], &[]),
602
            "after a scene rebuild the property bindings start over - unchanged values still have \
603
             to reach the renderer"
604
        );
605
1
        assert!(m.submitted_digest_changed(SubmittedDigest::Images, 7));
606
1
        assert!(m.submitted_digest_changed(SubmittedDigest::ScrollOffsets, 9));
607
1
    }
608

            
609
    /// The digest must be sensitive to WHICH key holds a value, not just to the
610
    /// multiset of values: swapping two scrollbars' opacities is a change.
611
    #[test]
612
1
    fn swapping_two_keys_values_is_a_change() {
613
1
        let mut m = GpuStateManager::default();
614
1
        assert!(m.gpu_values_changed(&[(1, 1.0), (2, 0.0)], &[]));
615
1
        assert!(m.gpu_values_changed(&[(1, 0.0), (2, 1.0)], &[]));
616
1
    }
617

            
618
    /// ...but the ORDER the caller happens to collect them in is not a change.
619
    /// The values come out of `HashMap`s (`GpuValueCache` is keyed by
620
    /// `(DomId, NodeId)`), whose iteration order is not a promise; if a
621
    /// reordering read as a change, an idle window would draw whenever the map
622
    /// felt like handing them over differently.
623
    #[test]
624
1
    fn the_order_the_values_arrive_in_is_not_a_change() {
625
1
        let mut m = GpuStateManager::default();
626
1
        assert!(m.gpu_values_changed(&[(1, 1.0), (2, 0.25)], &[(7, [1.0; 16]), (8, [2.0; 16])]));
627
1
        assert!(
628
1
            !m.gpu_values_changed(&[(2, 0.25), (1, 1.0)], &[(8, [2.0; 16]), (7, [1.0; 16])]),
629
            "the same set in a different order is the same set"
630
        );
631
1
    }
632
}
633

            
634
#[cfg(test)]
635
mod autotest_generated {
636
    use azul_core::{
637
        dom::{Dom, FormattingContext, IdOrClass, NodeType},
638
        resources::OpacityKey,
639
        styled_dom::StyledDom,
640
        task::{Instant, SystemTick, SystemTickDiff},
641
    };
642

            
643
    use super::*;
644
    use crate::{
645
        managers::{NodeIdMap, NodeIdRemap},
646
        solver3::{
647
            cache::apply_virtual_scroll_necessity,
648
            geometry::PackedBoxProps,
649
            layout_tree::{LayoutNodeCold, LayoutNodeHot, LayoutNodeWarm},
650
            scrollbar::ScrollbarRequirements,
651
        },
652
    };
653

            
654
    // ------------------------------------------------------------------
655
    // Fixtures
656
    // ------------------------------------------------------------------
657

            
658
    fn dom(inner: usize) -> DomId {
659
        DomId { inner }
660
    }
661

            
662
    fn t0() -> Instant {
663
        Instant::Tick(SystemTick::new(0))
664
    }
665

            
666
    fn millis(ms: u64) -> Duration {
667
        Duration::System(SystemTimeDiff::from_millis(ms))
668
    }
669

            
670
    /// Translation transform — the only shape `update_scrollbar_transforms`
671
    /// ever produces.
672
    fn tx(x: f32, y: f32) -> ComputedTransform3D {
673
        ComputedTransform3D::new_translation(x, y, 0.0)
674
    }
675

            
676
    fn hot(dom_node_id: Option<NodeId>, used: Option<LogicalSize>) -> LayoutNodeHot {
677
        LayoutNodeHot {
678
            box_props: PackedBoxProps::default(),
679
            dom_node_id,
680
            used_size: used,
681
            formatting_context: FormattingContext::Block {
682
                establishes_new_context: true,
683
            },
684
            parent: None,
685
        }
686
    }
687

            
688
    fn warm_node(
689
        scrollbar_info: Option<ScrollbarRequirements>,
690
        content: Option<LogicalSize>,
691
    ) -> LayoutNodeWarm {
692
        LayoutNodeWarm {
693
            scrollbar_info,
694
            overflow_content_size: content,
695
            ..Default::default()
696
        }
697
    }
698

            
699
    /// What layout computes for an `overflow-y: auto` VirtualView: nothing.
700
    /// The node is a replaced element with no flow content, so its laid-out
701
    /// content never exceeds its box and `check_scrollbar_necessity` finds no
702
    /// reason for a bar — only `visual_width_px` survives from the CSS style.
703
    fn auto_no_scrollbar() -> ScrollbarRequirements {
704
        ScrollbarRequirements {
705
            needs_horizontal: false,
706
            needs_vertical: false,
707
            scrollbar_width: 0.0,
708
            scrollbar_height: 0.0,
709
            visual_width_px: 16.0,
710
        }
711
    }
712

            
713
    /// `body(0) > VirtualView(1)` with `overflow-x: hidden; overflow-y: auto`.
714
    /// NodeId 1 is the node every fixture in this module registers.
715
    fn auto_virtual_view_dom() -> StyledDom {
716
        let mut dom = Dom::create_body().with_child(
717
            Dom::create_node(NodeType::VirtualView)
718
                .with_ids_and_classes(vec![IdOrClass::Class("vv".into())].into()),
719
        );
720
        let (css, _warnings) =
721
            azul_css::parser2::new_from_str(".vv { overflow-x: hidden; overflow-y: auto; }");
722
        StyledDom::create(&mut dom, css)
723
    }
724

            
725
    /// A classic (space-reserving) vertical scrollbar with an explicit visual
726
    /// width — the un-ambiguous case where no field-fallback logic kicks in.
727
    fn v_scrollbar() -> ScrollbarRequirements {
728
        ScrollbarRequirements {
729
            needs_horizontal: false,
730
            needs_vertical: true,
731
            scrollbar_width: 16.0,
732
            scrollbar_height: 16.0,
733
            visual_width_px: 16.0,
734
        }
735
    }
736

            
737
    fn h_scrollbar() -> ScrollbarRequirements {
738
        ScrollbarRequirements {
739
            needs_horizontal: true,
740
            needs_vertical: false,
741
            scrollbar_width: 16.0,
742
            scrollbar_height: 16.0,
743
            visual_width_px: 16.0,
744
        }
745
    }
746

            
747
    fn tree(nodes: Vec<LayoutNodeHot>, warm: Vec<LayoutNodeWarm>) -> LayoutTree {
748
        let n = nodes.len();
749
        LayoutTree {
750
            nodes,
751
            warm,
752
            cold: vec![LayoutNodeCold::default(); n],
753
            root: 0,
754
            dom_to_layout: BTreeMap::new(),
755
            children_arena: Vec::new(),
756
            children_offsets: vec![(0, 0); n],
757
            subtree_needs_intrinsic: Vec::new(),
758
        }
759
    }
760

            
761
    /// Single scrollable node: 100×100 border-box, `content` content-box.
762
    fn one_node_tree(sb: ScrollbarRequirements, content: LogicalSize) -> LayoutTree {
763
        tree(
764
            vec![hot(
765
                Some(NodeId::new(1)),
766
                Some(LogicalSize::new(100.0, 100.0)),
767
            )],
768
            vec![warm_node(Some(sb), Some(content))],
769
        )
770
    }
771

            
772
    /// The y-translation of the single transform event emitted, if any.
773
    fn sole_added_y(changes: &GpuEventChanges) -> f32 {
774
        assert_eq!(changes.transform_key_changes.len(), 1);
775
        match changes.transform_key_changes[0] {
776
            GpuTransformKeyEvent::Added(_, _, t) => t.m[3][1],
777
            ref other => panic!("expected Added, got {other:?}"),
778
        }
779
    }
780

            
781
    fn sole_added_x(changes: &GpuEventChanges) -> f32 {
782
        assert_eq!(changes.transform_key_changes.len(), 1);
783
        match changes.transform_key_changes[0] {
784
            GpuTransformKeyEvent::Added(_, _, t) => t.m[3][0],
785
            ref other => panic!("expected Added, got {other:?}"),
786
        }
787
    }
788

            
789
    // ------------------------------------------------------------------
790
    // GpuStateManager::new / Default — constructor invariants
791
    // ------------------------------------------------------------------
792

            
793
    #[test]
794
    fn new_stores_both_durations_and_starts_empty_and_idle() {
795
        let m = GpuStateManager::new(millis(1), millis(2));
796
        assert_eq!(m.fade_delay, millis(1));
797
        assert_eq!(m.fade_duration, millis(2));
798
        assert!(m.caches.is_empty());
799
        assert!(!m.scrollbar_fade_active);
800
        assert!(m.pending_changes.is_empty());
801
    }
802

            
803
    #[test]
804
    fn new_survives_zero_and_u64_max_durations_without_panicking() {
805
        // Zero fade window: the fade math elsewhere divides by fade_duration,
806
        // so a 0 duration must at least be constructible without panicking here.
807
        let zero = GpuStateManager::new(millis(0), millis(0));
808
        assert_eq!(zero.fade_delay, millis(0));
809
        assert_eq!(zero.fade_duration, millis(0));
810

            
811
        // from_millis(u64::MAX) is ~584 million years — no overflow, no panic.
812
        let huge = GpuStateManager::new(millis(u64::MAX), millis(u64::MAX));
813
        assert_eq!(huge.fade_delay, millis(u64::MAX));
814
        assert!(huge.caches.is_empty());
815
    }
816

            
817
    #[test]
818
    fn new_accepts_tick_durations_not_just_system_durations() {
819
        // Duration is an enum; the constructor must not assume the System variant.
820
        let tick = Duration::Tick(SystemTickDiff {
821
            tick_diff: u64::MAX,
822
        });
823
        let m = GpuStateManager::new(tick, tick);
824
        assert_eq!(m.fade_delay, tick);
825
        assert_eq!(m.fade_duration, tick);
826
    }
827

            
828
    #[test]
829
    fn default_matches_the_documented_fade_constants() {
830
        let m = GpuStateManager::default();
831
        assert_eq!(m.fade_delay, millis(DEFAULT_FADE_DELAY_MS));
832
        assert_eq!(m.fade_duration, millis(DEFAULT_FADE_DURATION_MS));
833
        assert_eq!(DEFAULT_FADE_DELAY_MS, 500);
834
        assert_eq!(DEFAULT_FADE_DURATION_MS, 200);
835
    }
836

            
837
    // ------------------------------------------------------------------
838
    // take_pending_changes
839
    // ------------------------------------------------------------------
840

            
841
    #[test]
842
    fn take_pending_changes_drains_the_buffer_and_the_second_take_is_empty() {
843
        let mut m = GpuStateManager::default();
844
        m.pending_changes
845
            .transform_key_changes
846
            .push(GpuTransformKeyEvent::Added(
847
                NodeId::new(1),
848
                TransformKey::unique(),
849
                tx(0.0, 4.0),
850
            ));
851

            
852
        let taken = m.take_pending_changes();
853
        assert_eq!(taken.transform_key_changes.len(), 1);
854
        // The whole point of `take`: the buffer must not replay next frame.
855
        assert!(m.pending_changes.is_empty());
856
        assert!(m.take_pending_changes().is_empty());
857
    }
858

            
859
    #[test]
860
    fn take_pending_changes_on_a_fresh_manager_is_an_empty_no_panic() {
861
        let mut m = GpuStateManager::default();
862
        for _ in 0..3 {
863
            assert_eq!(m.take_pending_changes(), GpuEventChanges::empty());
864
        }
865
    }
866

            
867
    // ------------------------------------------------------------------
868
    // get_cache / get_or_create_cache
869
    // ------------------------------------------------------------------
870

            
871
    #[test]
872
    fn get_cache_on_an_unknown_dom_returns_none_and_does_not_create_it() {
873
        let m = GpuStateManager::default();
874
        assert!(m.get_cache(dom(0)).is_none());
875
        assert!(m.get_cache(dom(usize::MAX)).is_none());
876
        assert!(m.caches.is_empty(), "get_cache must not mutate");
877
    }
878

            
879
    #[test]
880
    fn get_or_create_cache_is_idempotent_and_never_clobbers_existing_state() {
881
        let mut m = GpuStateManager::default();
882
        let node = NodeId::new(7);
883
        let key = TransformKey::unique();
884

            
885
        m.get_or_create_cache(dom(0))
886
            .transform_keys
887
            .insert(node, key);
888
        assert_eq!(m.caches.len(), 1);
889

            
890
        // Second call must hand back the *same* cache, not a fresh default one —
891
        // otherwise every frame would mint new GPU keys and leak them.
892
        let again = m.get_or_create_cache(dom(0));
893
        assert_eq!(again.transform_keys.get(&node), Some(&key));
894
        assert_eq!(m.caches.len(), 1);
895
        assert!(m.get_cache(dom(0)).is_some());
896
    }
897

            
898
    #[test]
899
    fn caches_for_distinct_dom_ids_including_usize_max_do_not_alias() {
900
        let mut m = GpuStateManager::default();
901
        let node = NodeId::new(0);
902

            
903
        m.get_or_create_cache(dom(0))
904
            .current_opacity_values
905
            .insert(node, 0.25);
906
        m.get_or_create_cache(dom(usize::MAX))
907
            .current_opacity_values
908
            .insert(node, 0.75);
909

            
910
        assert_eq!(m.caches.len(), 2);
911
        assert_eq!(
912
            m.get_cache(dom(0))
913
                .unwrap()
914
                .current_opacity_values
915
                .get(&node),
916
            Some(&0.25)
917
        );
918
        assert_eq!(
919
            m.get_cache(dom(usize::MAX))
920
                .unwrap()
921
                .current_opacity_values
922
                .get(&node),
923
            Some(&0.75)
924
        );
925
    }
926

            
927
    // ------------------------------------------------------------------
928
    // update_scrollbar_transform_key (private)
929
    // ------------------------------------------------------------------
930

            
931
    #[test]
932
    fn first_update_emits_added_and_populates_both_the_key_and_value_map() {
933
        let mut cache = GpuValueCache::default();
934
        let mut changes = GpuEventChanges::empty();
935
        let node = NodeId::new(3);
936
        let t = tx(0.0, 12.0);
937

            
938
        update_scrollbar_transform_key(
939
            &mut cache,
940
            &mut changes,
941
            node,
942
            t,
943
            ScrollbarOrientation::Vertical,
944
        );
945

            
946
        let key = cache
947
            .transform_keys
948
            .get(&node)
949
            .copied()
950
            .expect("key stored");
951
        assert_eq!(cache.current_transform_values.get(&node), Some(&t));
952
        assert_eq!(
953
            changes.transform_key_changes,
954
            vec![GpuTransformKeyEvent::Added(node, key, t)]
955
        );
956
    }
957

            
958
    #[test]
959
    fn re_updating_with_an_identical_transform_emits_nothing() {
960
        // The cache exists to suppress redundant GPU traffic: a node that did not
961
        // move must produce zero events, forever.
962
        let mut cache = GpuValueCache::default();
963
        let node = NodeId::new(3);
964
        let t = tx(0.0, 12.0);
965

            
966
        let mut first = GpuEventChanges::empty();
967
        update_scrollbar_transform_key(
968
            &mut cache,
969
            &mut first,
970
            node,
971
            t,
972
            ScrollbarOrientation::Vertical,
973
        );
974
        let key = cache.transform_keys.get(&node).copied().unwrap();
975

            
976
        for _ in 0..10 {
977
            let mut again = GpuEventChanges::empty();
978
            update_scrollbar_transform_key(
979
                &mut cache,
980
                &mut again,
981
                node,
982
                t,
983
                ScrollbarOrientation::Vertical,
984
            );
985
            assert!(again.is_empty(), "unchanged transform must not re-emit");
986
        }
987
        // ...and the key must be stable across those no-op frames.
988
        assert_eq!(cache.transform_keys.get(&node).copied(), Some(key));
989
    }
990

            
991
    #[test]
992
    fn changing_the_transform_emits_changed_with_old_and_new_and_reuses_the_key() {
993
        let mut cache = GpuValueCache::default();
994
        let node = NodeId::new(3);
995
        let old = tx(0.0, 12.0);
996
        let new = tx(0.0, 40.0);
997

            
998
        let mut changes = GpuEventChanges::empty();
999
        update_scrollbar_transform_key(
            &mut cache,
            &mut changes,
            node,
            old,
            ScrollbarOrientation::Vertical,
        );
        let key = cache.transform_keys.get(&node).copied().unwrap();
        let mut changes = GpuEventChanges::empty();
        update_scrollbar_transform_key(
            &mut cache,
            &mut changes,
            node,
            new,
            ScrollbarOrientation::Vertical,
        );
        assert_eq!(
            changes.transform_key_changes,
            vec![GpuTransformKeyEvent::Changed(node, key, old, new)]
        );
        // Key is reused (not re-minted) and the stored value advances.
        assert_eq!(cache.transform_keys.get(&node).copied(), Some(key));
        assert_eq!(cache.current_transform_values.get(&node), Some(&new));
    }
    #[test]
    fn vertical_and_horizontal_keys_for_the_same_node_are_fully_independent() {
        // Both orientations key off the same NodeId but must land in disjoint
        // maps — otherwise a node with both scrollbars would have its vertical
        // thumb overwritten by its horizontal one (SpatialTreeItemKey collision).
        let mut cache = GpuValueCache::default();
        let mut changes = GpuEventChanges::empty();
        let node = NodeId::new(5);
        let v = tx(0.0, 10.0);
        let h = tx(20.0, 0.0);
        update_scrollbar_transform_key(
            &mut cache,
            &mut changes,
            node,
            v,
            ScrollbarOrientation::Vertical,
        );
        update_scrollbar_transform_key(
            &mut cache,
            &mut changes,
            node,
            h,
            ScrollbarOrientation::Horizontal,
        );
        assert_eq!(changes.transform_key_changes.len(), 2);
        assert_eq!(cache.current_transform_values.get(&node), Some(&v));
        assert_eq!(cache.h_current_transform_values.get(&node), Some(&h));
        assert_ne!(
            cache.transform_keys.get(&node),
            cache.h_transform_keys.get(&node),
            "the two orientations must not share a TransformKey"
        );
    }
    #[test]
    fn a_value_without_its_key_silently_drops_the_update_and_stays_stale() {
        // Desync #1: current_transform_values has an entry but transform_keys does
        // not. The `let Some(&transform_key) = keys.get(..) else { return }` bails
        // out *before* writing the new value, so the node is stuck at the stale
        // transform and never self-heals — no event, no repair, forever.
        let mut cache = GpuValueCache::default();
        let node = NodeId::new(3);
        let stale = tx(0.0, 5.0);
        cache.current_transform_values.insert(node, stale);
        let mut changes = GpuEventChanges::empty();
        update_scrollbar_transform_key(
            &mut cache,
            &mut changes,
            node,
            tx(0.0, 99.0),
            ScrollbarOrientation::Vertical,
        );
        assert!(
            changes.is_empty(),
            "no event is emitted for a keyless value"
        );
        assert_eq!(
            cache.current_transform_values.get(&node),
            Some(&stale),
            "the value is left stale rather than repaired"
        );
        assert!(
            !cache.transform_keys.contains_key(&node),
            "and no key is minted to recover"
        );
    }
    #[test]
    fn a_key_without_its_value_mints_a_fresh_key_and_orphans_the_old_one() {
        // Desync #2 (the mirror image): transform_keys has an entry but
        // current_transform_values does not. The else-branch unconditionally
        // overwrites the key, so the previously-published TransformKey is
        // orphaned — the renderer still holds it, nothing ever removes it.
        let mut cache = GpuValueCache::default();
        let node = NodeId::new(3);
        let orphan = TransformKey::unique();
        cache.transform_keys.insert(node, orphan);
        let mut changes = GpuEventChanges::empty();
        let t = tx(0.0, 7.0);
        update_scrollbar_transform_key(
            &mut cache,
            &mut changes,
            node,
            t,
            ScrollbarOrientation::Vertical,
        );
        let fresh = cache.transform_keys.get(&node).copied().unwrap();
        assert_ne!(fresh, orphan, "a brand-new key replaces the orphan");
        assert_eq!(
            changes.transform_key_changes,
            vec![GpuTransformKeyEvent::Added(node, fresh, t)],
            "and it is announced as Added, never as Removed(orphan)"
        );
    }
    #[test]
    fn a_nan_transform_never_converges_and_re_emits_changed_every_single_call() {
        // ComputedTransform3D derives PartialEq over f32s, so NaN != NaN. Once a
        // NaN thumb offset lands in the cache, `*existing != transform` is true on
        // every subsequent call *even for the bit-identical transform* — the cache
        // can never converge and the renderer gets an unbounded stream of Changed
        // events, one per frame, for a node that is not moving.
        let mut cache = GpuValueCache::default();
        let node = NodeId::new(3);
        let nan = tx(0.0, f32::NAN);
        let mut changes = GpuEventChanges::empty();
        update_scrollbar_transform_key(
            &mut cache,
            &mut changes,
            node,
            nan,
            ScrollbarOrientation::Vertical,
        );
        assert_eq!(changes.transform_key_changes.len(), 1, "Added");
        // Feed the exact same NaN transform back in 5 more times.
        for _ in 0..5 {
            update_scrollbar_transform_key(
                &mut cache,
                &mut changes,
                node,
                nan,
                ScrollbarOrientation::Vertical,
            );
        }
        assert_eq!(
            changes.transform_key_changes.len(),
            6,
            "NaN re-emits Changed on every call instead of settling"
        );
        assert!(cache.current_transform_values[&node].m[3][1].is_nan());
    }
    // ------------------------------------------------------------------
    // remap_hashmap
    // ------------------------------------------------------------------
    /// `NodeIdMap` in which nothing survived the rebuild.
    fn no_survivors() -> NodeIdMap {
        NodeIdMap::from_pairs(Vec::<(NodeId, NodeId)>::new())
    }
    #[test]
    fn remap_hashmap_on_empty_inputs_is_a_no_op() {
        let mut map: HashMap<NodeId, u32> = HashMap::new();
        remap_hashmap(&mut map, &no_survivors());
        assert!(map.is_empty());
    }
    #[test]
    fn remap_hashmap_drops_entries_for_unmounted_nodes() {
        let mut map: HashMap<NodeId, u32> = HashMap::new();
        map.insert(NodeId::new(1), 10);
        map.insert(NodeId::new(2), 20);
        map.insert(NodeId::new(3), 30);
        // Only node 2 survives the rebuild (as node 9).
        remap_hashmap(
            &mut map,
            &NodeIdMap::from_pairs([(NodeId::new(2), NodeId::new(9))]),
        );
        assert_eq!(map.len(), 1);
        assert_eq!(map.get(&NodeId::new(9)), Some(&20));
        assert!(!map.contains_key(&NodeId::new(1)));
        assert!(!map.contains_key(&NodeId::new(2)), "old id must not linger");
    }
    #[test]
    fn remap_hashmap_survives_a_full_id_swap_without_losing_entries() {
        // 1 -> 2 and 2 -> 1 simultaneously. An in-place rewrite would clobber one
        // of them depending on iteration order; the take-then-reinsert must not.
        let mut map: HashMap<NodeId, u32> = HashMap::new();
        map.insert(NodeId::new(1), 111);
        map.insert(NodeId::new(2), 222);
        remap_hashmap(
            &mut map,
            &NodeIdMap::from_pairs([
                (NodeId::new(1), NodeId::new(2)),
                (NodeId::new(2), NodeId::new(1)),
            ]),
        );
        assert_eq!(map.len(), 2, "no entry may be lost to the swap");
        assert_eq!(map.get(&NodeId::new(2)), Some(&111));
        assert_eq!(map.get(&NodeId::new(1)), Some(&222));
    }
    #[test]
    fn remap_hashmap_collapses_two_old_ids_that_alias_onto_one_new_id() {
        // A malformed NodeIdMap (two survivors claiming the same new slot) must
        // not panic — one entry silently wins. Pinning the *shape* of that loss:
        // the map shrinks rather than corrupting.
        let mut map: HashMap<NodeId, u32> = HashMap::new();
        map.insert(NodeId::new(1), 111);
        map.insert(NodeId::new(2), 222);
        remap_hashmap(
            &mut map,
            &NodeIdMap::from_pairs([
                (NodeId::new(1), NodeId::new(5)),
                (NodeId::new(2), NodeId::new(5)),
            ]),
        );
        assert_eq!(map.len(), 1, "the alias collapses both entries into one");
        let survivor = map.get(&NodeId::new(5)).copied().unwrap();
        assert!(survivor == 111 || survivor == 222);
    }
    #[test]
    fn remap_hashmap_handles_node_id_max_without_overflowing() {
        let mut map: HashMap<NodeId, u32> = HashMap::new();
        map.insert(NodeId::new(usize::MAX), 1);
        map.insert(NodeId::ZERO, 2);
        remap_hashmap(
            &mut map,
            &NodeIdMap::from_pairs([
                (NodeId::new(usize::MAX), NodeId::ZERO),
                (NodeId::ZERO, NodeId::new(usize::MAX)),
            ]),
        );
        assert_eq!(map.get(&NodeId::ZERO), Some(&1));
        assert_eq!(map.get(&NodeId::new(usize::MAX)), Some(&2));
    }
    // ------------------------------------------------------------------
    // remap_dom_hashmap
    // ------------------------------------------------------------------
    #[test]
    fn remap_dom_hashmap_leaves_other_doms_completely_untouched() {
        let mut map: HashMap<(DomId, NodeId), u32> = HashMap::new();
        map.insert((dom(0), NodeId::new(1)), 1);
        map.insert((dom(1), NodeId::new(1)), 2);
        // Reconcile DOM 0 only: 1 -> 4. DOM 1's node 1 is *not* mentioned in the
        // map, but it must survive anyway — this reconciliation says nothing
        // about a different DOM.
        remap_dom_hashmap(
            &mut map,
            dom(0),
            &NodeIdMap::from_pairs([(NodeId::new(1), NodeId::new(4))]),
        );
        assert_eq!(map.len(), 2);
        assert_eq!(map.get(&(dom(0), NodeId::new(4))), Some(&1));
        assert_eq!(
            map.get(&(dom(1), NodeId::new(1))),
            Some(&2),
            "a foreign DOM's entry must not be dropped as 'unmounted'"
        );
    }
    #[test]
    fn remap_dom_hashmap_drops_only_the_target_doms_unmounted_nodes() {
        let mut map: HashMap<(DomId, NodeId), u32> = HashMap::new();
        map.insert((dom(0), NodeId::new(1)), 1); // survives -> 4
        map.insert((dom(0), NodeId::new(2)), 2); // unmounted -> dropped
        map.insert((dom(1), NodeId::new(2)), 3); // other DOM -> kept as-is
        remap_dom_hashmap(
            &mut map,
            dom(0),
            &NodeIdMap::from_pairs([(NodeId::new(1), NodeId::new(4))]),
        );
        assert_eq!(map.len(), 2);
        assert_eq!(map.get(&(dom(0), NodeId::new(4))), Some(&1));
        assert!(!map.contains_key(&(dom(0), NodeId::new(2))));
        assert_eq!(map.get(&(dom(1), NodeId::new(2))), Some(&3));
    }
    #[test]
    fn remap_dom_hashmap_does_not_let_a_remap_collide_across_doms() {
        // (dom0, 1) -> (dom0, 2), while (dom1, 2) already exists. Different DOM,
        // so the tuple keys stay distinct and neither entry is lost.
        let mut map: HashMap<(DomId, NodeId), u32> = HashMap::new();
        map.insert((dom(0), NodeId::new(1)), 11);
        map.insert((dom(1), NodeId::new(2)), 22);
        remap_dom_hashmap(
            &mut map,
            dom(0),
            &NodeIdMap::from_pairs([(NodeId::new(1), NodeId::new(2))]),
        );
        assert_eq!(map.len(), 2);
        assert_eq!(map.get(&(dom(0), NodeId::new(2))), Some(&11));
        assert_eq!(map.get(&(dom(1), NodeId::new(2))), Some(&22));
    }
    #[test]
    fn remap_dom_hashmap_survives_a_shift_chain_within_one_dom() {
        // 1->2 and 2->3 at once. Resolving from the *old* snapshot means the
        // 1->2 insert cannot clobber the entry that used to live at 2.
        let mut map: HashMap<(DomId, NodeId), u32> = HashMap::new();
        map.insert((dom(0), NodeId::new(1)), 11);
        map.insert((dom(0), NodeId::new(2)), 22);
        remap_dom_hashmap(
            &mut map,
            dom(0),
            &NodeIdMap::from_pairs([
                (NodeId::new(1), NodeId::new(2)),
                (NodeId::new(2), NodeId::new(3)),
            ]),
        );
        assert_eq!(map.len(), 2);
        assert_eq!(map.get(&(dom(0), NodeId::new(2))), Some(&11));
        assert_eq!(map.get(&(dom(0), NodeId::new(3))), Some(&22));
    }
    // ------------------------------------------------------------------
    // NodeIdRemap for GpuStateManager
    // ------------------------------------------------------------------
    #[test]
    fn remap_node_ids_for_a_dom_with_no_cache_is_a_no_op() {
        let mut m = GpuStateManager::default();
        m.remap_node_ids(
            dom(3),
            &NodeIdMap::from_pairs([(NodeId::new(1), NodeId::new(2))]),
        );
        assert!(m.caches.is_empty());
    }
    #[test]
    fn remap_node_ids_rewrites_every_one_of_the_twelve_cache_maps() {
        // A single map left un-remapped is a stale scrollbar thumb / stuck
        // animation, so assert all twelve move together.
        let mut m = GpuStateManager::default();
        let old = NodeId::new(1);
        let new = NodeId::new(8);
        let d = dom(0);
        {
            let c = m.get_or_create_cache(d);
            c.transform_keys.insert(old, TransformKey::unique());
            c.current_transform_values.insert(old, tx(0.0, 1.0));
            c.h_transform_keys.insert(old, TransformKey::unique());
            c.h_current_transform_values.insert(old, tx(2.0, 0.0));
            c.css_transform_keys.insert(old, TransformKey::unique());
            c.css_current_transform_values.insert(old, tx(3.0, 3.0));
            c.opacity_keys.insert(old, OpacityKey::unique());
            c.current_opacity_values.insert(old, 0.5);
            c.scrollbar_v_opacity_keys
                .insert((d, old), OpacityKey::unique());
            c.scrollbar_h_opacity_keys
                .insert((d, old), OpacityKey::unique());
            c.scrollbar_v_opacity_values.insert((d, old), 0.25);
            c.scrollbar_h_opacity_values.insert((d, old), 0.75);
        }
        m.remap_node_ids(d, &NodeIdMap::from_pairs([(old, new)]));
        let c = m.get_cache(d).unwrap();
        assert!(c.transform_keys.contains_key(&new));
        assert_eq!(c.current_transform_values.get(&new), Some(&tx(0.0, 1.0)));
        assert!(c.h_transform_keys.contains_key(&new));
        assert_eq!(c.h_current_transform_values.get(&new), Some(&tx(2.0, 0.0)));
        assert!(c.css_transform_keys.contains_key(&new));
        assert_eq!(
            c.css_current_transform_values.get(&new),
            Some(&tx(3.0, 3.0))
        );
        assert!(c.opacity_keys.contains_key(&new));
        assert_eq!(c.current_opacity_values.get(&new), Some(&0.5));
        assert!(c.scrollbar_v_opacity_keys.contains_key(&(d, new)));
        assert!(c.scrollbar_h_opacity_keys.contains_key(&(d, new)));
        assert_eq!(c.scrollbar_v_opacity_values.get(&(d, new)), Some(&0.25));
        assert_eq!(c.scrollbar_h_opacity_values.get(&(d, new)), Some(&0.75));
        // ...and nothing is left behind under the old id.
        assert!(!c.transform_keys.contains_key(&old));
        assert!(!c.current_opacity_values.contains_key(&old));
        assert!(!c.scrollbar_v_opacity_values.contains_key(&(d, old)));
    }
    #[test]
    fn remap_node_ids_drops_the_gpu_keys_of_an_unmounted_node() {
        let mut m = GpuStateManager::default();
        let gone = NodeId::new(1);
        let d = dom(0);
        {
            let c = m.get_or_create_cache(d);
            c.transform_keys.insert(gone, TransformKey::unique());
            c.current_transform_values.insert(gone, tx(0.0, 1.0));
            c.scrollbar_v_opacity_values.insert((d, gone), 1.0);
        }
        // Empty map == every node unmounted.
        m.remap_node_ids(d, &no_survivors());
        let c = m.get_cache(d).unwrap();
        assert!(c.transform_keys.is_empty());
        assert!(c.current_transform_values.is_empty());
        assert!(c.scrollbar_v_opacity_values.is_empty());
    }
    // ------------------------------------------------------------------
    // update_scrollbar_transforms
    // ------------------------------------------------------------------
    #[test]
    fn update_scrollbar_transforms_on_an_empty_tree_yields_no_events() {
        let mut m = GpuStateManager::default();
        let sm = ScrollManager::new();
        let t = tree(Vec::new(), Vec::new());
        let changes = m.update_scrollbar_transforms(dom(0), &sm, &t);
        assert!(changes.is_empty());
        // ...but the cache is created (get_or_create_cache runs unconditionally).
        assert!(m.get_cache(dom(0)).is_some());
    }
    #[test]
    fn nodes_without_scrollbar_info_or_without_a_dom_node_id_are_skipped() {
        let mut m = GpuStateManager::default();
        let sm = ScrollManager::new();
        let t = tree(
            vec![
                // has scrollbar info but is an anonymous box (no dom_node_id)
                hot(None, Some(LogicalSize::new(100.0, 100.0))),
                // has a dom_node_id but no scrollbar info
                hot(Some(NodeId::new(2)), Some(LogicalSize::new(100.0, 100.0))),
            ],
            vec![
                warm_node(Some(v_scrollbar()), Some(LogicalSize::new(100.0, 1000.0))),
                warm_node(None, None),
            ],
        );
        let changes = m.update_scrollbar_transforms(dom(0), &sm, &t);
        assert!(changes.is_empty());
        assert!(m.get_cache(dom(0)).unwrap().transform_keys.is_empty());
    }
    #[test]
    fn a_warm_array_shorter_than_the_node_array_does_not_index_out_of_bounds() {
        // Mismatched SoA lengths: `warm(idx)` returns None for the tail nodes and
        // they must be skipped, not panic.
        let mut m = GpuStateManager::default();
        let sm = ScrollManager::new();
        let t = tree(
            vec![
                hot(Some(NodeId::new(1)), Some(LogicalSize::new(100.0, 100.0))),
                hot(Some(NodeId::new(2)), Some(LogicalSize::new(100.0, 100.0))),
            ],
            // only one warm entry for two hot nodes
            vec![warm_node(
                Some(v_scrollbar()),
                Some(LogicalSize::new(100.0, 1000.0)),
            )],
        );
        let changes = m.update_scrollbar_transforms(dom(0), &sm, &t);
        assert_eq!(
            changes.transform_key_changes.len(),
            1,
            "only node 0 is seen"
        );
    }
    #[test]
    fn a_vertical_scrollbar_at_scroll_zero_parks_the_thumb_at_offset_zero() {
        let mut m = GpuStateManager::default();
        let sm = ScrollManager::new();
        let t = one_node_tree(v_scrollbar(), LogicalSize::new(100.0, 1000.0));
        let changes = m.update_scrollbar_transforms(dom(0), &sm, &t);
        // No scroll state registered at all -> get_current_offset() is None ->
        // unwrap_or_default() -> (0, 0). Thumb sits at the top.
        assert_eq!(sole_added_y(&changes), 0.0);
    }
    #[test]
    fn scrolling_to_the_bottom_drives_the_thumb_to_the_end_of_the_usable_track() {
        // inner 100x100, content 100x1000, 16px bar with 16px buttons:
        //   usable_track = 100 - 2*16 = 68
        //   thumb        = max(68 * (100/1000), 16*2) = 32
        //   max_scroll   = 1000 - 100 = 900
        // At full scroll the thumb must land exactly at 68 - 32 = 36, never past it.
        let mut m = GpuStateManager::default();
        let mut sm = ScrollManager::new();
        sm.set_scroll_position_unclamped(
            dom(0),
            NodeId::new(1),
            LogicalPosition::new(0.0, 900.0),
            t0(),
        );
        let t = one_node_tree(v_scrollbar(), LogicalSize::new(100.0, 1000.0));
        let y = sole_added_y(&m.update_scrollbar_transforms(dom(0), &sm, &t));
        assert!((y - 36.0).abs() < 0.01, "expected thumb at 36.0, got {y}");
    }
    #[test]
    fn an_overscrolled_offset_clamps_the_thumb_instead_of_running_off_the_track() {
        // Rubber-banding pushes the offset far past max_scroll; scroll_ratio is
        // clamped to [0, 1] so the thumb must stop at the same 36.0.
        let mut m = GpuStateManager::default();
        let mut sm = ScrollManager::new();
        sm.set_scroll_position_unclamped(
            dom(0),
            NodeId::new(1),
            LogicalPosition::new(0.0, 1.0e9),
            t0(),
        );
        let t = one_node_tree(v_scrollbar(), LogicalSize::new(100.0, 1000.0));
        let y = sole_added_y(&m.update_scrollbar_transforms(dom(0), &sm, &t));
        assert!((y - 36.0).abs() < 0.01, "overscroll must clamp, got {y}");
    }
    #[test]
    fn a_negative_overscroll_offset_parks_the_thumb_at_the_top_of_the_track() {
        // Rubber-banding *above* the top is the only source of a negative offset.
        // The ratio clamp pins the thumb at 0 — it must not mirror the pull into
        // the 36.0 that the equivalent positive offset produces.
        let mut m = GpuStateManager::default();
        let mut sm = ScrollManager::new();
        sm.set_scroll_position_unclamped(
            dom(0),
            NodeId::new(1),
            LogicalPosition::new(0.0, -900.0),
            t0(),
        );
        let t = one_node_tree(v_scrollbar(), LogicalSize::new(100.0, 1000.0));
        let y = sole_added_y(&m.update_scrollbar_transforms(dom(0), &sm, &t));
        assert!(y >= 0.0, "thumb offset must never go negative, got {y}");
        assert!(
            y.abs() < 0.01,
            "an overscroll above the top must leave the thumb at the start, got {y}"
        );
    }
    #[test]
    fn a_virtual_view_thumb_is_sized_from_the_virtual_scroll_size_like_paint_scrollbars() {
        // A VirtualView is a replaced element with no flow content, so its laid-out
        // content size IS the viewport and `get_content_size` alone reports "nothing
        // to scroll" (full-length thumb parked at 0). `paint_scrollbars` seeds the
        // transform key from `ScrollPosition::children_rect.size`, which carries the
        // callback's virtual size; this path overwrites that key on every live
        // scroll, so both must land on the same thumb offset.
        const NODE: NodeId = NodeId::new(1);
        let mut m = GpuStateManager::default();
        let mut sm = ScrollManager::new();
        sm.register_or_update_scroll_node(
            dom(0),
            NODE,
            LogicalRect::new(
                LogicalPosition::new(250.0, 120.0),
                LogicalSize::new(100.0, 100.0),
            ),
            LogicalSize::new(100.0, 100.0),
            t0(),
            16.0,
            16.0,
            false,
            true,
        );
        sm.update_virtual_scroll_bounds(dom(0), NODE, LogicalSize::new(100.0, 1000.0), None);
        sm.set_scroll_position(dom(0), NODE, LogicalPosition::new(0.0, 450.0), t0());
        // The layout tree only ever saw the viewport-sized content box.
        let t = one_node_tree(v_scrollbar(), LogicalSize::new(100.0, 100.0));
        let y = sole_added_y(&m.update_scrollbar_transforms(dom(0), &sm, &t));
        // ...what display_list::paint_scrollbars computes for the same node.
        let states = sm.get_scroll_states_for_dom(dom(0));
        let pos = states
            .get(&NODE)
            .expect("the node must report a scroll state");
        assert_eq!(pos.children_rect.size, LogicalSize::new(100.0, 1000.0));
        let painted = compute_scrollbar_geometry_with_button_size(
            ScrollbarOrientation::Vertical,
            LogicalRect::new(LogicalPosition::zero(), LogicalSize::new(100.0, 100.0)),
            pos.children_rect.size,
            pos.children_rect.origin.y,
            16.0,
            false,
            16.0,
        );
        // Both producers of the thumb TRANSFORM quantise (see
        // `quantize_thumb_offset`), so the agreement is asserted against the
        // painter's quantised value — comparing against the raw geometry would
        // make this pass only for fixtures whose offset happens to be integral.
        let painted_transform =
            crate::solver3::scrollbar::quantize_thumb_offset(painted.thumb_offset);
        assert!(
            (y - painted_transform).abs() < 0.01,
            "GPU path put the thumb at {y}, the painter at {painted_transform}"
        );
        // usable = 100 - 2*16 = 68, thumb = max(68 * 100/1000, 32) = 32,
        // max_scroll = 1000 - 100 = 900 -> half scroll = (68 - 32) * 0.5 = 18.
        // Sizing from the laid-out 100x100 instead gives max_scroll 0 and a
        // full-track thumb parked at 0.
        assert!(
            (y - 18.0).abs() < 0.01,
            "expected the half-track thumb at 18.0, got {y}"
        );
    }
    #[test]
    fn an_auto_virtual_view_agrees_on_the_flag_the_painted_thumb_and_the_gpu_thumb() {
        // The half-landed state this pins: `paint_scrollbars` raised its own
        // booleans locally and drew a bar, while this path kept gating on the
        // layout-computed `warm.scrollbar_info.needs_*` — all-false for an
        // `auto` VirtualView — so the thumb froze at the display list's seed
        // value on every live scroll. One function now decides, and
        // `register_scroll_nodes` stores the decision where this path reads it.
        const NODE: NodeId = NodeId::new(1);
        let styled_dom = auto_virtual_view_dom();
        // 1. Layout ran: the VirtualView's box is 100x100 and its laid-out content is the same
        //    100x100, so no bar is warranted yet.
        let mut t = one_node_tree(auto_no_scrollbar(), LogicalSize::new(100.0, 100.0));
        // 2. The VirtualView callback published a 100x1000 document.
        let mut sm = ScrollManager::new();
        sm.update_virtual_scroll_bounds(dom(0), NODE, LogicalSize::new(100.0, 1000.0), None);
        // 3. What `register_scroll_nodes` then does: amend the flags from the virtual size and
        //    store the answer back on the node, which is what makes the node registrable at all
        //    (the old gate skipped it, so its container_rect stayed zero and its clamp bound was
        //    the whole virtual size).
        let states = sm.get_scroll_states_for_dom(dom(0));
        let pos = states
            .get(&NODE)
            .expect("the callback created a scroll state");
        let mut info = t
            .warm(LayoutNodeId::new(0))
            .and_then(|w| w.scrollbar_info)
            .expect("layout stored one");
        assert!(
            apply_virtual_scroll_necessity(
                &styled_dom,
                NODE,
                pos.children_rect.size,
                LogicalSize::new(100.0, 100.0),
                &mut info,
            ),
            "a 1000px document in a 100px auto viewport needs a bar"
        );
        assert!(
            info.needs_vertical,
            "the amended flag is the one the GPU path gates on"
        );
        assert!(
            !info.needs_horizontal,
            "overflow-x: hidden must not gain a bar"
        );
        assert_eq!(
            (info.scrollbar_width, info.scrollbar_height),
            (0.0, 0.0),
            "no layout gutter is reserved after the fact — the bar overlays"
        );
        t.warm_mut(LayoutNodeId::new(0))
            .expect("the fixture has a warm node")
            .scrollbar_info = Some(info);
        sm.register_or_update_scroll_node(
            dom(0),
            NODE,
            LogicalRect::new(
                LogicalPosition::new(250.0, 120.0),
                LogicalSize::new(100.0, 100.0),
            ),
            LogicalSize::new(100.0, 100.0),
            t0(),
            info.scrollbar_width.max(info.scrollbar_height),
            info.visual_width_px,
            info.needs_horizontal,
            info.needs_vertical,
        );
        // 4. Half a document down.
        sm.set_scroll_position(dom(0), NODE, LogicalPosition::new(0.0, 450.0), t0());
        let mut m = GpuStateManager::default();
        let y = sole_added_y(&m.update_scrollbar_transforms(dom(0), &sm, &t));
        // ...and what `paint_scrollbars` computes for the same node from the
        // same ScrollPosition: overlay bar (scrollbar_height == 0) => no arrow
        // buttons on either path.
        let states = sm.get_scroll_states_for_dom(dom(0));
        let pos = states.get(&NODE).expect("the node is registered now");
        let painted = compute_scrollbar_geometry_with_button_size(
            ScrollbarOrientation::Vertical,
            LogicalRect::new(LogicalPosition::zero(), LogicalSize::new(100.0, 100.0)),
            pos.children_rect.size,
            pos.children_rect.origin.y,
            info.visual_width_px,
            info.needs_horizontal,
            0.0,
        );
        // Both producers of the thumb TRANSFORM quantise (see
        // `quantize_thumb_offset`), so the agreement is asserted against the
        // painter's quantised value — comparing against the raw geometry would
        // make this pass only for fixtures whose offset happens to be integral.
        let painted_transform =
            crate::solver3::scrollbar::quantize_thumb_offset(painted.thumb_offset);
        assert!(
            (y - painted_transform).abs() < 0.01,
            "GPU path put the thumb at {y}, the painter at {painted_transform}"
        );
        // usable track = 100 (no buttons), thumb = max(100 * 100/1000, 2*16) = 32,
        // max_scroll = 900 -> half travel = (100 - 32) * 0.5 = 34.
        assert!(
            (y - 34.0).abs() < 0.01,
            "expected the half-track thumb at 34.0, got {y}"
        );
        // The pre-fix tree — layout's flags, unamended — emits nothing at all,
        // which is exactly the frozen thumb under a painted bar.
        let stale = one_node_tree(auto_no_scrollbar(), LogicalSize::new(100.0, 100.0));
        let mut fresh = GpuStateManager::default();
        assert!(
            fresh
                .update_scrollbar_transforms(dom(0), &sm, &stale)
                .is_empty(),
            "without the amendment the GPU path never sees the bar"
        );
    }
    #[test]
    fn running_the_same_layout_twice_emits_no_second_event() {
        // The convergence invariant: a static scroll position must not generate
        // GPU traffic every frame.
        let mut m = GpuStateManager::default();
        let sm = ScrollManager::new();
        let t = one_node_tree(v_scrollbar(), LogicalSize::new(100.0, 1000.0));
        let first = m.update_scrollbar_transforms(dom(0), &sm, &t);
        assert_eq!(first.transform_key_changes.len(), 1);
        for _ in 0..5 {
            let again = m.update_scrollbar_transforms(dom(0), &sm, &t);
            assert!(again.is_empty(), "an idle scrollbar must stay silent");
        }
    }
    #[test]
    fn scrolling_after_a_first_pass_emits_changed_and_reuses_the_key() {
        let mut m = GpuStateManager::default();
        let mut sm = ScrollManager::new();
        let t = one_node_tree(v_scrollbar(), LogicalSize::new(100.0, 1000.0));
        m.update_scrollbar_transforms(dom(0), &sm, &t);
        let key = m
            .get_cache(dom(0))
            .unwrap()
            .transform_keys
            .get(&NodeId::new(1))
            .copied()
            .unwrap();
        sm.set_scroll_position_unclamped(
            dom(0),
            NodeId::new(1),
            LogicalPosition::new(0.0, 900.0),
            t0(),
        );
        let changes = m.update_scrollbar_transforms(dom(0), &sm, &t);
        assert_eq!(changes.transform_key_changes.len(), 1);
        match changes.transform_key_changes[0] {
            GpuTransformKeyEvent::Changed(node, k, old, new) => {
                assert_eq!(node, NodeId::new(1));
                assert_eq!(k, key, "the key must be reused across the scroll");
                assert_eq!(old.m[3][1], 0.0);
                assert!((new.m[3][1] - 36.0).abs() < 0.01);
            }
            ref other => panic!("expected Changed, got {other:?}"),
        }
    }
    #[test]
    fn a_horizontal_scrollbar_translates_on_x_and_leaves_y_at_zero() {
        let mut m = GpuStateManager::default();
        let mut sm = ScrollManager::new();
        sm.set_scroll_position_unclamped(
            dom(0),
            NodeId::new(1),
            LogicalPosition::new(900.0, 0.0),
            t0(),
        );
        let t = one_node_tree(h_scrollbar(), LogicalSize::new(1000.0, 100.0));
        let changes = m.update_scrollbar_transforms(dom(0), &sm, &t);
        let x = sole_added_x(&changes);
        assert!((x - 36.0).abs() < 0.01, "expected thumb at x=36.0, got {x}");
        // The horizontal thumb must be filed under the h_* maps, not the v_* ones.
        let c = m.get_cache(dom(0)).unwrap();
        assert!(c.h_transform_keys.contains_key(&NodeId::new(1)));
        assert!(c.transform_keys.is_empty());
    }
    #[test]
    fn a_node_needing_both_scrollbars_gets_two_independent_keys_and_two_events() {
        let mut m = GpuStateManager::default();
        let sm = ScrollManager::new();
        let both = ScrollbarRequirements {
            needs_horizontal: true,
            needs_vertical: true,
            scrollbar_width: 16.0,
            scrollbar_height: 16.0,
            visual_width_px: 16.0,
        };
        let t = one_node_tree(both, LogicalSize::new(1000.0, 1000.0));
        let changes = m.update_scrollbar_transforms(dom(0), &sm, &t);
        assert_eq!(changes.transform_key_changes.len(), 2);
        let c = m.get_cache(dom(0)).unwrap();
        let node = NodeId::new(1);
        let v = c.transform_keys.get(&node).copied().unwrap();
        let h = c.h_transform_keys.get(&node).copied().unwrap();
        assert_ne!(v, h);
    }
    #[test]
    fn borders_wider_than_the_border_box_clamp_the_inner_size_to_zero() {
        // 50x50 border-box with a 100px border on every side would give a -150px
        // inner size; the `.max(0.0)` must clamp it, and the geometry must stay
        // finite (no NaN thumb offset from a negative track).
        let mut m = GpuStateManager::default();
        let sm = ScrollManager::new();
        let mut node = hot(Some(NodeId::new(1)), Some(LogicalSize::new(50.0, 50.0)));
        node.box_props = PackedBoxProps {
            border: [1000, 1000, 1000, 1000], // 100.0 px each, i16 x10 encoding
            // `PackedBoxProps` grew margin/padding/margin_auto after this test
            // was written, which broke the whole azul-layout TEST build while
            // the lib kept compiling — so no layout test could run at all.
            // Zeroed: this test is about a border wider than the box.
            ..Default::default()
        };
        let t = tree(
            vec![node],
            vec![warm_node(
                Some(v_scrollbar()),
                Some(LogicalSize::new(100.0, 1000.0)),
            )],
        );
        let y = sole_added_y(&m.update_scrollbar_transforms(dom(0), &sm, &t));
        assert!(y.is_finite(), "a degenerate inner box must not yield {y}");
        assert_eq!(y, 0.0);
    }
    #[test]
    fn a_zero_sized_node_with_zero_content_does_not_divide_by_zero() {
        let mut m = GpuStateManager::default();
        let sm = ScrollManager::new();
        let t = tree(
            vec![hot(Some(NodeId::new(1)), Some(LogicalSize::zero()))],
            vec![warm_node(Some(v_scrollbar()), Some(LogicalSize::zero()))],
        );
        let y = sole_added_y(&m.update_scrollbar_transforms(dom(0), &sm, &t));
        assert!(y.is_finite());
        assert_eq!(y, 0.0);
    }
    #[test]
    fn a_missing_used_size_defaults_to_zero_rather_than_panicking() {
        let mut m = GpuStateManager::default();
        let sm = ScrollManager::new();
        let t = tree(
            vec![hot(Some(NodeId::new(1)), None)],
            vec![warm_node(Some(v_scrollbar()), None)],
        );
        let y = sole_added_y(&m.update_scrollbar_transforms(dom(0), &sm, &t));
        assert!(y.is_finite());
        assert_eq!(y, 0.0);
    }
    #[test]
    fn an_infinite_used_size_is_sanitised_instead_of_emitting_a_nan_thumb() {
        // An infinite border-box makes both the viewport and the content length
        // +inf, so compute_thumb_geometry ends at
        //   thumb_offset = (inf - inf) * 0.0 = NaN
        // This used to be fed straight into a translation matrix: combined with
        // `a_nan_transform_never_converges_...` above, one infinite used_size
        // meant the scrollbar re-emitted a Changed event on *every* frame,
        // forever, and WebRender was handed a NaN transform. The finite-guard in
        // `quantize_thumb_offset` (which the paint path applies identically) is
        // that future guard the old characterisation test was waiting for.
        let mut m = GpuStateManager::default();
        let sm = ScrollManager::new();
        let t = tree(
            vec![hot(
                Some(NodeId::new(1)),
                Some(LogicalSize::new(f32::INFINITY, f32::INFINITY)),
            )],
            vec![warm_node(Some(v_scrollbar()), None)],
        );
        let y = sole_added_y(&m.update_scrollbar_transforms(dom(0), &sm, &t));
        assert!(
            y.is_finite(),
            "a NaN must never reach the transform, got {y}"
        );
        assert_eq!(y, 0.0);
        // And it SETTLES: a second identical pass emits nothing.
        let again = m.update_scrollbar_transforms(dom(0), &sm, &t);
        assert!(
            again.transform_key_changes.is_empty(),
            "the sanitised value must converge, not re-emit Changed forever"
        );
    }
    #[test]
    fn a_nan_used_size_is_sanitised_to_zero_by_the_max_clamp() {
        // Unlike infinity, NaN *is* neutralised: f32::max(NaN, 0.0) == 0.0, so the
        // `.max(0.0)` on the inner size scrubs it before it reaches the geometry.
        let mut m = GpuStateManager::default();
        let sm = ScrollManager::new();
        let t = tree(
            vec![hot(
                Some(NodeId::new(1)),
                Some(LogicalSize::new(f32::NAN, f32::NAN)),
            )],
            vec![warm_node(Some(v_scrollbar()), None)],
        );
        let y = sole_added_y(&m.update_scrollbar_transforms(dom(0), &sm, &t));
        assert!(y.is_finite(), "NaN width/height must be clamped, got {y}");
        assert_eq!(y, 0.0);
    }
    #[test]
    fn overlay_vertical_scrollbars_fall_back_to_the_default_width() {
        // visual_width_px == 0 and no reserved space at all -> the DEFAULT_SCROLLBAR
        // _WIDTH_PX (16.0) fallback with button_size 0:
        //   usable = 100, thumb = max(100*0.1, 32) = 32, offset@full = 100 - 32 = 68
        let mut m = GpuStateManager::default();
        let mut sm = ScrollManager::new();
        sm.set_scroll_position_unclamped(
            dom(0),
            NodeId::new(1),
            LogicalPosition::new(0.0, 900.0),
            t0(),
        );
        let overlay = ScrollbarRequirements {
            needs_horizontal: false,
            needs_vertical: true,
            scrollbar_width: 0.0,
            scrollbar_height: 0.0,
            visual_width_px: 0.0,
        };
        let t = one_node_tree(overlay, LogicalSize::new(100.0, 1000.0));
        let y = sole_added_y(&m.update_scrollbar_transforms(dom(0), &sm, &t));
        assert!(
            (y - 68.0).abs() < 0.01,
            "expected the 16px default, got {y}"
        );
        assert_eq!(DEFAULT_SCROLLBAR_WIDTH_PX, 16.0);
    }
    #[test]
    fn classic_vertical_scrollbar_overlay_check_reads_the_wrong_reserved_field() {
        // BUG (characterisation). ScrollbarRequirements documents:
        //   scrollbar_width  = layout-reserved width  for a *vertical*   scrollbar
        //   scrollbar_height = layout-reserved height for a *horizontal* scrollbar
        // but the needs_vertical branch tests `scrollbar_height == 0.0` to decide
        // whether the *vertical* bar is an overlay, and falls back to
        // `scrollbar_height` for its width. The two fields are swapped.
        //
        // Repro: a classic, space-reserving vertical-only scrollbar --
        //   scrollbar_width  = 16.0  (16px reserved for the vertical bar)
        //   scrollbar_height =  0.0  (no horizontal bar -> nothing reserved)
        //   visual_width_px  =  0.0  (unset, so the fallback actually runs)
        // is misread as an overlay: button_size collapses to 0, so the usable
        // track is 100 instead of 68 and the thumb travels to 68.0 rather than the
        // correct 36.0 -- the thumb overshoots its own track by ~32px.
        let mut m = GpuStateManager::default();
        let mut sm = ScrollManager::new();
        sm.set_scroll_position_unclamped(
            dom(0),
            NodeId::new(1),
            LogicalPosition::new(0.0, 900.0),
            t0(),
        );
        let classic_vertical_only = ScrollbarRequirements {
            needs_horizontal: false,
            needs_vertical: true,
            scrollbar_width: 16.0,
            scrollbar_height: 0.0,
            visual_width_px: 0.0,
        };
        let t = one_node_tree(classic_vertical_only, LogicalSize::new(100.0, 1000.0));
        let y = sole_added_y(&m.update_scrollbar_transforms(dom(0), &sm, &t));
        assert!(
            (y - 68.0).abs() < 0.01,
            "pinning the buggy value; 36.0 once the field swap is fixed, got {y}"
        );
    }
    #[test]
    fn classic_horizontal_scrollbar_overlay_check_reads_the_wrong_reserved_field() {
        // The mirror image of the above: the needs_horizontal branch tests
        // `scrollbar_width == 0.0` (the *vertical* bar's reserved width) to decide
        // whether the *horizontal* bar is an overlay.
        let mut m = GpuStateManager::default();
        let mut sm = ScrollManager::new();
        sm.set_scroll_position_unclamped(
            dom(0),
            NodeId::new(1),
            LogicalPosition::new(900.0, 0.0),
            t0(),
        );
        let classic_horizontal_only = ScrollbarRequirements {
            needs_horizontal: true,
            needs_vertical: false,
            scrollbar_width: 0.0,
            scrollbar_height: 16.0,
            visual_width_px: 0.0,
        };
        let t = one_node_tree(classic_horizontal_only, LogicalSize::new(1000.0, 100.0));
        let x = sole_added_x(&m.update_scrollbar_transforms(dom(0), &sm, &t));
        assert!(
            (x - 68.0).abs() < 0.01,
            "pinning the buggy value; 36.0 once the field swap is fixed, got {x}"
        );
    }
    #[test]
    fn transforms_are_recorded_per_dom_and_do_not_leak_across_caches() {
        let mut m = GpuStateManager::default();
        let sm = ScrollManager::new();
        let t = one_node_tree(v_scrollbar(), LogicalSize::new(100.0, 1000.0));
        let a = m.update_scrollbar_transforms(dom(0), &sm, &t);
        let b = m.update_scrollbar_transforms(dom(1), &sm, &t);
        // The same layout tree under a different DomId is a *different* cache, so
        // it must Add (not stay silent) and mint its own key.
        assert_eq!(a.transform_key_changes.len(), 1);
        assert_eq!(b.transform_key_changes.len(), 1);
        assert_eq!(m.caches.len(), 2);
        let node = NodeId::new(1);
        let ka = m.get_cache(dom(0)).unwrap().transform_keys[&node];
        let kb = m.get_cache(dom(1)).unwrap().transform_keys[&node];
        assert_ne!(ka, kb, "each DOM must get its own TransformKey");
    }
    #[test]
    fn update_scrollbar_transforms_does_not_touch_pending_changes() {
        // The function *returns* its changes; it must not also stash them, or the
        // renderer would apply every event twice.
        let mut m = GpuStateManager::default();
        let sm = ScrollManager::new();
        let t = one_node_tree(v_scrollbar(), LogicalSize::new(100.0, 1000.0));
        let changes = m.update_scrollbar_transforms(dom(0), &sm, &t);
        assert!(!changes.is_empty());
        assert!(
            m.pending_changes.is_empty(),
            "returned events must not be double-queued"
        );
    }
    #[test]
    fn a_thousand_scrollable_nodes_each_get_exactly_one_distinct_key() {
        let mut m = GpuStateManager::default();
        let sm = ScrollManager::new();
        let n = 1000;
        let t = tree(
            (0..n)
                .map(|i| hot(Some(NodeId::new(i)), Some(LogicalSize::new(100.0, 100.0))))
                .collect(),
            (0..n)
                .map(|_| warm_node(Some(v_scrollbar()), Some(LogicalSize::new(100.0, 1000.0))))
                .collect(),
        );
        let changes = m.update_scrollbar_transforms(dom(0), &sm, &t);
        assert_eq!(changes.transform_key_changes.len(), n);
        let cache = m.get_cache(dom(0)).unwrap();
        assert_eq!(cache.transform_keys.len(), n);
        let mut keys: Vec<_> = cache.transform_keys.values().map(|k| k.id).collect();
        keys.sort_unstable();
        keys.dedup();
        assert_eq!(keys.len(), n, "every node must get a unique TransformKey");
    }
    #[test]
    fn two_layout_nodes_sharing_one_dom_node_id_fight_over_a_single_key() {
        // Anonymous-box splitting can produce two layout nodes pointing at the same
        // DOM node. The cache keys off dom_node_id, not the layout index, so the
        // second node is misread as a *change* to the first: one key, two events
        // in a single pass, and the last node in tree order silently wins.
        //
        //   node 0: inner 100x100, content 100x1000 -> thumb 36.0
        //   node 1: inner 200x200, content 200x2000 -> thumb 68.0
        let mut m = GpuStateManager::default();
        let mut sm = ScrollManager::new();
        sm.set_scroll_position_unclamped(
            dom(0),
            NodeId::new(1),
            LogicalPosition::new(0.0, 900.0),
            t0(),
        );
        let t = tree(
            vec![
                hot(Some(NodeId::new(1)), Some(LogicalSize::new(100.0, 100.0))),
                hot(Some(NodeId::new(1)), Some(LogicalSize::new(200.0, 200.0))),
            ],
            vec![
                warm_node(Some(v_scrollbar()), Some(LogicalSize::new(100.0, 1000.0))),
                warm_node(Some(v_scrollbar()), Some(LogicalSize::new(200.0, 2000.0))),
            ],
        );
        let changes = m.update_scrollbar_transforms(dom(0), &sm, &t);
        assert_eq!(
            m.get_cache(dom(0)).unwrap().transform_keys.len(),
            1,
            "both layout nodes collapse onto one TransformKey"
        );
        assert!(matches!(
            changes.transform_key_changes.as_slice(),
            [
                GpuTransformKeyEvent::Added(..),
                GpuTransformKeyEvent::Changed(..)
            ]
        ));
        // The second node overwrote the first within the same pass.
        let stored = m.get_cache(dom(0)).unwrap().current_transform_values[&NodeId::new(1)];
        assert!((stored.m[3][1] - 68.0).abs() < 0.01);
    }
}