1
//! CPU render backend for the headless E2E runner.
2
//!
3
//! Verbatim port of the DLL's `desktop::shell2::headless::CpuBackend`
4
//! (`dll/src/desktop/shell2/headless/mod.rs`) minus the pieces that need a
5
//! `PlatformWindow` (the hit tester, the `AZ_MAP_DEBUG` / `AZ_DUMP_FRAME_DIR`
6
//! dumps). Everything it calls lives in `azul_layout::cpurender`, so the port is
7
//! mechanical.
8
//!
9
//! WHY THIS EXISTS: the damage assertions (`assert_changed`,
10
//! `assert_damage_covers_changes`, `assert_damage_incremental`,
11
//! `assert_idle_stable`) read `LayoutWindow::frame_report`, which is written by
12
//! `FrameReport::record_frame` — and the ONLY producer of the paint/present
13
//! damage it records is this render pass. A runner that never renders a frame
14
//! reports `FrameDamage::None` forever, so every damage assertion fails with
15
//! "nothing was repainted (stale screen)" no matter what the engine did.
16

            
17
use std::{
18
    collections::{BTreeMap, BTreeSet},
19
    sync::Arc,
20
};
21

            
22
use azul_core::{
23
    dom::DomId,
24
    geom::{LogicalRect, LogicalSize},
25
    resources::RendererResources,
26
};
27
use azul_layout::{
28
    cpurender,
29
    solver3::display_list::DisplayList,
30
    window::{FrameDamage, LayoutWindow},
31
};
32

            
33
/// CPU rendering backend (the headless replacement for `WebRender`).
34
///
35
/// Holds the retained compositor state, the previous frame's display list /
36
/// scroll offsets / GPU values — everything the frame-to-frame damage diff
37
/// needs — and the damage of the most recent `render_frame`.
38
pub(super) struct CpuBackend {
39
    /// Last rendered pixmap.
40
    pub(super) last_frame: Option<cpurender::AzulPixmap>,
41
    /// Retained compositor state with per-layer pixbufs.
42
    pub(super) compositor: Option<cpurender::CompositorState>,
43
    /// Glyph cache — persists across frames for text rendering.
44
    pub(super) glyph_cache: azul_layout::glyph_cache::GlyphCache,
45
    /// Previous display list for damage-rect computation.
46
    pub(super) previous_display_list: Option<Arc<DisplayList>>,
47
    /// `LayoutCache::build_seq` at the last present — drains the patch log
48
    /// from there, so two patched builds between presents both repaint.
49
    pub(super) last_consumed_build_seq: u64,
50
    /// Arc pointer of the display list the translate blit last shifted —
51
    /// the already-shifted guard (a re-present of the same list must not
52
    /// blit twice). Mirrors the dll headless backend.
53
    pub(super) last_patch_shift_dl: usize,
54
    /// PAINT damage of the most recent `render_frame` — the region actually
55
    /// re-rasterised.
56
    pub(super) last_frame_damage: FrameDamage,
57
    /// PRESENT damage of the most recent `render_frame` — the region that
58
    /// visually CHANGED on screen (⊇ paint damage; a scroll memmoves a large
59
    /// region but paints a strip).
60
    pub(super) last_present_damage: FrameDamage,
61
    /// Scroll offsets of the previous frame (`scroll_id` → (x,y)).
62
    pub(super) previous_scroll_offsets: cpurender::ScrollOffsetMap,
63
    /// Where zombie exits painted LAST frame (logical px). Per frame the
64
    /// zombie contribution to damage is `previous ∪ current`: restore the
65
    /// live pixels where an exit was, paint it where it is — the reap frame
66
    /// (zombies gone, previous non-empty) erases the leftovers the same way.
67
    pub(super) previous_zombie_rects: Vec<LogicalRect>,
68
    /// Previous frame's `VirtualView` child-DOM display lists.
69
    pub(super) previous_vview_dls: BTreeMap<DomId, Arc<DisplayList>>,
70
    /// GPU-animated values of the previous frame, for the frame-to-frame diff.
71
    pub(super) previous_gpu_transforms:
72
        std::collections::HashMap<usize, azul_core::transform::ComputedTransform3D>,
73
    pub(super) previous_gpu_opacities: std::collections::HashMap<usize, f32>,
74
}
75

            
76
impl Default for CpuBackend {
77
    fn default() -> Self {
78
        Self::new()
79
    }
80
}
81

            
82
impl CpuBackend {
83
    #[must_use]
84
66
    pub(super) fn new() -> Self {
85
66
        Self {
86
66
            last_frame: None,
87
66
            compositor: None,
88
66
            glyph_cache: azul_layout::glyph_cache::GlyphCache::new(),
89
66
            previous_display_list: None,
90
66
            last_consumed_build_seq: 0,
91
66
            last_patch_shift_dl: 0,
92
66
            last_frame_damage: FrameDamage::None,
93
66
            last_present_damage: FrameDamage::None,
94
66
            previous_scroll_offsets: cpurender::ScrollOffsetMap::new(),
95
66
            previous_zombie_rects: Vec::new(),
96
66
            previous_vview_dls: BTreeMap::new(),
97
66
            previous_gpu_transforms: std::collections::HashMap::new(),
98
66
            previous_gpu_opacities: std::collections::HashMap::new(),
99
66
        }
100
66
    }
101

            
102
    /// Render the current display list into `last_frame`, recording the paint /
103
    /// present damage of the frame.
104
    ///
105
    /// Uses damage-rect-based incremental rendering when possible: the current
106
    /// display list is diffed against `previous_display_list`, and only the
107
    /// changed regions are repainted. Returns the damage rects that were
108
    /// rendered (empty = nothing changed, or a full repaint).
109
    #[allow(clippy::too_many_lines)]
110
16763
    pub(super) fn render_frame(
111
16763
        &mut self,
112
16763
        layout_window: &LayoutWindow,
113
16763
        renderer_resources: &RendererResources,
114
16763
        width: f32,
115
16763
        height: f32,
116
16763
        dpi_factor: f32,
117
16763
    ) -> Vec<LogicalRect> {
118
        // Engine observability: every e2e/headless frame reports its
119
        // duration + probe spans (drop-guard covers all return paths).
120
        #[cfg(feature = "telemetry")]
121
        let _frame_pump = crate::telemetry::FramePump::begin("present");
122

            
123
16763
        let dom_id = DomId { inner: 0 };
124
16763
        let Some(result) = layout_window.layout_results.get(&dom_id) else {
125
            return Vec::new();
126
        };
127
16763
        let display_list = &result.display_list;
128

            
129
16763
        let pixel_w = (width * dpi_factor).ceil() as u32;
130
16763
        let pixel_h = (height * dpi_factor).ceil() as u32;
131
16763
        if pixel_w == 0 || pixel_h == 0 {
132
            return Vec::new();
133
16763
        }
134

            
135
        // Allocate or resize compositor
136
16763
        let compositor = self
137
16763
            .compositor
138
16763
            .get_or_insert_with(|| cpurender::CompositorState::new(pixel_w, pixel_h));
139

            
140
16763
        let root = compositor.layers.get(&compositor.root_layer);
141
16763
        let (old_pw, old_ph) = match root {
142
16763
            Some(layer) => (layer.pixbuf.width(), layer.pixbuf.height()),
143
            None => (0, 0),
144
        };
145
16763
        let needs_resize = old_pw != pixel_w || old_ph != pixel_h;
146

            
147
16763
        let mut resize_damage = Vec::new();
148
        // A GROW preserves the previous frame: `resize_grow_only` copies the old
149
        // pixels into the top-left of the enlarged buffer (and `resize_reuse`
150
        // does the same for `last_frame` below), so the frame stays a valid base
151
        // for an incremental repaint and only the newly-exposed L is unknown.
152
        // A SHRINK throws the whole compositor away, so nothing may be reused.
153
16763
        let mut resize_preserved_pixels = false;
154
16763
        if needs_resize {
155
13
            let is_grow = pixel_w >= old_pw && pixel_h >= old_ph && old_pw > 0 && old_ph > 0;
156
13
            if is_grow {
157
7
                resize_preserved_pixels = true;
158
7
                if let Some(root_layer) = compositor.layers.get_mut(&compositor.root_layer) {
159
7
                    let _ = root_layer
160
7
                        .pixbuf
161
7
                        .resize_grow_only(pixel_w, pixel_h, 255, 255, 255, 255);
162
7
                    root_layer.bounds.size = LogicalSize {
163
7
                        width: pixel_w as f32,
164
7
                        height: pixel_h as f32,
165
7
                    };
166
7
                }
167
                // Damage rects are LOGICAL everywhere downstream.
168
7
                resize_damage = cpurender::compute_resize_damage(
169
7
                    old_pw as f32 / dpi_factor,
170
7
                    old_ph as f32 / dpi_factor,
171
7
                    width,
172
7
                    height,
173
                );
174
6
            } else {
175
6
                // Shrink (or a MIXED resize — wider but shorter lands here too,
176
6
                // `is_grow` demands both axes). This branch stays a FULL
177
6
                // repaint, and that is a measured decision, not an oversight: it
178
6
                // recreates the compositor AND never calls
179
6
                // `compute_resize_damage`, so letting it reuse the previous
180
6
                // frame under-paints. Measured with the resize probe at
181
6
                // 500x600 -> 700x400: 53200 changed pixels uncovered by any
182
6
                // damage rect, the first at (500, 134) — i.e. the whole
183
6
                // newly-exposed right strip, stale on a real screen. A shrink
184
6
                // also exposes nothing new, so a full repaint here costs at most
185
6
                // the NEW (smaller) buffer.
186
6
                *compositor = cpurender::CompositorState::new(pixel_w, pixel_h);
187
6
            }
188
16750
        }
189

            
190
        // Real scroll offsets for this frame — needed by the damage diff (items
191
        // inside scroll frames are stored at CONTENT coords) and by the
192
        // scroll-shift machinery further down.
193
16763
        let scroll_offsets = layout_window
194
16763
            .scroll_manager
195
16763
            .build_scroll_offset_map(dom_id, &result.scroll_id_to_node_id);
196

            
197
        // GPU-value diff: thumb position / fade opacity / transforms change
198
        // WITHOUT any display-list item changing (items only carry the keys).
199
16763
        let gpu_cache_early = layout_window.gpu_state_manager.get_cache(dom_id);
200
16763
        let (gpu_transforms, gpu_opacities) =
201
16763
            cpurender::extract_gpu_values(gpu_cache_early, dom_id);
202
16763
        let gpu_damage = cpurender::gpu_value_damage(
203
16763
            display_list,
204
16763
            &self.previous_gpu_transforms,
205
16763
            &self.previous_gpu_opacities,
206
16763
            &gpu_transforms,
207
16763
            &gpu_opacities,
208
        );
209
16763
        let has_gpu_damage = !gpu_damage.rects.is_empty() || gpu_damage.needs_full;
210
16763
        if has_gpu_damage && std::env::var_os("AZ_PATCH_DEBUG").is_some() {
211
            let td: Vec<_> = gpu_transforms
212
                .iter()
213
                .filter(|(k, v)| self.previous_gpu_transforms.get(k) != Some(v))
214
                .map(|(k, v)| (*k, v.m[3][0], v.m[3][1]))
215
                .collect();
216
            let od: Vec<_> = gpu_opacities
217
                .iter()
218
                .filter(|(k, v)| self.previous_gpu_opacities.get(k) != Some(v))
219
                .map(|(k, v)| (*k, *v))
220
                .collect();
221
            eprintln!(
222
                "[GPUDMG] prev_t={} cur_t={} prev_o={} cur_o={} changed_t={td:?} changed_o={od:?} \
223
                 rects={:?}",
224
                self.previous_gpu_transforms.len(),
225
                gpu_transforms.len(),
226
                self.previous_gpu_opacities.len(),
227
                gpu_opacities.len(),
228
                gpu_damage.rects,
229
            );
230
16763
        }
231
        // Retained exits repaint every tick without any display-list item
232
        // changing — their per-frame truth is `previous ∪ current` painted
233
        // rects: restore the live frame where the exit WAS, paint it where
234
        // it IS. That keeps the incremental path (and even the reap frame's
235
        // cleanup) on bounded damage instead of forcing full composites for
236
        // the whole exit duration.
237
16763
        let zombies_active = layout_window.has_zombies();
238
16763
        let zombie_rects = if zombies_active {
239
18
            layout_window.zombie_paint_rects()
240
        } else {
241
16745
            Vec::new()
242
        };
243
16763
        let zombie_damage: Vec<LogicalRect> = self
244
16763
            .previous_zombie_rects
245
16763
            .iter()
246
16763
            .chain(zombie_rects.iter())
247
16763
            .copied()
248
16763
            .collect();
249
16763
        self.previous_gpu_transforms = gpu_transforms;
250
16763
        self.previous_gpu_opacities = gpu_opacities;
251

            
252
        // Can the pixels of the previous frame still be trusted? Yes when the
253
        // buffer did not change size at all, and yes on a GROW (the old pixels
254
        // were copied over verbatim). No on a shrink / first allocation.
255
16763
        let can_reuse_previous_frame = !needs_resize || resize_preserved_pixels;
256

            
257
        // Translate hint: identical decision to the dll headless backend, so
258
        // the harness executes the SAME blit path a device does (it used to
259
        // have no notion of a TranslateHint at all — every mover-blit bug was
260
        // structurally untestable here).
261
16763
        let dl_arc_ptr = Arc::as_ptr(display_list) as usize;
262
16763
        let patch_hint = cpurender::translate_hint_for_patch(
263
16763
            layout_window.layout_cache.last_patch_move.as_ref(),
264
16763
            dpi_factor,
265
16763
            can_reuse_previous_frame,
266
16763
            self.last_patch_shift_dl == dl_arc_ptr,
267
16763
            layout_window.scroll_manager.any_nonzero_offset(),
268
        );
269

            
270
        // Display-list damage (incremental path)
271
16763
        let mut patch_moved_union: Option<LogicalRect> = None;
272
16763
        let dl_damage = match &self.previous_display_list {
273
            // SAME Arc = the DL cache served the identical list (scroll
274
            // steady state): zero item changes by definition - mirror of the
275
            // dll present path's shortcut, so the twin measures what the
276
            // device does.
277
16697
            Some(old_dl)
278
16697
                if can_reuse_previous_frame
279
16691
                    && !gpu_damage.needs_full
280
16691
                    && Arc::ptr_eq(old_dl, display_list) =>
281
            {
282
16567
                Some(Vec::new())
283
            }
284
130
            Some(old_dl) if can_reuse_previous_frame && !gpu_damage.needs_full => {
285
124
                match cpurender::compute_display_list_damage_translated(
286
124
                    old_dl,
287
124
                    display_list,
288
124
                    &self.previous_scroll_offsets,
289
124
                    &scroll_offsets,
290
124
                    patch_hint.as_ref().map(|(h, _)| h),
291
                ) {
292
122
                    Some((damage, moved)) => {
293
122
                        patch_moved_union = moved;
294
122
                        Some(damage)
295
                    }
296
2
                    None => None,
297
                }
298
            }
299
72
            _ => None, // first frame, shrink or ref-frame transform → full repaint
300
        };
301

            
302
        // VirtualView child-DOM damage.
303
16763
        let vview_dls: BTreeMap<DomId, Arc<DisplayList>> = layout_window
304
16763
            .layout_results
305
16763
            .iter()
306
16763
            .filter(|(id, _)| id.inner != dom_id.inner)
307
16763
            .map(|(id, r)| (*id, r.display_list.clone()))
308
16763
            .collect();
309
16763
        let vview_damage = cpurender::compute_virtual_view_damage(
310
16763
            display_list,
311
16763
            &vview_dls,
312
16763
            &self.previous_vview_dls,
313
        );
314
16763
        let has_vview_damage = !vview_damage.is_empty();
315
16763
        self.previous_vview_dls = vview_dls.clone();
316

            
317
        // Scroll: the display list is UNCHANGED on scroll, so the diff above
318
        // only ever catches the scrollbar. Collect (clip, delta) per frame whose
319
        // offset changed so the still-visible pixels can be MOVED and only the
320
        // exposed strip repainted.
321
        // One shared, viewport-projected collector with the shell - see
322
        // `cpurender::collect_scroll_shifts`.
323
16763
        let scroll_shifts = cpurender::collect_scroll_shifts(
324
16763
            display_list,
325
16763
            &scroll_offsets,
326
16763
            &self.previous_scroll_offsets,
327
16763
            dpi_factor,
328
        );
329
16763
        let has_scroll = !scroll_shifts.is_empty();
330
        // Advance the scroll baseline ONLY for frames actually painted at their
331
        // new offset this call, so sub-device-pixel deltas ACCUMULATE instead of
332
        // being swallowed frame after frame.
333
16763
        let shifted_ids: BTreeSet<u64> = scroll_shifts.iter().map(|(sid, ..)| *sid).collect();
334
16763
        let next_scroll_baseline: cpurender::ScrollOffsetMap = scroll_offsets
335
16763
            .iter()
336
16763
            .map(|(id, off)| {
337
16454
                if shifted_ids.contains(id) {
338
14
                    (*id, *off)
339
                } else {
340
16440
                    (
341
16440
                        *id,
342
16440
                        self.previous_scroll_offsets
343
16440
                            .get(id)
344
16440
                            .copied()
345
16440
                            .unwrap_or(*off),
346
16440
                    )
347
                }
348
16454
            })
349
16763
            .collect();
350

            
351
        // Determine render path.
352
        let mut all_damage: Vec<LogicalRect>;
353
        let is_incremental;
354

            
355
        // A PATCHED build may change the item count, which the old-vs-new
356
        // item diff reads as structural (None -> full). The patch recorded
357
        // its own precise damage at build time — and on a patched build it
358
        // is AUTHORITATIVE, not a fallback: the index-pairing diff
359
        // under-damages a same-count splice (re-emitted node + translated
360
        // neighbours mis-pair). Guarded to the same conditions the diff ran
361
        // under, so gpu needs_full / shrink / first frame stay full repaints.
362
16763
        let diff_path_ran = self.previous_display_list.is_some()
363
16697
            && can_reuse_previous_frame
364
16691
            && !gpu_damage.needs_full;
365
16763
        let dl_damage = if diff_path_ran && layout_window.layout_cache.last_build_was_patched {
366
            // On a PATCHED build the patch's own damage AUGMENTS the item
367
            // diff: the index-pairing diff under-damages a same-count splice
368
            // (one stale rect where a reflow moved three nodes), so union
369
            // the two when the diff produced rects, and use the patch's
370
            // damage alone when the diff gave up (count change -> None).
371
            // Never REPLACE a Some(diff) wholesale: unpatched-equal frames
372
            // must keep their baseline damage exactly (an empty diff on a
373
            // quiet frame stays the idle skip).
374
            // EVERY patched build since this backend last presented (see
375
            // the headless twin): two patched builds in one pass each know
376
            // only their own vacated rects.
377
            use azul_layout::solver3::cache::PendingPatchDamage as P;
378
11
            let pending = layout_window
379
11
                .layout_cache
380
11
                .pending_patch_damage(self.last_consumed_build_seq);
381
            // Patch rects are CONTENT-space (no scroll projection on the
382
            // producer); with any active offset they land offset-pixels away
383
            // from the changed pixels. Demote to full-build semantics then —
384
            // same gate as the dll present path.
385
11
            let patch_rects_trustworthy = !layout_window.scroll_manager.any_nonzero_offset();
386
11
            match (dl_damage, pending) {
387
                // An EMPTY diff on a patched build means the splice produced a
388
                // byte-identical list (same-text re-shape) — the frame is IDLE
389
                // and must stay idle; painting patch rects here flips the
390
                // idle-skip and drifts the frame scheduling (scrollbar-fade
391
                // clock) off the baseline.
392
4
                (Some(d), P::Rects(_)) if d.is_empty() => Some(d),
393
                (d, P::Rects(_)) if !patch_rects_trustworthy => d,
394
4
                (Some(mut d), P::Rects(p)) => {
395
4
                    d.extend(p);
396
4
                    Some(d)
397
                }
398
                (None, P::Rects(p)) => Some(p),
399
                (d, P::FullBuildSincePresent) => d,
400
7
                (d, P::None) => d,
401
                (_, P::Unknown) => None,
402
            }
403
        } else {
404
16752
            dl_damage
405
        };
406
16763
        if std::env::var_os("AZ_PATCH_DEBUG").is_some() {
407
            eprintln!(
408
                "[E2EDMG] dl_damage={:?} diff_ran={} patched={} resize={:?} gpu_full={} \
409
                 gpu_rects={} zombie={}",
410
                dl_damage.as_ref().map(Vec::len),
411
                diff_path_ran,
412
                layout_window.layout_cache.last_build_was_patched,
413
                resize_damage.len(),
414
                gpu_damage.needs_full,
415
                gpu_damage.rects.len(),
416
                zombie_damage.len(),
417
            );
418
16763
        }
419
123
        match dl_damage {
420
16566
            Some(rects)
421
16689
                if rects.is_empty()
422
16577
                    && !needs_resize
423
16576
                    && resize_damage.is_empty()
424
16576
                    && !has_scroll
425
16576
                    && !has_vview_damage
426
16576
                    && !has_gpu_damage
427
16569
                    && zombie_damage.is_empty() =>
428
            {
429
                // Nothing changed — skip rendering entirely.
430
                //
431
                // `!needs_resize` is load-bearing now that a resize can reach
432
                // this match at all: skipping leaves `last_frame` at the OLD
433
                // dimensions while the compositor is already at the new ones, so
434
                // the host would publish (and present) a wrongly-sized buffer.
435
                // A frame whose backing store changed size is never "nothing".
436
16566
                self.previous_display_list = Some(display_list.clone());
437
16566
                self.last_consumed_build_seq = layout_window.layout_cache.build_seq;
438
16566
                self.previous_scroll_offsets = next_scroll_baseline;
439
16566
                self.last_frame_damage = FrameDamage::None;
440
16566
                self.last_present_damage = FrameDamage::None;
441
16566
                return Vec::new();
442
            }
443
            // The display-list diff plus, on a grow, the newly-exposed L. The
444
            // guard used to be `!needs_resize`, which meant a grow BUILT the
445
            // bounded repaint (`compute_resize_damage` + `resize_grow_only`
446
            // preserving the old pixels) and then threw it away: `dl_damage` was
447
            // forced to `None`, the match fell through to `_`, the buffer was
448
            // filled white and everything was repainted — `FrameDamage::Full`
449
            // for a window that only grew by a strip.
450
123
            Some(mut rects) if can_reuse_previous_frame => {
451
123
                rects.extend(resize_damage);
452
123
                all_damage = rects;
453
123
                is_incremental = true;
454
123
            }
455
74
            _ => {
456
74
                all_damage = resize_damage;
457
74
                is_incremental = false;
458
74
            }
459
        }
460

            
461
197
        if is_incremental && has_vview_damage {
462
            all_damage.extend(vview_damage);
463
197
        }
464
197
        if is_incremental && !gpu_damage.rects.is_empty() {
465
59
            all_damage.extend(gpu_damage.rects.iter().copied());
466
138
        }
467
197
        if is_incremental && !zombie_damage.is_empty() {
468
24
            all_damage.extend(zombie_damage.iter().copied());
469
173
        }
470

            
471
        // Acquire output pixmap — reuse buffer for both grow and shrink
472
197
        let mut output = match self.last_frame.take() {
473
131
            Some(p) if p.width() == pixel_w && p.height() == pixel_h => p,
474
13
            Some(mut p) => {
475
13
                p.resize_reuse(pixel_w, pixel_h, 255, 255, 255, 255);
476
13
                p
477
            }
478
66
            None => match cpurender::AzulPixmap::new(pixel_w, pixel_h) {
479
66
                Some(mut p) => {
480
66
                    p.fill(255, 255, 255, 255);
481
66
                    p
482
                }
483
                None => return Vec::new(),
484
            },
485
        };
486

            
487
        // Thin-strip scroll: MOVE the still-visible pixels and repaint only the
488
        // strip that scrolled into view. Regions that were pixel-SHIFTED belong
489
        // to PRESENT damage (the whole clip changed on screen) but not to paint
490
        // damage (only a strip was rasterised).
491
197
        let mut present_extra: Vec<LogicalRect> = Vec::new();
492
197
        if is_incremental {
493
            if let (Some((hint, exceptions)), Some(moved)) =
494
123
                (patch_hint.as_ref(), patch_moved_union)
495
            {
496
                self.last_patch_shift_dl = dl_arc_ptr;
497
                let _ = moved;
498
                let mover_rects = layout_window
499
                    .layout_cache
500
                    .last_patch_move
501
                    .as_ref()
502
                    .map(|m| m.mover_rects_old.clone())
503
                    .unwrap_or_default();
504
                let blit = cpurender::execute_translate_blit(
505
                    &mut output,
506
                    hint,
507
                    exceptions,
508
                    &mover_rects,
509
                    display_list,
510
                    dpi_factor,
511
                    false, // e2e twin renders owned pixmaps, never pool-order
512
                );
513
                all_damage.extend(blit.damage);
514
                present_extra.extend(blit.present_extra);
515
123
            }
516
137
            for (scroll_id, clip, delta, offset) in &scroll_shifts {
517
14
                // One shared recipe with the shell — see
518
14
                // `cpurender::execute_scroll_shift`.
519
14
                let out = cpurender::execute_scroll_shift(
520
14
                    &mut output,
521
14
                    display_list,
522
14
                    *scroll_id,
523
14
                    clip,
524
14
                    *delta,
525
14
                    *offset,
526
14
                    dpi_factor,
527
14
                    false, // e2e twin renders owned pixmaps, never pool-order
528
14
                );
529
14
                all_damage.extend(out.damage);
530
14
                present_extra.extend(out.present_extra);
531
14
            }
532
74
        }
533

            
534
        // The recorded paint/present damage must not double-count a region.
535
197
        if is_incremental {
536
123
            cpurender::coalesce_damage_rects(&mut all_damage);
537
123
        }
538

            
539
197
        let gpu_cache = layout_window.gpu_state_manager.get_cache(dom_id);
540
        // Incremental repaints must raster at the offsets the surrounding
541
        // (un-repainted) pixels are ALREADY at — the baseline.
542
197
        let render_offsets = if is_incremental {
543
123
            &next_scroll_baseline
544
        } else {
545
74
            &scroll_offsets
546
        };
547
197
        let render_state =
548
197
            cpurender::CpuRenderState::from_gpu_cache(gpu_cache, dom_id, render_offsets)
549
197
                .with_system_style(layout_window.system_style.clone())
550
197
                .with_virtual_view_display_lists(vview_dls);
551

            
552
197
        if is_incremental && !all_damage.is_empty() {
553
123
            drop(cpurender::render_display_list_damaged(
554
123
                display_list,
555
123
                &mut output,
556
123
                dpi_factor,
557
123
                renderer_resources,
558
123
                &layout_window.font_manager,
559
123
                &mut self.glyph_cache,
560
123
                &render_state,
561
123
                &all_damage,
562
            ));
563
            // Exits paint ON TOP of the restored live pixels; their current
564
            // rects are inside `all_damage` by construction.
565
123
            if zombies_active {
566
18
                layout_window.composite_zombies_cpu(
567
18
                    &mut output,
568
18
                    dpi_factor,
569
18
                    renderer_resources,
570
18
                    &mut self.glyph_cache,
571
18
                );
572
105
            }
573
74
        } else {
574
74
            output.fill(255, 255, 255, 255);
575
74
            compositor.allocate_layers_from_display_list(
576
74
                display_list,
577
74
                dpi_factor,
578
74
                &render_state.transforms,
579
74
                &render_state.opacities,
580
74
            );
581
74
            drop(compositor.render_layers(
582
74
                display_list,
583
74
                dpi_factor,
584
74
                renderer_resources,
585
74
                &layout_window.font_manager,
586
74
                &mut self.glyph_cache,
587
74
                &render_state,
588
74
            ));
589
74
            compositor.composite_frame(&mut output, dpi_factor);
590
74
            // The design doc's invariant: the rendered frame is B ∪ zombies.
591
74
            layout_window.composite_zombies_cpu(
592
74
                &mut output,
593
74
                dpi_factor,
594
74
                renderer_resources,
595
74
                &mut self.glyph_cache,
596
74
            );
597
74
        }
598

            
599
197
        self.previous_zombie_rects = zombie_rects;
600
197
        self.previous_display_list = Some(display_list.clone());
601
197
        self.last_consumed_build_seq = layout_window.layout_cache.build_seq;
602
197
        self.previous_scroll_offsets = if is_incremental {
603
123
            next_scroll_baseline
604
        } else {
605
74
            scroll_offsets.clone()
606
        };
607
197
        self.last_frame = Some(output);
608
197
        self.last_frame_damage = if is_incremental {
609
123
            FrameDamage::Rects(all_damage.clone())
610
        } else {
611
74
            FrameDamage::Full
612
        };
613
197
        self.last_present_damage = if is_incremental {
614
123
            let mut present = all_damage.clone();
615
123
            present.extend(present_extra);
616
123
            FrameDamage::Rects(present)
617
        } else {
618
74
            FrameDamage::Full
619
        };
620
197
        all_damage
621
16763
    }
622
}
623

            
624
#[cfg(test)]
625
mod tests {
626
    use azul_core::{
627
        dom::{Dom, DomId, NodeId},
628
        geom::LogicalSize,
629
        resources::RendererResources,
630
        styled_dom::StyledDom,
631
    };
632
    use azul_css::AzString;
633
    use rust_fontconfig::FcFontCache;
634

            
635
    use super::*;
636

            
637
    /// `::placeholder` is REAL CSS: an author rule restyles the prompt the
638
    /// engine paints, through the same cascade every other property uses.
639
    ///
640
    /// Pinned by COLOUR, because that is what a stylesheet actually controls
641
    /// here: with no rule the prompt is the host's colour at half alpha;
642
    /// with `::placeholder { color: red }` it is exactly red.
643
    #[test]
644
    fn a_placeholder_rule_restyles_the_prompt_through_the_cascade() {
645
        use azul_core::dom::AttributeType;
646

            
647
        let prompt_pixels = |css_src: &str| -> Vec<(u8, u8, u8)> {
648
            let mut dom = Dom::create_body().with_child(
649
                Dom::create_div()
650
                    .with_ids_and_classes(
651
                        vec![azul_core::dom::IdOrClass::Class("ed".into())].into(),
652
                    )
653
                    .with_attribute(AttributeType::ContentEditable(true))
654
                    .with_attribute(AttributeType::Placeholder("Hint me".into())),
655
            );
656
            let (css, _) = azul_css::parser2::new_from_str(css_src);
657
            let styled_dom = StyledDom::create(&mut dom, css);
658
            let mut lw = crate::window::LayoutWindow::new(FcFontCache::build()).unwrap();
659
            lw.system_animations_override =
660
                Some(azul_core::resources::SystemAnimations::disabled());
661
            let mut ws = crate::window_state::FullWindowState::default();
662
            ws.size.dimensions = LogicalSize::new(400.0, 100.0);
663
            lw.current_window_state = ws.clone();
664
            let resources = RendererResources::default();
665
            let cbs = crate::callbacks::ExternalSystemCallbacks::rust_internal();
666
            let mut dbg = Some(Vec::new());
667
            lw.layout_and_generate_display_list(styled_dom, &ws, &resources, &cbs, &mut dbg)
668
                .unwrap();
669
            let lr = lw.get_layout_result(&DomId::ROOT_ID).unwrap();
670
            lr.display_list
671
                .items
672
                .iter()
673
                .filter_map(|it| match it {
674
                    crate::solver3::display_list::DisplayListItem::Text {
675
                        color, glyphs, ..
676
                    } if !glyphs.is_empty() => Some((color.r, color.g, color.b)),
677
                    _ => None,
678
                })
679
                .collect()
680
        };
681

            
682
        const BASE: &str = "body { width: 400px; height: 100px; } .ed { width: 300px; height: \
683
                            40px; font-size: 16px; color: black; }";
684

            
685
        let unstyled = prompt_pixels(BASE);
686
        assert_eq!(unstyled.len(), 1, "exactly one prompt run: {unstyled:?}");
687

            
688
        let styled = prompt_pixels(&format!(
689
            "{BASE} .ed::placeholder {{ color: rgb(255, 0, 0); }}"
690
        ));
691
        assert_eq!(
692
            styled,
693
            vec![(255, 0, 0)],
694
            "a ::placeholder rule must restyle the prompt (unstyled was {unstyled:?})"
695
        );
696
        assert_ne!(styled, unstyled, "the rule must actually change something");
697
    }
