1
//! The content overlay: the ONE home for quickly-mutable content state.
2
//!
3
//! The DOM (`StyledDom`) is immutable by design — `NodeId`s stay stable, and
4
//! every fast-changing piece of content (camera frames, canvas repaints,
5
//! swapped images, in-progress text edits) lives in an overlay that readers
6
//! consult FIRST, falling back to the DOM. Before this module, that overlay
7
//! was scattered: a side map only the CPU rasterizer knew about
8
//! (`cpu_image_callback_results`), an in-place `set_node_type` DOM mutation
9
//! only some paths performed, a css-id image cache mirrored between shell and
10
//! layout, and text in `dirty_text_nodes`. Every combination that missed one
11
//! of them was a shipped bug — per BACKEND, because each of the 8 event loops
12
//! assembled the pipeline by hand.
13
//!
14
//! The rules this module enforces:
15
//!
16
//! 1. **One write chokepoint**: [`crate::window::LayoutWindow::apply_content_change`] is the only
17
//!    way content state changes. It validates, writes the overlay arm, journals the change, and
18
//!    returns the dirty tier the frame loop must honor. Backends never see content — they receive a
19
//!    tier.
20
//! 2. **One read order**: overlay first, immutable DOM second, via [`ResolvedContent`]. Every
21
//!    consumer (display-list build, IFC build, raster, hit-test, a11y, exports) resolves through
22
//!    it.
23
//! 3. **One retention clock**: [`ContentJournal`] entries are retired by frame age (swapchain
24
//!    depth), never by document size or session length. Journal = what the RENDERER may still need;
25
//!    the `UndoRedoManager` (user intent) is fed separately by the same chokepoint.
26

            
27
use std::collections::{BTreeMap, VecDeque};
28

            
29
use azul_core::{
30
    dom::{DomId, NodeId, NodeType},
31
    resources::{ImageRef, ImageRefHash},
32
    selection::TextCursor,
33
    styled_dom::StyledDom,
34
};
35
use azul_css::AzString;
36

            
37
use crate::{
38
    managers::{NodeIdMap, NodeIdRemap},
39
    text3::cache::InlineContent,
40
};
41

            
42
/// The text overlay entry: an IFC root's edited inline content, layered over
43
/// the immutable DOM's (now stale) text until the app's next generation
44
/// catches up ("optimistic state").
45
#[derive(Debug, Clone)]
46
pub struct DirtyTextNode {
47
    /// The new inline content (text + images) after editing
48
    pub content: Vec<InlineContent>,
49
    /// The new cursor position after editing
50
    pub cursor: Option<TextCursor>,
51
    /// Whether this edit requires ancestor relayout (e.g., text grew taller)
52
    pub needs_ancestor_relayout: bool,
53
    /// The document text revision that wrote this entry
54
    /// (`LayoutWindow::document_text_revision` after its bump). `0` = written
55
    /// by a path that predates revisions (tests, direct construction) — such
56
    /// entries are exempt from the acked-revision GC and fall back to the
57
    /// text-equality rule.
58
    pub revision: u64,
59
}
60

            
61
/// Flatten inline content to the plain string it displays.
62
///
63
/// This is the SAME flattening every consumer (a11y, convergence GC,
64
/// exports) must share, or two of them will disagree about whether an edit
65
/// "is" committed.
66
#[must_use]
67
11148
pub fn flatten_inline_content(content: &[InlineContent]) -> String {
68
11148
    let mut result = String::new();
69
26456
    for item in content {
70
15308
        match item {
71
13088
            InlineContent::Text(text_run) => result.push_str(&text_run.text),
72
            InlineContent::Space(_) => result.push(' '),
73
2220
            InlineContent::LineBreak(_) => result.push('\n'),
74
            InlineContent::Tab { .. } => result.push('\t'),
75
            InlineContent::Ruby { base, .. } => {
76
                result.push_str(&flatten_inline_content(base));
77
            }
78
            InlineContent::Marker { run, .. } => result.push_str(&run.text),
79
            InlineContent::Image(_) | InlineContent::Shape(_) => {}
80
        }
81
    }
82
11148
    result
83
11148
}
84

            
85
/// How many PRESENTED frames of history the journal keeps.
86
///
87
/// A backend re-presenting a not-fully-redrawn buffer composed `k` frames
88
/// ago may still sample the previous image of a node via
89
/// [`ContentJournal::image_as_of`]; `3` covers the deepest swapchain in the
90
/// tree (triple buffering — `wl_shm` double-buffer needs 2).
91
pub const JOURNAL_RETENTION_FRAMES: u64 = 3;
92

            
93
/// A content mutation, as accepted by the chokepoint.
94
///
95
/// Constructors on `LayoutWindow` (e.g. `apply_content_change`) decide
96
/// per-variant whether the change is user-undoable; per-frame producer writes
97
/// (camera/callback frames) never are.
98
#[derive(Debug, Clone)]
99
pub enum ContentChange {
100
    /// Swap the displayed image of a node (camera / video / screenshare /
101
    /// explicit `ChangeNodeImage`). Participates in intrinsic-size tier
102
    /// detection: a different-sized image relayouts, a same-sized one repaints.
103
    Image {
104
        dom_id: DomId,
105
        node_id: NodeId,
106
        image: ImageRef,
107
    },
108
    /// A `RenderImageCallback` produced a frame for a callback-image node.
109
    /// Always paint-tier: callback frames are PAINT content — the box is
110
    /// CSS-determined, and the callback's declared image stays the layout
111
    /// authority (otherwise a producer could resize the document per frame).
112
    ImageCallbackResult {
113
        dom_id: DomId,
114
        node_id: NodeId,
115
        image: ImageRef,
116
    },
117
    /// Register (`Some`) or remove (`None`) an image under a css id
118
    /// (`background-image: url("id")`). Takes effect on the NEXT display-list
119
    /// build — the chokepoint returns the rebuild tier instead of the old
120
    /// `DoNothing`.
121
    ImageById {
122
        id: AzString,
123
        image: Option<ImageRef>,
124
    },
125
    /// Restyle a node at runtime (animation frames, `:hover`-driven writes,
126
    /// the css-override e2e op). Writes go through the retained cascade
127
    /// (`restyle_user_property` — the property cache's single write site);
128
    /// with `override_only` the node's inline vec is left alone (the
129
    /// fast animation channel). Tier: paint-only properties rebuild the DL,
130
    /// layout-affecting ones relayout — decided by
131
    /// `callbacks::css_properties_need_relayout`, so hosts cannot drift.
132
    NodeCss {
133
        dom_id: DomId,
134
        node_id: NodeId,
135
        props: Vec<azul_css::props::property::CssProperty>,
136
        override_only: bool,
137
    },
138
    /// Change a node's image mask (an attribute-slot write like css props —
139
    /// fingerprinted by reconcile, not a content-identity mutation).
140
    ImageMask {
141
        dom_id: DomId,
142
        node_id: NodeId,
143
        mask: azul_core::resources::ImageMask,
144
    },
145
}
146

            
147
/// What the frame loop must do after a content change — the ONLY thing
148
/// backends learn about content. Ordered weakest → strongest so results merge
149
/// with `max`.
150
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
151
pub enum ContentDirtyTier {
152
    /// The change was a no-op (same image re-set, unknown node).
153
    Unchanged,
154
    /// Display-list items were patched in place; repaint. Damage discovery is
155
    /// the backend diff's job — `ImageRef` identity makes patched items
156
    /// unequal to the previous frame's.
157
    Paint,
158
    /// The display list must be rebuilt (css-id images resolve at build time).
159
    RebuildDisplayList,
160
    /// Intrinsic content size changed: relayout (which also rebuilds the DL).
161
    Relayout,
162
}
163

            
164
impl ContentDirtyTier {
165
    /// The ONE mapping from content dirty tier to the event-loop result every
166
    /// host consumes. Defined here — next to the tier — so a backend cannot
167
    /// invent its own interpretation:
168
    /// - `Paint`: the DL was already patched in place; a re-render picks it up (CPU: the DL diff
169
    ///   sees the `ImageRef` identity change and damages those bounds; GPU: the translator re-reads
170
    ///   the patched DL).
171
    /// - `RebuildDisplayList`: DL regeneration + re-render.
172
    /// - `Relayout`: incremental relayout (which rebuilds the DL).
173
14
    pub const fn to_process_event_result(self) -> azul_core::events::ProcessEventResult {
174
        use azul_core::events::ProcessEventResult;
175
14
        match self {
176
            Self::Unchanged => ProcessEventResult::DoNothing,
177
1
            Self::Paint => ProcessEventResult::ShouldReRenderCurrentWindow,
178
8
            Self::RebuildDisplayList => ProcessEventResult::ShouldUpdateDisplayListCurrentWindow,
179
5
            Self::Relayout => ProcessEventResult::ShouldIncrementalRelayout,
180
        }
181
14
    }
182
}
183

            
184
/// Result of one `apply_content_change`.
185
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
186
pub struct ContentChangeResult {
187
    pub tier: ContentDirtyTier,
188
}
189

            
190
/// Identity of one overlay part — "NodeIdGen2": minted from a monotonic
191
/// per-process counter, NEVER a real `NodeId` (a previewed part has no DOM
192
/// node until the app's re-render creates one).
193
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
194
pub struct OverlayPartId(pub u64);
195

            
196
impl OverlayPartId {
197
180
    fn mint() -> Self {
198
        use std::sync::atomic::{AtomicU64, Ordering};
199
        static NEXT: AtomicU64 = AtomicU64::new(1);
200
180
        Self(NEXT.fetch_add(1, Ordering::Relaxed))
201
180
    }
202
}
203

            
204
/// A pending STRUCTURAL delta over the immutable DOM.
205
///
206
/// What a mutable DOM would have done with `insertChild` / `removeChild` /
207
/// `replaceChild` / split / merge, recorded here as a PREVIEW until the
208
/// app's re-render lands. The preview never copies content: it references
209
/// DOM nodes (by id) and pending subtrees (the changeset's own `Dom`
210
/// payloads).
211
#[derive(Debug, Clone)]
212
pub enum StructuralPreview {
213
    /// `node` renders as TWO parts split at the structural position.
214
    Split {
215
        node: NodeId,
216
        at: crate::managers::changeset::NodePosition,
217
        part_ids: [OverlayPartId; 2],
218
    },
219
    /// `second` renders MERGED into `first` (its children appended; `second`
220
    /// itself hidden).
221
    Merge { first: NodeId, second: NodeId },
222
    /// A pending subtree renders under `parent` at child `index`.
223
    Insert {
224
        parent: NodeId,
225
        index: u32,
226
        content: azul_core::dom::Dom,
227
    },
228
    /// `parent`'s children `[start, end)` render REMOVED.
229
    Remove {
230
        parent: NodeId,
231
        start: u32,
232
        end: u32,
233
    },
234
    /// `parent`'s children `[start, end)` render REPLACED by a pending
235
    /// subtree.
236
    Replace {
237
        parent: NodeId,
238
        start: u32,
239
        end: u32,
240
        content: azul_core::dom::Dom,
241
    },
242
}
243

            
244
/// One entry in the pending-structure list: the changeset it anticipates
245
/// (the commit handshake ties the two lifecycles) + the delta.
246
#[derive(Debug, Clone)]
247
pub struct PendingStructure {
248
    pub changeset_id: u64,
249
    pub preview: StructuralPreview,
250
}
251

            
252
/// One RESOLVED child in a node's adjusted child list — what a consumer
253
/// iterating "the children of X as the user should see them" receives.
254
#[derive(Debug, Clone)]
255
pub enum ResolvedChild<'a> {
256
    /// An existing DOM child, unchanged.
