Lines
96.72 %
Functions
87.33 %
Branches
100 %
//! Centralized GPU state management.
//!
//! This module provides management of GPU property keys
//! (opacity, transforms, etc.), fade-in/fade-out animations
//! for scrollbar opacity - as a single source of truth for
//! the GPU cache.
use alloc::collections::BTreeMap;
#[cfg(not(feature = "std"))]
use alloc::collections::BTreeMap as HashMap;
#[cfg(feature = "std")]
use std::collections::HashMap;
use azul_core::{
dom::{DomId, NodeId, ScrollbarOrientation},
geom::{LogicalPosition, LogicalRect, LogicalSize},
gpu::{GpuEventChanges, GpuTransformKeyEvent, GpuValueCache},
resources::TransformKey,
task::{Duration, SystemTimeDiff},
transform::ComputedTransform3D,
};
use crate::{
managers::scroll_state::ScrollManager,
solver3::{
fc::DEFAULT_SCROLLBAR_WIDTH_PX,
layout_tree::{LayoutNodeId, LayoutTree},
scrollbar::compute_scrollbar_geometry_with_button_size,
},
/// Default delay before scrollbars start fading out (500ms)
pub const DEFAULT_FADE_DELAY_MS: u64 = 500;
/// Default duration of scrollbar fade-out animation (200ms)
pub const DEFAULT_FADE_DURATION_MS: u64 = 200;
/// Manages GPU-accelerated properties across all DOMs.
///
/// The `GpuStateManager` maintains caches for transform and opacity keys
/// that are used by the GPU renderer. It handles:
/// - Scrollbar thumb position transforms (updated on scroll)
/// - Opacity fading for scrollbars (fade in on activity, fade out after delay)
/// - Per-DOM GPU value caches for efficient rendering
/// A tiny FNV-1a accumulator for "is this the same payload I sent last frame?".
/// Floats go in BITWISE (`to_bits`): a NaN opacity compares unequal to itself
/// and would reinstate the very redraw loop this exists to break.
#[derive(Debug, Copy, Clone)]
pub struct FrameDigest(u64);
impl Default for FrameDigest {
fn default() -> Self {
Self::new()
}
impl FrameDigest {
#[must_use]
pub const fn new() -> Self {
Self(0xcbf2_9ce4_8422_2325)
pub fn push_u64(&mut self, v: u64) {
for b in v.to_le_bytes() {
self.0 ^= u64::from(b);
self.0 = self.0.wrapping_mul(0x0000_0100_0000_01B3);
pub fn push_f32(&mut self, v: f32) {
self.push_u64(u64::from(v.to_bits()));
pub const fn finish(&self) -> u64 {
self.0
/// Which of the renderer submissions [`GpuStateManager::submitted_digest_changed`]
/// is being asked about.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum SubmittedDigest {
/// Image keys registered / updated on the transaction.
Images,
/// Scroll offsets pushed to `WebRender`'s scroll frames.
ScrollOffsets,
#[derive(Debug, Clone)]
pub struct GpuStateManager {
/// GPU value caches indexed by DOM ID
pub caches: BTreeMap<DomId, GpuValueCache>,
/// Delay before scrollbars start fading out after last activity
pub fade_delay: Duration,
/// Duration of the fade-out animation
pub fade_duration: Duration,
/// Whether any scrollbar has non-zero opacity and needs continued frame
/// generation. Set during both the `fade_delay` period (opacity == 1.0)
/// and the active fade-out phase (0 < opacity < 1).
/// Set by `LayoutWindow::synchronize_scrollbar_opacity`, read by the platform render loop.
pub scrollbar_fade_active: bool,
/// Digest of the dynamic properties (scrollbar opacities + transforms)
/// last handed to the renderer, so an IDENTICAL set can be recognised and
/// skipped. See [`GpuStateManager::gpu_values_changed`].
pub last_gpu_value_digest: Option<u64>,
/// Digest of the image registrations last handed to the renderer.
/// See [`GpuStateManager::submitted_digest_changed`].
pub last_image_digest: Option<u64>,
/// Digest of the scroll offsets last handed to the renderer.
pub last_scroll_digest: Option<u64>,
/// GPU events produced during layout (CSS transform / opacity synchronization,
/// scrollbar transform / opacity updates) that have not yet been pushed to
/// the renderer. Drained by the platform render path when a transaction is
/// built.
pub pending_changes: GpuEventChanges,
impl Default for GpuStateManager {
Self::new(
Duration::System(SystemTimeDiff::from_millis(DEFAULT_FADE_DELAY_MS)),
Duration::System(SystemTimeDiff::from_millis(DEFAULT_FADE_DURATION_MS)),
)
impl GpuStateManager {
/// Have the dynamic GPU properties changed since they were last submitted?
/// THE IDLE REDRAW LOOP THIS EXISTS TO BREAK. The lightweight transaction
/// path — taken precisely because nothing needs rebuilding — pushed these
/// values and then asked `WebRender` for a frame unconditionally.
/// `WebRender`
/// built one, signalled `new_frame_ready`, the backend woke and presented,
/// and the present ran the lightweight path again. Measured idle on
/// `X11`/GPU: 1087 submissions, 1087 frame-ready signals, 1086 presents, all
/// carrying the same two floats and two transforms — ~59 fps of full
/// render+present for a window nobody was touching.
/// Floats are compared BITWISE (`to_bits`), not by value: a NaN opacity
/// compares unequal to itself and would reinstate the loop it is meant to
/// prevent.
/// Returns `true` the first time (nothing to compare against) and whenever
/// the set genuinely differs — a changed value, a new key, or a lost one.
pub fn gpu_values_changed(
&mut self,
floats: &[(u64, f32)],
transforms: &[(u64, [f32; 16])],
) -> bool {
// Sorted by key before digesting. The caller collects these out of
// `HashMap`s, whose iteration order is not a promise; an order that
// flapped while the values stayed the same would report a change on a
// frame that changed nothing, and the loop would be back.
let mut sorted_floats = floats.iter().collect::<Vec<_>>();
sorted_floats.sort_unstable_by_key(|(k, _)| *k);
let mut sorted_transforms = transforms.iter().collect::<Vec<_>>();
sorted_transforms.sort_unstable_by_key(|(k, _)| *k);
let mut h = FrameDigest::new();
h.push_u64(floats.len() as u64);
for (k, v) in sorted_floats {
h.push_u64(*k);
h.push_f32(*v);
h.push_u64(transforms.len() as u64);
for (k, m) in sorted_transforms {
for f in m {
h.push_f32(*f);
let digest = h.finish();
if self.last_gpu_value_digest == Some(digest) {
return false;
self.last_gpu_value_digest = Some(digest);
true
/// Same idea as [`Self::gpu_values_changed`] for the other two things a
/// "nothing was rebuilt" transaction carries: image registrations and
/// scroll offsets. The caller digests its own payload (the types live in
/// the renderer crate); this only owns the remembering.
/// `slot` picks which of the two is meant.
pub fn submitted_digest_changed(&mut self, slot: SubmittedDigest, digest: u64) -> bool {
let stored = match slot {
SubmittedDigest::Images => &mut self.last_image_digest,
SubmittedDigest::ScrollOffsets => &mut self.last_scroll_digest,
if *stored == Some(digest) {
*stored = Some(digest);
/// Forget what was last submitted, so the next submission pushes
/// everything again.
/// The full-frame path MUST call this before it builds: a scene rebuild
/// gives `WebRender` a new display list whose property bindings start from
/// the values baked into the list, and "identical to what I sent last
/// time" is then the wrong question — the values have to be re-pushed even
/// though they did not change.
pub const fn invalidate_submitted_digests(&mut self) {
self.last_gpu_value_digest = None;
self.last_image_digest = None;
self.last_scroll_digest = None;
/// Creates a new GPU state manager with specified fade timing.
pub fn new(fade_delay: Duration, fade_duration: Duration) -> Self {
Self {
caches: BTreeMap::new(),
fade_delay,
fade_duration,
scrollbar_fade_active: false,
last_gpu_value_digest: None,
last_image_digest: None,
last_scroll_digest: None,
pending_changes: GpuEventChanges::empty(),
/// Take any queued transform / opacity events that have been accumulated
/// during layout. Clears the internal buffer.
pub fn take_pending_changes(&mut self) -> GpuEventChanges {
core::mem::take(&mut self.pending_changes)
// NOTE: the per-frame scrollbar-fade interpolation lives in
// `LayoutWindow::synchronize_scrollbar_opacity` (layout/src/window.rs),
// which reads the last-activity time straight from the `ScrollManager` and
// is the single source of truth for fade opacity. An earlier duplicate
// tick-based subsystem here (`tick` / `record_scroll_activity` /
// `calculate_fade_opacity` + a `fade_states` map) was never wired into any
// render loop and has been removed.
/// Gets or creates the GPU cache for a specific DOM.
pub fn get_cache(&self, dom_id: DomId) -> Option<&GpuValueCache> {
self.caches.get(&dom_id)
pub fn get_or_create_cache(&mut self, dom_id: DomId) -> &mut GpuValueCache {
self.caches.entry(dom_id).or_default()
/// Updates scrollbar thumb transforms based on current scroll positions.
/// Calculates the transform needed to position scrollbar thumbs correctly
/// based on the scroll offset and content/container sizes. Returns the
/// GPU event changes that need to be applied by the renderer.
pub fn update_scrollbar_transforms(
dom_id: DomId,
scroll_manager: &ScrollManager,
layout_tree: &LayoutTree,
) -> GpuEventChanges {
let mut changes = GpuEventChanges::empty();
let gpu_cache = self.get_or_create_cache(dom_id);
for (node_idx, node) in layout_tree.nodes.iter().enumerate() {
let warm = layout_tree.warm(LayoutNodeId::new(node_idx));
// The necessity flags are the layout pass's, amended after layout by
// `cache::apply_virtual_scroll_necessity` (via `register_scroll_nodes`)
// for a `VirtualView`, whose scrollable extent layout cannot see. This
// path deliberately re-derives nothing: it reads the one stored answer,
// so a bar that `paint_scrollbars` drew always gets its thumb moved.
let Some(scrollbar_info) = warm.and_then(|w| w.scrollbar_info.as_ref()) else {
continue;
let Some(node_id) = node.dom_node_id else {
let scroll_offset = scroll_manager
.get_current_offset(dom_id, node_id)
.unwrap_or_default();
// Compute inner_rect (padding-box) by subtracting borders from used_size
let border_box_size = node.used_size.unwrap_or_default();
let nbp = node.box_props.unpack();
let border = &nbp.border;
let inner_size = LogicalSize {
width: (border_box_size.width - border.left - border.right).max(0.0),
height: (border_box_size.height - border.top - border.bottom).max(0.0),
// Use zero origin since we only need the geometry ratios, not absolute position
let inner_rect = LogicalRect {
origin: LogicalPosition::new(0.0, 0.0),
size: inner_size,
// `display_list::paint_scrollbars` sizes the thumb from
// `ScrollPosition::children_rect.size` — the `VirtualView` virtual size
// when the callback reported one, else the laid-out content size. This
// path OVERWRITES the transform key that path seeds, so it has to size
// from the same number: a `VirtualView` is a replaced element with no
// flow content, so `get_content_size` returns roughly the viewport and
// the thumb would snap to the full track on the first live scroll.
let content_size = scroll_manager
.get_scroll_state(dom_id, node_id)
.and_then(|s| s.virtual_scroll_size)
.unwrap_or_else(|| layout_tree.get_content_size(LayoutNodeId::new(node_idx)));
if scrollbar_info.needs_vertical {
// Use the visual width from the scrollbar style — same value used
// by display_list.rs to paint the scrollbar. For overlay scrollbars,
// visual_width_px is non-zero (e.g. 8.0) even though the layout-
// reserved width (scrollbar_height) is 0.0.
let is_overlay = scrollbar_info.scrollbar_height == 0.0;
let scrollbar_width_px = if scrollbar_info.visual_width_px > 0.0 {
scrollbar_info.visual_width_px
} else if !is_overlay {
scrollbar_info.scrollbar_height
} else {
DEFAULT_SCROLLBAR_WIDTH_PX
// Overlay scrollbars (macOS-style) have no arrow buttons
let button_size = if is_overlay { 0.0 } else { scrollbar_width_px };
let v_geom = compute_scrollbar_geometry_with_button_size(
ScrollbarOrientation::Vertical,
inner_rect,
content_size,
scroll_offset.y,
scrollbar_width_px,
scrollbar_info.needs_horizontal,
button_size,
);
// Quantised to whole logical pixels: this value is the only
// channel that can damage the bar, and a sub-pixel thumb move
// repaints a gutter that did not visibly change. See
// `quantize_thumb_offset` — `paint_scrollbars` bakes the
// display list's initial value through the same rounding.
let transform = ComputedTransform3D::new_translation(
0.0,
crate::solver3::scrollbar::quantize_thumb_offset(v_geom.thumb_offset),
update_scrollbar_transform_key(
gpu_cache,
&mut changes,
node_id,
transform,
if scrollbar_info.needs_horizontal {
let is_overlay = scrollbar_info.scrollbar_width == 0.0;
scrollbar_info.scrollbar_width
let h_geom = compute_scrollbar_geometry_with_button_size(
ScrollbarOrientation::Horizontal,
scroll_offset.x,
scrollbar_info.needs_vertical,
crate::solver3::scrollbar::quantize_thumb_offset(h_geom.thumb_offset),
changes
/// Updates or creates a scrollbar transform key in the GPU cache for the given orientation.
fn update_scrollbar_transform_key(
gpu_cache: &mut GpuValueCache,
changes: &mut GpuEventChanges,
node_id: NodeId,
transform: ComputedTransform3D,
orientation: ScrollbarOrientation,
) {
let (keys, values) = match orientation {
ScrollbarOrientation::Vertical => (
&mut gpu_cache.transform_keys,
&mut gpu_cache.current_transform_values,
),
ScrollbarOrientation::Horizontal => (
&mut gpu_cache.h_transform_keys,
&mut gpu_cache.h_current_transform_values,
if let Some(existing_transform) = values.get(&node_id) {
if *existing_transform != transform {
let Some(&transform_key) = keys.get(&node_id) else {
return;
.transform_key_changes
.push(GpuTransformKeyEvent::Changed(
transform_key,
*existing_transform,
));
values.insert(node_id, transform);
let transform_key = TransformKey::unique();
keys.insert(node_id, transform_key);
.push(GpuTransformKeyEvent::Added(
impl crate::managers::NodeIdRemap for GpuStateManager {
/// Remap the per-node GPU caches (transform / opacity keys and values).
/// Without this, a rebuild that shifts `NodeIds` left the scrollbar/CSS
/// transform + opacity keys attached to the wrong node — the visible symptom
/// being a scrollbar thumb (or an animated element) that keeps painting at a
/// stale offset, plus `scrollbar_fade_active` never settling because the
/// platform loop keeps generating frames for a node that is not the one
/// actually scrolling.
fn remap_node_ids(&mut self, dom: DomId, map: &crate::managers::NodeIdMap) {
let Some(cache) = self.caches.get_mut(&dom) else {
remap_hashmap(&mut cache.transform_keys, map);
remap_hashmap(&mut cache.current_transform_values, map);
remap_hashmap(&mut cache.h_transform_keys, map);
remap_hashmap(&mut cache.h_current_transform_values, map);
remap_hashmap(&mut cache.css_transform_keys, map);
remap_hashmap(&mut cache.css_current_transform_values, map);
remap_hashmap(&mut cache.opacity_keys, map);
remap_hashmap(&mut cache.current_opacity_values, map);
remap_dom_hashmap(&mut cache.scrollbar_v_opacity_keys, dom, map);
remap_dom_hashmap(&mut cache.scrollbar_h_opacity_keys, dom, map);
remap_dom_hashmap(&mut cache.scrollbar_v_opacity_values, dom, map);
remap_dom_hashmap(&mut cache.scrollbar_h_opacity_values, dom, map);
/// Rewrite `NodeId` keys, dropping entries for unmounted nodes.
fn remap_hashmap<V>(map: &mut HashMap<NodeId, V>, node_map: &crate::managers::NodeIdMap) {
let old = core::mem::take(map);
for (old_id, v) in old {
if let Some(new_id) = node_map.resolve(old_id) {
map.insert(new_id, v);
/// Rewrite `(DomId, NodeId)` keys for `dom` only, dropping unmounted nodes.
fn remap_dom_hashmap<V>(
map: &mut HashMap<(DomId, NodeId), V>,
dom: DomId,
node_map: &crate::managers::NodeIdMap,
for ((d, old_id), v) in old {
if d != dom {
map.insert((d, old_id), v);
} else if let Some(new_id) = node_map.resolve(old_id) {
map.insert((d, new_id), v);
#[cfg(test)]
mod redundant_frame_tests {
use super::GpuStateManager;
/// The idle redraw loop, in one invariant.
/// `build_image_only_transaction` — the LIGHTWEIGHT path a backend takes
/// precisely because nothing needs rebuilding — pushed the scrollbar
/// opacities and transforms and then called `txn.generate_frame()`
/// unconditionally. WebRender built a frame, signalled `new_frame_ready`,
/// the backend woke and presented, and presenting ran the lightweight path
/// again. Measured on X11/GPU, 2026-09-05, with the window completely idle:
/// 1087 synchronize_gpu_values -> 1087 new_frame_ready -> 1086 presents
/// every one reporting the SAME payload: floats=2 transforms=2 colors=0
/// ~59 fps of full render+present for a static window. All four backends
/// (X11, Wayland, macOS, Windows) call that path, so this is shared, not
/// X11-specific; X11 merely spins fastest because its present is driven by
/// the frame-ready wake rather than a frame callback or CVDisplayLink.
/// The rule: pushing the SAME values again is not a reason to draw.
#[test]
fn resubmitting_identical_gpu_values_is_not_a_reason_to_draw() {
let mut m = GpuStateManager::default();
// First push of a value set: genuinely new, so it must be sent.
assert!(
m.gpu_values_changed(&[(1, 1.0), (2, 0.0)], &[]),
"the first submission has nothing to compare against and must go"
// The idle case: byte-identical values, over and over. None of these
// may request a frame.
assert!(!m.gpu_values_changed(&[(1, 1.0), (2, 0.0)], &[]));
// A real change (a scrollbar fading) must still get through.
assert!(m.gpu_values_changed(&[(1, 0.5), (2, 0.0)], &[]));
assert!(!m.gpu_values_changed(&[(1, 0.5), (2, 0.0)], &[]));
// So must a transform change on its own.
assert!(m.gpu_values_changed(&[(1, 0.5), (2, 0.0)], &[(7, [1.0; 16])]));
assert!(!m.gpu_values_changed(&[(1, 0.5), (2, 0.0)], &[(7, [1.0; 16])]));
// And losing a property is a change too - the set shrank.
assert!(m.gpu_values_changed(&[(1, 0.5)], &[(7, [1.0; 16])]));
/// NaN must not make every frame look different from itself. Opacity is an
/// f32 and a NaN compares unequal to itself, so a bitwise digest is what
/// keeps a degenerate value from reinstating the very loop this prevents.
fn a_nan_value_still_compares_equal_to_itself() {
assert!(m.gpu_values_changed(&[(1, f32::NAN)], &[]));
!m.gpu_values_changed(&[(1, f32::NAN)], &[]),
"NaN == NaN bitwise, or a NaN opacity spins the redraw loop forever"
/// The other two payloads a lightweight transaction carries - image
/// registrations and scroll offsets - answer the same question, through the
/// same remembering.
fn image_and_scroll_digests_are_independent() {
use super::SubmittedDigest;
assert!(m.submitted_digest_changed(SubmittedDigest::Images, 42));
assert!(!m.submitted_digest_changed(SubmittedDigest::Images, 42));
// A scroll offset that happens to digest to the same number is still a
// first submission for ITS slot: the two must not share a memory.
assert!(m.submitted_digest_changed(SubmittedDigest::ScrollOffsets, 42));
assert!(!m.submitted_digest_changed(SubmittedDigest::ScrollOffsets, 42));
assert!(m.submitted_digest_changed(SubmittedDigest::Images, 43));
/// A full frame rebuilds the scene. The values then have to be pushed again
/// even though they did not change, so the full path invalidates first.
fn a_scene_rebuild_forgets_what_was_submitted() {
assert!(m.gpu_values_changed(&[(1, 1.0)], &[]));
assert!(m.submitted_digest_changed(SubmittedDigest::Images, 7));
assert!(m.submitted_digest_changed(SubmittedDigest::ScrollOffsets, 9));
assert!(!m.gpu_values_changed(&[(1, 1.0)], &[]));
m.invalidate_submitted_digests();
m.gpu_values_changed(&[(1, 1.0)], &[]),
"after a scene rebuild the property bindings start over - unchanged values still have \
to reach the renderer"
/// The digest must be sensitive to WHICH key holds a value, not just to the
/// multiset of values: swapping two scrollbars' opacities is a change.
fn swapping_two_keys_values_is_a_change() {
assert!(m.gpu_values_changed(&[(1, 1.0), (2, 0.0)], &[]));
assert!(m.gpu_values_changed(&[(1, 0.0), (2, 1.0)], &[]));
/// ...but the ORDER the caller happens to collect them in is not a change.
/// The values come out of `HashMap`s (`GpuValueCache` is keyed by
/// `(DomId, NodeId)`), whose iteration order is not a promise; if a
/// reordering read as a change, an idle window would draw whenever the map
/// felt like handing them over differently.
fn the_order_the_values_arrive_in_is_not_a_change() {
assert!(m.gpu_values_changed(&[(1, 1.0), (2, 0.25)], &[(7, [1.0; 16]), (8, [2.0; 16])]));
!m.gpu_values_changed(&[(2, 0.25), (1, 1.0)], &[(8, [2.0; 16]), (7, [1.0; 16])]),
"the same set in a different order is the same set"
mod autotest_generated {
dom::{Dom, FormattingContext, IdOrClass, NodeType},
resources::OpacityKey,
styled_dom::StyledDom,
task::{Instant, SystemTick, SystemTickDiff},
use super::*;
managers::{NodeIdMap, NodeIdRemap},
cache::apply_virtual_scroll_necessity,
geometry::PackedBoxProps,
layout_tree::{LayoutNodeCold, LayoutNodeHot, LayoutNodeWarm},
scrollbar::ScrollbarRequirements,
// ------------------------------------------------------------------
// Fixtures
fn dom(inner: usize) -> DomId {
DomId { inner }
fn t0() -> Instant {
Instant::Tick(SystemTick::new(0))
fn millis(ms: u64) -> Duration {
Duration::System(SystemTimeDiff::from_millis(ms))
/// Translation transform — the only shape `update_scrollbar_transforms`
/// ever produces.
fn tx(x: f32, y: f32) -> ComputedTransform3D {
ComputedTransform3D::new_translation(x, y, 0.0)
fn hot(dom_node_id: Option<NodeId>, used: Option<LogicalSize>) -> LayoutNodeHot {
LayoutNodeHot {
box_props: PackedBoxProps::default(),
dom_node_id,
used_size: used,
formatting_context: FormattingContext::Block {
establishes_new_context: true,
parent: None,
fn warm_node(
scrollbar_info: Option<ScrollbarRequirements>,
content: Option<LogicalSize>,
) -> LayoutNodeWarm {
LayoutNodeWarm {
scrollbar_info,
overflow_content_size: content,
..Default::default()
/// What layout computes for an `overflow-y: auto` VirtualView: nothing.
/// The node is a replaced element with no flow content, so its laid-out
/// content never exceeds its box and `check_scrollbar_necessity` finds no
/// reason for a bar — only `visual_width_px` survives from the CSS style.
fn auto_no_scrollbar() -> ScrollbarRequirements {
ScrollbarRequirements {
needs_horizontal: false,
needs_vertical: false,
scrollbar_width: 0.0,
scrollbar_height: 0.0,
visual_width_px: 16.0,
/// `body(0) > VirtualView(1)` with `overflow-x: hidden; overflow-y: auto`.
/// NodeId 1 is the node every fixture in this module registers.
fn auto_virtual_view_dom() -> StyledDom {
let mut dom = Dom::create_body().with_child(
Dom::create_node(NodeType::VirtualView)
.with_ids_and_classes(vec![IdOrClass::Class("vv".into())].into()),
let (css, _warnings) =
azul_css::parser2::new_from_str(".vv { overflow-x: hidden; overflow-y: auto; }");
StyledDom::create(&mut dom, css)
/// A classic (space-reserving) vertical scrollbar with an explicit visual
/// width — the un-ambiguous case where no field-fallback logic kicks in.
fn v_scrollbar() -> ScrollbarRequirements {
needs_vertical: true,
scrollbar_width: 16.0,
scrollbar_height: 16.0,
fn h_scrollbar() -> ScrollbarRequirements {
needs_horizontal: true,
fn tree(nodes: Vec<LayoutNodeHot>, warm: Vec<LayoutNodeWarm>) -> LayoutTree {
let n = nodes.len();
LayoutTree {
nodes,
warm,
cold: vec![LayoutNodeCold::default(); n],
root: 0,
dom_to_layout: BTreeMap::new(),
children_arena: Vec::new(),
children_offsets: vec![(0, 0); n],
subtree_needs_intrinsic: Vec::new(),
/// Single scrollable node: 100×100 border-box, `content` content-box.
fn one_node_tree(sb: ScrollbarRequirements, content: LogicalSize) -> LayoutTree {
tree(
vec![hot(
Some(NodeId::new(1)),
Some(LogicalSize::new(100.0, 100.0)),
)],
vec![warm_node(Some(sb), Some(content))],
/// The y-translation of the single transform event emitted, if any.
fn sole_added_y(changes: &GpuEventChanges) -> f32 {
assert_eq!(changes.transform_key_changes.len(), 1);
match changes.transform_key_changes[0] {
GpuTransformKeyEvent::Added(_, _, t) => t.m[3][1],
ref other => panic!("expected Added, got {other:?}"),
fn sole_added_x(changes: &GpuEventChanges) -> f32 {
GpuTransformKeyEvent::Added(_, _, t) => t.m[3][0],
// GpuStateManager::new / Default — constructor invariants
fn new_stores_both_durations_and_starts_empty_and_idle() {
let m = GpuStateManager::new(millis(1), millis(2));
assert_eq!(m.fade_delay, millis(1));
assert_eq!(m.fade_duration, millis(2));
assert!(m.caches.is_empty());
assert!(!m.scrollbar_fade_active);
assert!(m.pending_changes.is_empty());
fn new_survives_zero_and_u64_max_durations_without_panicking() {
// Zero fade window: the fade math elsewhere divides by fade_duration,
// so a 0 duration must at least be constructible without panicking here.
let zero = GpuStateManager::new(millis(0), millis(0));
assert_eq!(zero.fade_delay, millis(0));
assert_eq!(zero.fade_duration, millis(0));
// from_millis(u64::MAX) is ~584 million years — no overflow, no panic.
let huge = GpuStateManager::new(millis(u64::MAX), millis(u64::MAX));
assert_eq!(huge.fade_delay, millis(u64::MAX));
assert!(huge.caches.is_empty());
fn new_accepts_tick_durations_not_just_system_durations() {
// Duration is an enum; the constructor must not assume the System variant.
let tick = Duration::Tick(SystemTickDiff {
tick_diff: u64::MAX,
});
let m = GpuStateManager::new(tick, tick);
assert_eq!(m.fade_delay, tick);
assert_eq!(m.fade_duration, tick);
fn default_matches_the_documented_fade_constants() {
let m = GpuStateManager::default();
assert_eq!(m.fade_delay, millis(DEFAULT_FADE_DELAY_MS));
assert_eq!(m.fade_duration, millis(DEFAULT_FADE_DURATION_MS));
assert_eq!(DEFAULT_FADE_DELAY_MS, 500);
assert_eq!(DEFAULT_FADE_DURATION_MS, 200);
// take_pending_changes
fn take_pending_changes_drains_the_buffer_and_the_second_take_is_empty() {
m.pending_changes
NodeId::new(1),
TransformKey::unique(),
tx(0.0, 4.0),
let taken = m.take_pending_changes();
assert_eq!(taken.transform_key_changes.len(), 1);
// The whole point of `take`: the buffer must not replay next frame.
assert!(m.take_pending_changes().is_empty());
fn take_pending_changes_on_a_fresh_manager_is_an_empty_no_panic() {
for _ in 0..3 {
assert_eq!(m.take_pending_changes(), GpuEventChanges::empty());
// get_cache / get_or_create_cache
fn get_cache_on_an_unknown_dom_returns_none_and_does_not_create_it() {
assert!(m.get_cache(dom(0)).is_none());
assert!(m.get_cache(dom(usize::MAX)).is_none());
assert!(m.caches.is_empty(), "get_cache must not mutate");
fn get_or_create_cache_is_idempotent_and_never_clobbers_existing_state() {
let node = NodeId::new(7);
let key = TransformKey::unique();
m.get_or_create_cache(dom(0))
.transform_keys
.insert(node, key);
assert_eq!(m.caches.len(), 1);
// Second call must hand back the *same* cache, not a fresh default one —
// otherwise every frame would mint new GPU keys and leak them.
let again = m.get_or_create_cache(dom(0));
assert_eq!(again.transform_keys.get(&node), Some(&key));
assert!(m.get_cache(dom(0)).is_some());
fn caches_for_distinct_dom_ids_including_usize_max_do_not_alias() {
let node = NodeId::new(0);
.current_opacity_values
.insert(node, 0.25);
m.get_or_create_cache(dom(usize::MAX))
.insert(node, 0.75);
assert_eq!(m.caches.len(), 2);
assert_eq!(
m.get_cache(dom(0))
.unwrap()
.get(&node),
Some(&0.25)
m.get_cache(dom(usize::MAX))
Some(&0.75)
// update_scrollbar_transform_key (private)
fn first_update_emits_added_and_populates_both_the_key_and_value_map() {
let mut cache = GpuValueCache::default();
let node = NodeId::new(3);
let t = tx(0.0, 12.0);
&mut cache,
node,
t,
let key = cache
.get(&node)
.copied()
.expect("key stored");
assert_eq!(cache.current_transform_values.get(&node), Some(&t));
changes.transform_key_changes,
vec![GpuTransformKeyEvent::Added(node, key, t)]
fn re_updating_with_an_identical_transform_emits_nothing() {
// The cache exists to suppress redundant GPU traffic: a node that did not
// move must produce zero events, forever.
let mut first = GpuEventChanges::empty();
&mut first,
let key = cache.transform_keys.get(&node).copied().unwrap();
for _ in 0..10 {
let mut again = GpuEventChanges::empty();
&mut again,
assert!(again.is_empty(), "unchanged transform must not re-emit");
// ...and the key must be stable across those no-op frames.
assert_eq!(cache.transform_keys.get(&node).copied(), Some(key));
fn changing_the_transform_emits_changed_with_old_and_new_and_reuses_the_key() {
let old = tx(0.0, 12.0);
let new = tx(0.0, 40.0);
old,
new,
vec![GpuTransformKeyEvent::Changed(node, key, old, new)]
// Key is reused (not re-minted) and the stored value advances.
assert_eq!(cache.current_transform_values.get(&node), Some(&new));
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 node = NodeId::new(5);
let v = tx(0.0, 10.0);
let h = tx(20.0, 0.0);
v,
h,
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"
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 stale = tx(0.0, 5.0);
cache.current_transform_values.insert(node, stale);
tx(0.0, 99.0),
changes.is_empty(),
"no event is emitted for a keyless value"
cache.current_transform_values.get(&node),
Some(&stale),
"the value is left stale rather than repaired"
!cache.transform_keys.contains_key(&node),
"and no key is minted to recover"
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 orphan = TransformKey::unique();
cache.transform_keys.insert(node, orphan);
let t = tx(0.0, 7.0);
let fresh = cache.transform_keys.get(&node).copied().unwrap();
assert_ne!(fresh, orphan, "a brand-new key replaces the orphan");
vec![GpuTransformKeyEvent::Added(node, fresh, t)],
"and it is announced as Added, never as Removed(orphan)"
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 nan = tx(0.0, f32::NAN);
nan,
assert_eq!(changes.transform_key_changes.len(), 1, "Added");
// Feed the exact same NaN transform back in 5 more times.
for _ in 0..5 {
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())
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());
fn remap_hashmap_drops_entries_for_unmounted_nodes() {
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");
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.
map.insert(NodeId::new(1), 111);
map.insert(NodeId::new(2), 222);
&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));
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.
(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);
fn remap_hashmap_handles_node_id_max_without_overflowing() {
map.insert(NodeId::new(usize::MAX), 1);
map.insert(NodeId::ZERO, 2);
(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
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(
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));
map.get(&(dom(1), NodeId::new(1))),
Some(&2),
"a foreign DOM's entry must not be dropped as 'unmounted'"
fn remap_dom_hashmap_drops_only_the_target_doms_unmounted_nodes() {
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
assert!(!map.contains_key(&(dom(0), NodeId::new(2))));
assert_eq!(map.get(&(dom(1), NodeId::new(2))), Some(&3));
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.
map.insert((dom(0), NodeId::new(1)), 11);
map.insert((dom(1), NodeId::new(2)), 22);
&NodeIdMap::from_pairs([(NodeId::new(1), NodeId::new(2))]),
assert_eq!(map.get(&(dom(0), NodeId::new(2))), Some(&11));
assert_eq!(map.get(&(dom(1), NodeId::new(2))), Some(&22));
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.
map.insert((dom(0), NodeId::new(2)), 22);
(NodeId::new(2), NodeId::new(3)),
assert_eq!(map.get(&(dom(0), NodeId::new(3))), Some(&22));
// NodeIdRemap for GpuStateManager
fn remap_node_ids_for_a_dom_with_no_cache_is_a_no_op() {
m.remap_node_ids(
dom(3),
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 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
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));
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)));
fn remap_node_ids_drops_the_gpu_keys_of_an_unmounted_node() {
let gone = NodeId::new(1);
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());
assert!(c.transform_keys.is_empty());
assert!(c.current_transform_values.is_empty());
assert!(c.scrollbar_v_opacity_values.is_empty());
// update_scrollbar_transforms
fn update_scrollbar_transforms_on_an_empty_tree_yields_no_events() {
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).
fn nodes_without_scrollbar_info_or_without_a_dom_node_id_are_skipped() {
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))),
],
warm_node(Some(v_scrollbar()), Some(LogicalSize::new(100.0, 1000.0))),
warm_node(None, None),
assert!(m.get_cache(dom(0)).unwrap().transform_keys.is_empty());
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.
hot(Some(NodeId::new(1)), 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)),
1,
"only node 0 is seen"
fn a_vertical_scrollbar_at_scroll_zero_parks_the_thumb_at_offset_zero() {
let t = one_node_tree(v_scrollbar(), LogicalSize::new(100.0, 1000.0));
// 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);
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 sm = ScrollManager::new();
sm.set_scroll_position_unclamped(
LogicalPosition::new(0.0, 900.0),
t0(),
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}");
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.
LogicalPosition::new(0.0, 1.0e9),
assert!((y - 36.0).abs() < 0.01, "overscroll must clamp, got {y}");
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.
LogicalPosition::new(0.0, -900.0),
assert!(y >= 0.0, "thumb offset must never go negative, got {y}");
y.abs() < 0.01,
"an overscroll above the top must leave the thumb at the start, got {y}"
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);
sm.register_or_update_scroll_node(
NODE,
LogicalRect::new(
LogicalPosition::new(250.0, 120.0),
LogicalSize::new(100.0, 100.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));
// ...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(
LogicalRect::new(LogicalPosition::zero(), LogicalSize::new(100.0, 100.0)),
pos.children_rect.size,
pos.children_rect.origin.y,
// 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);
(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.
(y - 18.0).abs() < 0.01,
"expected the half-track thumb at 18.0, got {y}"
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.
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.
// 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).
.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");
apply_virtual_scroll_necessity(
&styled_dom,
&mut info,
"a 1000px document in a 100px auto viewport needs a bar"
info.needs_vertical,
"the amended flag is the one the GPU path gates on"
!info.needs_horizontal,
"overflow-x: hidden must not gain a bar"
(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);
info.scrollbar_width.max(info.scrollbar_height),
info.visual_width_px,
info.needs_horizontal,
// 4. Half a document down.
// ...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 pos = states.get(&NODE).expect("the node is registered now");
// usable track = 100 (no buttons), thumb = max(100 * 100/1000, 2*16) = 32,
// max_scroll = 900 -> half travel = (100 - 32) * 0.5 = 34.
(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();
fresh
.update_scrollbar_transforms(dom(0), &sm, &stale)
.is_empty(),
"without the amendment the GPU path never sees the bar"
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 first = m.update_scrollbar_transforms(dom(0), &sm, &t);
assert_eq!(first.transform_key_changes.len(), 1);
let again = m.update_scrollbar_transforms(dom(0), &sm, &t);
assert!(again.is_empty(), "an idle scrollbar must stay silent");
fn scrolling_after_a_first_pass_emits_changed_and_reuses_the_key() {
m.update_scrollbar_transforms(dom(0), &sm, &t);
let key = m
.get_cache(dom(0))
.get(&NodeId::new(1))
.unwrap();
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:?}"),
fn a_horizontal_scrollbar_translates_on_x_and_leaves_y_at_zero() {
LogicalPosition::new(900.0, 0.0),
let t = one_node_tree(h_scrollbar(), LogicalSize::new(1000.0, 100.0));
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)));
fn a_node_needing_both_scrollbars_gets_two_independent_keys_and_two_events() {
let both = ScrollbarRequirements {
let t = one_node_tree(both, LogicalSize::new(1000.0, 1000.0));
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);
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 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.
vec![node],
assert!(y.is_finite(), "a degenerate inner box must not yield {y}");
assert_eq!(y, 0.0);
fn a_zero_sized_node_with_zero_content_does_not_divide_by_zero() {
vec![hot(Some(NodeId::new(1)), Some(LogicalSize::zero()))],
vec![warm_node(Some(v_scrollbar()), Some(LogicalSize::zero()))],
assert!(y.is_finite());
fn a_missing_used_size_defaults_to_zero_rather_than_panicking() {
vec![hot(Some(NodeId::new(1)), None)],
vec![warm_node(Some(v_scrollbar()), None)],
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.
Some(LogicalSize::new(f32::INFINITY, f32::INFINITY)),
y.is_finite(),
"a NaN must never reach the transform, got {y}"
// And it SETTLES: a second identical pass emits nothing.
again.transform_key_changes.is_empty(),
"the sanitised value must converge, not re-emit Changed forever"
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.
Some(LogicalSize::new(f32::NAN, f32::NAN)),
assert!(y.is_finite(), "NaN width/height must be clamped, got {y}");
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 overlay = ScrollbarRequirements {
visual_width_px: 0.0,
let t = one_node_tree(overlay, LogicalSize::new(100.0, 1000.0));
(y - 68.0).abs() < 0.01,
"expected the 16px default, got {y}"
assert_eq!(DEFAULT_SCROLLBAR_WIDTH_PX, 16.0);
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 classic_vertical_only = ScrollbarRequirements {
let t = one_node_tree(classic_vertical_only, LogicalSize::new(100.0, 1000.0));
"pinning the buggy value; 36.0 once the field swap is fixed, got {y}"
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 classic_horizontal_only = ScrollbarRequirements {
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));
(x - 68.0).abs() < 0.01,
"pinning the buggy value; 36.0 once the field swap is fixed, got {x}"
fn transforms_are_recorded_per_dom_and_do_not_leak_across_caches() {
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);
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");
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.
assert!(!changes.is_empty());
m.pending_changes.is_empty(),
"returned events must not be double-queued"
fn a_thousand_scrollable_nodes_each_get_exactly_one_distinct_key() {
let n = 1000;
(0..n)
.map(|i| hot(Some(NodeId::new(i)), Some(LogicalSize::new(100.0, 100.0))))
.collect(),
.map(|_| warm_node(Some(v_scrollbar()), Some(LogicalSize::new(100.0, 1000.0))))
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");
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
hot(Some(NodeId::new(1)), Some(LogicalSize::new(200.0, 200.0))),
warm_node(Some(v_scrollbar()), Some(LogicalSize::new(200.0, 2000.0))),
m.get_cache(dom(0)).unwrap().transform_keys.len(),
"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);