698

            
699
    /// ENGINE-LEVEL PLACEHOLDER: the `placeholder` ATTRIBUTE on a
700
    /// contenteditable host paints a prompt while the host is EMPTY and
701
    /// UNFOCUSED - no overlay <p>, no per-widget toggle code. The control
702
    /// (no attribute) must paint nothing, pinning that the ink really is
703
    /// the attribute's doing.
704
    #[test]
705
    fn the_placeholder_attribute_paints_for_an_empty_unfocused_editable() {
706
        use azul_core::dom::AttributeType;
707

            
708
        let ink_rows = |with_attr: bool, focused: bool, value: &str| -> usize {
709
            let mut ed = Dom::create_div()
710
                .with_ids_and_classes(vec![azul_core::dom::IdOrClass::Class("ed".into())].into())
711
                .with_attribute(AttributeType::ContentEditable(true));
712
            if with_attr {
713
                ed = ed.with_attribute(AttributeType::Placeholder("Hint me".into()));
714
            }
715
            if !value.is_empty() {
716
                ed = ed.with_children(
717
                    vec![crate::widgets::widget_p().with_children(
718
                        vec![Dom::create_text_do_not_use_without_block_level_wrapper(
719
                            value.to_string(),
720
                        )]
721
                        .into(),
722
                    )]
723
                    .into(),
724
                );
725
            }
726
            let mut dom = Dom::create_body().with_child(ed);
727
            let (css, _) = azul_css::parser2::new_from_str(
728
                "body { width: 400px; height: 100px; } .ed { width: 300px; height: 40px; \
729
                 font-size: 16px; }",
730
            );
731
            let styled_dom = StyledDom::create(&mut dom, css);
732
            let mut lw = crate::window::LayoutWindow::new(FcFontCache::build()).unwrap();
733
            lw.system_animations_override =
734
                Some(azul_core::resources::SystemAnimations::disabled());
735
            let styled_dom = if focused {
736
                // Stamp :focus exactly the way the SHELL does before layout
737
                // (dll `apply_runtime_states_before_layout`) - that stamping
738
                // lives in the shell, so an engine-only harness must mirror
739
                // it or the painter's focus check can never see focus.
740
                let mut sd = styled_dom;
741
                {
742
                    let mut styled_nodes = sd.styled_nodes.as_container_mut();
743
                    if let Some(n) = styled_nodes.get_mut(NodeId::new(1)) {
744
                        n.styled_node_state.focused = true;
745
                    }
746
                }
747
                sd
748
            } else {
749
                styled_dom
750
            };
751
            let mut ws = crate::window_state::FullWindowState::default();
752
            ws.size.dimensions = LogicalSize::new(400.0, 100.0);
753
            lw.current_window_state = ws.clone();
754
            let resources = RendererResources::default();
755
            let cbs = crate::callbacks::ExternalSystemCallbacks::rust_internal();
756
            let mut dbg = Some(Vec::new());
757
            lw.layout_and_generate_display_list(styled_dom, &ws, &resources, &cbs, &mut dbg)
758
                .unwrap();
759
            let lr = lw.get_layout_result(&DomId::ROOT_ID).unwrap();
760
            let mut gc = crate::glyph_cache::GlyphCache::new();
761
            let frame = crate::cpurender::render_with_font_manager(
762
                &lr.display_list,
763
                &resources,
764
                &lw.font_manager,
765
                crate::cpurender::RenderOptions {
766
                    width: 400.0,
767
                    height: 100.0,
768
                    dpi_factor: 1.0,
769
                },
770
                &mut gc,
771
            )
772
            .unwrap();
773
            let (w, data) = (frame.width() as usize, frame.data());
774
            (0..40usize)
775
                .filter(|y| {
776
                    (0..300usize).any(|x| {
777
                        let i = ((y * w + x) * 4).min(data.len().saturating_sub(4));
778
                        (u16::from(data[i]) + u16::from(data[i + 1]) + u16::from(data[i + 2])) < 690
779
                    })
780
                })
781
                .count()
782
        };