257
    Existing(NodeId),
258
    /// An existing DOM child that is part of a SPLIT: render only the given
259
    /// byte range of its text (`None` end = to the end).
260
    ExistingTextSlice {
261
        node: NodeId,
262
        start_byte: u32,
263
        end_byte: Option<u32>,
264
    },
265
    /// A pending (not-yet-real) subtree from a recorded insert/replace.
266
    Pending(&'a azul_core::dom::Dom),
267
}
268

            
269
/// The overlay proper. Fields are private on purpose: reads go through
270
/// [`ResolvedContent`] / the accessors below, writes only through the
271
/// chokepoint (`pub(crate)` mutators).
272
#[derive(Debug, Default)]
273
pub struct ContentOverlay {
274
    /// Node-image arm: the currently-displayed image for a node, overriding
275
    /// the immutable DOM's `NodeType::Image` content.
276
    images: BTreeMap<(DomId, NodeId), ImageRef>,
277
    /// Text arm: edited inline content per IFC root ("optimistic state"),
278
    /// overriding the immutable DOM's text. Written only through
279
    /// `LayoutWindow::update_text_cache_after_edit` (the documented single
280
    /// text mutation point, itself fed by `apply_text_changeset`); retired by
281
    /// [`Self::gc_converged_text`] when the app's regenerated DOM catches up.
282
    text: BTreeMap<(DomId, NodeId), DirtyTextNode>,
283
    /// Structural arm: pending tree deltas (split/merge/insert/remove/
284
    /// replace) previewed ahead of the app's re-render. Consumers resolve
285
    /// via [`ResolvedContent::children_for_node`] /
286
    /// [`Self::pending_structure`]; empty = the DOM is the whole truth.
287
    pending_structure: BTreeMap<DomId, Vec<PendingStructure>>,
288
}
289

            
290
impl ContentOverlay {
291
    /// The overlay's image for a node, if any. Callers wanting the full
292
    /// overlay→DOM read order use [`ResolvedContent`] instead.
293
    #[must_use]
294
253
    pub fn image_for_node(&self, dom_id: DomId, node_id: NodeId) -> Option<&ImageRef> {
295
253
        self.images.get(&(dom_id, node_id))
296
253
    }
297

            
298
    /// Iterate all image-overlay entries (renderer registration: the WR/GL
299
    /// backend walks produced callback frames to register external textures).
300
    pub fn iter_images(&self) -> impl Iterator<Item = (&(DomId, NodeId), &ImageRef)> {
301
        self.images.iter()
302
    }
303

            
304
    /// The overlay's edited text entry for an IFC root, if any.
305
    #[must_use]
306
18678
    pub fn text_for_node(&self, dom_id: DomId, node_id: NodeId) -> Option<&DirtyTextNode> {
307
18678
        self.text.get(&(dom_id, node_id))
308
18678
    }
309

            
310
    /// Iterate all text-overlay entries (a11y snapshot, diagnostics).
311
25325
    pub fn iter_text(&self) -> impl Iterator<Item = (&(DomId, NodeId), &DirtyTextNode)> {
312
25325
        self.text.iter()
313
25325
    }
314

            
315
    /// Number of text-overlay entries (manager fingerprints, tests).
316
    #[must_use]
317
    pub fn text_len(&self) -> usize {
318
        self.text.len()
319
    }
320

            
321
    /// Whether ANY text entry needs an ancestor relayout.
322
    #[must_use]
323
2850
    pub fn any_text_needs_ancestor_relayout(&self) -> bool {
324
2850
        self.text.values().any(|d| d.needs_ancestor_relayout)
325
2850
    }
326

            
327
    #[must_use]
328
    pub fn is_empty(&self) -> bool {
329
        self.images.is_empty() && self.text.is_empty() && self.pending_structure.is_empty()
330
    }
331

            
332
6
    pub(crate) fn set_image(
333
6
        &mut self,
334
6
        dom_id: DomId,
335
6
        node_id: NodeId,
336
6
        image: ImageRef,
337
6
    ) -> Option<ImageRef> {
338
6
        self.images.insert((dom_id, node_id), image)
339
6
    }
340

            
341
2916
    pub(crate) fn set_text(
342
2916
        &mut self,
343
2916
        dom_id: DomId,
344
2916
        node_id: NodeId,
345
2916
        entry: DirtyTextNode,
346
2916
    ) -> Option<DirtyTextNode> {
347
2916
        self.text.insert((dom_id, node_id), entry)
348
2916
    }
349

            
350
3450
    pub(crate) fn text_for_node_mut(
351
3450
        &mut self,
352
3450
        dom_id: DomId,
353
3450
        node_id: NodeId,
354
3450
    ) -> Option<&mut DirtyTextNode> {
355
3450
        self.text.get_mut(&(dom_id, node_id))
356
3450
    }
357

            
358
    /// The pending structural deltas of `dom` (empty slice = none).
359
    #[must_use]
360
8484
    pub fn pending_structure(&self, dom_id: DomId) -> &[PendingStructure] {
361
8484
        self.pending_structure
362
8484
            .get(&dom_id)
363
8484
            .map_or(&[], |v| v.as_slice())
364
8484
    }
365

            
366
    /// Number of pending structural deltas across all DOMs (tests).
367
    #[must_use]
368
31
    pub fn pending_structure_len(&self) -> usize {
369
31
        self.pending_structure.values().map(Vec::len).sum()
370
31
    }
371

            
372
    /// Materialize a recorded structural changeset as a PREVIEW — the
373
    /// generic entry for EVERY operation kind (the recorded delta IS the
374
    /// preview; nothing is copied except the changeset's own subtree
375
    /// payloads, which are refcounted).
376
272
    pub(crate) fn preview_structural_change(
377
272
        &mut self,
378
272
        dom_id: DomId,
379
272
        changeset: &crate::managers::changeset::DocumentChangeset,
380
272
    ) {
381
        use crate::managers::changeset::DocumentOperation as Op;
382
272
        let preview = match &changeset.operation {
383
90
            Op::SplitNode(sp) => {
384
90
                sp.node
385
90
                    .node
386
90
                    .into_crate_internal()
387
90
                    .map(|node| StructuralPreview::Split {
388
90
                        node,
389
90
                        at: sp.at,
390
90
                        part_ids: [OverlayPartId::mint(), OverlayPartId::mint()],
391
90
                    })
392
            }
393
80
            Op::MergeNodes(m) => match (
394
80
                m.first.node.into_crate_internal(),
395
80
                m.second.node.into_crate_internal(),
396
            ) {
397
80
                (Some(first), Some(second)) => Some(StructuralPreview::Merge { first, second }),
398
                _ => None,
399
            },
400
1
            Op::InsertChildren(i) => {
401
1
                i.parent
402
1
                    .node
403
1
                    .into_crate_internal()
404
1
                    .map(|parent| StructuralPreview::Insert {
405
1
                        parent,
406
1
                        index: i.index,
407
1
                        content: i.content.clone(),
408
1
                    })
409
            }
410
11
            Op::RemoveChildren(r) => {
411
11
                r.parent
412
11
                    .node
413
11
                    .into_crate_internal()
414
11
                    .map(|parent| StructuralPreview::Remove {
415
11
                        parent,
416
11
                        start: r.start,
417
11
                        end: r.end,
418
11
                    })
419
            }
420
90
            Op::ReplaceChildren(r) => {
421
90
                r.parent
422
90
                    .node
423
90
                    .into_crate_internal()
424
90
                    .map(|parent| StructuralPreview::Replace {
425
90
                        parent,
426
90
                        start: r.start,
427
90
                        end: r.end,
428
90
                        content: r.content.clone(),
429
90
                    })
430
            }
431
            // Wrap/unwrap previews are staged with the render consumption
432
            // (they restructure WITHIN a node — the child-list adjustment
433
            // needs the part-aware renderer to matter visually).
434
            Op::WrapRange(_) | Op::UnwrapRange(_) => None,
435
        };
436
272
        if let Some(preview) = preview {
437
272
            self.pending_structure
438
272
                .entry(dom_id)
439
272
                .or_default()
440
272
                .push(PendingStructure {
441
272
                    changeset_id: changeset.id,
442
272
                    preview,
443
272
                });
444
272
        }
445
272
    }
446

            
447
    /// Acked-revision GC — the EXPLICIT half of convergence: the app declared
448
    /// (via `LayoutWindow::mark_text_revision_synced`) that its model has
449
    /// incorporated every text edit up to and including `acked`, so entries
450
    /// stamped at or below it are committed and dropped — even when the app
451
    /// NORMALIZED the text on the way in (trimming, canonicalization), which
452
    /// the equality rule in [`Self::gc_converged_text`] can never see past.
453
    /// Un-stamped entries (`revision == 0`) are left for the equality rule.
454
296
    pub(crate) fn gc_acked_text(&mut self, dom_id: DomId, acked: u64) {
455
296
        if acked == 0 {
456
285
            return;
457
11
        }
458
11
        self.text
459
13
            .retain(|&(d, _), dirty| d != dom_id || dirty.revision == 0 || dirty.revision > acked);
460
296
    }
461

            
462
    /// Drop every pending structural delta of `dom` — called when a new
463
    /// generation lands (the app either applied the changeset, so REAL nodes
464
    /// exist, or rejected it, so the content reverts; both end the preview).
465
371
    pub(crate) fn gc_splits(&mut self, dom_id: DomId) {
466
371
        self.pending_structure.remove(&dom_id);
467
371
    }
468

            
469
    /// Convergence GC — the rule that closes the edit commit loop: after a
470
    /// generation swap (keys already remapped), an overlay text entry whose
471
    /// flattened text EQUALS the new DOM's text at that node has been
472
    /// committed by the app → drop it. Not equal → the app hasn't caught up;
473
    /// the overlay stays authoritative. Before this rule, entries were
474
    /// remapped forward FOREVER and DOM-reading exports silently saw pre-edit
475
    /// text.
476
7993
    pub(crate) fn gc_converged_text(&mut self, dom_id: DomId, styled_dom: &StyledDom) {
477
7993
        let node_data = styled_dom.node_data.as_container();
478
7993
        self.text.retain(|&(d, node_id), dirty| {
479
253
            if d != dom_id {
480
10
                return true;
481
243
            }
482
243
            let Some(node) = node_data.get(node_id) else {
483
                // Node gone in the new generation: nothing to converge to.
484
                return false;
485
            };
486
243
            let dom_text = if let NodeType::Text(s) = node.get_node_type() {
487
32
                s.as_str().to_string()
488
            } else {
489
                // Non-text IFC roots (contenteditable hosts): compare against
490
                // the concatenated text of DIRECT text children.
491
211
                let hierarchy = styled_dom.node_hierarchy.as_container();
492
211
                let mut s = String::new();
493
211
                if let Some(n) = hierarchy.get(node_id) {
494
211
                    let mut child = n.first_child_id(node_id);
495
422
                    while let Some(c) = child {
496
211
                        if let Some(cd) = node_data.get(c) {
497
211
                            if let NodeType::Text(t) = cd.get_node_type() {
498
201
                                s.push_str(t.as_str());
499
201
                            }
500
                        }
501
211
                        child = hierarchy
502
211
                            .get(c)
503
211
                            .and_then(azul_core::styled_dom::NodeHierarchyItem::next_sibling_id);
504
                    }
505
                }
506
211
                s
507
            };
508
243
            flatten_inline_content(&dirty.content) != dom_text
509
253
        });
510
7993
    }
511

            
512
    /// Drop every overlay entry of `dom` (full DOM regeneration without a
513
    /// remap — the new generation's DOM is the authority again).
514
1
    pub(crate) fn clear_dom(&mut self, dom_id: DomId) {
515
1
        self.images.retain(|(d, _), _| *d != dom_id);
516
1
        self.text.retain(|(d, _), _| *d != dom_id);
517
1
        self.pending_structure.remove(&dom_id);
518
1
    }
519
}
520

            
521
impl NodeIdRemap for ContentOverlay {
522
447
    fn remap_node_ids(&mut self, dom: DomId, map: &NodeIdMap) {
523
447
        crate::managers::remap_dom_keys(&mut self.images, dom, map);
524
447
        crate::managers::remap_dom_keys(&mut self.text, dom, map);
525
        // Previews do NOT remap: a remap means a new generation landed,
526
        // which ends every preview's life (gc at the layout tail); remapping
527
        // would keep a preview alive over content that superseded it.
528
447
        self.pending_structure.remove(&dom);
529
447
    }
530
}
531

            
532
/// The one overlay→DOM read order, borrowed by every consumer.
533
///
534
/// Constructed at the few pipeline entries that own both halves (display-list
535
/// build / IFC build via `LayoutContext`, exports); everything downstream
536
/// takes this instead of reaching into `StyledDom` for content.
537
#[derive(Debug, Clone, Copy)]
538
pub struct ResolvedContent<'a> {
539
    pub overlay: Option<&'a ContentOverlay>,
