1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//! The window-level entry points: build-or-patch the retained window tree
//! ([`HydrolysisRenderer::capture_window_tree`]) and the per-frame pass
//! ([`HydrolysisRenderer::flush_window_tree`]), plus [`RenderNode::patch`].
use super::*;
impl RenderNode {
/// Apply pending reactive `Dynamic` content changes by rebuilding only the
/// affected child subtree — no whole-window re-dispatch. Returns whether
/// anything changed; the caller relays the whole (retained, cheap) tree out
/// when so, which lets a size-changing swap reflow its ancestors without
/// resetting the scene and re-dispatching, which is visible as a flash.
/// Walks the whole tree.
pub(crate) fn patch(&mut self, renderer: &mut SemanticCore) -> bool {
// No environment is threaded through: a rebuild uses the node's own captured
// environment (`Dynamic`/`Collection`/`Env` carry it), so the walk only needs
// the renderer.
match self {
RenderNode::Dynamic(node) => {
let pending = node.pending.borrow_mut().take();
if let Some(content) = pending {
let node_env = node.env.clone();
node.child = RenderNode::build(content, &node_env, renderer);
true
} else {
node.child.patch(renderer)
}
}
RenderNode::Container(container) => {
let mut changed = false;
for child in &mut container.children {
changed |= child.patch(renderer);
}
changed
}
RenderNode::Opacity(node) => node.child.patch(renderer),
RenderNode::Scale(node) => node.child.patch(renderer),
RenderNode::Rotation(node) => node.child.patch(renderer),
RenderNode::Offset(node) => node.child.patch(renderer),
RenderNode::Retain(node) => node.child.patch(renderer),
RenderNode::Env(node) => node.child.patch(renderer),
RenderNode::Wrapper(node) => node.child.patch(renderer),
RenderNode::Collection(node) => {
// Reconcile membership first (keeps surviving items' nodes and,
// with a transition, starts enters/exits), then advance the
// transition clock — settling finished phases and resolving this
// frame's presence factors — then always patch every entry so
// surviving items' nested reactive content (e.g. an
// active-indicator `.background(Computed)`) updates.
let membership_changed = node.dirty.replace(false);
if membership_changed {
node.reconcile(renderer);
}
let mut changed = membership_changed | node.advance_transitions(renderer);
for entry in &mut node.entries {
changed |= entry.node.patch(renderer);
}
changed
}
RenderNode::Scroll(node) => node.child.patch(renderer),
// A ViewEffect and an AppliedFilter wrap a child render node whose
// reactive descendants must keep patching, so the walk recurses into
// them (the effect itself owns its runtime, with no structural patch).
RenderNode::ViewEffect(node) => node.child.borrow_mut().patch(renderer),
RenderNode::AppliedFilter(node) => node.child.patch(renderer),
RenderNode::Color(_)
| RenderNode::Text(_)
| RenderNode::SceneView(_)
// A GpuSurface owns its runtime and re-renders every flush; like a
// self-drawn scene it has no structural patch.
| RenderNode::GpuSurface(_)
// A widget leaf re-dispatches from its live config every flush, so it
// needs no structural patch.
| RenderNode::Widget(_) => false,
// A lazy stack keeps only visible item subtrees. Patch those retained
// items before parent layout so a Dynamic row-height change updates the
// scroll extent in the same refresh instead of one frame later.
RenderNode::LazyStack(node) => node.patch_visible(renderer),
}
}
/// Collect the identities of every live `DynamicHostNode` in this retained
/// subtree, so the measure-path dynamic dimension cache can be pruned to the
/// `Dynamic`s still present in the tree. Walks the same child-bearing variants
/// as [`RenderNode::patch`]. A set, not a list: the prune tests every cached
/// identity against it, which is quadratic over a linear scan.
pub(crate) fn collect_dynamic_identities(&self) -> FxHashSet<usize> {
let mut out = FxHashSet::default();
self.collect_dynamic_identities_into(&mut out);
out
}
pub(super) fn collect_dynamic_identities_into(&self, out: &mut FxHashSet<usize>) {
match self {
RenderNode::Dynamic(node) => {
out.insert(node.source.identity());
node.child.collect_dynamic_identities_into(out);
}
RenderNode::Container(container) => {
for child in &container.children {
child.collect_dynamic_identities_into(out);
}
}
RenderNode::Opacity(node) => node.child.collect_dynamic_identities_into(out),
RenderNode::Scale(node) => node.child.collect_dynamic_identities_into(out),
RenderNode::Rotation(node) => node.child.collect_dynamic_identities_into(out),
RenderNode::Offset(node) => node.child.collect_dynamic_identities_into(out),
RenderNode::Retain(node) => node.child.collect_dynamic_identities_into(out),
RenderNode::Env(node) => node.child.collect_dynamic_identities_into(out),
RenderNode::Wrapper(node) => node.child.collect_dynamic_identities_into(out),
RenderNode::Collection(node) => {
for entry in &node.entries {
entry.node.collect_dynamic_identities_into(out);
}
}
RenderNode::Scroll(node) => node.child.collect_dynamic_identities_into(out),
RenderNode::ViewEffect(node) => {
node.child.borrow().collect_dynamic_identities_into(out);
}
RenderNode::AppliedFilter(node) => node.child.collect_dynamic_identities_into(out),
RenderNode::Color(_)
| RenderNode::Text(_)
| RenderNode::SceneView(_)
| RenderNode::GpuSurface(_)
| RenderNode::Widget(_) => {}
RenderNode::LazyStack(node) => node
.item_cache
.borrow()
.collect_dynamic_identities_into(out),
}
}
}
impl SemanticCore {
/// The emit-pass equivalent of `HydrolysisRenderer::reset_scene`: clears
/// every pure-emission registry the accessibility walk re-pushes — input
/// targets, gesture targets, text-input targets and the accessibility
/// builder's node/action state — so each walk re-registers exactly what is
/// live. Callers then roll the frame boundaries the walk's signal reads
/// and retained-state bindings live under.
fn begin_semantic_emit_frame(&mut self) {
self.lifecycle.begin_rebuild_frame();
self.hit_test.begin_rebuild_frame();
self.hit_test.reset_scene();
self.gesture_engine.clear_targets();
self.text_editing.text_input_targets.clear();
self.lazy.begin_rebuild_frame();
self.navigation.begin_rebuild_frame();
#[cfg(feature = "accessibility")]
self.accessibility.begin_rebuild_frame();
}
/// The emit-pass equivalent of the non-scene half of
/// `HydrolysisRenderer::finish_rebuild_frame`: Retain watcher rollover, the
/// measurement-cache and animation-slot prunes, focus validation, and the
/// accessibility tree's publication. `signals.finish_rebuild` stays with
/// the caller — only a build entered one.
fn finish_semantic_emit_frame(&mut self, live_dynamics: &FxHashSet<usize>) {
self.lifecycle.finish_rebuild_frame();
self.prune_dynamic_measurements(live_dynamics);
self.validate_focused_text_input_after_flush();
self.animation_controller
.finish_rebuild_frame_with_inactive_slot_retention(false);
self.hit_test
.finish_rebuild_frame(&self.text_editing.text_input_targets);
self.navigation.finish_rebuild_frame();
#[cfg(feature = "accessibility")]
self.finalize_accessibility_tree_update();
}
/// Build the retained window tree from `content` and emit its
/// accessibility tree — the semantic analogue of
/// [`HydrolysisRenderer::capture_window_tree`]: dispatch and emission only,
/// with no layout, no encode and no theme.
///
/// Like the rendered path, a call made with a tree already built applies
/// the pending patch and re-emits instead of re-dispatching.
pub(crate) fn capture_window_semantics(&mut self, content: AnyView, env: &Environment) {
if self.render_tree.is_some() {
assert!(
self.flush_window_semantics(env),
"hydrolysis renderer: retained window tree vanished during semantics capture"
);
return;
}
self.signals.begin_rebuild();
self.begin_semantic_emit_frame();
self.render_depth = 0;
let tree = RenderNode::build(content, env, self);
let live_dynamics = tree.collect_dynamic_identities();
#[cfg(feature = "accessibility")]
tree.emit_accessibility(self, env);
self.render_tree = Some(tree);
self.finish_semantic_emit_frame(&live_dynamics);
self.signals.finish_rebuild();
}
/// Apply pending structural changes and re-emit the retained tree's
/// accessibility tree without laying out or encoding — the semantic
/// analogue of [`HydrolysisRenderer::flush_window_tree`]. Returns `false`
/// if no tree is built.
///
/// A `Dynamic` can reconnect (its initial update is gated on the rebuild
/// generation), so patching is the only structural path here: a rebuild
/// request would be a programmer error — re-dispatching `body()` is the
/// one-time build's job.
pub(crate) fn flush_window_semantics(&mut self, _env: &Environment) -> bool {
let Some(mut tree) = self.render_tree.take() else {
return false;
};
self.begin_semantic_emit_frame();
let structural_change = self.take_subview_structural_change() | tree.patch(self);
if structural_change {
self.animation_controller.begin_rebuild_frame();
}
#[cfg(feature = "accessibility")]
tree.emit_accessibility(self, _env);
let live_dynamics = tree.collect_dynamic_identities();
self.render_tree = Some(tree);
self.finish_semantic_emit_frame(&live_dynamics);
true
}
}
impl HydrolysisRenderer {
/// Build the retained tree before its first sized frame. Embedded GPU hosts
/// use this during async setup so every statically reachable `GpuSurface`
/// can finish its own setup before the first render target is presented.
pub(crate) fn prepare_window_tree(&mut self, content: AnyView, env: &Environment) {
assert!(
self.render_tree.is_none(),
"hydrolysis renderer: window tree prepared more than once"
);
self.begin_rebuild_frame();
self.render_depth = 0;
let tree = RenderNode::build(content, env, self);
self.render_tree = Some(tree);
self.finish_rebuild_frame();
}
/// Build the window render tree from `content`, lay it out at `bounds`, and
/// flush it into the scene — the render-tree analogue of
/// `HydrolysisRenderer::capture_window_scene`. The built tree is retained in
/// `render_tree` for subsequent per-frame flushes.
pub fn capture_window_tree(
&mut self,
content: AnyView,
env: &Environment,
bounds: vello::kurbo::Rect,
transform: vello::kurbo::Affine,
hit_transform: vello::kurbo::Affine,
) {
let size = Size::new(bounds.width() as f32, bounds.height() as f32);
let proposal = ProposalSize::new(Some(size.width), Some(size.height));
// The viewport is recorded here rather than by each caller: every host
// that builds a window tree — the runner, and a `HydrolysisGpuView`
// embedding one in someone else's surface — has to agree on where the
// window lands in device pixels, and forgetting to say so left the
// embedded host reading a stale one.
self.set_window_viewport(bounds, transform);
let ctx = RenderContext::with_transforms(bounds, transform, hit_transform);
// The tree is built once and persists. A later "rebuild" request reuses
// it — applying pending Dynamic patches, relaying out, and re-flushing —
// rather than rebuilding (which would re-connect each `Dynamic`, and a
// `Dynamic` can only connect once). Called within a begin/finish rebuild
// frame, so scene/layer flushing is handled by the caller.
if let Some(mut tree) = self.render_tree.take() {
tree.patch(self);
tree.prepare_for_measure(self);
tree.layout(self, env, proposal, size);
tree.flush(self, ctx, env);
self.flush_subtree_captures(0);
self.render_tree = Some(tree);
return;
}
self.render_depth = 0;
let mut node = RenderNode::build(content, env, self);
node.prepare_for_measure(self);
node.layout(self, env, proposal, size);
node.flush(self, ctx, env);
self.flush_subtree_captures(0);
self.render_tree = Some(node);
}
/// Apply pending structural changes, run layout, and re-encode the retained
/// window tree without rebuilding it. Returns `false` if no tree is built.
/// This is the one per-frame pass: every awake frame patches, lays out, and
/// re-encodes, so the presented scene can never go stale against layout.
pub fn flush_window_tree(
&mut self,
env: &Environment,
bounds: vello::kurbo::Rect,
transform: vello::kurbo::Affine,
hit_transform: vello::kurbo::Affine,
) -> bool {
let Some(mut tree) = self.render_tree.take() else {
return false;
};
// Track the live window viewport every frame: text-context-menu clamping,
// effect-rect checks and the direct-to-target test read it.
self.set_window_viewport(bounds, transform);
// Roll over this frame's Retain watcher guards exactly like the build path:
// every re-encode re-reads and re-subscribes reactive visual inputs.
self.lifecycle.begin_rebuild_frame();
// Reset frame-bound input registrations. Scroll, list, and table state are
// owned by their semantic retained nodes.
self.hit_test.begin_rebuild_frame();
self.lazy.begin_rebuild_frame();
self.navigation.begin_rebuild_frame();
// Fold in a structural patch a widget-owned sub-view applied during
// the previous frame's flush (mid-flush, past that frame's
// bookkeeping window).
let structural_change = self.take_subview_structural_change() | tree.patch(self);
if structural_change {
self.animation_controller.begin_rebuild_frame();
}
self.reset_scene();
self.begin_redraw_frame();
// Layout runs every frame: geometry can never go stale against the
// scene encoded right after it.
let size = Size::new(bounds.width() as f32, bounds.height() as f32);
let proposal = ProposalSize::new(Some(size.width), Some(size.height));
tree.prepare_for_measure(self);
tree.layout(self, env, proposal, size);
let ctx = RenderContext::with_transforms(bounds, transform, hit_transform);
tree.flush(self, ctx, env);
// Every filtered subtree captured during the flush is rendered and
// filtered now, before the scene that draws their outputs is.
self.flush_subtree_captures(0);
// The overlay-mode text context menu re-encodes with the frame it floats
// over; drawing it only on the one-time build path would leave it visible
// for a single frame.
self.render_active_text_context_menu_overlay(env, transform);
self.flush_vello_scene_layer();
self.core
.hit_test
.finish_rebuild_frame(&self.core.text_editing.text_input_targets);
self.core.navigation.finish_rebuild_frame();
if structural_change {
// The flush re-bound every live animation. Drop slots and cached
// Dynamic measurements belonging to subtrees removed by the patch.
self.core
.animation_controller
.finish_rebuild_frame_with_inactive_slot_retention(false);
self.prune_dynamic_measurements(&tree.collect_dynamic_identities());
}
self.lifecycle.finish_rebuild_frame();
// Drop focus or drag targets that are no longer emitted, then publish the
// refreshed accessibility tree.
self.validate_focused_text_input_after_flush();
#[cfg(feature = "accessibility")]
self.finalize_accessibility_tree_update();
self.render_tree = Some(tree);
true
}
/// Measures the window content's minimum and maximum sizes, or `None`
/// before the tree is built.
///
/// These are whole-tree measure passes at proposals the frame's own
/// layout never uses, so it is demand-driven rather than run on every
/// refresh: only the runner calls it, and only once it knows the answer will
/// reach a window that acts on it (see `apply_window_size_limits`).
pub(crate) fn measure_content_size_limits(
&mut self,
env: &Environment,
) -> Option<ContentSizeLimits> {
let tree = self.render_tree.take()?;
let limits = self.content_size_limits_of(&tree, env);
self.render_tree = Some(tree);
Some(limits)
}
/// Both axes are probed together, not independently: what a view answers on
/// one axis depends on what the other was offered — text re-wraps at the
/// minimum width and then needs more height than its single-line ideal —
/// so a per-axis probe with the cross axis unspecified returns a box the
/// content can never actually occupy. `ProposalSize::ZERO` asks for the
/// smallest self-consistent box the content can occupy; `INFINITY` asks for
/// the largest it ever wants.
fn content_size_limits_of(
&mut self,
tree: &RenderNode,
env: &Environment,
) -> ContentSizeLimits {
let theme = self.theme();
let min_box = tree
.measure(&mut self.state, env, &theme, ProposalSize::ZERO)
.size;
let minimum = Size::new(
validated_minimum_axis(min_box.width, "width"),
validated_minimum_axis(min_box.height, "height"),
);
let max_box = tree
.measure(&mut self.state, env, &theme, ProposalSize::INFINITY)
.size;
let maximum = content_maximum_size(max_box.width, max_box.height).map(|size| {
// A finite maximum may legitimately fall below the coupled minimum:
// the box at unbounded width is shorter than the box the same
// wrapping content needs at its narrowest. Floor each axis at the
// minimum so the allowed box is never empty.
Size::new(
size.width.max(minimum.width),
size.height.max(minimum.height),
)
});
ContentSizeLimits { minimum, maximum }
}
}
fn validated_minimum_axis(value: f32, axis: &str) -> f32 {
assert!(
value.is_finite() && value >= 0.0,
"hydrolysis window layout reported invalid minimum {axis}: {value}"
);
value
}
fn validated_maximum_axis(value: f32, axis: &str) -> Option<f32> {
assert!(
!value.is_nan() && value >= 0.0,
"hydrolysis window layout reported invalid maximum {axis}: {value}"
);
value.is_finite().then_some(value)
}
fn content_maximum_size(width: f32, height: f32) -> Option<Size> {
let width = validated_maximum_axis(width, "width");
let height = validated_maximum_axis(height, "height");
if width.is_none() && height.is_none() {
return None;
}
Some(Size::new(
width.unwrap_or(f32::MAX),
height.unwrap_or(f32::MAX),
))
}