783

            
784
        assert_eq!(
785
            ink_rows(false, false, ""),
786
            0,
787
            "the control (no placeholder attribute) must paint nothing"
788
        );
789
        let with_attr = ink_rows(true, false, "");
790
        assert!(
791
            with_attr >= 6,
792
            "the placeholder attribute must paint a text line (got {with_attr} ink rows)"
793
        );
794
        assert_eq!(
795
            ink_rows(true, true, ""),
796
            0,
797
            "a FOCUSED host hides its prompt (2026-08-31 ruling) - recomputed per build, no latch \
798
             to stick"
799
        );
800

            
801
        // THE DEVICE REGRESSION (2026-08-31): a DEFOCUSED host that HAS text
802
        // painted its prompt under that text, because emptiness was read off
803
        // `inline_layout_result` and its absence counted as empty. Emptiness
804
        // is a question about CONTENT: the filled host must paint exactly
805
        // what a host with no placeholder attribute paints.
806
        let filled_with_prompt = ink_rows(true, false, "typed");
807
        let filled_control = ink_rows(false, false, "typed");
808
        assert_eq!(
809
            filled_with_prompt, filled_control,
810
            "a defocused FILLED host must paint no prompt: {filled_with_prompt} ink rows with the \
811
             attribute vs {filled_control} without it"
812
        );