540
    pub styled_dom: &'a StyledDom,
541
    pub dom_id: DomId,
542
}
543

            
544
impl ResolvedContent<'_> {
545
    /// The image to PAINT for `node_id`: overlay first (produced callback
546
    /// frames, swapped images), then the DOM's `NodeType::Image`.
547
    #[must_use]
548
157
    pub fn image_for_paint(&self, node_id: NodeId) -> Option<ImageRef> {
549
157
        if let Some(overlay) = self.overlay {
550
126
            if let Some(img) = overlay.image_for_node(self.dom_id, node_id) {
551
3
                return Some(img.clone());
552
123
            }
553
31
        }
554
154
        self.dom_image(node_id)
555
157
    }
556

            
557
    /// The image whose intrinsic size LAYOUT uses for `node_id`. Overlay
558
    /// first — EXCEPT when the DOM declares a callback image: produced frames
559
    /// are paint content and must not resize the box per frame.
560
    #[must_use]
561
153
    pub fn image_for_layout(&self, node_id: NodeId) -> Option<ImageRef> {
562
153
        let dom_image = self.dom_image(node_id);
563
153
        if let Some(dom_ref) = &dom_image {
564
153
            if dom_ref.is_callback() {
565
                return dom_image;
566
153
            }
567
        }
568
153
        if let Some(overlay) = self.overlay {
569
123
            if let Some(img) = overlay.image_for_node(self.dom_id, node_id) {
570
1
                return Some(img.clone());
571
122
            }
572
30
        }
573
152
        dom_image
574
153
    }
