Skip to main content

euv_core/render/command/
impl.rs

1use super::*;
2
3/// Default empty per-frame arena initialized with FNV-1a digest seeds.
4impl Default for DisplayListFrameArena {
5    /// Creates an empty `DisplayListFrameArena`.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Ready display list frame arena.
10    fn default() -> Self {
11        Self {
12            string_pool: Vec::new(),
13            portals_scratch: Vec::new(),
14            z_sort_scratch: Vec::new(),
15            portal_ancestors_scratch: Vec::new(),
16            base_layer_version: 0,
17            prev_base_digest: 0,
18            cur_base_digest: FNV1A_OFFSET_BASIS,
19            running_fast_hash: FNV1A_OFFSET_BASIS,
20            base_layer_finalized: false,
21        }
22    }
23}
24
25/// Non-allocating `Clone` preserving digest/version metadata while keeping cloned scratch buffers empty.
26impl Clone for DisplayListFrameArena {
27    /// Clones digest and version metadata without copying transient scratch buffers.
28    ///
29    /// # Arguments
30    ///
31    /// - `&Self` - Source frame arena.
32    ///
33    /// # Returns
34    ///
35    /// - `Self` - Cloned metadata with empty scratch buffers.
36    fn clone(&self) -> Self {
37        let Self {
38            base_layer_version,
39            prev_base_digest,
40            cur_base_digest,
41            running_fast_hash,
42            base_layer_finalized,
43            ..
44        } = self;
45        Self {
46            string_pool: Vec::new(),
47            portals_scratch: Vec::new(),
48            z_sort_scratch: Vec::new(),
49            portal_ancestors_scratch: Vec::new(),
50            base_layer_version: *base_layer_version,
51            prev_base_digest: *prev_base_digest,
52            cur_base_digest: *cur_base_digest,
53            running_fast_hash: *running_fast_hash,
54            base_layer_finalized: *base_layer_finalized,
55        }
56    }
57}
58
59/// Scratch-oblivious equality so internal pool/version state never perturbs logical `DisplayList` equality.
60impl PartialEq for DisplayListFrameArena {
61    /// Treats all frame arenas as equal for logical `DisplayList` comparisons.
62    ///
63    /// # Arguments
64    ///
65    /// - `&Self` - First frame arena.
66    /// - `&Self` - Second frame arena.
67    ///
68    /// # Returns
69    ///
70    /// - `bool` - Always `true`.
71    fn eq(&self, _other: &Self) -> bool {
72        true
73    }
74}
75
76/// Command emission helpers for `DisplayList`.
77impl DisplayList {
78    /// Pre-reserves persistent command and string-pool storage so steady-state frames incur zero container reallocations.
79    ///
80    /// # Arguments
81    ///
82    /// - `&Self` - Mutable display list.
83    pub(crate) fn reserve_steady_state(&mut self) {
84        let Self {
85            commands, arena, ..
86        } = self;
87        if commands.capacity() < 512 {
88            commands.reserve(512 - commands.len());
89        }
90        if arena.string_pool.capacity() < DISPLAY_LIST_STRING_POOL_CAP {
91            arena
92                .string_pool
93                .reserve(DISPLAY_LIST_STRING_POOL_CAP - arena.string_pool.len());
94        }
95    }
96
97    /// Pre-populates spare pooled string buffers for scrollable scenes whose visible text count varies slightly across scroll positions.
98    ///
99    /// # Arguments
100    ///
101    /// - `&Self` - Mutable display list.
102    /// - `usize` - Number of spare 128-byte pooled string slots to append up to `DISPLAY_LIST_STRING_POOL_CAP`.
103    pub(crate) fn prewarm_scroll_string_pool(&mut self, spare_count: usize) {
104        let Self { arena, .. } = self;
105        let target: usize = arena
106            .string_pool
107            .len()
108            .saturating_add(spare_count)
109            .min(DISPLAY_LIST_STRING_POOL_CAP);
110        if arena.string_pool.capacity() < DISPLAY_LIST_STRING_POOL_CAP {
111            arena
112                .string_pool
113                .reserve(DISPLAY_LIST_STRING_POOL_CAP - arena.string_pool.len());
114        }
115        while arena.string_pool.len() < target {
116            arena.string_pool.push(String::with_capacity(128));
117        }
118    }
119
120    /// Clears all commands while recycling backing `String` buffers into the per-frame string pool.
121    ///
122    /// # Arguments
123    ///
124    /// - `&Self` - Mutable display list.
125    /// - `Size` - Target logical viewport size.
126    /// - `f32` - Active DPI scale factor.
127    pub fn reset(&mut self, viewport: Size, scale_factor: f32) {
128        let safe_scale: f32 = scale_factor.max(0.5);
129        let Self {
130            commands,
131            viewport: view_proj,
132            scale_factor: sf,
133            portal_split_index,
134            arena,
135        } = self;
136        if arena.string_pool.capacity() < DISPLAY_LIST_STRING_POOL_CAP {
137            arena
138                .string_pool
139                .reserve(DISPLAY_LIST_STRING_POOL_CAP - arena.string_pool.len());
140        }
141        let pool_start: usize = arena.string_pool.len();
142        for cmd in commands.drain(..) {
143            match cmd {
144                DrawCommand::TextRun { mut text, .. } | DrawCommand::TextCaret { mut text, .. }
145                    if text.capacity() > 0
146                        && arena.string_pool.len() < DISPLAY_LIST_STRING_POOL_CAP =>
147                {
148                    text.clear();
149                    arena.string_pool.push(text);
150                }
151                _ => {}
152            }
153        }
154        if arena.string_pool.len() > pool_start + 1 {
155            arena.string_pool[pool_start..].reverse();
156        }
157        *view_proj = viewport;
158        *sf = safe_scale;
159        *portal_split_index = 0;
160        let mut seed: u64 = FNV1A_OFFSET_BASIS;
161        Self::mix_hash(&mut seed, viewport.get_width().to_bits() as u64);
162        Self::mix_hash(&mut seed, viewport.get_height().to_bits() as u64);
163        Self::mix_hash(&mut seed, safe_scale.to_bits() as u64);
164        arena.prev_base_digest = arena.cur_base_digest;
165        arena.cur_base_digest = seed;
166        arena.running_fast_hash = seed;
167        arena.base_layer_finalized = false;
168    }
169
170    /// Allocates or reuses a pooled `String` filled with `src` so steady-state text emission performs zero heap allocations.
171    ///
172    /// # Arguments
173    ///
174    /// - `&Self` - Mutable display list owning the string pool.
175    /// - `&str` - Source UTF-8 text slice.
176    ///
177    /// # Returns
178    ///
179    /// - `String` - Reused or newly allocated string equal to `src`.
180    #[inline]
181    #[must_use]
182    pub(crate) fn alloc_text(&mut self, src: &str) -> String {
183        if src.is_empty() {
184            return String::new();
185        }
186        let Self { arena, .. } = self;
187        let pool: &mut Vec<String> = &mut arena.string_pool;
188        let len: usize = pool.len();
189        if len > 0 {
190            let need: usize = src.len();
191            if pool[len - 1].capacity() >= need
192                && let Some(mut reused) = pool.pop()
193            {
194                reused.clear();
195                reused.push_str(src);
196                return reused;
197            }
198            for idx in (0..len.saturating_sub(1)).rev() {
199                if pool[idx].capacity() >= need {
200                    let mut reused: String = pool.swap_remove(idx);
201                    reused.clear();
202                    reused.push_str(src);
203                    return reused;
204                }
205            }
206            if let Some(mut reused) = pool.pop() {
207                reused.clear();
208                reused.push_str(src);
209                return reused;
210            }
211        }
212        let mut fresh: String = String::with_capacity(src.len().max(128));
213        fresh.push_str(src);
214        fresh
215    }
216
217    /// Appends a single `DrawCommand` to the list and updates O(1) streaming digests incrementally.
218    ///
219    /// # Arguments
220    ///
221    /// - `&Self` - Mutable display list.
222    /// - `DrawCommand` - Command to push.
223    pub fn push(&mut self, command: DrawCommand) {
224        let Self {
225            commands, arena, ..
226        } = self;
227        Self::fold_command_fast(&mut arena.running_fast_hash, &command);
228        if !arena.base_layer_finalized {
229            Self::fold_command_full(&mut arena.cur_base_digest, &command);
230        }
231        commands.push(command);
232    }
233
234    /// Appends a slice of `DrawCommand` items while updating streaming fast/base digests incrementally.
235    ///
236    /// # Arguments
237    ///
238    /// - `&Self` - Mutable display list.
239    /// - `&[DrawCommand]` - Slice of commands to clone and append.
240    pub fn extend_commands(&mut self, commands_slice: &[DrawCommand]) {
241        for command_item in commands_slice.iter() {
242            self.push(command_item.clone());
243        }
244    }
245
246    /// Returns the incrementally folded 64-bit fast digest over all emitted draw commands.
247    ///
248    /// # Arguments
249    ///
250    /// - `&Self` - Display list reference.
251    ///
252    /// # Returns
253    ///
254    /// - `u64` - Streaming fast command digest.
255    #[must_use]
256    pub fn fast_digest(&self) -> u64 {
257        let Self { arena, .. } = self;
258        arena.running_fast_hash
259    }
260
261    /// Captures the current streaming digest pair before a speculative clip push so empty-clip rollback stays exact.
262    ///
263    /// # Arguments
264    ///
265    /// - `&Self` - Display list reference.
266    ///
267    /// # Returns
268    ///
269    /// - `(u64, u64)` - Tuple `(running_fast_hash, cur_base_digest)`.
270    #[inline]
271    #[must_use]
272    pub(crate) fn snapshot_digest_state(&self) -> (u64, u64) {
273        let Self { arena, .. } = self;
274        (arena.running_fast_hash, arena.cur_base_digest)
275    }
276
277    /// Pops an empty speculative clip command and restores streaming digests to `saved`.
278    ///
279    /// # Arguments
280    ///
281    /// - `&Self` - Mutable display list.
282    /// - `(u64, u64)` - Saved `(running_fast_hash, cur_base_digest)` prior to the clip push.
283    #[inline]
284    pub(crate) fn pop_empty_clip(&mut self, saved: (u64, u64)) {
285        let Self {
286            commands, arena, ..
287        } = self;
288        let _: Option<DrawCommand> = commands.pop();
289        arena.running_fast_hash = saved.0;
290        arena.cur_base_digest = saved.1;
291    }
292
293    /// Attenuates color and alpha channels across `commands[start..end]` by `opacity` and mixes `opacity` into streaming digests.
294    ///
295    /// # Arguments
296    ///
297    /// - `&Self` - Mutable display list.
298    /// - `usize` - Inclusive start command index.
299    /// - `usize` - Exclusive end command index.
300    /// - `f32` - Effective opacity factor in `(0.0, 1.0)`.
301    pub(crate) fn attenuate_range_opacity(&mut self, start: usize, end: usize, opacity: f32) {
302        if opacity >= 0.999 || start >= end {
303            return;
304        }
305        let clamped: f32 = opacity.clamp(0.0, 1.0);
306        let Self {
307            commands, arena, ..
308        } = self;
309        let end_clamped: usize = end.min(commands.len());
310        for cmd in commands[start..end_clamped].iter_mut() {
311            match cmd {
312                DrawCommand::Clear(char_item)
313                | DrawCommand::Line {
314                    color: char_item, ..
315                }
316                | DrawCommand::Circle {
317                    color: char_item, ..
318                }
319                | DrawCommand::Triangle {
320                    color: char_item, ..
321                }
322                | DrawCommand::TextCaret {
323                    color: char_item, ..
324                } => {
325                    *char_item = char_item.multiply_alpha(clamped);
326                }
327                DrawCommand::FillRoundedRect { color, border, .. } => {
328                    *color = color.multiply_alpha(clamped);
329                    border.set_color(border.get_color().multiply_alpha(clamped));
330                }
331                DrawCommand::LinearGradientRect { gradient, .. } => {
332                    gradient.set_start_color(gradient.get_start_color().multiply_alpha(clamped));
333                    gradient.set_end_color(gradient.get_end_color().multiply_alpha(clamped));
334                }
335                DrawCommand::BoxShadow { shadow, .. } => {
336                    shadow.set_color(shadow.get_color().multiply_alpha(clamped));
337                }
338                DrawCommand::TextRun { style, .. } => {
339                    style.set_color(style.get_color().multiply_alpha(clamped));
340                }
341                DrawCommand::SpriteRegion { tint, .. } => {
342                    *tint = tint.multiply_alpha(clamped);
343                }
344                DrawCommand::BackdropBlur { .. }
345                | DrawCommand::Image { .. }
346                | DrawCommand::SharedImage { .. }
347                | DrawCommand::PushClip(_)
348                | DrawCommand::PushRoundedClip { .. }
349                | DrawCommand::PopClip => {}
350            }
351        }
352        let op_bits: u64 = clamped.to_bits() as u64;
353        Self::mix_hash(&mut arena.running_fast_hash, op_bits);
354        if !arena.base_layer_finalized {
355            Self::mix_hash(&mut arena.cur_base_digest, op_bits);
356        }
357    }
358
359    /// Locks the base-layer split index and bumps the monotonic `base_layer_version` only if base commands changed.
360    ///
361    /// # Arguments
362    ///
363    /// - `&Self` - Mutable display list.
364    /// - `usize` - Command index separating base-scene commands from top-layer portals.
365    #[inline]
366    pub(crate) fn finalize_base_layer(&mut self, split_index: usize) {
367        let Self {
368            portal_split_index,
369            arena,
370            ..
371        } = self;
372        *portal_split_index = split_index;
373        Self::mix_hash(&mut arena.cur_base_digest, split_index as u64);
374        if arena.base_layer_version == 0 || arena.cur_base_digest != arena.prev_base_digest {
375            arena.base_layer_version = arena.base_layer_version.wrapping_add(1).max(1);
376        }
377        arena.base_layer_finalized = true;
378    }
379
380    /// Returns the O(1) monotonic base-layer version counter (`0` before the first finalized paint).
381    ///
382    /// # Arguments
383    ///
384    /// - `&Self` - Display list reference.
385    ///
386    /// # Returns
387    ///
388    /// - `u64` - Monotonic base-layer version incremented only when base commands change.
389    #[inline]
390    #[must_use]
391    pub fn base_layer_version(&self) -> u64 {
392        let Self { arena, .. } = self;
393        arena.base_layer_version
394    }
395
396    /// Returns total emitted command count.
397    ///
398    /// # Arguments
399    ///
400    /// - `&Self` - Display list reference.
401    ///
402    /// # Returns
403    ///
404    /// - `usize` - Number of commands.
405    #[must_use]
406    pub fn len(&self) -> usize {
407        self.get_commands().len()
408    }
409
410    /// Returns true when the display list contains zero commands.
411    ///
412    /// # Arguments
413    ///
414    /// - `&Self` - Display list reference.
415    ///
416    /// # Returns
417    ///
418    /// - `bool` - True if empty.
419    #[must_use]
420    pub fn is_empty(&self) -> bool {
421        self.get_commands().is_empty()
422    }
423
424    /// Folds a 64-bit value into an FNV-1a accumulator.
425    ///
426    /// # Arguments
427    ///
428    /// - `&mut u64` - Mutable hash accumulator.
429    /// - `u64` - Value to fold into the digest.
430    #[inline(always)]
431    fn mix_hash(hash: &mut u64, value: u64) {
432        *hash ^= value;
433        *hash = hash.wrapping_mul(FNV1A_PRIME);
434    }
435
436    /// Folds a single `DrawCommand` into the lightweight O(1)-per-push fast frame digest.
437    ///
438    /// # Arguments
439    ///
440    /// - `&mut u64` - Running FNV-1a accumulator.
441    /// - `&DrawCommand` - Command to fold.
442    #[inline]
443    fn fold_command_fast(hash: &mut u64, cmd: &DrawCommand) {
444        match cmd {
445            DrawCommand::Clear(char_item) => {
446                Self::mix_hash(hash, 1);
447                Self::mix_hash(hash, u32::from_le_bytes(char_item.to_rgba_bytes()) as u64);
448            }
449            DrawCommand::FillRoundedRect {
450                rect,
451                color,
452                border,
453                ..
454            } => {
455                Self::mix_hash(hash, 2);
456                Self::mix_hash(hash, rect.get_x().to_bits() as u64);
457                Self::mix_hash(hash, rect.get_y().to_bits() as u64);
458                Self::mix_hash(hash, rect.get_width().to_bits() as u64);
459                Self::mix_hash(hash, rect.get_height().to_bits() as u64);
460                Self::mix_hash(hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
461                Self::mix_hash(hash, border.get_width().to_bits() as u64);
462            }
463            DrawCommand::LinearGradientRect { rect, gradient, .. } => {
464                Self::mix_hash(hash, 3);
465                Self::mix_hash(hash, rect.get_x().to_bits() as u64);
466                Self::mix_hash(hash, rect.get_y().to_bits() as u64);
467                Self::mix_hash(
468                    hash,
469                    u32::from_le_bytes(gradient.get_start_color().to_rgba_bytes()) as u64,
470                );
471            }
472            DrawCommand::BoxShadow { rect, shadow, .. } => {
473                Self::mix_hash(hash, 4);
474                Self::mix_hash(hash, rect.get_x().to_bits() as u64);
475                Self::mix_hash(hash, shadow.get_blur_radius().to_bits() as u64);
476            }
477            DrawCommand::BackdropBlur {
478                rect, blur_radius, ..
479            } => {
480                Self::mix_hash(hash, 15);
481                Self::mix_hash(hash, rect.get_x().to_bits() as u64);
482                Self::mix_hash(hash, rect.get_y().to_bits() as u64);
483                Self::mix_hash(hash, blur_radius.to_bits() as u64);
484            }
485            DrawCommand::TextRun { rect, text, style } => {
486                Self::mix_hash(hash, 5);
487                Self::mix_hash(hash, rect.get_x().to_bits() as u64);
488                Self::mix_hash(hash, rect.get_y().to_bits() as u64);
489                Self::mix_hash(hash, text.len() as u64);
490                let bytes: &[u8] = text.as_bytes();
491                let prefix_len: usize = bytes.len().min(16);
492                for &byte in bytes[..prefix_len].iter() {
493                    Self::mix_hash(hash, byte as u64);
494                }
495                Self::mix_hash(
496                    hash,
497                    u32::from_le_bytes(style.get_color().to_rgba_bytes()) as u64,
498                );
499            }
500            DrawCommand::TextCaret {
501                text_rect,
502                text,
503                color,
504                ..
505            } => {
506                Self::mix_hash(hash, 13);
507                Self::mix_hash(hash, text_rect.get_x().to_bits() as u64);
508                Self::mix_hash(hash, text_rect.get_y().to_bits() as u64);
509                Self::mix_hash(hash, text.len() as u64);
510                Self::mix_hash(hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
511            }
512            DrawCommand::Image { rect, buffer, .. } => {
513                Self::mix_hash(hash, 6);
514                Self::mix_hash(hash, rect.get_x().to_bits() as u64);
515                Self::mix_hash(hash, buffer.get_width() as u64);
516                Self::mix_hash(hash, buffer.get_height() as u64);
517            }
518            DrawCommand::SharedImage {
519                rect,
520                width,
521                height,
522                ..
523            } => {
524                Self::mix_hash(hash, 6);
525                Self::mix_hash(hash, rect.get_x().to_bits() as u64);
526                Self::mix_hash(hash, *width as u64);
527                Self::mix_hash(hash, *height as u64);
528            }
529            DrawCommand::Line {
530                from,
531                to,
532                color,
533                width,
534            } => {
535                Self::mix_hash(hash, 7);
536                Self::mix_hash(hash, from.get_x().to_bits() as u64);
537                Self::mix_hash(hash, to.get_y().to_bits() as u64);
538                Self::mix_hash(hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
539                Self::mix_hash(hash, width.to_bits() as u64);
540            }
541            DrawCommand::Circle {
542                center,
543                radius,
544                color,
545            } => {
546                Self::mix_hash(hash, 8);
547                Self::mix_hash(hash, center.get_x().to_bits() as u64);
548                Self::mix_hash(hash, center.get_y().to_bits() as u64);
549                Self::mix_hash(hash, radius.to_bits() as u64);
550                Self::mix_hash(hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
551            }
552            DrawCommand::Triangle { p0, p1, p2, color } => {
553                Self::mix_hash(hash, 9);
554                Self::mix_hash(hash, p0.get_x().to_bits() as u64);
555                Self::mix_hash(hash, p1.get_y().to_bits() as u64);
556                Self::mix_hash(hash, p2.get_x().to_bits() as u64);
557                Self::mix_hash(hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
558            }
559            DrawCommand::SpriteRegion {
560                rect,
561                src_rect,
562                tint,
563                ..
564            } => {
565                Self::mix_hash(hash, 10);
566                Self::mix_hash(hash, rect.get_x().to_bits() as u64);
567                Self::mix_hash(hash, src_rect.get_x().to_bits() as u64);
568                Self::mix_hash(hash, u32::from_le_bytes(tint.to_rgba_bytes()) as u64);
569            }
570            DrawCommand::PushClip(red_val) => {
571                Self::mix_hash(hash, 11);
572                Self::mix_hash(hash, red_val.get_x().to_bits() as u64);
573                Self::mix_hash(hash, red_val.get_y().to_bits() as u64);
574            }
575            DrawCommand::PushRoundedClip { rect, radius } => {
576                Self::mix_hash(hash, 14);
577                Self::mix_hash(hash, rect.get_x().to_bits() as u64);
578                Self::mix_hash(hash, rect.get_y().to_bits() as u64);
579                Self::mix_hash(hash, radius.max_radius().to_bits() as u64);
580            }
581            DrawCommand::PopClip => {
582                Self::mix_hash(hash, 12);
583            }
584        }
585    }
586
587    /// Folds a byte slice into an FNV-1a accumulator 8 bytes at a time for fast base-layer digesting.
588    ///
589    /// # Arguments
590    ///
591    /// - `&mut u64` - Running hash accumulator.
592    /// - `&[u8]` - UTF-8 text byte slice.
593    #[inline]
594    fn fold_bytes_wordwise(hash: &mut u64, bytes: &[u8]) {
595        Self::mix_hash(hash, bytes.len() as u64);
596        let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
597        for chunk in chunks.iter() {
598            Self::mix_hash(hash, u64::from_ne_bytes(*chunk));
599        }
600        if !rem.is_empty() {
601            let mut tail: u64 = 0;
602            for (idx, &blue_val) in rem.iter().enumerate() {
603                tail |= (blue_val as u64) << (idx * 8);
604            }
605            Self::mix_hash(hash, tail);
606        }
607    }
608
609    /// Folds a single `DrawCommand` with full visual fidelity into a running base-layer or canvas digest.
610    ///
611    /// # Arguments
612    ///
613    /// - `&mut u64` - Running FNV-1a accumulator.
614    /// - `&DrawCommand` - Command to fold.
615    #[inline]
616    pub(crate) fn fold_command_full(hash: &mut u64, cmd: &DrawCommand) {
617        match cmd {
618            DrawCommand::Clear(char_item) => {
619                Self::mix_hash(hash, 1);
620                Self::mix_hash(hash, u32::from_le_bytes(char_item.to_rgba_bytes()) as u64);
621            }
622            DrawCommand::FillRoundedRect {
623                rect,
624                color,
625                radius,
626                border,
627            } => {
628                Self::mix_hash(hash, 2);
629                Self::mix_hash(
630                    hash,
631                    ((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
632                );
633                Self::mix_hash(
634                    hash,
635                    ((rect.get_width().to_bits() as u64) << 32)
636                        | (rect.get_height().to_bits() as u64),
637                );
638                Self::mix_hash(
639                    hash,
640                    ((u32::from_le_bytes(color.to_rgba_bytes()) as u64) << 32)
641                        | (u32::from_le_bytes(border.get_color().to_rgba_bytes()) as u64),
642                );
643                Self::mix_hash(
644                    hash,
645                    ((radius.get_top_left().to_bits() as u64) << 32)
646                        | (radius.get_top_right().to_bits() as u64),
647                );
648                Self::mix_hash(
649                    hash,
650                    ((radius.get_bottom_right().to_bits() as u64) << 32)
651                        | (radius.get_bottom_left().to_bits() as u64),
652                );
653                Self::mix_hash(hash, border.get_width().to_bits() as u64);
654            }
655            DrawCommand::LinearGradientRect {
656                rect,
657                gradient,
658                radius,
659            } => {
660                Self::mix_hash(hash, 3);
661                Self::mix_hash(
662                    hash,
663                    ((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
664                );
665                Self::mix_hash(
666                    hash,
667                    ((rect.get_width().to_bits() as u64) << 32)
668                        | (rect.get_height().to_bits() as u64),
669                );
670                Self::mix_hash(
671                    hash,
672                    ((u32::from_le_bytes(gradient.get_start_color().to_rgba_bytes()) as u64) << 32)
673                        | (u32::from_le_bytes(gradient.get_end_color().to_rgba_bytes()) as u64),
674                );
675                Self::mix_hash(
676                    hash,
677                    ((gradient.get_angle_deg().to_bits() as u64) << 32)
678                        | (radius.max_radius().to_bits() as u64),
679                );
680            }
681            DrawCommand::BoxShadow {
682                rect,
683                radius,
684                shadow,
685            } => {
686                Self::mix_hash(hash, 4);
687                Self::mix_hash(
688                    hash,
689                    ((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
690                );
691                Self::mix_hash(
692                    hash,
693                    ((rect.get_width().to_bits() as u64) << 32)
694                        | (rect.get_height().to_bits() as u64),
695                );
696                Self::mix_hash(
697                    hash,
698                    ((shadow.get_offset_x().to_bits() as u64) << 32)
699                        | (shadow.get_offset_y().to_bits() as u64),
700                );
701                Self::mix_hash(
702                    hash,
703                    ((shadow.get_blur_radius().to_bits() as u64) << 32)
704                        | (shadow.get_spread_radius().to_bits() as u64),
705                );
706                Self::mix_hash(
707                    hash,
708                    ((radius.max_radius().to_bits() as u64) << 32)
709                        | (u32::from_le_bytes(shadow.get_color().to_rgba_bytes()) as u64),
710                );
711            }
712            DrawCommand::BackdropBlur {
713                rect,
714                radius,
715                blur_radius,
716            } => {
717                Self::mix_hash(hash, 15);
718                Self::mix_hash(
719                    hash,
720                    ((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
721                );
722                Self::mix_hash(
723                    hash,
724                    ((rect.get_width().to_bits() as u64) << 32)
725                        | (rect.get_height().to_bits() as u64),
726                );
727                Self::mix_hash(
728                    hash,
729                    ((radius.max_radius().to_bits() as u64) << 32) | (blur_radius.to_bits() as u64),
730                );
731            }
732            DrawCommand::TextRun { rect, text, style } => {
733                Self::mix_hash(hash, 5);
734                Self::mix_hash(
735                    hash,
736                    ((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
737                );
738                Self::mix_hash(
739                    hash,
740                    ((rect.get_width().to_bits() as u64) << 32)
741                        | (rect.get_height().to_bits() as u64),
742                );
743                let style_flags: u64 = (style.get_family() as u64)
744                    | ((style.get_weight() as u64) << 8)
745                    | ((style.get_align() as u64) << 16)
746                    | (u64::from(style.get_italic()) << 24)
747                    | ((u32::from_le_bytes(style.get_color().to_rgba_bytes()) as u64) << 32);
748                Self::mix_hash(hash, style_flags);
749                Self::mix_hash(hash, style.get_font_size().to_bits() as u64);
750                Self::fold_bytes_wordwise(hash, text.as_bytes());
751            }
752            DrawCommand::TextCaret {
753                text_rect,
754                content_rect,
755                text,
756                style,
757                caret_height,
758                color,
759                multiline,
760            } => {
761                Self::mix_hash(hash, 13);
762                Self::mix_hash(
763                    hash,
764                    ((text_rect.get_x().to_bits() as u64) << 32)
765                        | (text_rect.get_y().to_bits() as u64),
766                );
767                Self::mix_hash(
768                    hash,
769                    ((content_rect.get_width().to_bits() as u64) << 32)
770                        | (caret_height.to_bits() as u64),
771                );
772                Self::mix_hash(
773                    hash,
774                    ((style.get_font_size().to_bits() as u64) << 32)
775                        | (u32::from_le_bytes(color.to_rgba_bytes()) as u64)
776                            ^ u64::from(*multiline),
777                );
778                Self::fold_bytes_wordwise(hash, text.as_bytes());
779            }
780            DrawCommand::Image {
781                rect,
782                buffer,
783                radius,
784            } => {
785                Self::mix_hash(hash, 6);
786                Self::mix_hash(
787                    hash,
788                    ((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
789                );
790                Self::mix_hash(
791                    hash,
792                    ((rect.get_width().to_bits() as u64) << 32)
793                        | (rect.get_height().to_bits() as u64),
794                );
795                Self::mix_hash(
796                    hash,
797                    ((buffer.get_width() as u64) << 32) | (buffer.get_height() as u64),
798                );
799                Self::mix_hash(hash, buffer.get_pixels().as_ptr() as usize as u64);
800                Self::mix_hash(hash, radius.max_radius().to_bits() as u64);
801            }
802            DrawCommand::SharedImage {
803                rect,
804                width,
805                height,
806                pixels,
807                radius,
808            } => {
809                Self::mix_hash(hash, 6);
810                Self::mix_hash(
811                    hash,
812                    ((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
813                );
814                Self::mix_hash(
815                    hash,
816                    ((rect.get_width().to_bits() as u64) << 32)
817                        | (rect.get_height().to_bits() as u64),
818                );
819                Self::mix_hash(hash, ((*width as u64) << 32) | (*height as u64));
820                Self::mix_hash(hash, pixels.as_ptr() as usize as u64);
821                Self::mix_hash(hash, radius.max_radius().to_bits() as u64);
822            }
823            DrawCommand::Line {
824                from,
825                to,
826                color,
827                width,
828            } => {
829                Self::mix_hash(hash, 7);
830                Self::mix_hash(
831                    hash,
832                    ((from.get_x().to_bits() as u64) << 32) | (from.get_y().to_bits() as u64),
833                );
834                Self::mix_hash(
835                    hash,
836                    ((to.get_x().to_bits() as u64) << 32) | (to.get_y().to_bits() as u64),
837                );
838                Self::mix_hash(
839                    hash,
840                    ((u32::from_le_bytes(color.to_rgba_bytes()) as u64) << 32)
841                        | (width.to_bits() as u64),
842                );
843            }
844            DrawCommand::Circle {
845                center,
846                radius,
847                color,
848            } => {
849                Self::mix_hash(hash, 8);
850                Self::mix_hash(
851                    hash,
852                    ((center.get_x().to_bits() as u64) << 32) | (center.get_y().to_bits() as u64),
853                );
854                Self::mix_hash(
855                    hash,
856                    ((radius.to_bits() as u64) << 32)
857                        | (u32::from_le_bytes(color.to_rgba_bytes()) as u64),
858                );
859            }
860            DrawCommand::Triangle { p0, p1, p2, color } => {
861                Self::mix_hash(hash, 9);
862                Self::mix_hash(
863                    hash,
864                    ((p0.get_x().to_bits() as u64) << 32) | (p0.get_y().to_bits() as u64),
865                );
866                Self::mix_hash(
867                    hash,
868                    ((p1.get_x().to_bits() as u64) << 32) | (p1.get_y().to_bits() as u64),
869                );
870                Self::mix_hash(
871                    hash,
872                    ((p2.get_x().to_bits() as u64) << 32) | (p2.get_y().to_bits() as u64),
873                );
874                Self::mix_hash(hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
875            }
876            DrawCommand::SpriteRegion {
877                rect,
878                buffer,
879                src_rect,
880                tint,
881            } => {
882                Self::mix_hash(hash, 10);
883                Self::mix_hash(
884                    hash,
885                    ((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
886                );
887                Self::mix_hash(
888                    hash,
889                    ((rect.get_width().to_bits() as u64) << 32)
890                        | (rect.get_height().to_bits() as u64),
891                );
892                Self::mix_hash(hash, buffer.get_pixels().as_ptr() as usize as u64);
893                Self::mix_hash(
894                    hash,
895                    ((src_rect.get_x().to_bits() as u64) << 32)
896                        | (src_rect.get_y().to_bits() as u64),
897                );
898                Self::mix_hash(hash, u32::from_le_bytes(tint.to_rgba_bytes()) as u64);
899            }
900            DrawCommand::PushClip(red_val) => {
901                Self::mix_hash(hash, 11);
902                Self::mix_hash(
903                    hash,
904                    ((red_val.get_x().to_bits() as u64) << 32) | (red_val.get_y().to_bits() as u64),
905                );
906                Self::mix_hash(
907                    hash,
908                    ((red_val.get_width().to_bits() as u64) << 32)
909                        | (red_val.get_height().to_bits() as u64),
910                );
911            }
912            DrawCommand::PushRoundedClip { rect, radius } => {
913                Self::mix_hash(hash, 14);
914                Self::mix_hash(
915                    hash,
916                    ((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
917                );
918                Self::mix_hash(
919                    hash,
920                    ((rect.get_width().to_bits() as u64) << 32)
921                        | (rect.get_height().to_bits() as u64),
922                );
923                Self::mix_hash(
924                    hash,
925                    ((radius.get_top_left().to_bits() as u64) << 32)
926                        | (radius.get_top_right().to_bits() as u64),
927                );
928                Self::mix_hash(
929                    hash,
930                    ((radius.get_bottom_right().to_bits() as u64) << 32)
931                        | (radius.get_bottom_left().to_bits() as u64),
932                );
933            }
934            DrawCommand::PopClip => {
935                Self::mix_hash(hash, 12);
936            }
937        }
938    }
939
940    /// Returns the O(1) incrementally maintained 64-bit FNV-1a digest over the display list.
941    ///
942    /// # Arguments
943    ///
944    /// - `&Self` - Display list reference.
945    ///
946    /// # Returns
947    ///
948    /// - `u64` - Deterministic command-stream digest.
949    #[inline]
950    #[must_use]
951    pub fn fast_hash(&self) -> u64 {
952        let Self {
953            commands, arena, ..
954        } = self;
955        let mut hash: u64 = arena.running_fast_hash;
956        Self::mix_hash(&mut hash, commands.len() as u64);
957        hash
958    }
959
960    /// Returns an O(1) monotonic base-layer cache token for lossless portal backdrop reuse without re-hashing command bytes.
961    ///
962    /// # Arguments
963    ///
964    /// - `&Self` - Display list reference.
965    ///
966    /// # Returns
967    ///
968    /// - `u64` - Non-zero O(1) base-layer version or streaming digest.
969    #[inline]
970    #[must_use]
971    pub fn base_layer_hash(&self) -> u64 {
972        let Self {
973            commands, arena, ..
974        } = self;
975        if arena.base_layer_finalized {
976            return arena.base_layer_version.max(1);
977        }
978        let mut hash: u64 = arena.cur_base_digest;
979        Self::mix_hash(&mut hash, commands.len() as u64);
980        if hash == 0 { 1 } else { hash }
981    }
982}
983
984/// Telemetry and invalidation helpers for `PaintFragmentCache`.
985impl PaintFragmentCache {
986    /// Clears cached whole-list signature, canvas stability records, and all retained subtree fragments.
987    ///
988    /// # Arguments
989    ///
990    /// - `&Self` - Mutable fragment cache reference.
991    pub fn clear(&mut self) {
992        let Self {
993            has_last_scene,
994            last_has_canvas,
995            slots,
996            cmd_slab,
997            text_slab,
998            canvas_stability,
999            ..
1000        } = self;
1001        *has_last_scene = false;
1002        *last_has_canvas = false;
1003        slots.fill(RetainedPaintFragment::default());
1004        cmd_slab.clear();
1005        text_slab.clear();
1006        for entry in canvas_stability.iter_mut() {
1007            *entry = CanvasStabilityEntry::default();
1008        }
1009    }
1010
1011    /// Returns cumulative retention telemetry `(whole_list_hits, fragment_hits, fragment_misses, fragment_evictions)`.
1012    ///
1013    /// # Arguments
1014    ///
1015    /// - `&Self` - Fragment cache reference.
1016    ///
1017    /// # Returns
1018    ///
1019    /// - `(u64, u64, u64, u64)` - Tuple of whole-list hits, fragment hits, misses, and evictions.
1020    #[must_use]
1021    pub fn stats(&self) -> (u64, u64, u64, u64) {
1022        (
1023            self.get_whole_list_hits(),
1024            self.get_fragment_hits(),
1025            self.get_fragment_misses(),
1026            self.get_fragment_evictions(),
1027        )
1028    }
1029
1030    /// Ensures the bounded direct-mapped slot table and flat command/text slabs are pre-allocated once for zero steady-state allocations.
1031    ///
1032    /// # Arguments
1033    ///
1034    /// - `&Self` - Mutable fragment cache reference.
1035    #[inline]
1036    fn ensure_slots(&mut self) {
1037        let Self {
1038            slots,
1039            cmd_slab,
1040            text_slab,
1041            ..
1042        } = self;
1043        if slots.len() != PAINT_FRAGMENT_CACHE_SLOTS {
1044            slots.resize(PAINT_FRAGMENT_CACHE_SLOTS, RetainedPaintFragment::default());
1045        }
1046        if cmd_slab.capacity() < PAINT_FRAGMENT_CMD_SLAB_CAP {
1047            cmd_slab.reserve_exact(PAINT_FRAGMENT_CMD_SLAB_CAP - cmd_slab.len());
1048        }
1049        if text_slab.capacity() < PAINT_FRAGMENT_TEXT_SLAB_CAP {
1050            text_slab.reserve_exact(PAINT_FRAGMENT_TEXT_SLAB_CAP - text_slab.len());
1051        }
1052    }
1053
1054    /// Converts one `DrawCommand` into a slab-backed `CachedDrawCommand`, writing any text bytes into `text_dst` at `*text_cursor`.
1055    ///
1056    /// # Arguments
1057    ///
1058    /// - `&DrawCommand` - Source display-list draw command.
1059    /// - `&mut [u8]` - Destination UTF-8 byte buffer slice (either in-place slot or freshly extended tail).
1060    /// - `&mut usize` - Running write cursor within `text_dst`.
1061    /// - `usize` - Absolute base byte offset of `text_dst` inside `text_slab`.
1062    ///
1063    /// # Returns
1064    ///
1065    /// - `CachedDrawCommand` - Zero-String slab-backed draw command.
1066    #[inline]
1067    fn encode_cached_command(
1068        cmd: &DrawCommand,
1069        text_dst: &mut [u8],
1070        text_cursor: &mut usize,
1071        text_base: usize,
1072    ) -> CachedDrawCommand {
1073        match cmd {
1074            DrawCommand::Clear(char_item) => CachedDrawCommand::Clear(*char_item),
1075            DrawCommand::FillRoundedRect {
1076                rect,
1077                color,
1078                radius,
1079                border,
1080            } => CachedDrawCommand::FillRoundedRect {
1081                rect: *rect,
1082                color: *color,
1083                radius: *radius,
1084                border: *border,
1085            },
1086            DrawCommand::LinearGradientRect {
1087                rect,
1088                gradient,
1089                radius,
1090            } => CachedDrawCommand::LinearGradientRect {
1091                rect: *rect,
1092                gradient: *gradient,
1093                radius: *radius,
1094            },
1095            DrawCommand::BoxShadow {
1096                rect,
1097                radius,
1098                shadow,
1099            } => CachedDrawCommand::BoxShadow {
1100                rect: *rect,
1101                radius: *radius,
1102                shadow: *shadow,
1103            },
1104            DrawCommand::BackdropBlur {
1105                rect,
1106                radius,
1107                blur_radius,
1108            } => CachedDrawCommand::BackdropBlur {
1109                rect: *rect,
1110                radius: *radius,
1111                blur_radius: *blur_radius,
1112            },
1113            DrawCommand::TextRun { rect, text, style } => {
1114                let bytes: &[u8] = text.as_bytes();
1115                let start_rel: usize = *text_cursor;
1116                let end_rel: usize = start_rel.saturating_add(bytes.len());
1117                text_dst[start_rel..end_rel].copy_from_slice(bytes);
1118                *text_cursor = end_rel;
1119                CachedDrawCommand::TextRun {
1120                    rect: *rect,
1121                    text_start: (text_base.saturating_add(start_rel)) as u32,
1122                    text_len: bytes.len() as u32,
1123                    style: *style,
1124                }
1125            }
1126            DrawCommand::TextCaret {
1127                text_rect,
1128                content_rect,
1129                text,
1130                style,
1131                caret_height,
1132                color,
1133                multiline,
1134            } => {
1135                let bytes: &[u8] = text.as_bytes();
1136                let start_rel: usize = *text_cursor;
1137                let end_rel: usize = start_rel.saturating_add(bytes.len());
1138                text_dst[start_rel..end_rel].copy_from_slice(bytes);
1139                *text_cursor = end_rel;
1140                CachedDrawCommand::TextCaret {
1141                    text_rect: *text_rect,
1142                    content_rect: *content_rect,
1143                    text_start: (text_base.saturating_add(start_rel)) as u32,
1144                    text_len: bytes.len() as u32,
1145                    style: *style,
1146                    caret_height: *caret_height,
1147                    color: *color,
1148                    multiline: *multiline,
1149                }
1150            }
1151            DrawCommand::Image {
1152                rect,
1153                buffer,
1154                radius,
1155            } => CachedDrawCommand::Image {
1156                rect: *rect,
1157                buffer: buffer.clone(),
1158                radius: *radius,
1159            },
1160            DrawCommand::SharedImage {
1161                rect,
1162                width,
1163                height,
1164                pixels,
1165                radius,
1166            } => CachedDrawCommand::SharedImage {
1167                rect: *rect,
1168                width: *width,
1169                height: *height,
1170                pixels: Arc::clone(pixels),
1171                radius: *radius,
1172            },
1173            DrawCommand::Line {
1174                from,
1175                to,
1176                color,
1177                width,
1178            } => CachedDrawCommand::Line {
1179                from: *from,
1180                to: *to,
1181                color: *color,
1182                width: *width,
1183            },
1184            DrawCommand::Circle {
1185                center,
1186                radius,
1187                color,
1188            } => CachedDrawCommand::Circle {
1189                center: *center,
1190                radius: *radius,
1191                color: *color,
1192            },
1193            DrawCommand::Triangle { p0, p1, p2, color } => CachedDrawCommand::Triangle {
1194                p0: *p0,
1195                p1: *p1,
1196                p2: *p2,
1197                color: *color,
1198            },
1199            DrawCommand::SpriteRegion {
1200                rect,
1201                buffer,
1202                src_rect,
1203                tint,
1204            } => CachedDrawCommand::SpriteRegion {
1205                rect: *rect,
1206                buffer: buffer.clone(),
1207                src_rect: *src_rect,
1208                tint: *tint,
1209            },
1210            DrawCommand::PushClip(rect) => CachedDrawCommand::PushClip(*rect),
1211            DrawCommand::PushRoundedClip { rect, radius } => CachedDrawCommand::PushRoundedClip {
1212                rect: *rect,
1213                radius: *radius,
1214            },
1215            DrawCommand::PopClip => CachedDrawCommand::PopClip,
1216        }
1217    }
1218
1219    /// Captures `cmd_slice` into `slot_idx` inside the pre-allocated flat command and text slabs with zero heap allocations.
1220    ///
1221    /// # Arguments
1222    ///
1223    /// - `&Self` - Mutable fragment cache reference.
1224    /// - `usize` - Direct-mapped slot index in `0..PAINT_FRAGMENT_CACHE_SLOTS`.
1225    /// - `(NodeId, u32, u32, Point, u64, u64)` - Metadata `(node_id, phys_scale_milli, opacity_bits, offset_phys, geom_hash, style_text_hash)`.
1226    /// - `&[DrawCommand]` - Commands emitted for this subtree.
1227    fn capture_fragment(
1228        &mut self,
1229        slot_idx: usize,
1230        meta: (NodeId, u32, u32, Point, u64, u64),
1231        cmd_slice: &[DrawCommand],
1232    ) {
1233        let (node_id, phys_scale_milli, opacity_bits, offset_phys, geom_hash, style_text_hash): (
1234            NodeId,
1235            u32,
1236            u32,
1237            Point,
1238            u64,
1239            u64,
1240        ) = meta;
1241        let Self {
1242            slots,
1243            cmd_slab,
1244            text_slab,
1245            fragment_misses,
1246            fragment_evictions,
1247            ..
1248        } = self;
1249        if slot_idx >= slots.len() {
1250            return;
1251        }
1252        *fragment_misses = fragment_misses.wrapping_add(1);
1253        let need_cmds: usize = cmd_slice.len();
1254        let mut need_text: usize = 0;
1255        for cmd in cmd_slice.iter() {
1256            match cmd {
1257                DrawCommand::TextRun { text, .. } | DrawCommand::TextCaret { text, .. } => {
1258                    need_text = need_text.saturating_add(text.len());
1259                }
1260                _ => {}
1261            }
1262        }
1263        if need_cmds > PAINT_FRAGMENT_CMD_SLAB_CAP || need_text > PAINT_FRAGMENT_TEXT_SLAB_CAP {
1264            return;
1265        }
1266        let existing: RetainedPaintFragment = slots[slot_idx];
1267        if existing.occupied && existing.node_id != node_id {
1268            *fragment_evictions = fragment_evictions.wrapping_add(1);
1269        }
1270        if existing.occupied
1271            && need_cmds <= (existing.cmd_cap as usize)
1272            && need_text <= (existing.text_cap as usize)
1273        {
1274            let cmd_base: usize = existing.cmd_start as usize;
1275            let text_base: usize = existing.text_start as usize;
1276            let text_end: usize = text_base.saturating_add(need_text);
1277            let mut text_cursor: usize = 0;
1278            let text_dst: &mut [u8] = &mut text_slab[text_base..text_end];
1279            for (item_index, cmd) in cmd_slice.iter().enumerate() {
1280                cmd_slab[cmd_base + item_index] =
1281                    Self::encode_cached_command(cmd, text_dst, &mut text_cursor, text_base);
1282            }
1283            slots[slot_idx] = RetainedPaintFragment {
1284                occupied: true,
1285                node_id,
1286                phys_scale_milli,
1287                opacity_bits,
1288                offset_phys,
1289                geom_hash,
1290                style_text_hash,
1291                cmd_start: existing.cmd_start,
1292                cmd_len: need_cmds as u32,
1293                cmd_cap: existing.cmd_cap,
1294                text_start: existing.text_start,
1295                text_cap: existing.text_cap,
1296            };
1297            return;
1298        }
1299        if cmd_slab.len().saturating_add(need_cmds) > PAINT_FRAGMENT_CMD_SLAB_CAP
1300            || text_slab.len().saturating_add(need_text) > PAINT_FRAGMENT_TEXT_SLAB_CAP
1301        {
1302            let mut evicted: u64 = 0;
1303            for source_val in slots.iter_mut() {
1304                if source_val.occupied {
1305                    evicted = evicted.saturating_add(1);
1306                    *source_val = RetainedPaintFragment::default();
1307                }
1308            }
1309            *fragment_evictions = fragment_evictions.wrapping_add(evicted);
1310            cmd_slab.clear();
1311            text_slab.clear();
1312        }
1313        let cmd_start: usize = cmd_slab.len();
1314        let text_base: usize = text_slab.len();
1315        let text_end: usize = text_base.saturating_add(need_text);
1316        text_slab.resize(text_end, 0);
1317        let mut text_cursor: usize = 0;
1318        let text_dst: &mut [u8] = &mut text_slab[text_base..text_end];
1319        for cmd in cmd_slice.iter() {
1320            cmd_slab.push(Self::encode_cached_command(
1321                cmd,
1322                text_dst,
1323                &mut text_cursor,
1324                text_base,
1325            ));
1326        }
1327        slots[slot_idx] = RetainedPaintFragment {
1328            occupied: true,
1329            node_id,
1330            phys_scale_milli,
1331            opacity_bits,
1332            offset_phys,
1333            geom_hash,
1334            style_text_hash,
1335            cmd_start: cmd_start as u32,
1336            cmd_len: need_cmds as u32,
1337            cmd_cap: need_cmds as u32,
1338            text_start: text_base as u32,
1339            text_cap: need_text as u32,
1340        };
1341    }
1342
1343    /// Records the commands emitted by one `NodeKind::Canvas` and returns `true` only if the canvas is dynamic or unverified.
1344    ///
1345    /// # Arguments
1346    ///
1347    /// - `&Self` - Mutable fragment cache reference.
1348    /// - `NodeId` - Canvas node handle.
1349    /// - `u32` - Quantized physical scale (`(scale * 1000.0).round() as u32`).
1350    /// - `Rect` - Canvas logical bounds.
1351    /// - `u64` - Active `SceneTree::revision`.
1352    /// - `&[DrawCommand]` - Commands emitted by the canvas callback on this frame.
1353    ///
1354    /// # Returns
1355    ///
1356    /// - `bool` - `true` when the canvas must disable whole-list retention; `false` when proven static pure-vector.
1357    #[inline]
1358    fn record_canvas_output(
1359        &mut self,
1360        node_id: NodeId,
1361        phys_scale_milli: u32,
1362        bounds: Rect,
1363        tree_revision: u64,
1364        cmds: &[DrawCommand],
1365    ) -> bool {
1366        let slot_idx: usize = (node_id.get_index() as usize) & (CANVAS_STABILITY_SLOTS - 1);
1367        let Self {
1368            canvas_stability, ..
1369        } = self;
1370        let slot: &mut CanvasStabilityEntry = &mut canvas_stability[slot_idx];
1371        let mut has_raster: bool = false;
1372        let mut cmd_hash: u64 = FNV1A_OFFSET_BASIS;
1373        for cmd in cmds.iter() {
1374            if matches!(
1375                cmd,
1376                DrawCommand::Image { .. }
1377                    | DrawCommand::SharedImage { .. }
1378                    | DrawCommand::SpriteRegion { .. }
1379            ) {
1380                has_raster = true;
1381                break;
1382            }
1383            DisplayList::fold_command_full(&mut cmd_hash, cmd);
1384        }
1385        if has_raster {
1386            *slot = CanvasStabilityEntry {
1387                node_id,
1388                phys_scale_milli,
1389                bounds,
1390                tree_revision,
1391                cmd_hash: 0,
1392                stable_hits: 0,
1393                proven_dynamic: true,
1394                occupied: true,
1395            };
1396            return true;
1397        }
1398        if slot.occupied
1399            && slot.node_id == node_id
1400            && slot.phys_scale_milli == phys_scale_milli
1401            && slot.bounds == bounds
1402        {
1403            if slot.proven_dynamic {
1404                return true;
1405            }
1406            if slot.cmd_hash == cmd_hash {
1407                slot.tree_revision = tree_revision;
1408                slot.stable_hits = slot.stable_hits.saturating_add(1);
1409                return slot.stable_hits < 2;
1410            }
1411            if slot.tree_revision == tree_revision {
1412                slot.proven_dynamic = true;
1413                return true;
1414            }
1415            slot.tree_revision = tree_revision;
1416            slot.cmd_hash = cmd_hash;
1417            slot.stable_hits = 1;
1418            return true;
1419        }
1420        *slot = CanvasStabilityEntry {
1421            node_id,
1422            phys_scale_milli,
1423            bounds,
1424            tree_revision,
1425            cmd_hash,
1426            stable_hits: 1,
1427            proven_dynamic: false,
1428            occupied: true,
1429        };
1430        true
1431    }
1432}
1433
1434/// Scene-to-display-list compilation pass.
1435impl PaintPass {
1436    /// Computes a deterministic 64-bit signature of the active text selection state.
1437    ///
1438    /// # Arguments
1439    ///
1440    /// - `&SceneTree` - Retained scene tree.
1441    ///
1442    /// # Returns
1443    ///
1444    /// - `u64` - Selection digest (`0` when no text selection is active).
1445    #[inline]
1446    #[must_use]
1447    fn text_selection_sig(tree: &SceneTree) -> u64 {
1448        let Some(sel) = tree.text_selection() else {
1449            return 0;
1450        };
1451        if sel.is_empty() {
1452            return 0;
1453        }
1454        let anchor_id: NodeId = sel.get_anchor_node();
1455        let focus_id: NodeId = sel.get_focus_node();
1456        let mut height_val: u64 =
1457            ((anchor_id.get_index() as u64) << 32) | (anchor_id.get_generation() as u64);
1458        height_val =
1459            (height_val ^ (sel.get_anchor_char() as u64)).wrapping_mul(PAINT_FRAGMENT_FX_MULT);
1460        let focus_bits: u64 =
1461            ((focus_id.get_index() as u64) << 32) | (focus_id.get_generation() as u64);
1462        height_val = (height_val ^ focus_bits).wrapping_mul(PAINT_FRAGMENT_FX_MULT);
1463        height_val =
1464            (height_val ^ (sel.get_focus_char() as u64)).wrapping_mul(PAINT_FRAGMENT_FX_MULT);
1465        if height_val == 0 { 1 } else { height_val }
1466    }
1467
1468    /// Folds one `u64` word into a running FxHash accumulator.
1469    ///
1470    /// # Arguments
1471    ///
1472    /// - `&mut u64` - Running hash accumulator.
1473    /// - `u64` - Word to fold.
1474    #[inline(always)]
1475    fn fx_fold(hash: &mut u64, word: u64) {
1476        *hash = (*hash ^ word).wrapping_mul(PAINT_FRAGMENT_FX_MULT);
1477    }
1478
1479    /// Folds a `Rect`'s exact IEEE-754 bit pattern into `hash`.
1480    ///
1481    /// # Arguments
1482    ///
1483    /// - `&mut u64` - Running hash accumulator.
1484    /// - `Rect` - Rectangle to hash.
1485    #[inline(always)]
1486    fn fx_fold_rect(hash: &mut u64, rect: Rect) {
1487        let lo: u64 = ((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64);
1488        let hi: u64 =
1489            ((rect.get_width().to_bits() as u64) << 32) | (rect.get_height().to_bits() as u64);
1490        Self::fx_fold(hash, lo);
1491        Self::fx_fold(hash, hi);
1492    }
1493
1494    /// Folds a `PaintStyle`'s visual fields into `hash`.
1495    ///
1496    /// # Arguments
1497    ///
1498    /// - `&mut u64` - Running hash accumulator.
1499    /// - `&PaintStyle` - Paint style reference.
1500    #[inline]
1501    fn fx_fold_paint(hash: &mut u64, paint: &PaintStyle) {
1502        let bg_bits: u64 = paint
1503            .background_color()
1504            .map(|color_value: Color| {
1505                u32::from_le_bytes(color_value.to_rgba_bytes()) as u64 | (1_u64 << 32)
1506            })
1507            .unwrap_or(0);
1508        Self::fx_fold(hash, bg_bits);
1509        if let Some(grad) = paint.background_gradient() {
1510            let g0: u64 = u32::from_le_bytes(grad.get_start_color().to_rgba_bytes()) as u64;
1511            let g1: u64 = u32::from_le_bytes(grad.get_end_color().to_rgba_bytes()) as u64;
1512            Self::fx_fold(hash, (g0 << 32) | g1);
1513            Self::fx_fold(hash, grad.get_angle_deg().to_bits() as u64 | (1_u64 << 33));
1514        }
1515        let border: Border = paint.get_border();
1516        let b_word: u64 = ((border.get_width().to_bits() as u64) << 32)
1517            | (u32::from_le_bytes(border.get_color().to_rgba_bytes()) as u64);
1518        Self::fx_fold(hash, b_word);
1519        let red_val: CornerRadius = paint.get_radius();
1520        let r0: u64 = ((red_val.get_top_left().to_bits() as u64) << 32)
1521            | (red_val.get_top_right().to_bits() as u64);
1522        let r1: u64 = ((red_val.get_bottom_right().to_bits() as u64) << 32)
1523            | (red_val.get_bottom_left().to_bits() as u64);
1524        Self::fx_fold(hash, r0);
1525        Self::fx_fold(hash, r1);
1526        Self::fx_fold(hash, paint.get_opacity().to_bits() as u64);
1527        if let Some(sh) = paint.box_shadow() {
1528            let s0: u64 =
1529                ((sh.get_offset_x().to_bits() as u64) << 32) | (sh.get_offset_y().to_bits() as u64);
1530            let s1: u64 = ((sh.get_blur_radius().to_bits() as u64) << 32)
1531                | (sh.get_spread_radius().to_bits() as u64);
1532            Self::fx_fold(hash, s0);
1533            Self::fx_fold(hash, s1);
1534            Self::fx_fold(
1535                hash,
1536                u32::from_le_bytes(sh.get_color().to_rgba_bytes()) as u64 | (1_u64 << 34),
1537            );
1538        }
1539    }
1540
1541    /// Folds a `TextStyle` and UTF-8 string bytes into `hash`.
1542    ///
1543    /// # Arguments
1544    ///
1545    /// - `&mut u64` - Running hash accumulator.
1546    /// - `&TextStyle` - Typography style reference.
1547    /// - `&str` - Text content slice.
1548    #[inline]
1549    fn fx_fold_text(hash: &mut u64, text_style: &TextStyle, text: &str) {
1550        let m0: u64 = ((text_style.get_font_size().to_bits() as u64) << 32)
1551            | (text_style.get_line_height().to_bits() as u64);
1552        let m1: u64 = ((text_style.get_letter_spacing().to_bits() as u64) << 32)
1553            | (u32::from_le_bytes(text_style.get_color().to_rgba_bytes()) as u64);
1554        let flags: u64 = (text_style.get_family() as u64)
1555            | ((text_style.get_weight() as u64) << 8)
1556            | ((text_style.get_align() as u64) << 16)
1557            | ((text_style.get_overflow() as u64) << 24)
1558            | (u64::from(text_style.get_italic()) << 32);
1559        Self::fx_fold(hash, m0);
1560        Self::fx_fold(hash, m1);
1561        Self::fx_fold(hash, flags);
1562        let bytes: &[u8] = text.as_bytes();
1563        Self::fx_fold(hash, bytes.len() as u64);
1564        let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
1565        for chunk in chunks.iter() {
1566            Self::fx_fold(hash, u64::from_ne_bytes(*chunk));
1567        }
1568        if !rem.is_empty() {
1569            let mut tail: u64 = 0;
1570            for (idx, &blue_val) in rem.iter().enumerate() {
1571                tail |= (blue_val as u64) << (idx * 8);
1572            }
1573            Self::fx_fold(hash, tail);
1574        }
1575    }
1576
1577    /// Quantizes a DPI scale factor into integer milli-units (`1.25 -> 1250`, `2.625 -> 2625`, `3.0 -> 3000`).
1578    ///
1579    /// # Arguments
1580    ///
1581    /// - `f32` - Active DPI scale factor.
1582    ///
1583    /// # Returns
1584    ///
1585    /// - `u32` - Quantized physical scale key in milli-units.
1586    #[inline(always)]
1587    #[must_use]
1588    fn quantize_scale_milli(scale: f32) -> u32 {
1589        (scale.max(0.5) * 1000.0).round() as u32
1590    }
1591
1592    /// Recursively fingerprints children of a cacheable container up to bounded depth and node count.
1593    ///
1594    /// # Arguments
1595    ///
1596    /// - `&SceneTree` - Retained scene tree.
1597    /// - `NodeId` - Parent container node handle whose children are fingerprinted.
1598    /// - `usize` - Current nesting depth (`1..=PAINT_FRAGMENT_MAX_DEPTH`).
1599    /// - `Option<(Point, Rect, f32, f32)>` - Optional `(offset_phys, cull_rect, scale, inv_scale)` when ancestor overflow is unclipped.
1600    /// - `(Option<NodeId>, bool)` - Active `(hover_target, has_text_selection)` state.
1601    /// - `&mut (usize, u64, u64)` - Mutable `(nodes_visited, geom_hash, style_text_hash)` accumulator.
1602    ///
1603    /// # Returns
1604    ///
1605    /// - `bool` - `true` when all descendants are pure, clean, and eligible for retained fragment caching.
1606    #[inline]
1607    #[must_use]
1608    fn fingerprint_subtree_children(
1609        tree: &SceneTree,
1610        parent: NodeId,
1611        depth: usize,
1612        unclipped_cull: Option<(Point, Rect, f32, f32)>,
1613        focus_pair: (Option<NodeId>, bool),
1614        acc: &mut (usize, u64, u64),
1615    ) -> bool {
1616        let child_count: usize = tree.child_count(parent);
1617        if depth > PAINT_FRAGMENT_MAX_DEPTH || child_count > PAINT_FRAGMENT_MAX_CHILDREN {
1618            return false;
1619        }
1620        let (active_hover_target, has_text_sel): (Option<NodeId>, bool) = focus_pair;
1621        Self::fx_fold(&mut acc.1, child_count as u64);
1622        for cid in tree.children_iter(parent) {
1623            if acc.0 >= PAINT_FRAGMENT_MAX_NODES
1624                || active_hover_target == Some(cid)
1625                || (has_text_sel && tree.text_selection_range_for(cid).is_some())
1626                || tree.backdrop_blur_radius(cid) > 0.0
1627            {
1628                return false;
1629            }
1630            let Some(child) = tree.get_node(cid) else {
1631                return false;
1632            };
1633            acc.0 += 1;
1634            let c_inter: InteractionState = child.get_interaction();
1635            let c_active: bool = c_inter.get_hovered() || c_inter.get_pressed();
1636            if c_active || c_inter.get_focused() {
1637                return false;
1638            }
1639            let c_style: &Style = child.style_ref();
1640            let child_is_top_overlay: bool = c_style.layout.get_position() == Position::Fixed
1641                || (c_style.layout.get_position() == Position::Absolute
1642                    && c_style.layout.get_z_index() >= 50);
1643            if child_is_top_overlay {
1644                return false;
1645            }
1646            let c_tag: u64 = match child.get_kind() {
1647                NodeKind::View | NodeKind::Fragment => 1,
1648                NodeKind::Text(text) => {
1649                    Self::fx_fold_text(&mut acc.2, &c_style.text, text.as_str());
1650                    Self::fx_fold_rect(&mut acc.1, child.layout_box.get_content_bounds());
1651                    2
1652                }
1653                NodeKind::Image(buf) => {
1654                    Self::fx_fold(&mut acc.2, tree.node_paint_epoch(cid) as u64);
1655                    Self::fx_fold(
1656                        &mut acc.2,
1657                        ((buf.get_width() as u64) << 32) | (buf.get_height() as u64),
1658                    );
1659                    Self::fx_fold(&mut acc.2, buf.get_pixels().as_ptr() as usize as u64);
1660                    3
1661                }
1662                NodeKind::Canvas(CanvasCaching::RetainedStatic) => {
1663                    Self::fx_fold(&mut acc.2, tree.node_paint_epoch(cid) as u64);
1664                    if let Some(callback_fn) = child.canvas_callback() {
1665                        let cb_addr: u64 = (Rc::as_ptr(&callback_fn) as *const ()) as usize as u64;
1666                        Self::fx_fold(&mut acc.2, cb_addr);
1667                    }
1668                    4
1669                }
1670                NodeKind::Portal
1671                | NodeKind::Canvas(CanvasCaching::DynamicPerFrame)
1672                | NodeKind::Input(_)
1673                | NodeKind::ScrollView => {
1674                    return false;
1675                }
1676            };
1677            let c_id_bits: u64 = ((cid.get_index() as u64) << 32) | (cid.get_generation() as u64);
1678            Self::fx_fold(&mut acc.1, c_id_bits);
1679            let raw_b: Rect = child.layout_box.get_bounds();
1680            Self::fx_fold_rect(&mut acc.1, raw_b);
1681            let ct: Transform2D = c_style.paint.get_transform();
1682            Self::fx_fold(
1683                &mut acc.1,
1684                ((ct.get_translate_x().to_bits() as u64) << 32)
1685                    | (ct.get_translate_y().to_bits() as u64),
1686            );
1687            Self::fx_fold(
1688                &mut acc.1,
1689                ((ct.get_scale_x().to_bits() as u64) << 32) | (ct.get_scale_y().to_bits() as u64),
1690            );
1691            let c_lay_bits: u64 = (c_tag << 40)
1692                | ((c_style.layout.get_display() as u64) << 32)
1693                | ((c_style.layout.get_overflow() as u64) << 24)
1694                | ((c_style.layout.get_z_index() as u32) as u64);
1695            Self::fx_fold(&mut acc.2, c_lay_bits);
1696            Self::fx_fold_paint(&mut acc.2, &c_style.paint);
1697            let mut next_cull_check: Option<(Point, Rect, f32, f32)> = None;
1698            if let Some((off_phys, cull_rect, scale, inv_scale)) = unclipped_cull {
1699                let tx_phys: f32 = (ct.get_translate_x() * scale).round();
1700                let ty_phys: f32 = (ct.get_translate_y() * scale).round();
1701                let tot_x: f32 = off_phys.get_x() + tx_phys;
1702                let tot_y: f32 = off_phys.get_y() + ty_phys;
1703                let rx0: f32 = (raw_b.get_x() * scale).round();
1704                let ry0: f32 = (raw_b.get_y() * scale).round();
1705                let rx1: f32 = (raw_b.right() * scale).round();
1706                let ry1: f32 = (raw_b.bottom() * scale).round();
1707                let stroke_width: f32 = ((rx1 - rx0).max(0.0) * ct.get_scale_x()).round().max(0.0);
1708                let sh: f32 = ((ry1 - ry0).max(0.0) * ct.get_scale_y()).round().max(0.0);
1709                let sdx: f32 = (((rx1 - rx0).max(0.0) - stroke_width) * 0.5).round();
1710                let sdy: f32 = (((ry1 - ry0).max(0.0) - sh) * 0.5).round();
1711                let c_bounds: Rect = Rect::new(
1712                    (rx0 + tot_x + sdx) * inv_scale,
1713                    (ry0 + tot_y + sdy) * inv_scale,
1714                    stroke_width * inv_scale,
1715                    sh * inv_scale,
1716                );
1717                let c_vis: Rect = Self::conservative_self_vis_rect(
1718                    child,
1719                    c_bounds,
1720                    &c_style.paint,
1721                    false,
1722                    (tot_x, tot_y),
1723                    scale,
1724                    inv_scale,
1725                );
1726                let c_in_x: bool =
1727                    c_vis.get_x() >= cull_rect.get_x() && c_vis.right() <= cull_rect.right();
1728                let c_in_y: bool =
1729                    c_vis.get_y() >= cull_rect.get_y() && c_vis.bottom() <= cull_rect.bottom();
1730                if !c_in_x || !c_in_y {
1731                    return false;
1732                }
1733                if c_style.layout.get_overflow() != Overflow::Hidden {
1734                    let c_scroll: Point = child.layout_box.get_scroll_offset();
1735                    let next_off: Point = Point::new(
1736                        tot_x - (c_scroll.get_x() * scale).round(),
1737                        tot_y - (c_scroll.get_y() * scale).round(),
1738                    );
1739                    next_cull_check = Some((next_off, cull_rect, scale, inv_scale));
1740                }
1741            }
1742            if tree.has_children(cid)
1743                && !Self::fingerprint_subtree_children(
1744                    tree,
1745                    cid,
1746                    depth + 1,
1747                    next_cull_check,
1748                    focus_pair,
1749                    acc,
1750                )
1751            {
1752                return false;
1753            }
1754        }
1755        true
1756    }
1757
1758    /// Computes `(geom_hash, style_text_hash)` for an eligible nested container subtree, or `None` if uncacheable.
1759    ///
1760    /// # Arguments
1761    ///
1762    /// - `&SceneTree` - Retained scene tree.
1763    /// - `NodeId` - Candidate container node handle.
1764    /// - `&SceneNode` - Candidate container node reference.
1765    /// - `Option<(Point, Rect, f32, f32)>` - Optional child cull-verification context when container overflow is unclipped.
1766    /// - `(Option<NodeId>, bool)` - Active `(hover_target, has_text_selection)` state.
1767    ///
1768    /// # Returns
1769    ///
1770    /// - `Option<(u64, u64)>` - Tuple `(geom_hash, style_text_hash)` when the subtree is pure and cache-eligible.
1771    #[inline]
1772    #[must_use]
1773    fn fingerprint_subtree(
1774        tree: &SceneTree,
1775        node_id: NodeId,
1776        node: &SceneNode,
1777        unclipped_cull: Option<(Point, Rect, f32, f32)>,
1778        focus_pair: (Option<NodeId>, bool),
1779    ) -> Option<(u64, u64)> {
1780        let child_count: usize = tree.child_count(node_id);
1781        if child_count == 0
1782            || child_count > PAINT_FRAGMENT_MAX_CHILDREN
1783            || tree.backdrop_blur_radius(node_id) > 0.0
1784        {
1785            return None;
1786        }
1787        let style: &Style = node.style_ref();
1788        let transform: Transform2D = style.paint.get_transform();
1789        let scroll: Point = node.layout_box.get_scroll_offset();
1790        let mut geom_h: u64 = child_count as u64;
1791        Self::fx_fold_rect(&mut geom_h, node.layout_box.get_bounds());
1792        Self::fx_fold(
1793            &mut geom_h,
1794            ((transform.get_translate_x().to_bits() as u64) << 32)
1795                | (transform.get_translate_y().to_bits() as u64),
1796        );
1797        Self::fx_fold(
1798            &mut geom_h,
1799            ((transform.get_scale_x().to_bits() as u64) << 32)
1800                | (transform.get_scale_y().to_bits() as u64),
1801        );
1802        Self::fx_fold(
1803            &mut geom_h,
1804            ((scroll.get_x().to_bits() as u64) << 32) | (scroll.get_y().to_bits() as u64),
1805        );
1806        let mut style_h: u64 =
1807            ((node_id.get_index() as u64) << 32) | (node_id.get_generation() as u64);
1808        Self::fx_fold_paint(&mut style_h, &style.paint);
1809        let mut acc: (usize, u64, u64) = (0, geom_h, style_h);
1810        if !Self::fingerprint_subtree_children(
1811            tree,
1812            node_id,
1813            1,
1814            unclipped_cull,
1815            focus_pair,
1816            &mut acc,
1817        ) {
1818            return None;
1819        }
1820        Some((acc.1, acc.2))
1821    }
1822
1823    /// Translates a single physical-pixel-snapped logical coordinate by `d_phys` without cumulative drift across fractional DPRs.
1824    ///
1825    /// # Arguments
1826    ///
1827    /// - `f32` - Cached logical coordinate.
1828    /// - `f32` - Integer physical-pixel displacement delta.
1829    /// - `f32` - Active DPI scale factor.
1830    /// - `f32` - Reciprocal of `scale`.
1831    /// - `bool` - True when `scale` is an exact power-of-two (`1.0`, `2.0`, `4.0`).
1832    ///
1833    /// # Returns
1834    ///
1835    /// - `f32` - Bit-exact translated logical coordinate.
1836    #[inline(always)]
1837    #[must_use]
1838    fn translate_coord(
1839        item_val: f32,
1840        d_phys: f32,
1841        scale: f32,
1842        inv_scale: f32,
1843        dyadic: bool,
1844    ) -> f32 {
1845        if d_phys == 0.0 {
1846            return item_val;
1847        }
1848        if dyadic {
1849            return item_val + d_phys * inv_scale;
1850        }
1851        ((item_val * scale).round() + d_phys) * inv_scale
1852    }
1853
1854    /// Translates a cached logical `Rect` origin by `(dx_phys, dy_phys)` preserving exact physical-pixel snapping across all DPRs.
1855    ///
1856    /// # Arguments
1857    ///
1858    /// - `Rect` - Cached logical rectangle.
1859    /// - `f32` - Physical X displacement delta.
1860    /// - `f32` - Physical Y displacement delta.
1861    /// - `f32` - Active DPI scale factor.
1862    /// - `f32` - Reciprocal of `scale`.
1863    /// - `bool` - True when `scale` is dyadic (`1.0`, `2.0`, `4.0`).
1864    ///
1865    /// # Returns
1866    ///
1867    /// - `Rect` - Translated logical rectangle with invariant width and height.
1868    #[inline(always)]
1869    #[must_use]
1870    fn translate_rect(
1871        rect: Rect,
1872        dx_phys: f32,
1873        dy_phys: f32,
1874        scale: f32,
1875        inv_scale: f32,
1876        dyadic: bool,
1877    ) -> Rect {
1878        Rect::new(
1879            Self::translate_coord(rect.get_x(), dx_phys, scale, inv_scale, dyadic),
1880            Self::translate_coord(rect.get_y(), dy_phys, scale, inv_scale, dyadic),
1881            rect.get_width(),
1882            rect.get_height(),
1883        )
1884    }
1885
1886    /// Translates and emits one slab-backed `CachedDrawCommand` into `display_list` using the string pool for zero-alloc fragment reuse.
1887    ///
1888    /// # Arguments
1889    ///
1890    /// - `&CachedDrawCommand` - Cached draw command inside `PaintFragmentCache::cmd_slab`.
1891    /// - `&[u8]` - Backing UTF-8 byte slab (`PaintFragmentCache::text_slab`).
1892    /// - `(f32, f32)` - Physical pixel displacement `(dx_phys, dy_phys)`.
1893    /// - `(f32, f32, bool)` - Active `(scale, inv_scale, is_dyadic_scale)`.
1894    /// - `&mut DisplayList` - Output display list receiving the translated command.
1895    #[inline]
1896    fn push_translated_command(
1897        cmd: &CachedDrawCommand,
1898        text_slab: &[u8],
1899        delta_phys: (f32, f32),
1900        scale_info: (f32, f32, bool),
1901        display_list: &mut DisplayList,
1902    ) {
1903        let (dx_phys, dy_phys): (f32, f32) = delta_phys;
1904        let (scale, inv_scale, dyadic): (f32, f32, bool) = scale_info;
1905        let translated: DrawCommand = match cmd {
1906            CachedDrawCommand::Clear(char_item) => DrawCommand::Clear(*char_item),
1907            CachedDrawCommand::FillRoundedRect {
1908                rect,
1909                color,
1910                radius,
1911                border,
1912            } => DrawCommand::FillRoundedRect {
1913                rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
1914                color: *color,
1915                radius: *radius,
1916                border: *border,
1917            },
1918            CachedDrawCommand::LinearGradientRect {
1919                rect,
1920                gradient,
1921                radius,
1922            } => DrawCommand::LinearGradientRect {
1923                rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
1924                gradient: *gradient,
1925                radius: *radius,
1926            },
1927            CachedDrawCommand::BoxShadow {
1928                rect,
1929                radius,
1930                shadow,
1931            } => DrawCommand::BoxShadow {
1932                rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
1933                radius: *radius,
1934                shadow: *shadow,
1935            },
1936            CachedDrawCommand::BackdropBlur {
1937                rect,
1938                radius,
1939                blur_radius,
1940            } => DrawCommand::BackdropBlur {
1941                rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
1942                radius: *radius,
1943                blur_radius: *blur_radius,
1944            },
1945            CachedDrawCommand::TextRun {
1946                rect,
1947                text_start,
1948                text_len,
1949                style,
1950            } => {
1951                let source_val: usize = *text_start as usize;
1952                let event_ref: usize = source_val.saturating_add(*text_len as usize);
1953                let src: &str = text_slab
1954                    .get(source_val..event_ref)
1955                    .and_then(|blue_val: &[u8]| from_utf8(blue_val).ok())
1956                    .unwrap_or("");
1957                DrawCommand::TextRun {
1958                    rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
1959                    text: display_list.alloc_text(src),
1960                    style: *style,
1961                }
1962            }
1963            CachedDrawCommand::TextCaret {
1964                text_rect,
1965                content_rect,
1966                text_start,
1967                text_len,
1968                style,
1969                caret_height,
1970                color,
1971                multiline,
1972            } => {
1973                let scale_val: usize = *text_start as usize;
1974                let error_val: usize = scale_val.saturating_add(*text_len as usize);
1975                let src: &str = text_slab
1976                    .get(scale_val..error_val)
1977                    .and_then(|byte_val: &[u8]| from_utf8(byte_val).ok())
1978                    .unwrap_or("");
1979                DrawCommand::TextCaret {
1980                    text_rect: Self::translate_rect(
1981                        *text_rect, dx_phys, dy_phys, scale, inv_scale, dyadic,
1982                    ),
1983                    content_rect: Self::translate_rect(
1984                        *content_rect,
1985                        dx_phys,
1986                        dy_phys,
1987                        scale,
1988                        inv_scale,
1989                        dyadic,
1990                    ),
1991                    text: display_list.alloc_text(src),
1992                    style: *style,
1993                    caret_height: *caret_height,
1994                    color: *color,
1995                    multiline: *multiline,
1996                }
1997            }
1998            CachedDrawCommand::Image {
1999                rect,
2000                buffer,
2001                radius,
2002            } => DrawCommand::Image {
2003                rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
2004                buffer: buffer.clone(),
2005                radius: *radius,
2006            },
2007            CachedDrawCommand::SharedImage {
2008                rect,
2009                width,
2010                height,
2011                pixels,
2012                radius,
2013            } => DrawCommand::SharedImage {
2014                rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
2015                width: *width,
2016                height: *height,
2017                pixels: Arc::clone(pixels),
2018                radius: *radius,
2019            },
2020            CachedDrawCommand::Line {
2021                from,
2022                to,
2023                color,
2024                width,
2025            } => DrawCommand::Line {
2026                from: Point::new(
2027                    Self::translate_coord(from.get_x(), dx_phys, scale, inv_scale, dyadic),
2028                    Self::translate_coord(from.get_y(), dy_phys, scale, inv_scale, dyadic),
2029                ),
2030                to: Point::new(
2031                    Self::translate_coord(to.get_x(), dx_phys, scale, inv_scale, dyadic),
2032                    Self::translate_coord(to.get_y(), dy_phys, scale, inv_scale, dyadic),
2033                ),
2034                color: *color,
2035                width: *width,
2036            },
2037            CachedDrawCommand::Circle {
2038                center,
2039                radius,
2040                color,
2041            } => DrawCommand::Circle {
2042                center: Point::new(
2043                    Self::translate_coord(center.get_x(), dx_phys, scale, inv_scale, dyadic),
2044                    Self::translate_coord(center.get_y(), dy_phys, scale, inv_scale, dyadic),
2045                ),
2046                radius: *radius,
2047                color: *color,
2048            },
2049            CachedDrawCommand::Triangle { p0, p1, p2, color } => DrawCommand::Triangle {
2050                p0: Point::new(
2051                    Self::translate_coord(p0.get_x(), dx_phys, scale, inv_scale, dyadic),
2052                    Self::translate_coord(p0.get_y(), dy_phys, scale, inv_scale, dyadic),
2053                ),
2054                p1: Point::new(
2055                    Self::translate_coord(p1.get_x(), dx_phys, scale, inv_scale, dyadic),
2056                    Self::translate_coord(p1.get_y(), dy_phys, scale, inv_scale, dyadic),
2057                ),
2058                p2: Point::new(
2059                    Self::translate_coord(p2.get_x(), dx_phys, scale, inv_scale, dyadic),
2060                    Self::translate_coord(p2.get_y(), dy_phys, scale, inv_scale, dyadic),
2061                ),
2062                color: *color,
2063            },
2064            CachedDrawCommand::SpriteRegion {
2065                rect,
2066                buffer,
2067                src_rect,
2068                tint,
2069            } => DrawCommand::SpriteRegion {
2070                rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
2071                buffer: buffer.clone(),
2072                src_rect: *src_rect,
2073                tint: *tint,
2074            },
2075            CachedDrawCommand::PushClip(rect) => DrawCommand::PushClip(Self::translate_rect(
2076                *rect, dx_phys, dy_phys, scale, inv_scale, dyadic,
2077            )),
2078            CachedDrawCommand::PushRoundedClip { rect, radius } => DrawCommand::PushRoundedClip {
2079                rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
2080                radius: *radius,
2081            },
2082            CachedDrawCommand::PopClip => DrawCommand::PopClip,
2083        };
2084        display_list.push(translated);
2085    }
2086
2087    /// Compiles `tree` into `display_list`, culling offscreen nodes and honoring z-index stacking.
2088    ///
2089    /// # Arguments
2090    ///
2091    /// - `&SceneTree` - Laid-out scene tree.
2092    /// - `Size` - Logical viewport size.
2093    /// - `f32` - DPI scale factor.
2094    /// - `Color` - Surface clear background color.
2095    /// - `&mut DisplayList` - Output reusable display list.
2096    pub fn build(
2097        tree: &SceneTree,
2098        viewport: Size,
2099        scale_factor: f32,
2100        clear_color: Color,
2101        display_list: &mut DisplayList,
2102    ) {
2103        let mut saw_canvas: bool = false;
2104        Self::build_inner(
2105            tree,
2106            viewport,
2107            scale_factor,
2108            clear_color,
2109            display_list,
2110            None,
2111            &mut saw_canvas,
2112        );
2113    }
2114
2115    /// Packs an optional `NodeId` into a single `u64` (`u64::MAX` when `None`).
2116    ///
2117    /// # Arguments
2118    ///
2119    /// - `Option<NodeId>` - Optional node handle.
2120    ///
2121    /// # Returns
2122    ///
2123    /// - `u64` - Packed `(index << 32) | generation` or `u64::MAX`.
2124    #[inline(always)]
2125    #[must_use]
2126    fn pack_opt_node_id(node: Option<NodeId>) -> u64 {
2127        match node {
2128            Some(id) => ((id.get_index() as u64) << 32) | (id.get_generation() as u64),
2129            None => u64::MAX,
2130        }
2131    }
2132
2133    /// Compiles `tree` into `display_list` with cross-frame whole-list retention and subtree `DrawCommand` fragment caching.
2134    ///
2135    /// # Arguments
2136    ///
2137    /// - `&SceneTree` - Laid-out scene tree.
2138    /// - `Size` - Logical viewport size.
2139    /// - `f32` - DPI scale factor.
2140    /// - `Color` - Surface clear background color.
2141    /// - `bool` - Whether layout recomputed any node geometry on this frame.
2142    /// - `&mut DisplayList` - Output reusable display list.
2143    /// - `&mut PaintFragmentCache` - Persistent cross-frame fragment cache.
2144    pub fn build_retained(
2145        tree: &SceneTree,
2146        viewport: Size,
2147        scale_factor: f32,
2148        clear_color: Color,
2149        layout_changed: bool,
2150        display_list: &mut DisplayList,
2151        cache: &mut PaintFragmentCache,
2152    ) {
2153        let clamped_scale: f32 = scale_factor.max(0.5);
2154        let focus: FocusManager = tree.get_focus();
2155        let sig: PaintSceneSignature = PaintSceneSignature {
2156            tree_ptr: (tree as *const SceneTree) as usize,
2157            tree_revision: tree.get_revision(),
2158            viewport_w_bits: viewport.get_width().to_bits(),
2159            viewport_h_bits: viewport.get_height().to_bits(),
2160            scale_bits: clamped_scale.to_bits(),
2161            clear_rgba: u32::from_le_bytes(clear_color.to_rgba_bytes()),
2162            focused_packed: Self::pack_opt_node_id(focus.focused_node()),
2163            hovered_packed: Self::pack_opt_node_id(focus.hovered_node()),
2164            pressed_packed: Self::pack_opt_node_id(focus.pressed_node()),
2165            caret_visible: tree.get_caret_visible(),
2166            text_sel_sig: Self::text_selection_sig(tree),
2167        };
2168        if !layout_changed
2169            && !cache.last_has_canvas
2170            && !display_list.is_empty()
2171            && cache.has_last_scene
2172            && cache.last_scene_sig == sig
2173        {
2174            cache.whole_list_hits = cache.whole_list_hits.wrapping_add(1);
2175            return;
2176        }
2177        cache.ensure_slots();
2178        let mut saw_canvas: bool = false;
2179        Self::build_inner(
2180            tree,
2181            viewport,
2182            clamped_scale,
2183            clear_color,
2184            display_list,
2185            Some(cache),
2186            &mut saw_canvas,
2187        );
2188        cache.last_has_canvas = saw_canvas;
2189        cache.has_last_scene = true;
2190        cache.last_scene_sig = sig;
2191    }
2192
2193    /// Populates `out_ancestors` with deduplicated ancestor handles leading to every live `Portal` / `Position::Fixed` node.
2194    ///
2195    /// # Arguments
2196    ///
2197    /// - `&SceneTree` - Retained scene tree.
2198    /// - `&mut Vec<NodeId>` - Reusable output scratch buffer (cleared first).
2199    fn collect_portal_ancestors(tree: &SceneTree, out_ancestors: &mut Vec<NodeId>) {
2200        out_ancestors.clear();
2201        let portal_nodes: &[NodeId] = tree.portal_nodes();
2202        if portal_nodes.is_empty() {
2203            return;
2204        }
2205        for &pid in portal_nodes.iter() {
2206            let mut cur: Option<NodeId> = tree.get_node(pid).and_then(SceneNode::parent_id);
2207            while let Some(anc) = cur {
2208                if out_ancestors.contains(&anc) {
2209                    break;
2210                }
2211                out_ancestors.push(anc);
2212                cur = tree.get_node(anc).and_then(SceneNode::parent_id);
2213            }
2214        }
2215        if out_ancestors.len() > 16 {
2216            out_ancestors.sort_unstable_by_key(|id: &NodeId| {
2217                ((id.get_index() as u64) << 32) | (id.get_generation() as u64)
2218            });
2219        }
2220    }
2221
2222    /// Returns `true` when `node_id` lies on an ancestor chain above at least one live `Portal` or `Position::Fixed` node.
2223    ///
2224    /// # Arguments
2225    ///
2226    /// - `&[NodeId]` - Precomputed portal ancestor slice from `collect_portal_ancestors`.
2227    /// - `NodeId` - Candidate container node handle.
2228    ///
2229    /// # Returns
2230    ///
2231    /// - `bool` - True when a culled subtree rooted at `node_id` must still forward portal descendants.
2232    #[inline]
2233    #[must_use]
2234    fn is_portal_ancestor(ancestors: &[NodeId], node_id: NodeId) -> bool {
2235        if ancestors.is_empty() {
2236            return false;
2237        }
2238        if ancestors.len() <= 16 {
2239            return ancestors.contains(&node_id);
2240        }
2241        let target: u64 = ((node_id.get_index() as u64) << 32) | (node_id.get_generation() as u64);
2242        ancestors
2243            .binary_search_by_key(&target, |id: &NodeId| {
2244                ((id.get_index() as u64) << 32) | (id.get_generation() as u64)
2245            })
2246            .is_ok()
2247    }
2248
2249    /// Computes exact conservative logical paint bounds for `node`, accounting for directional `BoxShadow` spread/blur, focus rings, and text overhang.
2250    ///
2251    /// # Arguments
2252    ///
2253    /// - `&SceneNode` - Target scene node.
2254    /// - `Rect` - Transformed logical border-box bounds.
2255    /// - `&PaintStyle` - Active resolved paint style.
2256    /// - `bool` - Whether the node currently holds keyboard focus.
2257    /// - `(f32, f32)` - Accumulated physical pixel displacement `(total_off_x, total_off_y)`.
2258    /// - `f32` - Clamped DPI scale factor.
2259    /// - `f32` - Reciprocal of `scale`.
2260    ///
2261    /// # Returns
2262    ///
2263    /// - `Rect` - Conservative logical visual bounding rectangle matching software rasterization extents.
2264    #[inline]
2265    #[must_use]
2266    fn conservative_self_vis_rect(
2267        node: &SceneNode,
2268        bounds: Rect,
2269        paint: &PaintStyle,
2270        focused: bool,
2271        total_off_phys: (f32, f32),
2272        scale: f32,
2273        inv_scale: f32,
2274    ) -> Rect {
2275        let mut min_x: f32 = bounds.get_x() - 1.0;
2276        let mut min_y: f32 = bounds.get_y() - 1.0;
2277        let mut max_x: f32 = bounds.right() + 1.0;
2278        let mut max_y: f32 = bounds.bottom() + 1.0;
2279        if let Some(shadow) = paint.box_shadow()
2280            && shadow.get_color().get_alpha() > 0
2281        {
2282            let spread: f32 = shadow.get_spread_radius().max(0.0);
2283            let blur_phys: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
2284            let sigma_phys: f32 = (blur_phys * 0.5).max(0.75);
2285            let blur_pad: f32 = (sigma_phys * 3.0).ceil() * inv_scale + 2.0 * inv_scale;
2286            let pad: f32 = spread + blur_pad;
2287            let sx0: f32 = bounds.get_x() + shadow.get_offset_x() - pad;
2288            let sy0: f32 = bounds.get_y() + shadow.get_offset_y() - pad;
2289            let sx1: f32 = bounds.right() + shadow.get_offset_x() + pad;
2290            let sy1: f32 = bounds.bottom() + shadow.get_offset_y() + pad;
2291            min_x = min_x.min(sx0);
2292            min_y = min_y.min(sy0);
2293            max_x = max_x.max(sx1);
2294            max_y = max_y.max(sy1);
2295        }
2296        if focused && let Some(ring) = paint.focus_ring_border() {
2297            let rw: f32 = ring.get_width().max(0.0) + 1.0;
2298            min_x = min_x.min(bounds.get_x() - rw);
2299            min_y = min_y.min(bounds.get_y() - rw);
2300            max_x = max_x.max(bounds.right() + rw);
2301            max_y = max_y.max(bounds.bottom() + rw);
2302        }
2303        if matches!(node.get_kind(), NodeKind::Text(_)) {
2304            let content_b: Rect = node.layout_box.get_content_bounds();
2305            let cx0: f32 = ((content_b.get_x() * scale).round() + total_off_phys.0) * inv_scale;
2306            let cy0: f32 = ((content_b.get_y() * scale).round() + total_off_phys.1) * inv_scale;
2307            let pad: f32 = node.style_ref().text.get_font_size() * 0.5 + 2.0;
2308            min_x = min_x.min(cx0 - pad);
2309            min_y = min_y.min(cy0 - pad);
2310            max_x = max_x.max(cx0 + content_b.get_width() + pad);
2311            max_y = max_y.max(cy0 + content_b.get_height() + pad);
2312        }
2313        Rect::new(
2314            min_x,
2315            min_y,
2316            (max_x - min_x).max(0.0),
2317            (max_y - min_y).max(0.0),
2318        )
2319    }
2320
2321    /// Visits one child inside a clipped off-screen subtree solely to collect escaping `Portal` / `Position::Fixed` descendants in exact tree order.
2322    ///
2323    /// # Arguments
2324    ///
2325    /// - `&SceneTree` - Retained scene tree.
2326    /// - `NodeId` - Child node handle to inspect.
2327    /// - `f32` - Effective ancestor opacity.
2328    /// - `&mut PaintScratch<'_>` - Mutable portal queue and z-sort scratch buffers.
2329    fn visit_culled_portal_child(
2330        tree: &SceneTree,
2331        child_id: NodeId,
2332        parent_opacity: f32,
2333        scratch: &mut PaintScratch<'_>,
2334    ) {
2335        let Some(child) = tree.get_node(child_id) else {
2336            return;
2337        };
2338        let style: &Style = child.style_ref();
2339        let layout: &LayoutStyle = &style.layout;
2340        if layout.get_display() == Display::None {
2341            return;
2342        }
2343        let is_portal: bool = matches!(child.get_kind(), NodeKind::Portal)
2344            || layout.get_position() == Position::Fixed;
2345        if is_portal {
2346            if let Some(portal_queue) = scratch.portals.as_deref_mut() {
2347                portal_queue.push((layout.get_z_index(), portal_queue.len(), child_id));
2348            }
2349            return;
2350        }
2351        if !Self::is_portal_ancestor(scratch.portal_ancestors, child_id) {
2352            return;
2353        }
2354        let hovered: bool = child.get_interaction().get_hovered();
2355        let paint_opacity: f32 = if hovered {
2356            child
2357                .hover_paint()
2358                .map(|hp: PaintStyle| hp.get_opacity())
2359                .unwrap_or_else(|| style.paint.get_opacity())
2360        } else {
2361            style.paint.get_opacity()
2362        };
2363        let next_opacity: f32 = (parent_opacity * paint_opacity).clamp(0.0, 1.0);
2364        if next_opacity <= 0.0 {
2365            return;
2366        }
2367        Self::collect_portals_in_culled_subtree(tree, child_id, next_opacity, scratch);
2368    }
2369
2370    /// Walks only portal-ancestor branches below a culled clipped container so escaping `Portal` / `Position::Fixed` nodes preserve exact paint order with zero non-portal work.
2371    ///
2372    /// # Arguments
2373    ///
2374    /// - `&SceneTree` - Retained scene tree.
2375    /// - `NodeId` - Culled clipped ancestor node handle.
2376    /// - `f32` - Effective ancestor opacity.
2377    /// - `&mut PaintScratch<'_>` - Mutable portal queue and z-sort scratch buffers.
2378    fn collect_portals_in_culled_subtree(
2379        tree: &SceneTree,
2380        node_id: NodeId,
2381        parent_opacity: f32,
2382        scratch: &mut PaintScratch<'_>,
2383    ) {
2384        if tree.get_node(node_id).is_none() {
2385            return;
2386        }
2387        let child_count: usize = tree.child_count(node_id);
2388        if child_count == 0 {
2389            return;
2390        }
2391        let needs_z_sort: bool = child_count > 1 && tree.has_nonzero_z_child(node_id);
2392        if !needs_z_sort {
2393            for child_id in tree.children_iter(node_id) {
2394                Self::visit_culled_portal_child(tree, child_id, parent_opacity, scratch);
2395            }
2396        } else {
2397            let sort_start: usize = scratch.z_sort.len();
2398            for (idx, cid) in tree.children_iter(node_id).enumerate() {
2399                if let Some(char_item) = tree.get_node(cid) {
2400                    scratch
2401                        .z_sort
2402                        .push((char_item.style_ref().layout.get_z_index(), idx, cid));
2403                }
2404            }
2405            let sort_end: usize = scratch.z_sort.len();
2406            scratch.z_sort[sort_start..sort_end].sort_by(
2407                |target_node_id: &(i32, usize, NodeId), element_id: &(i32, usize, NodeId)| {
2408                    target_node_id
2409                        .0
2410                        .cmp(&element_id.0)
2411                        .then_with(|| target_node_id.1.cmp(&element_id.1))
2412                },
2413            );
2414            for slot_idx in sort_start..sort_end {
2415                let child_id: NodeId = scratch.z_sort[slot_idx].2;
2416                Self::visit_culled_portal_child(tree, child_id, parent_opacity, scratch);
2417            }
2418            scratch.z_sort.truncate(sort_start);
2419        }
2420    }
2421
2422    /// Shared internal scene-to-display-list builder supporting optional retained fragment caching.
2423    ///
2424    /// # Arguments
2425    ///
2426    /// - `&SceneTree` - Laid-out scene tree.
2427    /// - `Size` - Logical viewport size.
2428    /// - `f32` - DPI scale factor.
2429    /// - `Color` - Surface clear background color.
2430    /// - `&mut DisplayList` - Output reusable display list.
2431    /// - `Option<&mut PaintFragmentCache>` - Optional cross-frame fragment cache.
2432    /// - `&mut bool` - Output flag set when any `NodeKind::Canvas` is visited.
2433    fn build_inner(
2434        tree: &SceneTree,
2435        viewport: Size,
2436        scale_factor: f32,
2437        clear_color: Color,
2438        display_list: &mut DisplayList,
2439        mut fragments: Option<&mut PaintFragmentCache>,
2440        saw_canvas: &mut bool,
2441    ) {
2442        display_list.reset(viewport, scale_factor);
2443        display_list.push(DrawCommand::Clear(clear_color));
2444        let viewport_rect: Rect = Rect::new(0.0, 0.0, viewport.get_width(), viewport.get_height());
2445        let active_hover_target: Option<NodeId> = Self::resolve_active_hover_target(tree);
2446        let mut portals: Vec<(i32, usize, NodeId)> = take(&mut display_list.arena.portals_scratch);
2447        let mut z_sort: Vec<(i32, usize, NodeId)> = take(&mut display_list.arena.z_sort_scratch);
2448        let mut portal_ancestors: Vec<NodeId> =
2449            take(&mut display_list.arena.portal_ancestors_scratch);
2450        portals.clear();
2451        z_sort.clear();
2452        Self::collect_portal_ancestors(tree, &mut portal_ancestors);
2453        {
2454            let mut scratch: PaintScratch<'_> = PaintScratch {
2455                portals: Some(&mut portals),
2456                z_sort: &mut z_sort,
2457                portal_ancestors: portal_ancestors.as_slice(),
2458                fragments: fragments.as_deref_mut(),
2459                saw_canvas,
2460            };
2461            Self::emit_node(
2462                tree,
2463                tree.get_root(),
2464                (Point::new(0.0, 0.0), 1.0),
2465                viewport_rect,
2466                active_hover_target,
2467                &mut scratch,
2468                display_list,
2469            );
2470        }
2471        display_list.finalize_base_layer(display_list.len());
2472        if portals.len() > 1 {
2473            portals.sort_by(
2474                |target_node_id: &(i32, usize, NodeId), element_id: &(i32, usize, NodeId)| {
2475                    target_node_id
2476                        .0
2477                        .cmp(&element_id.0)
2478                        .then_with(|| target_node_id.1.cmp(&element_id.1))
2479                },
2480            );
2481        }
2482        {
2483            let mut portal_scratch: PaintScratch<'_> = PaintScratch {
2484                portals: None,
2485                z_sort: &mut z_sort,
2486                portal_ancestors: &[],
2487                fragments,
2488                saw_canvas,
2489            };
2490            for &(_, _, portal_id) in portals.iter() {
2491                Self::emit_node(
2492                    tree,
2493                    portal_id,
2494                    (Point::new(0.0, 0.0), 1.0),
2495                    viewport_rect,
2496                    active_hover_target,
2497                    &mut portal_scratch,
2498                    display_list,
2499                );
2500            }
2501        }
2502        portals.clear();
2503        z_sort.clear();
2504        portal_ancestors.clear();
2505        display_list.arena.portals_scratch = portals;
2506        display_list.arena.z_sort_scratch = z_sort;
2507        display_list.arena.portal_ancestors_scratch = portal_ancestors;
2508    }
2509
2510    /// Resolves the single innermost interactive non-scrim node along the active hover chain so nested controls never stack duplicate hover fills.
2511    ///
2512    /// # Arguments
2513    ///
2514    /// - `&SceneTree` - Retained scene tree.
2515    ///
2516    /// # Returns
2517    ///
2518    /// - `Option<NodeId>` - Innermost interactive node eligible for hover tinting.
2519    #[must_use]
2520    fn resolve_active_hover_target(tree: &SceneTree) -> Option<NodeId> {
2521        let mut cursor: Option<NodeId> = tree.get_focus().hovered_node();
2522        while let Some(id) = cursor {
2523            let Some(node) = tree.get_node(id) else {
2524                break;
2525            };
2526            let style: &Style = node.style_ref();
2527            let paint: &PaintStyle = &style.paint;
2528            let is_scrim: bool = matches!(node.get_kind(), NodeKind::Portal)
2529                || style.layout.get_position() == Position::Fixed;
2530            let is_transparent_canvas: bool = matches!(node.get_kind(), NodeKind::Canvas(_))
2531                && paint.background_color().is_none();
2532            if !is_scrim && !is_transparent_canvas {
2533                let is_interactive: bool = paint.get_cursor() == CursorIcon::Pointer
2534                    || node
2535                        .get_handlers()
2536                        .handler_for(&UiEventKind::Click(Point::default()))
2537                        .is_some();
2538                if is_interactive {
2539                    return Some(id);
2540                }
2541            }
2542            cursor = node.parent_id();
2543        }
2544        None
2545    }
2546
2547    /// Computes subtle shadcn-aligned hover/pressed color tinting for interactive controls.
2548    ///
2549    /// # Arguments
2550    ///
2551    /// - `Option<Color>` - Base background color, if any.
2552    /// - `bool` - Whether the pointer hovers the control.
2553    /// - `bool` - Whether the pointer actively presses the control.
2554    ///
2555    /// # Returns
2556    ///
2557    /// - `Option<Color>` - Tinted background color.
2558    fn interactive_tint(base: Option<Color>, hovered: bool, pressed: bool) -> Option<Color> {
2559        if !hovered && !pressed {
2560            return base;
2561        }
2562        let delta: i32 = if pressed { 24 } else { 14 };
2563        match base {
2564            Some(char_item) if char_item.get_alpha() > 0 => {
2565                let luma: u32 = (char_item.get_red() as u32) * 299
2566                    + (char_item.get_green() as u32) * 587
2567                    + (char_item.get_blue() as u32) * 114;
2568                if luma < 120_000 {
2569                    let lift: i32 = if pressed { 30 } else { 20 };
2570                    Some(Color::new(
2571                        (char_item.get_red() as i32 + lift).clamp(0, 255) as u8,
2572                        (char_item.get_green() as i32 + lift).clamp(0, 255) as u8,
2573                        (char_item.get_blue() as i32 + lift).clamp(0, 255) as u8,
2574                        char_item.get_alpha(),
2575                    ))
2576                } else {
2577                    Some(Color::new(
2578                        (char_item.get_red() as i32 - delta).clamp(0, 255) as u8,
2579                        (char_item.get_green() as i32 - delta).clamp(0, 255) as u8,
2580                        (char_item.get_blue() as i32 - delta).clamp(0, 255) as u8,
2581                        char_item.get_alpha(),
2582                    ))
2583                }
2584            }
2585            _ => Some(Color::rgba(113, 113, 122, if pressed { 42 } else { 26 })),
2586        }
2587    }
2588
2589    /// Recursively emits commands for `node_id` and its z-sorted children with hierarchical transform and physical-pixel lockstep.
2590    ///
2591    /// # Arguments
2592    ///
2593    /// - `&SceneTree` - Scene tree reference.
2594    /// - `NodeId` - Node to paint.
2595    /// - `(Point, f32)` - Accumulated ancestor physical pixel displacement `(tx_phys - scroll_phys)` and opacity.
2596    /// - `Rect` - Active cull clip rectangle.
2597    /// - `Option<NodeId>` - Innermost hovered interactive node eligible for automatic hover tinting.
2598    /// - `&mut PaintScratch<'_>` - Reusable portal queue and nested z-sort scratch buffers.
2599    /// - `&mut DisplayList` - Output command list.
2600    fn emit_node(
2601        tree: &SceneTree,
2602        node_id: NodeId,
2603        offset_and_opacity: (Point, f32),
2604        cull_rect: Rect,
2605        active_hover_target: Option<NodeId>,
2606        scratch: &mut PaintScratch<'_>,
2607        display_list: &mut DisplayList,
2608    ) {
2609        let (offset_phys, parent_opacity): (Point, f32) = offset_and_opacity;
2610        let Some(node) = tree.get_node(node_id) else {
2611            return;
2612        };
2613        let style: &Style = node.style_ref();
2614        let layout: &LayoutStyle = &style.layout;
2615        if layout.get_display() == Display::None {
2616            return;
2617        }
2618        let is_portal_or_fixed: bool =
2619            matches!(node.get_kind(), NodeKind::Portal) || layout.get_position() == Position::Fixed;
2620        let is_root_chrome_overlay: bool = layout.get_position() == Position::Absolute
2621            && layout.get_z_index() >= 50
2622            && layout.get_z_index() < 140
2623            && offset_phys == Point::new(0.0, 0.0)
2624            && (parent_opacity - 1.0).abs() <= 0.001
2625            && cull_rect.get_x() <= 0.0
2626            && cull_rect.get_y() <= 0.0;
2627        let promote_to_top_layer: bool = is_portal_or_fixed || is_root_chrome_overlay;
2628        if let Some(portal_queue) = scratch.portals.as_deref_mut()
2629            && promote_to_top_layer
2630        {
2631            portal_queue.push((layout.get_z_index(), portal_queue.len(), node_id));
2632            return;
2633        }
2634        let interaction: InteractionState = node.get_interaction();
2635        let hovered: bool = interaction.get_hovered();
2636        let pressed: bool = interaction.get_pressed();
2637        if !hovered && (parent_opacity * style.paint.get_opacity()) <= 0.0 {
2638            return;
2639        }
2640        let mut paint_owned: Option<PaintStyle> = if hovered { node.hover_paint() } else { None };
2641        let prelim_paint: &PaintStyle = paint_owned.as_ref().unwrap_or(&style.paint);
2642        let opacity: f32 = (parent_opacity * prelim_paint.get_opacity()).clamp(0.0, 1.0);
2643        if opacity <= 0.0 {
2644            return;
2645        }
2646        let scale: f32 = display_list.get_scale_factor().max(0.5);
2647        let inv_scale: f32 = 1.0 / scale;
2648        let raw_bounds: Rect = node.layout_box.get_bounds();
2649        let transform: Transform2D = prelim_paint.get_transform();
2650        let tx_phys: f32 = (transform.get_translate_x() * scale).round();
2651        let ty_phys: f32 = (transform.get_translate_y() * scale).round();
2652        let total_off_x: f32 = offset_phys.get_x() + tx_phys;
2653        let total_off_y: f32 = offset_phys.get_y() + ty_phys;
2654        let raw_x0: f32 = (raw_bounds.get_x() * scale).round();
2655        let raw_y0: f32 = (raw_bounds.get_y() * scale).round();
2656        let raw_x1: f32 = (raw_bounds.right() * scale).round();
2657        let raw_y1: f32 = (raw_bounds.bottom() * scale).round();
2658        let static_w_phys: f32 = (raw_x1 - raw_x0).max(0.0);
2659        let static_h_phys: f32 = (raw_y1 - raw_y0).max(0.0);
2660        let scaled_w_phys: f32 = (static_w_phys * transform.get_scale_x()).round().max(0.0);
2661        let scaled_h_phys: f32 = (static_h_phys * transform.get_scale_y()).round().max(0.0);
2662        let scale_dx_phys: f32 = ((static_w_phys - scaled_w_phys) * 0.5).round();
2663        let scale_dy_phys: f32 = ((static_h_phys - scaled_h_phys) * 0.5).round();
2664        let bounds: Rect = Rect::new(
2665            (raw_x0 + total_off_x + scale_dx_phys) * inv_scale,
2666            (raw_y0 + total_off_y + scale_dy_phys) * inv_scale,
2667            scaled_w_phys * inv_scale,
2668            scaled_h_phys * inv_scale,
2669        );
2670        let clipped: bool = matches!(layout.get_overflow(), Overflow::Hidden | Overflow::Scroll);
2671        let clipped_cull: Option<Rect> = if clipped {
2672            cull_rect.intersect(bounds)
2673        } else {
2674            Some(cull_rect)
2675        };
2676        let focused: bool = interaction.get_focused();
2677        let self_vis_rect: Rect = Self::conservative_self_vis_rect(
2678            node,
2679            bounds,
2680            prelim_paint,
2681            focused,
2682            (total_off_x, total_off_y),
2683            scale,
2684            inv_scale,
2685        );
2686        let self_visible: bool = bounds.get_width() > 0.0
2687            && bounds.get_height() > 0.0
2688            && self_vis_rect.intersect(cull_rect).is_some();
2689        if clipped && clipped_cull.is_none() {
2690            if self_visible {
2691                if let Some(mut shadow) = prelim_paint.box_shadow() {
2692                    shadow.set_color(shadow.get_color().multiply_alpha(opacity));
2693                    display_list.push(DrawCommand::BoxShadow {
2694                        rect: bounds,
2695                        radius: prelim_paint.get_radius(),
2696                        shadow,
2697                    });
2698                }
2699                if focused && let Some(mut ring) = prelim_paint.focus_ring_border() {
2700                    ring.set_color(ring.get_color().multiply_alpha(opacity));
2701                    let ring_w: f32 = ring.get_width();
2702                    let ring_rect: Rect = Rect::new(
2703                        bounds.get_x() - ring_w,
2704                        bounds.get_y() - ring_w,
2705                        bounds.get_width() + ring_w * 2.0,
2706                        bounds.get_height() + ring_w * 2.0,
2707                    );
2708                    display_list.push(DrawCommand::FillRoundedRect {
2709                        rect: ring_rect,
2710                        color: COLOR_TRANSPARENT,
2711                        radius: CornerRadius::all(prelim_paint.get_radius().max_radius() + ring_w),
2712                        border: ring,
2713                    });
2714                }
2715            }
2716            if scratch.portals.is_some()
2717                && Self::is_portal_ancestor(scratch.portal_ancestors, node_id)
2718            {
2719                Self::collect_portals_in_culled_subtree(tree, node_id, opacity, scratch);
2720            }
2721            return;
2722        }
2723        let child_count: usize = tree.child_count(node_id);
2724        if !self_visible && child_count == 0 {
2725            return;
2726        }
2727        let next_cull: Rect = clipped_cull.unwrap_or(cull_rect);
2728        let hover_visual: bool = hovered && active_hover_target == Some(node_id);
2729        if self_visible
2730            && (hover_visual || pressed)
2731            && paint_owned.is_none()
2732            && (hovered || node.hover_paint().is_none())
2733        {
2734            let base_paint: &PaintStyle = &style.paint;
2735            let is_scrim: bool = matches!(node.get_kind(), NodeKind::Portal)
2736                || layout.get_position() == Position::Fixed;
2737            let is_transparent_canvas: bool = matches!(node.get_kind(), NodeKind::Canvas(_))
2738                && base_paint.background_color().is_none();
2739            if !is_scrim && !is_transparent_canvas {
2740                let is_interactive: bool = base_paint.get_cursor() == CursorIcon::Pointer
2741                    || node
2742                        .get_handlers()
2743                        .handler_for(&UiEventKind::Click(Point::default()))
2744                        .is_some();
2745                if is_interactive {
2746                    let mut tinted: PaintStyle = *base_paint;
2747                    tinted.set_background(Self::interactive_tint(
2748                        tinted.background_color(),
2749                        hover_visual,
2750                        pressed,
2751                    ));
2752                    paint_owned = Some(tinted);
2753                }
2754            }
2755        }
2756        let paint: &PaintStyle = paint_owned.as_ref().unwrap_or(&style.paint);
2757        let phys_scale_milli: u32 = Self::quantize_scale_milli(scale);
2758        let mut frag_capture: Option<(usize, usize, u64, u64)> = None;
2759        let frag_overflow_ok: bool = layout.get_overflow() == Overflow::Hidden
2760            || (layout.get_overflow() == Overflow::Visible
2761                && node_id != tree.get_root()
2762                && child_count >= 2);
2763        if self_visible
2764            && scratch.fragments.is_some()
2765            && scratch.portals.is_some()
2766            && matches!(node.get_kind(), NodeKind::View)
2767            && frag_overflow_ok
2768            && !hovered
2769            && !pressed
2770            && !interaction.get_focused()
2771            && active_hover_target != Some(node_id)
2772        {
2773            let vis_x_in: bool = self_vis_rect.get_x() >= cull_rect.get_x()
2774                && self_vis_rect.right() <= cull_rect.right();
2775            let vis_y_in: bool = self_vis_rect.get_y() >= cull_rect.get_y()
2776                && self_vis_rect.bottom() <= cull_rect.bottom();
2777            if vis_x_in && vis_y_in {
2778                let has_text_sel: bool = !tree.text_selection_spans_ref().is_empty();
2779                let unclipped_cull: Option<(Point, Rect, f32, f32)> =
2780                    if layout.get_overflow() == Overflow::Hidden {
2781                        None
2782                    } else {
2783                        let raw_node_scroll: Point = node.layout_box.get_scroll_offset();
2784                        let child_off: Point = Point::new(
2785                            total_off_x - (raw_node_scroll.get_x() * scale).round(),
2786                            total_off_y - (raw_node_scroll.get_y() * scale).round(),
2787                        );
2788                        Some((child_off, cull_rect, scale, inv_scale))
2789                    };
2790                if let Some((geom_hash, style_text_hash)) = Self::fingerprint_subtree(
2791                    tree,
2792                    node_id,
2793                    node,
2794                    unclipped_cull,
2795                    (active_hover_target, has_text_sel),
2796                ) {
2797                    let slot_idx: usize =
2798                        (node_id.get_index() as usize) & (PAINT_FRAGMENT_CACHE_SLOTS - 1);
2799                    let opacity_bits: u32 = parent_opacity.to_bits();
2800                    let dyadic_12: bool = scale == 1.0 || scale == 2.0;
2801                    let dyadic_scale: bool = dyadic_12 || scale == 4.0;
2802                    if let Some(cache) = scratch.fragments.as_deref_mut()
2803                        && let Some(&cached) = cache.slots.get(slot_idx)
2804                        && cached.occupied
2805                        && cached.node_id == node_id
2806                        && cached.phys_scale_milli == phys_scale_milli
2807                        && cached.opacity_bits == opacity_bits
2808                        && cached.geom_hash == geom_hash
2809                        && cached.style_text_hash == style_text_hash
2810                    {
2811                        let dx_phys: f32 = offset_phys.get_x() - cached.offset_phys.get_x();
2812                        let dy_phys: f32 = offset_phys.get_y() - cached.offset_phys.get_y();
2813                        let c_start: usize = cached.cmd_start as usize;
2814                        let c_end: usize = c_start.saturating_add(cached.cmd_len as usize);
2815                        if let Some(cmds) = cache.cmd_slab.get(c_start..c_end) {
2816                            display_list.get_mut_commands().reserve(cmds.len());
2817                            let text_slab: &[u8] = cache.text_slab.as_slice();
2818                            for cmd in cmds.iter() {
2819                                Self::push_translated_command(
2820                                    cmd,
2821                                    text_slab,
2822                                    (dx_phys, dy_phys),
2823                                    (scale, inv_scale, dyadic_scale),
2824                                    display_list,
2825                                );
2826                            }
2827                            cache.fragment_hits = cache.fragment_hits.wrapping_add(1);
2828                            return;
2829                        }
2830                    }
2831                    frag_capture = Some((display_list.len(), slot_idx, geom_hash, style_text_hash));
2832                }
2833            }
2834        }
2835        let box_size: Size = display_list.get_viewport();
2836        let show_scrollbar: bool = box_size.get_width().min(box_size.get_height()) >= 540.0;
2837        let wants_scrollbar: bool = show_scrollbar
2838            && layout.get_overflow() == Overflow::Scroll
2839            && bounds.get_height() > 24.0;
2840        let emit_clip: bool = clipped && (child_count > 0 || wants_scrollbar);
2841        let has_canvas_clip: bool =
2842            matches!(node.get_kind(), NodeKind::Canvas(_)) && node.canvas_callback().is_some();
2843        let has_rounded_border: bool =
2844            paint.get_border().get_width() > 0.0 && paint.get_radius().max_radius() > 0.0;
2845        let defer_rounded_border: bool = has_rounded_border && (emit_clip || has_canvas_clip);
2846        if self_visible {
2847            let blur_r: f32 = tree.backdrop_blur_radius(node_id);
2848            if blur_r > 0.0 {
2849                display_list.push(DrawCommand::BackdropBlur {
2850                    rect: bounds,
2851                    radius: paint.get_radius(),
2852                    blur_radius: blur_r,
2853                });
2854            }
2855            if let Some(mut shadow) = paint.box_shadow() {
2856                shadow.set_color(shadow.get_color().multiply_alpha(opacity));
2857                display_list.push(DrawCommand::BoxShadow {
2858                    rect: bounds,
2859                    radius: paint.get_radius(),
2860                    shadow,
2861                });
2862            }
2863            if let Some(mut gradient) = paint.background_gradient() {
2864                gradient.set_start_color(gradient.get_start_color().multiply_alpha(opacity));
2865                gradient.set_end_color(gradient.get_end_color().multiply_alpha(opacity));
2866                display_list.push(DrawCommand::LinearGradientRect {
2867                    rect: bounds,
2868                    gradient,
2869                    radius: paint.get_radius(),
2870                });
2871            } else if let Some(bg) = paint.background_color() {
2872                let border: Border = if defer_rounded_border {
2873                    Border::default()
2874                } else {
2875                    let mut direct_border: Border = paint.get_border();
2876                    direct_border.set_color(direct_border.get_color().multiply_alpha(opacity));
2877                    direct_border
2878                };
2879                display_list.push(DrawCommand::FillRoundedRect {
2880                    rect: bounds,
2881                    color: bg.multiply_alpha(opacity),
2882                    radius: paint.get_radius(),
2883                    border,
2884                });
2885            } else if paint.get_border().get_width() > 0.0 && !defer_rounded_border {
2886                let mut border: Border = paint.get_border();
2887                border.set_color(border.get_color().multiply_alpha(opacity));
2888                display_list.push(DrawCommand::FillRoundedRect {
2889                    rect: bounds,
2890                    color: COLOR_TRANSPARENT,
2891                    radius: paint.get_radius(),
2892                    border,
2893                });
2894            }
2895            if interaction.get_focused()
2896                && let Some(mut ring) = paint.focus_ring_border()
2897            {
2898                ring.set_color(ring.get_color().multiply_alpha(opacity));
2899                let ring_w: f32 = ring.get_width();
2900                let ring_rect: Rect = Rect::new(
2901                    bounds.get_x() - ring_w,
2902                    bounds.get_y() - ring_w,
2903                    bounds.get_width() + ring_w * 2.0,
2904                    bounds.get_height() + ring_w * 2.0,
2905                );
2906                display_list.push(DrawCommand::FillRoundedRect {
2907                    rect: ring_rect,
2908                    color: COLOR_TRANSPARENT,
2909                    radius: CornerRadius::all(paint.get_radius().max_radius() + ring_w),
2910                    border: ring,
2911                });
2912            }
2913            match node.get_kind() {
2914                NodeKind::Text(text) => {
2915                    let mut text_style: TextStyle = style.text;
2916                    text_style.set_color(text_style.get_color().multiply_alpha(opacity));
2917                    let content_b: Rect = node.layout_box.get_content_bounds();
2918                    let cx0: f32 = (content_b.get_x() * scale).round();
2919                    let cy0: f32 = (content_b.get_y() * scale).round();
2920                    let shifted_content: Rect = Rect::new(
2921                        (cx0 + total_off_x) * inv_scale,
2922                        (cy0 + total_off_y) * inv_scale,
2923                        content_b.get_width(),
2924                        content_b.get_height(),
2925                    );
2926                    let has_box_chrome: bool = style
2927                        .paint
2928                        .background_color()
2929                        .is_some_and(|color_value: Color| color_value.get_alpha() > 0)
2930                        || style.paint.background_gradient().is_some()
2931                        || style.paint.get_border().get_width() > 0.0
2932                        || style.layout.get_height() != Length::Auto
2933                        || style.layout.get_min_height() != Length::Auto;
2934                    let text_run_rect: Rect = if has_box_chrome
2935                        && shifted_content.get_height() > 1.0
2936                    {
2937                        let cached_h: f32 = node.layout_box.get_content_size().get_height();
2938                        let measured_h: f32 =
2939                            if cached_h > 0.0 && cached_h + 0.5 < shifted_content.get_height() {
2940                                cached_h
2941                            } else {
2942                                DeterministicTextMeasurer
2943                                    .measure_size(
2944                                        text.as_str(),
2945                                        text_style,
2946                                        Some(shifted_content.get_width().max(1.0)),
2947                                    )
2948                                    .get_height()
2949                            };
2950                        if measured_h > 0.0 && shifted_content.get_height() > measured_h + 0.5 {
2951                            let v_off_phys: f32 =
2952                                (((shifted_content.get_height() - measured_h) * 0.5).max(0.0)
2953                                    * scale)
2954                                    .round();
2955                            Rect::new(
2956                                shifted_content.get_x(),
2957                                (cy0 + total_off_y + v_off_phys) * inv_scale,
2958                                shifted_content.get_width(),
2959                                measured_h,
2960                            )
2961                        } else {
2962                            shifted_content
2963                        }
2964                    } else {
2965                        shifted_content
2966                    };
2967                    if let Some(sel_range) = tree.text_selection_range_for(node_id) {
2968                        let sel_color: Color = tree
2969                            .effective_selection_color(node_id)
2970                            .multiply_alpha(opacity);
2971                        let sel_rects: Vec<Rect> = compute_text_selection_rects(
2972                            text.as_str(),
2973                            text_style,
2974                            text_run_rect,
2975                            sel_range,
2976                        );
2977                        let sel_single_to_end: bool = sel_rects.len() == 1
2978                            && text_style.get_align() == TextAlign::Left
2979                            && sel_range.1 >= text.chars().count();
2980                        let exact_span_right: f32 =
2981                            ((content_b.right() * scale).round() + total_off_x) * inv_scale;
2982                        for sel_rect in sel_rects.into_iter() {
2983                            let sx0: f32 = (sel_rect.get_x() * scale).round() * inv_scale;
2984                            let sy0: f32 = (sel_rect.get_y() * scale).round() * inv_scale;
2985                            let sx1: f32 = if sel_single_to_end {
2986                                exact_span_right.max(sx0 + inv_scale)
2987                            } else {
2988                                (sel_rect.right() * scale).round() * inv_scale
2989                            };
2990                            let sy1: f32 = (sel_rect.bottom() * scale).round() * inv_scale;
2991                            display_list.push(DrawCommand::FillRoundedRect {
2992                                rect: Rect::new(
2993                                    sx0,
2994                                    sy0,
2995                                    (sx1 - sx0).max(inv_scale),
2996                                    (sy1 - sy0).max(inv_scale),
2997                                ),
2998                                color: sel_color,
2999                                radius: CornerRadius::default(),
3000                                border: Border::default(),
3001                            });
3002                        }
3003                    }
3004                    let pooled_text: String = display_list.alloc_text(text.as_str());
3005                    display_list.push(DrawCommand::TextRun {
3006                        rect: text_run_rect,
3007                        text: pooled_text,
3008                        style: text_style,
3009                    });
3010                }
3011                NodeKind::Input(input_state) => {
3012                    let mut text_style: TextStyle = style.text;
3013                    let is_empty_value: bool = input_state.get_value().is_empty();
3014                    let is_focused: bool = interaction.get_focused();
3015                    let rendered_text: String = if is_empty_value {
3016                        text_style.set_color(text_style.get_color().multiply_alpha(opacity * 0.55));
3017                        display_list.alloc_text(input_state.get_placeholder().as_str())
3018                    } else if input_state.get_password() {
3019                        text_style.set_color(text_style.get_color().multiply_alpha(opacity));
3020                        let star_count: usize = input_state.get_value().chars().count();
3021                        let mut masked: String = display_list.alloc_text("");
3022                        for _ in 0..star_count {
3023                            masked.push('*');
3024                        }
3025                        masked
3026                    } else {
3027                        text_style.set_color(text_style.get_color().multiply_alpha(opacity));
3028                        display_list.alloc_text(input_state.get_value().as_str())
3029                    };
3030                    let content_b: Rect = node.layout_box.get_content_bounds();
3031                    let cx0: f32 = (content_b.get_x() * scale).round();
3032                    let cy0: f32 = (content_b.get_y() * scale).round();
3033                    let shifted_content: Rect = Rect::new(
3034                        (cx0 + total_off_x) * inv_scale,
3035                        (cy0 + total_off_y) * inv_scale,
3036                        content_b.get_width(),
3037                        content_b.get_height(),
3038                    );
3039                    let line_h: f32 =
3040                        (text_style.get_font_size() * text_style.get_line_height()).max(1.0);
3041                    let text_rect: Rect = if input_state.get_multiline() {
3042                        shifted_content
3043                    } else {
3044                        text_style.set_overflow(TextOverflow::Clip);
3045                        let v_off_phys: f32 =
3046                            (((shifted_content.get_height() - line_h) * 0.5).max(0.0) * scale)
3047                                .round();
3048                        let text_y: f32 = (cy0 + total_off_y + v_off_phys) * inv_scale;
3049                        Rect::new(
3050                            shifted_content.get_x(),
3051                            text_y,
3052                            shifted_content.get_width(),
3053                            line_h,
3054                        )
3055                    };
3056                    let run_rect: Rect =
3057                        if is_empty_value && is_focused && !rendered_text.is_empty() {
3058                            let clearance_phys: f32 =
3059                                (PLACEHOLDER_FOCUSED_CARET_CLEARANCE_PX * scale).round();
3060                            let clearance_logical: f32 = clearance_phys * inv_scale;
3061                            Rect::new(
3062                                text_rect.get_x() + clearance_logical,
3063                                text_rect.get_y(),
3064                                (text_rect.get_width() - clearance_logical).max(0.0),
3065                                text_rect.get_height(),
3066                            )
3067                        } else {
3068                            text_rect
3069                        };
3070                    let show_caret: bool = is_focused && tree.get_caret_visible();
3071                    let caret_text: String = if show_caret && !is_empty_value {
3072                        let caret_prefix: &str =
3073                            input_state.caret_prefix_for_display(rendered_text.as_str());
3074                        display_list.alloc_text(caret_prefix)
3075                    } else {
3076                        String::new()
3077                    };
3078                    display_list.push(DrawCommand::PushClip(shifted_content));
3079                    if is_focused
3080                        && !is_empty_value
3081                        && let Some(sel_range) = input_state.selection_char_range()
3082                    {
3083                        let sel_color: Color = tree
3084                            .effective_selection_color(node_id)
3085                            .multiply_alpha(opacity);
3086                        let sel_rects: Vec<Rect> = compute_text_selection_rects(
3087                            rendered_text.as_str(),
3088                            text_style,
3089                            text_rect,
3090                            sel_range,
3091                        );
3092                        for sel_rect in sel_rects.into_iter() {
3093                            let sx0: f32 = (sel_rect.get_x() * scale).round() * inv_scale;
3094                            let sy0: f32 = (sel_rect.get_y() * scale).round() * inv_scale;
3095                            let sx1: f32 = (sel_rect.right() * scale).round() * inv_scale;
3096                            let sy1: f32 = (sel_rect.bottom() * scale).round() * inv_scale;
3097                            display_list.push(DrawCommand::FillRoundedRect {
3098                                rect: Rect::new(
3099                                    sx0,
3100                                    sy0,
3101                                    (sx1 - sx0).max(inv_scale),
3102                                    (sy1 - sy0).max(inv_scale),
3103                                ),
3104                                color: sel_color,
3105                                radius: CornerRadius::default(),
3106                                border: Border::default(),
3107                            });
3108                        }
3109                    }
3110                    display_list.push(DrawCommand::TextRun {
3111                        rect: run_rect,
3112                        text: rendered_text,
3113                        style: text_style,
3114                    });
3115                    if show_caret {
3116                        let caret_h: f32 = (text_style.get_font_size() * 1.15)
3117                            .min(shifted_content.get_height().max(12.0));
3118                        display_list.push(DrawCommand::TextCaret {
3119                            text_rect,
3120                            content_rect: shifted_content,
3121                            text: caret_text,
3122                            style: text_style,
3123                            caret_height: caret_h,
3124                            color: style.text.get_color().multiply_alpha(opacity),
3125                            multiline: input_state.get_multiline(),
3126                        });
3127                    }
3128                    display_list.push(DrawCommand::PopClip);
3129                }
3130                NodeKind::Image(buffer) => {
3131                    display_list.push(DrawCommand::Image {
3132                        rect: bounds,
3133                        buffer: buffer.clone(),
3134                        radius: paint.get_radius(),
3135                    });
3136                }
3137                NodeKind::Canvas(caching) => {
3138                    if let Some(callback) = node.canvas_callback()
3139                        && let Ok(mut func) = callback.try_borrow_mut()
3140                    {
3141                        let canvas_bw: f32 = paint.get_border().get_width();
3142                        let canvas_inset: f32 = if canvas_bw > 0.0 {
3143                            ((canvas_bw * scale).ceil().max(1.0)) * inv_scale
3144                        } else {
3145                            0.0
3146                        };
3147                        let canvas_clip_rect: Rect = if canvas_inset > 0.0 {
3148                            Rect::new(
3149                                bounds.get_x() + canvas_inset,
3150                                bounds.get_y() + canvas_inset,
3151                                (bounds.get_width() - canvas_inset * 2.0).max(0.0),
3152                                (bounds.get_height() - canvas_inset * 2.0).max(0.0),
3153                            )
3154                        } else {
3155                            bounds
3156                        };
3157                        let canvas_max_r: f32 = (bounds.get_width() * 0.5)
3158                            .min(bounds.get_height() * 0.5)
3159                            .max(0.0);
3160                        let canvas_raw_r: CornerRadius = paint.get_radius();
3161                        let canvas_inner_r: CornerRadius = CornerRadius::new(
3162                            (canvas_raw_r.get_top_left().min(canvas_max_r) - canvas_inset).max(0.0),
3163                            (canvas_raw_r.get_top_right().min(canvas_max_r) - canvas_inset)
3164                                .max(0.0),
3165                            (canvas_raw_r.get_bottom_right().min(canvas_max_r) - canvas_inset)
3166                                .max(0.0),
3167                            (canvas_raw_r.get_bottom_left().min(canvas_max_r) - canvas_inset)
3168                                .max(0.0),
3169                        );
3170                        if canvas_inner_r.max_radius() > 0.25 {
3171                            display_list.push(DrawCommand::PushRoundedClip {
3172                                rect: canvas_clip_rect,
3173                                radius: canvas_inner_r,
3174                            });
3175                        } else {
3176                            display_list.push(DrawCommand::PushClip(canvas_clip_rect));
3177                        }
3178                        let canvas_cmd_start: usize = display_list.len();
3179                        func(bounds, display_list);
3180                        let canvas_cmd_end: usize = display_list.len();
3181                        if opacity < 0.999 {
3182                            display_list.attenuate_range_opacity(
3183                                canvas_cmd_start,
3184                                canvas_cmd_end,
3185                                opacity,
3186                            );
3187                        }
3188                        if *caching != CanvasCaching::RetainedStatic {
3189                            let canvas_is_dynamic: bool =
3190                                if let Some(cache) = scratch.fragments.as_deref_mut() {
3191                                    let emitted: &[DrawCommand] = &display_list.get_commands()
3192                                        [canvas_cmd_start..canvas_cmd_end];
3193                                    cache.record_canvas_output(
3194                                        node_id,
3195                                        phys_scale_milli,
3196                                        bounds,
3197                                        tree.get_revision(),
3198                                        emitted,
3199                                    )
3200                                } else {
3201                                    true
3202                                };
3203                            if canvas_is_dynamic {
3204                                *scratch.saw_canvas = true;
3205                            }
3206                        }
3207                        display_list.push(DrawCommand::PopClip);
3208                        if canvas_bw > 0.0 && canvas_raw_r.max_radius() > 0.0 {
3209                            let mut canvas_border: Border = paint.get_border();
3210                            canvas_border
3211                                .set_color(canvas_border.get_color().multiply_alpha(opacity));
3212                            display_list.push(DrawCommand::FillRoundedRect {
3213                                rect: bounds,
3214                                color: COLOR_TRANSPARENT,
3215                                radius: canvas_raw_r,
3216                                border: canvas_border,
3217                            });
3218                        }
3219                    } else if *caching == CanvasCaching::DynamicPerFrame {
3220                        *scratch.saw_canvas = true;
3221                    }
3222                }
3223                NodeKind::View | NodeKind::ScrollView | NodeKind::Portal | NodeKind::Fragment => {}
3224            }
3225        }
3226        let clip_push_idx: usize = display_list.len();
3227        let clip_saved_digest: (u64, u64) = display_list.snapshot_digest_state();
3228        if emit_clip {
3229            let border_width: f32 = paint.get_border().get_width();
3230            let border_inset: f32 = if border_width > 0.0 {
3231                ((border_width * scale).ceil().max(1.0)) * inv_scale
3232            } else {
3233                0.0
3234            };
3235            let clip_rect: Rect = if border_inset > 0.0 {
3236                Rect::new(
3237                    bounds.get_x() + border_inset,
3238                    bounds.get_y() + border_inset,
3239                    (bounds.get_width() - border_inset * 2.0).max(0.0),
3240                    (bounds.get_height() - border_inset * 2.0).max(0.0),
3241                )
3242            } else {
3243                bounds
3244            };
3245            let max_r: f32 = (bounds.get_width() * 0.5)
3246                .min(bounds.get_height() * 0.5)
3247                .max(0.0);
3248            let raw_r: CornerRadius = paint.get_radius();
3249            let inner_r: CornerRadius = CornerRadius::new(
3250                (raw_r.get_top_left().min(max_r) - border_inset).max(0.0),
3251                (raw_r.get_top_right().min(max_r) - border_inset).max(0.0),
3252                (raw_r.get_bottom_right().min(max_r) - border_inset).max(0.0),
3253                (raw_r.get_bottom_left().min(max_r) - border_inset).max(0.0),
3254            );
3255            if inner_r.max_radius() > 0.25 {
3256                display_list.push(DrawCommand::PushRoundedClip {
3257                    rect: clip_rect,
3258                    radius: inner_r,
3259                });
3260            } else {
3261                display_list.push(DrawCommand::PushClip(clip_rect));
3262            }
3263        }
3264        if child_count > 0 {
3265            let raw_node_scroll: Point = node.layout_box.get_scroll_offset();
3266            let scroll_x_phys: f32 = (raw_node_scroll.get_x() * scale).round();
3267            let scroll_y_phys: f32 = (raw_node_scroll.get_y() * scale).round();
3268            let child_offset_phys: Point =
3269                Point::new(total_off_x - scroll_x_phys, total_off_y - scroll_y_phys);
3270            let needs_z_sort: bool = child_count > 1 && tree.has_nonzero_z_child(node_id);
3271            if !needs_z_sort {
3272                for child_id in tree.children_iter(node_id) {
3273                    Self::emit_node(
3274                        tree,
3275                        child_id,
3276                        (child_offset_phys, opacity),
3277                        next_cull,
3278                        active_hover_target,
3279                        scratch,
3280                        display_list,
3281                    );
3282                }
3283            } else {
3284                let sort_start: usize = scratch.z_sort.len();
3285                for (idx, cid) in tree.children_iter(node_id).enumerate() {
3286                    if let Some(char_item) = tree.get_node(cid) {
3287                        scratch
3288                            .z_sort
3289                            .push((char_item.style_ref().layout.get_z_index(), idx, cid));
3290                    }
3291                }
3292                let sort_end: usize = scratch.z_sort.len();
3293                scratch.z_sort[sort_start..sort_end].sort_by(
3294                    |target_node_id: &(i32, usize, NodeId), element_id: &(i32, usize, NodeId)| {
3295                        target_node_id
3296                            .0
3297                            .cmp(&element_id.0)
3298                            .then_with(|| target_node_id.1.cmp(&element_id.1))
3299                    },
3300                );
3301                for slot_idx in sort_start..sort_end {
3302                    let child_id: NodeId = scratch.z_sort[slot_idx].2;
3303                    Self::emit_node(
3304                        tree,
3305                        child_id,
3306                        (child_offset_phys, opacity),
3307                        next_cull,
3308                        active_hover_target,
3309                        scratch,
3310                        display_list,
3311                    );
3312                }
3313                scratch.z_sort.truncate(sort_start);
3314            }
3315        }
3316        if wants_scrollbar {
3317            let computed_box: &LayoutBox = &node.layout_box;
3318            let border_w: f32 = paint.get_border().get_width();
3319            let inner_x: f32 = bounds.get_x() + border_w;
3320            let inner_y: f32 = bounds.get_y() + border_w;
3321            let inner_w: f32 = (bounds.get_width() - border_w * 2.0).max(1.0);
3322            let inner_h: f32 = (bounds.get_height() - border_w * 2.0).max(1.0);
3323            let view_w: f32 = computed_box.get_content_bounds().get_width().max(1.0);
3324            let view_h: f32 = computed_box.get_content_bounds().get_height().max(1.0);
3325            let (scroll_y, total_h): (f32, f32) = match node.virtual_scroll_metrics() {
3326                Some((vy, vh)) => (vy, vh),
3327                None => (
3328                    computed_box.get_scroll_offset().get_y(),
3329                    computed_box.get_content_size().get_height(),
3330                ),
3331            };
3332            let scroll_x: f32 = computed_box.get_scroll_offset().get_x();
3333            let total_w: f32 = computed_box.get_content_size().get_width();
3334            let max_scroll_y: f32 = (total_h - view_h).max(0.0);
3335            let max_scroll_x: f32 = (total_w - view_w).max(0.0);
3336            let has_v_bar: bool = max_scroll_y > 1.0;
3337            let has_h_bar: bool = max_scroll_x > 1.0 && bounds.get_width() > 24.0;
3338            let corner_inset: f32 = if has_v_bar && has_h_bar { 6.0 } else { 0.0 };
3339            if has_v_bar {
3340                let track_margin: f32 = 3.0;
3341                let edge_inset: f32 = 1.0;
3342                let thumb_w: f32 = if hovered || pressed { 4.5 } else { 3.0 };
3343                let track_x: f32 = (inner_x + inner_w - thumb_w - edge_inset).max(inner_x);
3344                let track_y: f32 = inner_y + track_margin;
3345                let track_h: f32 = (inner_h - track_margin * 2.0 - corner_inset).max(16.0);
3346                let ratio: f32 = (view_h / total_h.max(view_h)).clamp(0.0, 1.0);
3347                let min_thumb_h: f32 = 20.0_f32.min(track_h);
3348                let thumb_h: f32 = (track_h * ratio).clamp(min_thumb_h, track_h);
3349                let scroll_frac: f32 = (scroll_y / max_scroll_y).clamp(0.0, 1.0);
3350                let thumb_y: f32 = track_y + (track_h - thumb_h) * scroll_frac;
3351                let thumb_x_snapped: f32 = (track_x * scale).round() * inv_scale;
3352                let thumb_w_snapped: f32 = (thumb_w * scale).round().max(1.0) * inv_scale;
3353                let thumb_y_snapped: f32 = (thumb_y * scale).round() * inv_scale;
3354                let thumb_h_snapped: f32 = (thumb_h * scale).round().max(1.0) * inv_scale;
3355                let thumb_alpha: u8 = if pressed {
3356                    188
3357                } else if hovered {
3358                    148
3359                } else {
3360                    88
3361                };
3362                display_list.push(DrawCommand::FillRoundedRect {
3363                    rect: Rect::new(
3364                        thumb_x_snapped,
3365                        thumb_y_snapped,
3366                        thumb_w_snapped,
3367                        thumb_h_snapped,
3368                    ),
3369                    color: Color::rgba(113, 113, 122, thumb_alpha).multiply_alpha(opacity),
3370                    radius: CornerRadius::all(thumb_w * 0.5),
3371                    border: Border::default(),
3372                });
3373            }
3374            if has_h_bar {
3375                let track_margin: f32 = 3.0;
3376                let edge_inset: f32 = 1.0;
3377                let thumb_h: f32 = if hovered || pressed { 4.5 } else { 3.0 };
3378                let track_y: f32 = (inner_y + inner_h - thumb_h - edge_inset).max(inner_y);
3379                let track_x: f32 = inner_x + track_margin;
3380                let track_w: f32 = (inner_w - track_margin * 2.0 - corner_inset).max(16.0);
3381                let ratio: f32 = (view_w / total_w.max(view_w)).clamp(0.0, 1.0);
3382                let min_thumb_w: f32 = 20.0_f32.min(track_w);
3383                let thumb_w: f32 = (track_w * ratio).clamp(min_thumb_w, track_w);
3384                let scroll_frac: f32 = (scroll_x / max_scroll_x).clamp(0.0, 1.0);
3385                let thumb_x: f32 = track_x + (track_w - thumb_w) * scroll_frac;
3386                let thumb_x_snapped: f32 = (thumb_x * scale).round() * inv_scale;
3387                let thumb_y_snapped: f32 = (track_y * scale).round() * inv_scale;
3388                let thumb_w_snapped: f32 = (thumb_w * scale).round().max(1.0) * inv_scale;
3389                let thumb_h_snapped: f32 = (thumb_h * scale).round().max(1.0) * inv_scale;
3390                let thumb_alpha: u8 = if pressed {
3391                    188
3392                } else if hovered {
3393                    148
3394                } else {
3395                    88
3396                };
3397                display_list.push(DrawCommand::FillRoundedRect {
3398                    rect: Rect::new(
3399                        thumb_x_snapped,
3400                        thumb_y_snapped,
3401                        thumb_w_snapped,
3402                        thumb_h_snapped,
3403                    ),
3404                    color: Color::rgba(113, 113, 122, thumb_alpha).multiply_alpha(opacity),
3405                    radius: CornerRadius::all(thumb_h * 0.5),
3406                    border: Border::default(),
3407                });
3408            }
3409        }
3410        if emit_clip {
3411            if display_list.len() == clip_push_idx + 1 {
3412                display_list.pop_empty_clip(clip_saved_digest);
3413                if self_visible && defer_rounded_border && !has_canvas_clip {
3414                    let mut outer_border: Border = paint.get_border();
3415                    outer_border.set_color(outer_border.get_color().multiply_alpha(opacity));
3416                    display_list.push(DrawCommand::FillRoundedRect {
3417                        rect: bounds,
3418                        color: COLOR_TRANSPARENT,
3419                        radius: paint.get_radius(),
3420                        border: outer_border,
3421                    });
3422                }
3423            } else {
3424                display_list.push(DrawCommand::PopClip);
3425                if self_visible && has_rounded_border && !has_canvas_clip {
3426                    let mut outer_border: Border = paint.get_border();
3427                    outer_border.set_color(outer_border.get_color().multiply_alpha(opacity));
3428                    display_list.push(DrawCommand::FillRoundedRect {
3429                        rect: bounds,
3430                        color: COLOR_TRANSPARENT,
3431                        radius: paint.get_radius(),
3432                        border: outer_border,
3433                    });
3434                }
3435            }
3436        }
3437        if let Some((cmd_start, slot_idx, geom_hash, style_text_hash)) = frag_capture
3438            && let Some(cache) = scratch.fragments.as_deref_mut()
3439        {
3440            let cmd_slice: &[DrawCommand] = &display_list.get_commands()[cmd_start..];
3441            cache.capture_fragment(
3442                slot_idx,
3443                (
3444                    node_id,
3445                    phys_scale_milli,
3446                    parent_opacity.to_bits(),
3447                    offset_phys,
3448                    geom_hash,
3449                    style_text_hash,
3450                ),
3451                cmd_slice,
3452            );
3453        }
3454    }
3455}