813
    }
814

            
815
    /// Control: the same field WITHOUT the scroll column (no layer). If this
816
    /// is green while the column variant is red, the truncation lives in the
817
    /// LAYERED render path, not in text rendering itself.
818
    #[test]
819
    fn first_flat_frame_paints_the_placeholder_fully() {
820
        use crate::widgets::text_input::TextInput;
821
        let mut dom = Dom::create_body().with_child(
822
            TextInput::create()
823
                .with_placeholder("Type something".into())
824
                .dom(),
825
        );
826
        let (css, _) = azul_css::parser2::new_from_str("body { width: 640px; height: 480px; }");
827
        let styled_dom = StyledDom::create(&mut dom, css);
828
        let mut lw = crate::window::LayoutWindow::new(FcFontCache::build()).unwrap();
829
        lw.system_animations_override = Some(azul_core::resources::SystemAnimations::disabled());
830
        let mut ws = crate::window_state::FullWindowState::default();
831
        ws.size.dimensions = LogicalSize::new(640.0, 480.0);
832
        lw.current_window_state = ws.clone();
833
        let resources = RendererResources::default();
834
        let cbs = crate::callbacks::ExternalSystemCallbacks::rust_internal();
835
        let mut dbg = Some(Vec::new());
836
        lw.layout_and_generate_display_list(styled_dom, &ws, &resources, &cbs, &mut dbg)
837
            .unwrap();
838
        let lr = lw.get_layout_result(&DomId::ROOT_ID).unwrap();
839
        let idx = lr
840
            .layout_tree
841
            .dom_to_layout
842
            .get(&NodeId::new(1))
843
            .and_then(|v| v.first())
844
            .expect("container laid out")
845
            .index();
846
        let pos = lr.calculated_positions[idx];
847
        let size = lr
848
            .layout_tree
849
            .get(crate::solver3::LayoutNodeId::new(idx))
850
            .and_then(|n| n.used_size)
851
            .expect("container size");
852
        let dpi: f32 = std::env::var("AZ_REPRO_DPI")
853
            .ok()
854
            .and_then(|v| v.parse().ok())
855
            .unwrap_or(2.0);
856
        let ink = |frame: &crate::cpurender::AzulPixmap| -> (usize, Vec<usize>) {
857
            let (w, data) = (frame.width() as usize, frame.data());
858
            let x0 = ((pos.x + 4.0) * dpi) as usize;
859
            let x1 = ((pos.x + size.width - 4.0) * dpi) as usize;
860
            let rows: Vec<usize> =
861
                (0..frame.height() as usize)
862
                    .filter(|y| {
863
                        (x0..x1).any(|x| {
864
                            let i = ((y * w + x) * 4).min(data.len().saturating_sub(4)); // clamp: field can overflow the window row
865
                            (u16::from(data[i]) + u16::from(data[i + 1]) + u16::from(data[i + 2]))
866
                                < 690 // engine prompt = host colour at half alpha (~#A6A6A6)
867
                        })
868
                    })
869
                    .collect();
870
            let y0 = ((pos.y + 2.0) * dpi) as usize;
871
            let y1 = ((pos.y + size.height - 2.0) * dpi) as usize;
872
            let inside = rows.iter().filter(|y| (y0..y1).contains(y)).count();
873
            (inside, rows)
874
        };
875
        let mut backend = CpuBackend::new();
876
        backend.render_frame(&lw, &resources, 640.0, 480.0, dpi);
877
        let frame = backend.last_frame.as_ref().unwrap().clone_pixmap();
878
        let (inside_b, rows_b) = ink(&frame);
879
        let mut gc = crate::glyph_cache::GlyphCache::new();
880
        let flat = crate::cpurender::render_with_font_manager(
881
            &lr.display_list,
882
            &resources,
883
            &lw.font_manager,
884
            crate::cpurender::RenderOptions {
885
                width: 640.0,
886
                height: 480.0,
887
                dpi_factor: dpi,
888
            },
889
            &mut gc,
890
        )
891
        .unwrap();
892
        let (inside_f, rows_f) = ink(&flat);
893
        eprintln!(
894
            "[repro] dpi={dpi} field_y_dev={:?} backend: inside={inside_b} all_ink_rows={:?} | \
895
             flat: inside={inside_f} all_ink_rows={:?}",
896
            (
897
                ((pos.y + 2.0) * dpi) as usize,
898
                ((pos.y + size.height - 2.0) * dpi) as usize
899
            ),
900
            &rows_b[..rows_b.len().min(30)],
901
            &rows_f[..rows_f.len().min(30)]
902
        );
903
        assert!(
904
            inside_b >= 8,
905
            "flat control: got {inside_b} ink rows (backend)"
906
        );
907
    }