575

            
576
307
    fn dom_image(&self, node_id: NodeId) -> Option<ImageRef> {
577
307
        let node_data = self.styled_dom.node_data.as_container();
578
307
        match node_data.get(node_id)?.get_node_type() {
579
306
            NodeType::Image(image_ref) => Some(image_ref.as_ref().clone()),
580
1
            _ => None,
581
        }
582
307
    }
583

            
584
    /// The children of `node_id` AS THE USER SHOULD SEE THEM: the immutable
585
    /// DOM's child list with every pending structural delta applied on top —
586
    /// the read side of the `.insertChild`-through-the-overlay design.
587
    /// With no pending structure this is exactly the DOM's children.
588
    ///
589
    /// Split previews surface on the SPLIT NODE itself via
590
    /// [`Self::split_positions_for_node`]; here a split node still occupies
591
    /// one slot (its parts are an internal regrouping).
592
    #[must_use]
593
3
    pub fn children_for_node(&self, node_id: NodeId) -> Vec<ResolvedChild<'_>> {
594
3
        let hierarchy = self.styled_dom.node_hierarchy.as_container();
595
3
        let mut out: Vec<ResolvedChild<'_>> = Vec::new();
596
3
        let mut child = hierarchy
597
3
            .get(node_id)
598
3
            .and_then(|n| n.first_child_id(node_id));
