1use super::{AvailableSpace, EXPECT_MESSAGE, LayoutId, MeasureFn, NodeContext, TaffyLayoutEngine};
13use crate::{App, GlobalElementId, Pixels, Size, Window};
14use collections::FxHashMap;
15use std::{cell::RefCell, mem, rc::Rc};
16use taffy::{TraversePartialTree as _, tree::NodeId};
17
18#[derive(Clone, Copy, Debug, Default)]
20pub struct VnRetainedLayoutStats {
21 pub nodes_created: u64,
23 pub nodes_reused: u64,
25 pub style_writes: u64,
27 pub child_writes: u64,
29 pub probe_calls: u64,
31 pub probe_replays: u64,
33 pub probe_mismatches: u64,
35 pub settle_calls: u64,
37 pub nodes_freed: u64,
39}
40
41struct Slot {
44 bucket: usize,
45 index: usize,
46}
47
48struct Entry {
49 id: LayoutId,
50 log: Option<Rc<RefCell<MeasureLog>>>,
51}
52
53#[derive(Default)]
54struct ScopeBucket {
55 claimed_in_frame: u64,
56 next_slot: usize,
57 entries: Vec<Option<Entry>>,
58}
59
60#[derive(Default)]
61pub(super) struct Retention {
62 pub(super) enabled: bool,
63 pub(super) stats: Option<VnRetainedLayoutStats>,
64 frame: u64,
65 scale: Option<f32>,
66 scopes: FxHashMap<GlobalElementId, usize>,
69 buckets: Vec<Option<ScopeBucket>>,
70 free_buckets: Vec<usize>,
71 retained_nodes: usize,
72 claimed_nodes: usize,
73 transient: Vec<LayoutId>,
74 unstretched: FxHashMap<LayoutId, taffy::style::Style>,
75 pending: Vec<(LayoutId, Rc<RefCell<MeasureLog>>)>,
76 measured: FxHashMap<NodeId, Option<Pixels>>,
77}
78
79type Probe = (Size<Option<Pixels>>, Size<AvailableSpace>, Size<Pixels>);
80
81#[derive(Default)]
82struct MeasureLog {
83 probes: Vec<Probe>,
84 overflowed: bool,
85}
86
87impl MeasureLog {
88 fn record(
89 &mut self,
90 known: Size<Option<Pixels>>,
91 available: Size<AvailableSpace>,
92 size: Size<Pixels>,
93 ) {
94 if self.overflowed {
95 return;
96 }
97 if let Some(index) = self
98 .probes
99 .iter()
100 .position(|(k, a, _)| *k == known && *a == available)
101 {
102 self.probes.remove(index);
103 } else if self.probes.len() == 16 {
104 self.overflowed = true;
107 self.probes.clear();
108 return;
109 }
110 self.probes.push((known, available, size));
111 }
112
113 fn complete(&self) -> bool {
114 !self.overflowed && !self.probes.is_empty()
115 }
116}
117
118impl Retention {
119 fn count(&mut self, f: impl FnOnce(&mut VnRetainedLayoutStats)) {
120 if let Some(stats) = self.stats.as_mut() {
121 f(stats);
122 }
123 }
124
125 fn claim(&mut self, scope: Option<GlobalElementId>) -> (Option<Slot>, Option<Entry>) {
126 let Some(scope) = scope else {
127 return (None, None);
128 };
129 let Self {
130 scopes,
131 buckets,
132 free_buckets,
133 ..
134 } = self;
135 let bucket = *scopes.entry(scope).or_insert_with(|| {
136 if let Some(index) = free_buckets.pop() {
137 buckets[index] = Some(ScopeBucket::default());
138 index
139 } else {
140 let index = buckets.len();
141 buckets.push(Some(ScopeBucket::default()));
142 index
143 }
144 });
145 let scope = buckets[bucket]
146 .as_mut()
147 .expect("a scope owns its bucket until frame end");
148 if scope.claimed_in_frame != self.frame {
149 scope.claimed_in_frame = self.frame;
150 scope.next_slot = 0;
151 }
152 let index = scope.next_slot;
153 scope.next_slot = index
154 .checked_add(1)
155 .expect("too many layout requests in one scope");
156 if index == scope.entries.len() {
157 scope.entries.push(None);
158 }
159 let previous = scope.entries[index].take();
160 if previous.is_none() {
161 self.retained_nodes += 1;
162 }
163 self.claimed_nodes += 1;
164 (Some(Slot { bucket, index }), previous)
165 }
166}
167
168fn remember(
169 engine: &mut TaffyLayoutEngine,
170 slot: Option<Slot>,
171 id: LayoutId,
172 log: Option<Rc<RefCell<MeasureLog>>>,
173) {
174 if let Some(slot) = slot {
175 let bucket = engine.retention.buckets[slot.bucket]
176 .as_mut()
177 .expect("a request's bucket cannot expire before remember");
178 debug_assert!(bucket.entries[slot.index].is_none());
179 bucket.entries[slot.index] = Some(Entry { id, log });
180 } else {
181 engine.retention.transient.push(id);
182 }
183}
184
185fn style(engine: &mut TaffyLayoutEngine, id: LayoutId, requested: &taffy::style::Style) -> bool {
186 let previous = engine
187 .retention
188 .unstretched
189 .get(&id)
190 .unwrap_or_else(|| engine.taffy.style(id.into()).expect(EXPECT_MESSAGE));
191 if previous == requested {
192 return false;
193 }
194 engine.retention.unstretched.remove(&id);
195 engine.retention.count(|stats| stats.style_writes += 1);
196 engine
197 .taffy
198 .set_style(id.into(), requested.clone())
199 .expect(EXPECT_MESSAGE);
200 true
201}
202
203fn children(engine: &mut TaffyLayoutEngine, id: LayoutId, requested: &[LayoutId]) {
204 for child in requested {
205 if let Some(base) = engine.retention.unstretched.remove(child) {
208 if engine.taffy.style((*child).into()).expect(EXPECT_MESSAGE) != &base {
209 engine
210 .taffy
211 .set_style((*child).into(), base)
212 .expect(EXPECT_MESSAGE);
213 }
214 }
215 }
216 if engine
217 .taffy
218 .child_ids(id.into())
219 .eq(LayoutId::to_taffy_slice(requested).iter().copied())
220 {
221 return;
222 }
223 engine.retention.count(|stats| stats.child_writes += 1);
226 engine
227 .taffy
228 .set_children(id.into(), LayoutId::to_taffy_slice(requested))
229 .expect(EXPECT_MESSAGE);
230}
231
232pub(super) fn request_layout(
233 engine: &mut TaffyLayoutEngine,
234 scope: Option<GlobalElementId>,
235 requested: taffy::style::Style,
236 child_ids: &[LayoutId],
237) -> LayoutId {
238 let (slot, previous) = engine.retention.claim(scope);
239 let prior = previous.as_ref().map(|entry| entry.id);
240 engine.retention.count(|stats| {
241 if prior.is_some() {
242 stats.nodes_reused += 1;
243 } else {
244 stats.nodes_created += 1;
245 }
246 });
247 let id = if let Some(id) = prior {
248 style(engine, id, &requested);
249 children(engine, id, child_ids);
250 if engine.taffy.get_node_context(id.into()).is_some() {
251 engine
252 .taffy
253 .set_node_context(id.into(), None)
254 .expect(EXPECT_MESSAGE);
255 }
256 id
257 } else {
258 let id = engine
259 .taffy
260 .new_leaf(requested)
261 .expect(EXPECT_MESSAGE)
262 .into();
263 children(engine, id, child_ids);
264 id
265 };
266 remember(engine, slot, id, None);
267 id
268}
269
270pub(super) fn request_measured_layout(
271 engine: &mut TaffyLayoutEngine,
272 scope: Option<GlobalElementId>,
273 requested: taffy::style::Style,
274 mut measure: impl FnMut(
275 Size<Option<Pixels>>,
276 Size<AvailableSpace>,
277 &mut Window,
278 &mut App,
279 ) -> Size<Pixels>
280 + 'static,
281) -> LayoutId {
282 let (slot, previous) = engine.retention.claim(scope);
283 let prior = previous.as_ref().map(|entry| entry.id);
284 engine.retention.count(|stats| {
285 if prior.is_some() {
286 stats.nodes_reused += 1;
287 } else {
288 stats.nodes_created += 1;
289 }
290 });
291 let previous_log = previous.and_then(|entry| entry.log);
292 let unchanged_style = prior.is_some_and(|id| !style(engine, id, &requested));
293 let replay = unchanged_style
294 && previous_log
295 .as_ref()
296 .is_some_and(|log| log.borrow().complete());
297 let log = if replay {
298 previous_log.expect("a replay has a complete log")
299 } else {
300 Rc::default()
301 };
302 let measure: Box<MeasureFn> = Box::new({
303 let log = log.clone();
304 move |known, available, window, cx| {
305 let size = measure(known, available, window, cx);
306 log.borrow_mut().record(known, available, size);
307 size
308 }
309 });
310 #[cfg(feature = "stacker")]
311 let measure = super::StackSafe::new(measure);
312 let id = if let Some(id) = prior {
313 children(engine, id, &[]);
314 if let Some(context) = engine.taffy.get_node_context_mut(id.into()) {
315 context.measure = measure;
318 } else {
319 engine
320 .taffy
321 .set_node_context(id.into(), Some(NodeContext { measure }))
322 .expect(EXPECT_MESSAGE);
323 }
324 if replay {
325 engine.retention.pending.push((id, log.clone()));
326 } else {
327 engine.taffy.mark_dirty(id.into()).expect(EXPECT_MESSAGE);
328 }
329 id
330 } else {
331 engine
332 .taffy
333 .new_leaf_with_context(requested, NodeContext { measure })
334 .expect(EXPECT_MESSAGE)
335 .into()
336 };
337 remember(engine, slot, id, Some(log));
338 id
339}
340
341pub(super) fn note_measure(
342 engine: &mut Retention,
343 id: NodeId,
344 known: Size<Option<Pixels>>,
345 available: Size<AvailableSpace>,
346) {
347 engine.count(|stats| stats.probe_calls += 1);
348 record_width(engine, id, known, available);
349}
350
351fn record_width(
352 engine: &mut Retention,
353 id: NodeId,
354 known: Size<Option<Pixels>>,
355 available: Size<AvailableSpace>,
356) {
357 let width = known.width.or(match available.width {
358 AvailableSpace::Definite(width) => Some(width),
359 AvailableSpace::MinContent | AvailableSpace::MaxContent => None,
360 });
361 engine.measured.insert(id, width);
362}
363
364pub(super) fn prepare_compute(engine: &mut TaffyLayoutEngine, scale: f32) {
365 let changed = engine
366 .retention
367 .scale
368 .replace(scale)
369 .is_some_and(|previous| previous != scale);
370 if !changed {
371 return;
372 }
373 for id in engine
377 .retention
378 .buckets
379 .iter()
380 .flatten()
381 .flat_map(|bucket| bucket.entries.iter().flatten())
382 .map(|entry| entry.id)
383 .chain(engine.retention.transient.iter().copied())
384 {
385 engine.taffy.mark_dirty(id.into()).expect(EXPECT_MESSAGE);
386 }
387}
388
389pub(super) fn replay(engine: &mut TaffyLayoutEngine, window: &mut Window, cx: &mut App) {
390 let mut pending = mem::take(&mut engine.retention.pending);
391 for (id, log) in pending.drain(..) {
392 let probes = log.borrow().probes.clone();
393 let Some(context) = engine.taffy.get_node_context_mut(id.into()) else {
394 continue;
395 };
396 let mut last = None;
397 let stands = probes.iter().all(|(known, available, expected)| {
398 last = Some((*known, *available));
399 engine.retention.count(|stats| stats.probe_calls += 1);
400 (context.measure)(*known, *available, window, cx) == *expected
401 });
402 if let Some((known, available)) = last {
403 record_width(&mut engine.retention, id.into(), known, available);
404 }
405 if stands {
406 engine.retention.count(|stats| stats.probe_replays += 1);
407 } else {
408 engine.retention.count(|stats| stats.probe_mismatches += 1);
409 *log.borrow_mut() = MeasureLog::default();
412 engine.taffy.mark_dirty(id.into()).expect(EXPECT_MESSAGE);
413 }
414 }
415 engine.retention.pending = pending;
416}
417
418pub(super) fn settle(engine: &mut TaffyLayoutEngine, window: &mut Window, cx: &mut App) {
419 let mut measured = mem::take(&mut engine.retention.measured);
420 let scale = window.scale_factor();
421 for (node, last_width) in measured.drain() {
422 let layout = engine.taffy.layout(node).expect(EXPECT_MESSAGE);
423 let content = Size {
424 width: Pixels(
425 (layout.size.width
426 - layout.padding.left
427 - layout.padding.right
428 - layout.border.left
429 - layout.border.right)
430 .max(0.)
431 / scale,
432 ),
433 height: Pixels(
434 (layout.size.height
435 - layout.padding.top
436 - layout.padding.bottom
437 - layout.border.top
438 - layout.border.bottom)
439 .max(0.)
440 / scale,
441 ),
442 };
443 if last_width == Some(content.width) {
444 continue;
445 }
446 if let Some(context) = engine.taffy.get_node_context_mut(node) {
447 engine.retention.count(|stats| {
448 stats.probe_calls += 1;
449 stats.settle_calls += 1;
450 });
451 (context.measure)(
454 Size {
455 width: Some(content.width),
456 height: Some(content.height),
457 },
458 Size {
459 width: AvailableSpace::Definite(content.width),
460 height: AvailableSpace::Definite(content.height),
461 },
462 window,
463 cx,
464 );
465 }
466 }
467 engine.retention.measured = measured;
468}
469
470pub(super) fn stretch(
471 engine: &mut TaffyLayoutEngine,
472 id: LayoutId,
473 size: Size<Pixels>,
474 scale: f32,
475) {
476 let requested = engine
477 .retention
478 .unstretched
479 .get(&id)
480 .unwrap_or_else(|| engine.taffy.style(id.into()).expect(EXPECT_MESSAGE))
481 .clone();
482 let mut stretched = requested.clone();
483 if requested.size.width.is_auto() {
484 stretched.size.width = taffy::style::Dimension::length(crate::util::round_to_device_pixel(
485 size.width.0,
486 scale,
487 ));
488 }
489 if requested.size.height.is_auto() {
490 stretched.size.height = taffy::style::Dimension::length(
491 crate::util::round_to_device_pixel(size.height.0, scale),
492 );
493 }
494 if stretched == requested && !engine.retention.unstretched.contains_key(&id) {
495 return;
496 }
497 if engine.taffy.style(id.into()).expect(EXPECT_MESSAGE) != &stretched {
498 engine.retention.count(|stats| stats.style_writes += 1);
499 engine
500 .taffy
501 .set_style(id.into(), stretched)
502 .expect(EXPECT_MESSAGE);
503 }
504 engine.retention.unstretched.insert(id, requested);
505}
506
507fn remove(engine: &mut TaffyLayoutEngine, id: LayoutId) {
508 engine.retention.unstretched.remove(&id);
509 if let Some(context) = engine.taffy.get_node_context_mut(id.into()) {
510 let measure: Box<MeasureFn> = Box::new(|_, _, _, _| Size::default());
513 #[cfg(feature = "stacker")]
514 let measure = super::StackSafe::new(measure);
515 context.measure = measure;
516 }
517 engine.retention.count(|stats| stats.nodes_freed += 1);
518 if let Some(parent) = engine.taffy.parent(id.into()) {
522 engine.taffy.mark_dirty(parent).expect(EXPECT_MESSAGE);
523 }
524 engine.taffy.remove(id.into()).expect(EXPECT_MESSAGE);
525}
526
527pub(super) fn finish_frame(engine: &mut TaffyLayoutEngine) {
528 for (id, _) in mem::take(&mut engine.retention.pending) {
529 engine.taffy.mark_dirty(id.into()).expect(EXPECT_MESSAGE);
530 }
531 let mut transient = mem::take(&mut engine.retention.transient);
532 for id in transient.drain(..) {
533 remove(engine, id);
534 }
535 engine.retention.transient = transient;
536 if engine.retention.retained_nodes != engine.retention.claimed_nodes {
539 let retention = &mut engine.retention;
540 let mut expired = Vec::new();
541 let Retention {
542 scopes,
543 buckets,
544 free_buckets,
545 frame,
546 ..
547 } = retention;
548 scopes.retain(|_, index| {
549 let bucket_slot = &mut buckets[*index];
550 let bucket = bucket_slot.as_mut().expect("a scope owns a live bucket");
551 if bucket.claimed_in_frame != *frame {
552 expired.extend(bucket.entries.drain(..).flatten().map(|entry| entry.id));
553 *bucket_slot = None;
554 free_buckets.push(*index);
555 return false;
556 }
557 expired.extend(
558 bucket
559 .entries
560 .drain(bucket.next_slot..)
561 .flatten()
562 .map(|entry| entry.id),
563 );
564 if bucket.entries.capacity() > bucket.entries.len().saturating_mul(2).max(4) {
567 bucket.entries.shrink_to(bucket.entries.len().max(4));
568 }
569 true
570 });
571 retention.retained_nodes -= expired.len();
572 for id in expired {
573 remove(engine, id);
574 }
575 }
576 engine.retention.measured.clear();
577 engine.retention.claimed_nodes = 0;
578 engine.retention.frame = engine.retention.frame.wrapping_add(1);
579}
580
581#[cfg(test)]
582mod tests;