908

            
909
    /// DEVICE 2026-08-31: on the first frames, every 11px placeholder inside
910
    /// the page's scroll column rendered as a ~4px strip of glyph TOPS -
911
    /// while the display list carried a healthy 13px clip (dl dumps) and any
912
    /// damaged repaint painted the identical list correctly. The layered
913
    /// full render is the only path that differs. This pins it headlessly:
914
    /// the field's inner text region must contain a full line of ink.
915
    #[test]
916
    fn first_layered_frame_paints_the_placeholder_fully() {
917
        use crate::widgets::text_input::TextInput;
918
        let mut dom = Dom::create_body().with_child(
919
            Dom::create_div().with_class("col".into()).with_children(
920
                vec![
921
                    TextInput::create()
922
                        .with_placeholder("Type something".into())
923
                        .dom(),
924
                    Dom::create_div().with_class("filler".into()),
925
                ]
926
                .into(),
927
            ),
928
        );
929
        let (css, _) = azul_css::parser2::new_from_str(
930
            "body { width: 640px; height: 480px; }              .col { overflow-y: auto; width: \
931
             100%; height: 100%; }              .filler { height: 2000px; }",
932
        );
933
        let styled_dom = StyledDom::create(&mut dom, css);
934
        let mut lw = crate::window::LayoutWindow::new(FcFontCache::build()).unwrap();