599
9
        while let Some(c) = child {
600
6
            out.push(ResolvedChild::Existing(c));
601
6
            child = hierarchy
602
6
                .get(c)
603
6
                .and_then(azul_core::styled_dom::NodeHierarchyItem::next_sibling_id);
604
6
        }
605

            
606
3
        let Some(overlay) = self.overlay else {
607
            return out;
608
        };
609
3
        for pending in overlay.pending_structure(self.dom_id) {
610
2
            match &pending.preview {
611
                StructuralPreview::Insert {
612
2
                    parent,
613
2
                    index,
614
2
                    content,
615
2
                } if *parent == node_id => {
616
2
                    let at = (*index as usize).min(out.len());
617
2
                    for (offset, pending_child) in content.children.as_ref().iter().enumerate() {
618
2
                        out.insert(at + offset, ResolvedChild::Pending(pending_child));
619
2
                    }
620
                }
621
1
                StructuralPreview::Remove { parent, start, end } if *parent == node_id => {
622
1
                    let s = (*start as usize).min(out.len());
623
1
                    let e = (*end as usize).min(out.len());
624
1
                    out.drain(s..e);
625
1
                }
626
                StructuralPreview::Replace {
627
                    parent,
628
                    start,
629
                    end,
630
                    content,
631
                } if *parent == node_id => {
632
                    let s = (*start as usize).min(out.len());
633
                    let e = (*end as usize).min(out.len());
634
                    let replacement: Vec<ResolvedChild<'_>> = content
635
                        .children
636
                        .as_ref()
637
                        .iter()
638
                        .map(ResolvedChild::Pending)
639
                        .collect();
640
                    out.splice(s..e, replacement);
641
                }
642
                StructuralPreview::Merge { first, second } => {
643
                    // The merged-away node disappears from ITS parent's list;
644
                    // its children surface under `first` (when iterating
645
                    // first's children).
646
                    if out
647
                        .iter()
648
                        .any(|c| matches!(c, ResolvedChild::Existing(n) if n == second))
649
                    {
650
                        out.retain(|c| !matches!(c, ResolvedChild::Existing(n) if n == second));
651
                    }
652
                    if *first == node_id {
653
                        let mut sc = hierarchy
654
                            .get(*second)
655
                            .and_then(|n| n.first_child_id(*second));
656
                        while let Some(c) = sc {
657
                            out.push(ResolvedChild::Existing(c));
658
                            sc = hierarchy.get(c).and_then(
659
                                azul_core::styled_dom::NodeHierarchyItem::next_sibling_id,
660
                            );
661
                        }
662
                    }
663
                }
664
                // A split regroups the node's OWN content; its parent's child
665
                // list is unchanged (the second part becomes real only when
666
                // the app applies).
667
                _ => {}
668
            }
669
        }
670
3
        out
671
3
    }
672

            
673
    /// The pending SPLIT positions of `node_id` (usually 0 or 1) — a
674
    /// part-aware consumer renders the node's children regrouped at these
675
    /// structural positions.
676
    #[must_use]
677
    pub fn split_positions_for_node(
678
        &self,
679
        node_id: NodeId,
680
    ) -> Vec<crate::managers::changeset::NodePosition> {
681
        let Some(overlay) = self.overlay else {
682
            return Vec::new();
683
        };
684
        overlay
685
            .pending_structure(self.dom_id)
686
            .iter()
687
            .filter_map(|p| match &p.preview {
688
                StructuralPreview::Split { node, at, .. } if *node == node_id => Some(*at),
689
                _ => None,
690
            })
691
            .collect()
692
    }
693

            
694
    /// The text to READ for `node_id` (a11y, exports): the overlay's edited
695
    /// content flattened, falling back to the DOM's `NodeType::Text`.
696
    /// `None` when the node has neither.
697
    #[must_use]
698
149
    pub fn text_for_node(&self, node_id: NodeId) -> Option<String> {
699
149
        if let Some(overlay) = self.overlay {
700
149
            if let Some(dirty) = overlay.text_for_node(self.dom_id, node_id) {
701
20
                return Some(flatten_inline_content(&dirty.content));
702
129
            }
703
        }
704
129
        let node_data = self.styled_dom.node_data.as_container();
705
129
        match node_data.get(node_id)?.get_node_type() {
706
43
            NodeType::Text(s) => Some(s.as_str().to_string()),
707
86
            _ => None,
708
        }
709
149
    }