935
        lw.system_animations_override = Some(azul_core::resources::SystemAnimations::disabled());
936
        let mut ws = crate::window_state::FullWindowState::default();
937
        ws.size.dimensions = LogicalSize::new(640.0, 480.0);
938
        lw.current_window_state = ws.clone();
939
        let resources = RendererResources::default();
940
        let cbs = crate::callbacks::ExternalSystemCallbacks::rust_internal();
941
        let mut dbg = Some(Vec::new());
942
        lw.layout_and_generate_display_list(styled_dom, &ws, &resources, &cbs, &mut dbg)
943
            .unwrap();
944

            
945
        // The TextInput container: body(0) > col(1) > container(2).
946
        let lr = lw.get_layout_result(&DomId::ROOT_ID).unwrap();
947
        let idx = lr
948
            .layout_tree
949
            .dom_to_layout
950
            .get(&NodeId::new(2))
951
            .and_then(|v| v.first())
952
            .expect("container laid out")
953
            .index();
954
        let pos = lr.calculated_positions[idx];
955
        let size = lr
956
            .layout_tree
957
            .get(crate::solver3::LayoutNodeId::new(idx))
958
            .and_then(|n| n.used_size)
959
            .expect("container size");
960

            
961
        let dpi = 2.0;
962
        let mut backend = CpuBackend::new();