710
}
711

            
712
/// One journaled content mutation.
713
#[derive(Debug, Clone)]
714
pub struct JournalEntry {
715
    /// The frame sequence number the change was applied in.
716
    pub frame_seq: u64,
717
    pub change: AppliedChange,
718
}
719

            
720
/// The mechanical record of an applied change — enough for a compositor to
721
/// reach content as of frame `N − k` and for damage to know old vs new.
722
#[derive(Debug, Clone)]
723
pub enum AppliedChange {
724
    Image {
725
        dom_id: DomId,
726
        node_id: NodeId,
727
        /// The image displayed BEFORE this change (holds the pixels alive for
728
        /// backends still compositing an old buffer). `None`: node had none.
729
        old: Option<ImageRef>,
730
        new_hash: ImageRefHash,
731
    },
732
    ImageById {
733
        id: AzString,
734
        old: Option<ImageRef>,
735
        removed: bool,
736
    },
737
    /// Manager-mutated window state moved this frame (focus / text selection
738
    /// / scroll positions). These live OUTSIDE the DOM by design — the
739
    /// journal records THAT they changed (fingerprint transitions), so every
740
    /// non-DOM mutation is at least auditable per frame, same clock as
741
    /// content.
742
    ManagerState {
743
        focus_changed: bool,
744
        selection_changed: bool,
745
        scroll_changed: bool,
746
    },
747
}
748

            
749
/// Frame-scoped record of applied content changes.
750
///
751
/// Retention is bounded by the PRESENT loop: `begin_frame` (called once per
752
/// frame from shared frame code — never from a backend) retires entries older
753
/// than [`JOURNAL_RETENTION_FRAMES`]. The journal never grows with document
754
/// size or session length.
755
#[derive(Debug, Default)]
756
pub struct ContentJournal {
757
    frame_seq: u64,
758
    entries: VecDeque<JournalEntry>,
759
    /// Fingerprints of (focus, selection, scroll) as of the last frame —
760
    /// the diff basis for [`Self::record_manager_state`].
761
    last_manager_fingerprint: Option<[u64; 3]>,
762
}
763

            
764
impl ContentJournal {
765
    /// The current frame sequence number. Bumped only by [`Self::begin_frame`].
766
    #[must_use]
767
468
    pub const fn frame_seq(&self) -> u64 {
768
468
        self.frame_seq
769
468
    }
770

            
771
    /// Advance the frame clock and retire entries older than the swapchain
772
    /// depth. Called from shared per-frame code (`LayoutWindow::prepare_frame_cpu`
773
    /// / the GPU frame orchestration) — backends never call this directly.
774
16769
    pub fn begin_frame(&mut self) {
775
16769
        self.frame_seq = self.frame_seq.wrapping_add(1);
776
16769
        let cutoff = self.frame_seq.saturating_sub(JOURNAL_RETENTION_FRAMES);
777
16898
        while self.entries.front().is_some_and(|e| e.frame_seq < cutoff) {
778
129
            self.entries.pop_front();
779
129
        }
780
16769
    }
781

            
782
    /// Diff the manager-state fingerprints against last frame's and record
783
    /// a [`AppliedChange::ManagerState`] entry when anything moved. Called
784
    /// from the shared frame preparation (the same clock content uses).
785
16763
    pub(crate) fn record_manager_state(&mut self, fingerprint: [u64; 3]) {
786
16763
        if let Some(last) = self.last_manager_fingerprint {
787
16697
            let focus_changed = last[0] != fingerprint[0];
788
16697
            let selection_changed = last[1] != fingerprint[1];
789
16697
            let scroll_changed = last[2] != fingerprint[2];
790
16697
            if focus_changed || selection_changed || scroll_changed {
791
59
                self.record(AppliedChange::ManagerState {
792
59
                    focus_changed,
793
59
                    selection_changed,
794
59
                    scroll_changed,
795
59
                });
796
16638
            }
797
66
        }
798
16763
        self.last_manager_fingerprint = Some(fingerprint);
799
16763
    }
800

            
801
164
    pub(crate) fn record(&mut self, change: AppliedChange) {
802
164
        self.entries.push_back(JournalEntry {
803
164
            frame_seq: self.frame_seq,
804
164
            change,
805
164
        });
806
164
    }
807

            
808
    /// The image `node` displayed as of `frame_seq` (≤ [`JOURNAL_RETENTION_FRAMES`]
809
    /// frames back): the `old` of the first change recorded AFTER that frame,
810
    /// or `None` if the node's image hasn't changed since (current is valid).
811
    #[must_use]
812
2
    pub fn image_as_of(&self, dom_id: DomId, node_id: NodeId, frame_seq: u64) -> Option<&ImageRef> {
813
2
        self.entries.iter().find_map(|e| match &e.change {
814
            AppliedChange::Image {
815
2
                dom_id: d,
816
2
                node_id: n,
817
2
                old,
818
                ..
819
2
            } if *d == dom_id && *n == node_id && e.frame_seq > frame_seq => old.as_ref(),
820
1
            _ => None,
821
2
        })
822
2
    }
823

            
824
    /// Number of retained entries (test/diagnostic use).
825
    #[must_use]
826
1
    pub fn len(&self) -> usize {
827
1
        self.entries.len()
828
1
    }
829

            
830
    #[must_use]
831
1
    pub fn is_empty(&self) -> bool {
832
1
        self.entries.is_empty()
833
1
    }
834

            
835
    /// Drop journal history for a DOM whose generation was swapped — the old
836
    /// generation's node ids no longer mean anything, and the swap itself
837
    /// repaints everything.
838
446
    pub(crate) fn clear_dom(&mut self, dom_id: DomId) {
839
446
        self.entries.retain(|e| match &e.change {
840
            AppliedChange::Image { dom_id: d, .. } => *d != dom_id,
841
5
            AppliedChange::ImageById { .. } | AppliedChange::ManagerState { .. } => true,
842
5
        });
843
446
    }
844
}
845

            
846
#[cfg(test)]
847
mod tests {
848
    use super::*;
849

            
850
206
    fn img(w: usize, h: usize) -> ImageRef {
851
206
        ImageRef::null_image(
852
206
            w,
853
206
            h,
854
206
            azul_core::resources::RawImageFormat::BGRA8,
855
206
            Vec::new(),
856
        )
857
206
    }
858

            
859
141
    fn dom0() -> DomId {
860
141
        DomId { inner: 0 }
861
141
    }
862

            
863
    #[test]
864
1
    fn journal_retires_by_frame_age_never_by_count() {
865
1
        let mut journal = ContentJournal::default();
866
        // 100 changes in ONE frame: all retained (retention is frames, not entries).
867
101
        for i in 0..100_usize {
868
100
            journal.record(AppliedChange::Image {
869
100
                dom_id: dom0(),
870
100
                node_id: NodeId::new(i),
871
100
                old: Some(img(1, 1)),
872
100
                new_hash: img(1, 1).get_hash(),
873
100
            });
874
100
        }
875
1
        assert_eq!(journal.len(), 100);
876

            
877
        // After JOURNAL_RETENTION_FRAMES + 1 empty frames, everything is retired.
878
5
        for _ in 0..=JOURNAL_RETENTION_FRAMES {
879
4
            journal.begin_frame();
880
4
        }
881
1
        assert!(
882
1
            journal.is_empty(),
883
            "entries older than the swapchain depth must retire"
884
        );
885
1
    }
886

            
887
    #[test]
888
1
    fn image_as_of_returns_the_pre_change_image_within_retention() {
889
1
        let mut journal = ContentJournal::default();
890
1
        let node = NodeId::new(7);
891
1
        let old = img(10, 10);
892
1
        let old_hash = old.get_hash();
893

            
894
1
        journal.begin_frame(); // frame 1
895
1
        let composed_at = journal.frame_seq(); // a backend composited frame 1
896
1
        journal.begin_frame(); // frame 2
897
1
        journal.record(AppliedChange::Image {
898
1
            dom_id: dom0(),
899
1
            node_id: node,
900
1
            old: Some(old),
901
1
            new_hash: img(10, 10).get_hash(),
902
1
        });
903

            
904
        // The buffer composed at frame 1 may still sample the old image.
905
1
        let as_of = journal.image_as_of(dom0(), node, composed_at);
906
1
        assert_eq!(as_of.map(ImageRef::get_hash), Some(old_hash));
907

            
908
        // As of frame 2 (change applied in it), the current image is valid.
909
1
        assert!(journal
910
1
            .image_as_of(dom0(), node, journal.frame_seq())
911
1
            .is_none());
912
1
    }
913

            
914
    #[test]
915
1
    fn resolved_content_prefers_overlay_for_paint() {
916
1
        let styled_dom = StyledDom::default();
917
1
        let mut overlay = ContentOverlay::default();
918
1
        let node = NodeId::new(0);
919
1
        let overlay_img = img(4, 4);
920
1
        let overlay_hash = overlay_img.get_hash();
921
1
        overlay.set_image(dom0(), node, overlay_img);
922

            
923
1
        let resolved = ResolvedContent {
924
1
            overlay: Some(&overlay),
925
1
            styled_dom: &styled_dom,
926
1
            dom_id: dom0(),
927
1
        };
928
1
        assert_eq!(
929
1
            resolved.image_for_paint(node).map(|i| i.get_hash()),
930
1
            Some(overlay_hash),
931
            "overlay wins over the (empty) DOM"
932
        );
933

            
934
        // Without the overlay: falls back to the DOM (which has no image node).
935
1
        let resolved = ResolvedContent {
936
1
            overlay: None,
937
1
            styled_dom: &styled_dom,
938
1
            dom_id: dom0(),
939
1
        };
940
1
        assert!(resolved.image_for_paint(node).is_none());
941
1
    }
942

            
943
    #[test]
944
1
    fn structural_previews_adjust_the_resolved_child_list() {
945
        use azul_core::{
946
            dom::{Dom, DomNodeId},
947
            styled_dom::NodeHierarchyItemId,
948
            task::{Instant, SystemTick},
949
        };
950

            
951
        use crate::managers::changeset::{
952
            DocOpInsertChildren, DocOpRemoveChildren, DocumentChangeset, DocumentOperation,
953
            EditResumePoint, NodePosition,
954
        };
955

            
956
        // DOM: div > [p, p] (nodes 1, 2 with their text children 3, 4… the
957
        // exact ids come from creation order; resolve them dynamically).
958
1
        let mut dom = Dom::create_div();
959
1
        let mut p1 = Dom::create_p();
960
1
        p1.add_child(Dom::create_text_do_not_use_without_block_level_wrapper(
961
            "one",
962
        ));
963
1
        let mut p2 = Dom::create_p();
964
1
        p2.add_child(Dom::create_text_do_not_use_without_block_level_wrapper(
965
            "two",
966
        ));
967
1
        dom.add_child(p1);
968
1
        dom.add_child(p2);
969
1
        let styled = StyledDom::create_from_dom(dom);
970
1
        let root = NodeId::new(0);
971

            
972
1
        let dom_node = |n: NodeId| DomNodeId {
973
4
            dom: dom0(),
974
4
            node: NodeHierarchyItemId::from_crate_internal(Some(n)),
975
4
        };
976
1
        let resume = EditResumePoint {
977
1
            anchor_key: 1,
978
1
            node_path: vec![0].into(),
979
1
            position: NodePosition::before_child(0),
980
1
        };
981

            
982
1
        let mut overlay = ContentOverlay::default();
983

            
984
        // Baseline: with no pending structure the resolved children ARE the
985
        // DOM children (two <p> elements).
986
1
        let resolved = ResolvedContent {
987
1
            overlay: Some(&overlay),
988
1
            styled_dom: &styled,
989
1
            dom_id: dom0(),
990
1
        };
991
1
        let base = resolved.children_for_node(root);
992
1
        assert_eq!(base.len(), 2);
993
2
        assert!(base.iter().all(|c| matches!(c, ResolvedChild::Existing(_))));
994

            
995
        // A recorded INSERT previews a PENDING subtree between them — the
996
        // .insertChild made visible without any DOM mutation.
997
1
        let mut ul = Dom::create_node(azul_core::xml::tag_to_node_type("ul"));
998
1
        ul.add_child(Dom::create_p());
999
1
        let insert_cs = DocumentChangeset::new(
1
            dom_node(root),
1
            DocumentOperation::InsertChildren(DocOpInsertChildren {
1
                parent: dom_node(root),
1
                index: 1,
1
                content: {
1
                    let mut frag = Dom::create_div();
1
                    frag.add_child(ul);
1
                    frag
1
                },
1
            }),
1
            resume.clone(),
1
            Instant::Tick(SystemTick::new(0)),
        );
1
        overlay.preview_structural_change(dom0(), &insert_cs);
1
        let resolved = ResolvedContent {
1
            overlay: Some(&overlay),
1
            styled_dom: &styled,
1
            dom_id: dom0(),
1
        };
1
        let with_insert = resolved.children_for_node(root);
1
        assert_eq!(with_insert.len(), 3);
1
        assert!(matches!(with_insert[1], ResolvedChild::Pending(_)));
        // A recorded REMOVE previews children [0..1) gone.
1
        let remove_cs = DocumentChangeset::new(
1
            dom_node(root),
1
            DocumentOperation::RemoveChildren(DocOpRemoveChildren {
1
                parent: dom_node(root),
1
                start: 0,
1
                end: 1,
1
            }),
1
            resume,
1
            Instant::Tick(SystemTick::new(0)),
        );
1
        overlay.preview_structural_change(dom0(), &remove_cs);
1
        let resolved = ResolvedContent {
1
            overlay: Some(&overlay),
1
            styled_dom: &styled,
1
            dom_id: dom0(),
1
        };
1
        let with_both = resolved.children_for_node(root);
1
        assert_eq!(
1
            with_both.len(),
            2,
            "insert(+1) then remove(-1): {with_both:?}"
        );
        // A new generation ends every preview.
1
        overlay.gc_splits(dom0());
1
        assert_eq!(overlay.pending_structure_len(), 0);
1
    }
    #[test]
1
    fn acked_revision_gc_converges_where_text_equality_cannot() {
        use std::sync::Arc;
        use crate::text3::cache::{InlineContent, StyledRun};
3
        fn dirty_rev(text: &str, revision: u64) -> DirtyTextNode {
3
            DirtyTextNode {
3
                content: vec![InlineContent::Text(StyledRun {
3
                    text: Arc::from(text),
3
                    style: Arc::new(Default::default()),
3
                    logical_start_byte: 0,
3
                    source_node_id: None,
3
                })],
3
                cursor: None,
3
                needs_ancestor_relayout: false,
3
                revision,
3
            }
3
        }
1
        let mut overlay = ContentOverlay::default();
1
        let committed = NodeId::new(1); // acked (rev 3 ≤ 3): drops WITHOUT text comparison
1
        let unacked = NodeId::new(2); // typed after the ack (rev 5 > 3): stays
1
        let unstamped = NodeId::new(3); // rev 0: exempt, left for the equality rule
1
        overlay.set_text(dom0(), committed, dirty_rev("  hello  ", 3));
1
        overlay.set_text(dom0(), unacked, dirty_rev("newer typing", 5));
1
        overlay.set_text(dom0(), unstamped, dirty_rev("legacy path", 0));
        // acked == 0 (nothing ever acked) must be a no-op.
1
        overlay.gc_acked_text(dom0(), 0);
1
        assert!(overlay.text_for_node(dom0(), committed).is_some());
1
        overlay.gc_acked_text(dom0(), 3);
1
        assert!(
1
            overlay.text_for_node(dom0(), committed).is_none(),
            "an acked entry retires even though the app NORMALIZED the text (\"  hello  \" vs \
             whatever the DOM now carries) — the case the equality rule keeps authoritative \
             forever"
        );
1
        assert!(
1
            overlay.text_for_node(dom0(), unacked).is_some(),
            "an edit typed AFTER the acked revision must stay authoritative"
        );
1
        assert!(
1
            overlay.text_for_node(dom0(), unstamped).is_some(),
            "an un-stamped (revision 0) entry is exempt from the acked GC"
        );
1
    }
    #[test]
1
    fn text_gc_drops_converged_entries_and_keeps_diverged_ones() {
        use std::sync::Arc;
        use crate::text3::cache::{InlineContent, StyledRun};
3
        fn dirty(text: &str) -> DirtyTextNode {
3
            DirtyTextNode {
3
                content: vec![InlineContent::Text(StyledRun {
3
                    text: Arc::from(text),
3
                    style: Arc::new(Default::default()),
3
                    logical_start_byte: 0,
3
                    source_node_id: None,
3
                })],
3
                cursor: None,
3
                needs_ancestor_relayout: false,
3
                revision: 0,
3
            }
3
        }
        // DOM: div > [text "committed"]
1
        let mut dom = azul_core::dom::Dom::create_div();
1
        dom.add_child(
1
            azul_core::dom::Dom::create_text_do_not_use_without_block_level_wrapper("committed"),
        );
1
        let styled = StyledDom::create_from_dom(dom);
1
        let text_node = NodeId::new(1);
1
        let mut overlay = ContentOverlay::default();
        // Entry keyed on the TEXT node whose edit the app has committed:
1
        overlay.set_text(dom0(), text_node, dirty("committed"));
1
        overlay.gc_converged_text(dom0(), &styled);
1
        assert!(
1
            overlay.text_for_node(dom0(), text_node).is_none(),
            "app committed the edit → overlay entry retires (the commit loop closes)"
        );
        // Entry the app has NOT committed stays authoritative:
1
        overlay.set_text(dom0(), text_node, dirty("still-editing"));
1
        overlay.gc_converged_text(dom0(), &styled);
1
        assert!(
1
            overlay.text_for_node(dom0(), text_node).is_some(),
            "un-committed edit must survive the generation swap"
        );
        // Entry keyed on the HOST (div): compares against concatenated direct
        // text children.
1
        overlay.clear_dom(dom0());
1
        overlay.set_text(dom0(), NodeId::new(0), dirty("committed"));
1
        overlay.gc_converged_text(dom0(), &styled);
1
        assert!(
1
            overlay.text_for_node(dom0(), NodeId::new(0)).is_none(),
            "host-keyed entry converges against its direct text children"
        );
1
    }
    #[test]
1
    fn overlay_remap_moves_entries_and_drops_unmounted() {
        use std::collections::BTreeMap;
1
        let mut overlay = ContentOverlay::default();
1
        overlay.set_image(dom0(), NodeId::new(2), img(1, 1));
1
        overlay.set_image(dom0(), NodeId::new(3), img(2, 2));
1
        let other_dom = DomId { inner: 9 };
1
        let other_hash = {
1
            let i = img(5, 5);
1
            let h = i.get_hash();
1
            overlay.set_image(other_dom, NodeId::new(2), i);
1
            h
        };
        // Node 2 moved to 1; node 3 unmounted.
1
        let mut moves = BTreeMap::new();
1
        moves.insert(NodeId::new(2), NodeId::new(1));
1
        let map = NodeIdMap::from_pairs(moves);
1
        overlay.remap_node_ids(dom0(), &map);
1
        assert!(overlay.image_for_node(dom0(), NodeId::new(1)).is_some());
1
        assert!(overlay.image_for_node(dom0(), NodeId::new(2)).is_none());
1
        assert!(
1
            overlay.image_for_node(dom0(), NodeId::new(3)).is_none(),
            "unmounted dropped"
        );
1
        assert_eq!(
1
            overlay
1
                .image_for_node(other_dom, NodeId::new(2))
1
                .map(ImageRef::get_hash),
1
            Some(other_hash),
            "other DOMs untouched"
        );
1
    }
}