963
        backend.render_frame(&lw, &resources, 640.0, 480.0, dpi);
964
        let frame = backend
965
            .last_frame
966
            .as_ref()
967
            .expect("first layered frame")
968
            .clone_pixmap();
969

            
970
        // Count device rows with ink inside the field's inner text region.
971
        let (w, data) = (frame.width() as usize, frame.data());
972
        let x0 = ((pos.x + 4.0) * dpi) as usize;
973
        let x1 = ((pos.x + size.width - 4.0) * dpi) as usize;
974
        let y0 = ((pos.y + 2.0) * dpi) as usize;
975
        let y1 = ((pos.y + size.height - 2.0) * dpi) as usize;
976
        // Diagnostic: keep the frame on disk for eyeballing.
977
        if let Ok(dir) = std::env::var("AZ_REPRO_DUMP") {
978
            if let Ok(bytes) = frame.encode_png() {
979
                let _ = std::fs::write(format!("{dir}/repro_layered.png"), bytes);
980
            }
981
        }
982
        let ink_rows = (y0..y1)
983
            .filter(|y| {
984
                (x0..x1).any(|x| {
985
                    let i = ((y * w + x) * 4).min(data.len().saturating_sub(4)); // clamp: field can
986
                                                                                 // overflow the
987
                                                                                 // window row
988
                    let (r, g, b) = (data[i], data[i + 1], data[i + 2]);
989
                    // darker than the border grey - real glyph ink
990
                    // engine prompt = host colour at half alpha (~#A6A6A6)
991
                    (u16::from(r) + u16::from(g) + u16::from(b)) < 690
992
                })
993
            })
994
            .count();
995
        assert!(
996
            ink_rows >= 8,
997
            "the placeholder must paint a full text line in the first layered              frame; \
998
             got {ink_rows} ink rows in y {y0}..{y1} (the device strip              was <= 5 \
999
             rows). Field at {pos:?} {size:?}"
        );
    }
}