Skip to main content

gpui/
taffy.rs

1use crate::{
2    AbsoluteLength, App, Bounds, DefiniteLength, Edges, GridTemplate, Length, PathHash, Pixels,
3    Point, Size, Style, Window, size,
4    util::{
5        ceil_to_device_pixel, round_half_toward_zero, round_stroke_to_device_pixel,
6        round_to_device_pixel,
7    },
8};
9use collections::{FxHashMap, FxHashSet};
10use slotmap::{DefaultKey, KeyData, SecondaryMap};
11use smallvec::SmallVec;
12use std::{any::Any, fmt::Debug, ops::Range};
13use taffy::{
14    TaffyTree, TraversePartialTree as _,
15    geometry::{Point as TaffyPoint, Rect as TaffyRect, Size as TaffySize},
16    prelude::{max_content, min_content},
17    style::AvailableSpace as TaffyAvailableSpace,
18    tree::NodeId,
19};
20
21#[cfg(feature = "stacker")]
22type StackSafe<T> = stacksafe::StackSafe<T>;
23#[cfg(not(feature = "stacker"))]
24type StackSafe<T> = T;
25
26type NodeContext = StackSafe<Box<dyn Measure>>;
27
28/// Lets a node hold any [`KeyedMeasure`] in a single allocation.
29trait Measure: Any {
30    /// `final_layout` is false when Taffy is only probing the node's size.
31    fn measure(
32        &mut self,
33        known_dimensions: Size<Option<Pixels>>,
34        available_space: Size<AvailableSpace>,
35        final_layout: bool,
36        window: &mut Window,
37        cx: &mut App,
38    ) -> Size<Pixels>;
39}
40
41/// Replaces `previous` in place when it already holds a `KeyedMeasure<K, F>`, returning
42/// whether `reuse` said its cached sizes still apply. Returns `Err((key, measure))` when
43/// the node held a measure of a different type and needs a fresh allocation.
44///
45/// Unlike the rest of a layout request, this reads the node's context, which with the
46/// `stacker` feature may only be done from a stack-safe function.
47#[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
48fn replace_measure_in_place<K, F>(
49    previous: &mut NodeContext,
50    mut key: K,
51    reuse: fn(&mut K, &mut K) -> bool,
52    measure: F,
53) -> Result<bool, (K, F)>
54where
55    K: 'static,
56    F: FnMut(
57            &K,
58            Size<Option<Pixels>>,
59            Size<AvailableSpace>,
60            bool,
61            &mut Window,
62            &mut App,
63        ) -> Size<Pixels>
64        + 'static,
65{
66    let previous: &mut Box<dyn Measure> = previous;
67    let Some(previous) = (&mut **previous as &mut dyn Any).downcast_mut::<KeyedMeasure<K, F>>()
68    else {
69        return Err((key, measure));
70    };
71    let reused = reuse(&mut key, &mut previous.key);
72    previous.key = key;
73    previous.measure = measure;
74    Ok(reused)
75}
76
77fn box_measure<K, F>(key: K, measure: F) -> NodeContext
78where
79    K: 'static,
80    F: FnMut(
81            &K,
82            Size<Option<Pixels>>,
83            Size<AvailableSpace>,
84            bool,
85            &mut Window,
86            &mut App,
87        ) -> Size<Pixels>
88        + 'static,
89{
90    let measure: Box<dyn Measure> = Box::new(KeyedMeasure { key, measure });
91    #[cfg(feature = "stacker")]
92    let measure = StackSafe::new(measure);
93    measure
94}
95
96/// A measure function and the key describing what its measured size depends on.
97struct KeyedMeasure<K, F> {
98    key: K,
99    measure: F,
100}
101
102impl<K, F> Measure for KeyedMeasure<K, F>
103where
104    K: 'static,
105    F: FnMut(
106            &K,
107            Size<Option<Pixels>>,
108            Size<AvailableSpace>,
109            bool,
110            &mut Window,
111            &mut App,
112        ) -> Size<Pixels>
113        + 'static,
114{
115    fn measure(
116        &mut self,
117        known_dimensions: Size<Option<Pixels>>,
118        available_space: Size<AvailableSpace>,
119        final_layout: bool,
120        window: &mut Window,
121        cx: &mut App,
122    ) -> Size<Pixels> {
123        (self.measure)(
124            &self.key,
125            known_dimensions,
126            available_space,
127            final_layout,
128            window,
129            cx,
130        )
131    }
132}
133
134pub struct TaffyLayoutEngine {
135    taffy: TaffyTree,
136    /// Kept outside of Taffy, whose context map hashes every access and marks a node dirty
137    /// whenever its context is replaced.
138    contexts: SecondaryMap<DefaultKey, NodeContext>,
139    /// Keeps layout nodes alive from one frame to the next, so Taffy's layout cache can
140    /// skip subtrees whose styles and children didn't change.
141    cache: LayoutCache,
142    absolute_layout_bounds: FxHashMap<LayoutId, Bounds<Pixels>>,
143    /// Unrounded absolute border-box top-left per-node coordinate in device pixels.
144    absolute_outer_origins: FxHashMap<LayoutId, Point<f32>>,
145    computed_layouts: FxHashSet<LayoutId>,
146    layout_bounds_scratch_space: Vec<LayoutId>,
147}
148
149/// Layout nodes requested by elements under one element ID path, in request order.
150///
151/// Elements without IDs are distinguished only by their order within the nearest ancestor
152/// with one. Which node a request reuses only affects how much of Taffy's cache survives:
153/// a reused node's style, children and measure function are always brought up to date.
154#[derive(Default)]
155struct LayoutScope {
156    /// How many of `nodes` were requested this frame.
157    requested: usize,
158    nodes: SmallVec<[NodeId; 4]>,
159}
160
161struct CachedNode {
162    /// What the node's Taffy style was converted from, compared before converting again.
163    style: LayoutStyle,
164    /// The last frame the node was requested in.
165    frame: u64,
166    /// Whether `stretch_auto_size_to_fill` changed the Taffy style since it was converted.
167    stretched: bool,
168}
169
170#[derive(Default)]
171struct LayoutCache {
172    scopes: FxHashMap<PathHash, LayoutScope>,
173    nodes: SecondaryMap<DefaultKey, CachedNode>,
174    /// Nodes no element requested last frame, detached from the tree. A request that
175    /// misses reuses one before allocating, and those still unused at the end of this
176    /// frame are removed.
177    free_nodes: Vec<NodeId>,
178    frame: u64,
179    /// Scale factor Taffy's cached device-pixel styles and measurements were computed at.
180    scale_factor: Option<f32>,
181}
182
183fn node_key(id: NodeId) -> DefaultKey {
184    KeyData::from_ffi(id.into()).into()
185}
186
187const EXPECT_MESSAGE: &str = "we should avoid taffy layout errors by construction if possible";
188
189impl TaffyLayoutEngine {
190    pub fn new() -> Self {
191        let mut taffy = TaffyTree::new();
192        taffy.disable_rounding();
193        TaffyLayoutEngine {
194            taffy,
195            contexts: SecondaryMap::new(),
196            cache: LayoutCache::default(),
197            absolute_layout_bounds: FxHashMap::default(),
198            absolute_outer_origins: FxHashMap::default(),
199            computed_layouts: FxHashSet::default(),
200            layout_bounds_scratch_space: Vec::new(),
201        }
202    }
203
204    /// Drops every layout node kept from earlier frames, so the next frame builds its
205    /// tree from scratch.
206    pub(crate) fn clear_layout_cache(&mut self) {
207        self.taffy.clear();
208        self.contexts.clear();
209        self.cache = LayoutCache::default();
210        self.absolute_layout_bounds.clear();
211        self.absolute_outer_origins.clear();
212        self.computed_layouts.clear();
213    }
214
215    /// Clears the layout cache when the window's scale factor changes. Taffy stores styles
216    /// and measured leaf sizes in device pixels, so none of the cached layouts apply at a
217    /// different scale factor.
218    pub(crate) fn clear_if_scale_factor_changed(&mut self, scale_factor: f32) {
219        if self
220            .cache
221            .scale_factor
222            .is_some_and(|previous| previous != scale_factor)
223        {
224            self.clear_layout_cache();
225        }
226        self.cache.scale_factor = Some(scale_factor);
227    }
228
229    #[cfg(test)]
230    pub(crate) fn node_count(&self) -> usize {
231        self.taffy.total_node_count()
232    }
233
234    /// Ends the frame: nodes that weren't requested during it are evicted.
235    pub fn clear(&mut self) {
236        self.cache
237            .evict_unrequested(&mut self.taffy, &mut self.contexts);
238        self.absolute_layout_bounds.clear();
239        self.absolute_outer_origins.clear();
240        self.computed_layouts.clear();
241    }
242
243    pub fn request_layout(
244        &mut self,
245        scope: PathHash,
246        style: &Style,
247        rem_size: Pixels,
248        scale_factor: f32,
249        children: &[LayoutId],
250    ) -> LayoutId {
251        let id = self.acquire_node(scope, style, rem_size, scale_factor, children);
252        if self.contexts.remove(node_key(id)).is_some() {
253            self.taffy.mark_dirty(id).expect(EXPECT_MESSAGE);
254        }
255        id.into()
256    }
257
258    /// See [`Window::request_keyed_measure`].
259    pub(crate) fn request_keyed_measure<K, F>(
260        &mut self,
261        scope: PathHash,
262        style: &Style,
263        rem_size: Pixels,
264        scale_factor: f32,
265        key: K,
266        reuse: fn(&mut K, &mut K) -> bool,
267        measure: F,
268    ) -> LayoutId
269    where
270        K: 'static,
271        F: FnMut(
272                &K,
273                Size<Option<Pixels>>,
274                Size<AvailableSpace>,
275                bool,
276                &mut Window,
277                &mut App,
278            ) -> Size<Pixels>
279            + 'static,
280    {
281        let id = self.acquire_node(scope, style, rem_size, scale_factor, &[]);
282        let key_id = node_key(id);
283        // A measure that measures the same as the node's previous one keeps the sizes
284        // Taffy cached from it; any other must invalidate them. Updating a same-type
285        // context in place avoids allocating and freeing a Box on steady-state frames.
286        let reused = if let Some(previous) = self.contexts.get_mut(key_id) {
287            match replace_measure_in_place(previous, key, reuse, measure) {
288                Ok(reused) => reused,
289                Err((key, measure)) => {
290                    *previous = box_measure(key, measure);
291                    false
292                }
293            }
294        } else {
295            self.contexts.insert(key_id, box_measure(key, measure));
296            false
297        };
298        if !reused {
299            self.taffy.mark_dirty(id).expect(EXPECT_MESSAGE);
300        }
301        id.into()
302    }
303
304    fn acquire_node(
305        &mut self,
306        scope: PathHash,
307        style: &Style,
308        rem_size: Pixels,
309        scale_factor: f32,
310        children: &[LayoutId],
311    ) -> NodeId {
312        // This is safe because LayoutId is repr(transparent) to taffy::tree::NodeId.
313        let children = LayoutId::to_taffy_slice(children);
314        let taffy = &mut self.taffy;
315        let cache = &mut self.cache;
316
317        let frame = cache.frame;
318        let scope = cache.scopes.entry(scope).or_default();
319        let ordinal = scope.requested;
320        scope.requested += 1;
321        let id = if let Some(&id) = scope.nodes.get(ordinal) {
322            let node = &mut cache.nodes[node_key(id)];
323            debug_assert_ne!(
324                node.frame, frame,
325                "layout node requested twice in one frame"
326            );
327            if node.stretched || !node.style.matches(style, rem_size, scale_factor) {
328                node.style = LayoutStyle::new(style, rem_size, scale_factor);
329                node.stretched = false;
330                let taffy_style = node.style.to_taffy();
331                if taffy.style(id).expect(EXPECT_MESSAGE) != &taffy_style {
332                    taffy.set_style(id, taffy_style).expect(EXPECT_MESSAGE);
333                }
334            }
335            if !taffy.child_ids(id).eq(children.iter().copied()) {
336                taffy.set_children(id, children).expect(EXPECT_MESSAGE);
337            }
338            id
339        } else {
340            let style = LayoutStyle::new(style, rem_size, scale_factor);
341            let taffy_style = style.to_taffy();
342            let id = if let Some(id) = cache.free_nodes.pop() {
343                taffy.set_style(id, taffy_style).expect(EXPECT_MESSAGE);
344                let node = &mut cache.nodes[node_key(id)];
345                node.style = style;
346                node.stretched = false;
347                id
348            } else {
349                let id = taffy.new_leaf(taffy_style).expect(EXPECT_MESSAGE);
350                let node = CachedNode {
351                    style,
352                    frame,
353                    stretched: false,
354                };
355                cache.nodes.insert(node_key(id), node);
356                id
357            };
358            if !children.is_empty() {
359                // Unlike `new_with_children`, this detaches children from their previous parents.
360                taffy.set_children(id, children).expect(EXPECT_MESSAGE);
361            }
362            scope.nodes.push(id);
363            id
364        };
365
366        cache.nodes[node_key(id)].frame = frame;
367        id
368    }
369
370    /// Treats any `auto` dimension of the given node's style as filling `size`.
371    ///
372    /// This is applied to window roots before layout so they behave like the
373    /// root element on the web, which stretches to fill the initial containing
374    /// block (the viewport) unless given an explicit size. Explicitly styled
375    /// dimensions are preserved.
376    pub fn stretch_auto_size_to_fill(
377        &mut self,
378        id: LayoutId,
379        size: Size<Pixels>,
380        scale_factor: f32,
381    ) {
382        let style = self.taffy.style(id.0).expect(EXPECT_MESSAGE);
383        let stretch_width = style.size.width.is_auto();
384        let stretch_height = style.size.height.is_auto();
385        if !stretch_width && !stretch_height {
386            return;
387        }
388        // The next request for this node must restore its style, unless it is stretched
389        // again; it may not be a root by then.
390        if let Some(node) = self.cache.nodes.get_mut(node_key(id.0)) {
391            node.stretched = true;
392        }
393        let mut style = style.clone();
394        if stretch_width {
395            style.size.width =
396                taffy::style::Dimension::length(round_to_device_pixel(size.width.0, scale_factor));
397        }
398        if stretch_height {
399            style.size.height =
400                taffy::style::Dimension::length(round_to_device_pixel(size.height.0, scale_factor));
401        }
402        self.taffy.set_style(id.0, style).expect(EXPECT_MESSAGE);
403    }
404
405    // Used to understand performance
406    #[allow(dead_code)]
407    fn count_all_children(&self, parent: LayoutId) -> anyhow::Result<u32> {
408        let mut count = 0;
409
410        for child in self.taffy.children(parent.0)? {
411            // Count this child.
412            count += 1;
413
414            // Count all of this child's children.
415            count += self.count_all_children(LayoutId(child))?
416        }
417
418        Ok(count)
419    }
420
421    // Used to understand performance
422    #[allow(dead_code)]
423    fn max_depth(&self, depth: u32, parent: LayoutId) -> anyhow::Result<u32> {
424        println!(
425            "{parent:?} at depth {depth} has {} children",
426            self.taffy.child_count(parent.0)
427        );
428
429        let mut max_child_depth = 0;
430
431        for child in self.taffy.children(parent.0)? {
432            max_child_depth = std::cmp::max(max_child_depth, self.max_depth(0, LayoutId(child))?);
433        }
434
435        Ok(depth + 1 + max_child_depth)
436    }
437
438    // Used to understand performance
439    #[allow(dead_code)]
440    fn get_edges(&self, parent: LayoutId) -> anyhow::Result<Vec<(LayoutId, LayoutId)>> {
441        let mut edges = Vec::new();
442
443        for child in self.taffy.children(parent.0)? {
444            edges.push((parent, LayoutId(child)));
445
446            edges.extend(self.get_edges(LayoutId(child))?);
447        }
448
449        Ok(edges)
450    }
451
452    #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
453    pub fn compute_layout(
454        &mut self,
455        id: LayoutId,
456        available_space: Size<AvailableSpace>,
457        window: &mut Window,
458        cx: &mut App,
459    ) {
460        // Leaving this here until we have a better instrumentation approach.
461        // println!("Laying out {} children", self.count_all_children(id)?);
462        // println!("Max layout depth: {}", self.max_depth(0, id)?);
463
464        // Output the edges (branches) of the tree in Mermaid format for visualization.
465        // println!("Edges:");
466        // for (a, b) in self.get_edges(id)? {
467        //     println!("N{} --> N{}", u64::from(a), u64::from(b));
468        // }
469        //
470
471        // A node computed as a root may still be attached to a parent from an earlier
472        // frame that no element requested in this one. Its layout must not be relative to
473        // that parent.
474        let cache = &self.cache;
475        if let Some(parent) = self.taffy.parent(id.0)
476            && cache
477                .nodes
478                .get(node_key(parent))
479                .is_none_or(|node| node.frame != cache.frame)
480        {
481            self.taffy.remove_child(parent, id.0).expect(EXPECT_MESSAGE);
482        }
483
484        if !self.computed_layouts.insert(id) {
485            let stack = &mut self.layout_bounds_scratch_space;
486            stack.push(id);
487            while let Some(id) = stack.pop() {
488                self.absolute_layout_bounds.remove(&id);
489                self.absolute_outer_origins.remove(&id);
490                stack.extend(
491                    self.taffy
492                        .children(id.into())
493                        .expect(EXPECT_MESSAGE)
494                        .into_iter()
495                        .map(LayoutId::from),
496                );
497            }
498        }
499
500        let scale_factor = window.scale_factor();
501
502        let transform = |v: AvailableSpace| match v {
503            AvailableSpace::Definite(pixels) => {
504                AvailableSpace::Definite(Pixels(pixels.0 * scale_factor))
505            }
506            AvailableSpace::MinContent => AvailableSpace::MinContent,
507            AvailableSpace::MaxContent => AvailableSpace::MaxContent,
508        };
509        let available_space = size(
510            transform(available_space.width),
511            transform(available_space.height),
512        );
513
514        let contexts = &mut self.contexts;
515        self.taffy
516            .compute_layout_with_measure(
517                id.into(),
518                available_space.into(),
519                |input, id, _, style| {
520                    let node_context = contexts.get_mut(node_key(id));
521                    taffy::compute_leaf_layout(
522                        input,
523                        style,
524                        |_, _| 0.0,
525                        |known_dimensions, available_space| {
526                            let Some(node_context) = node_context else {
527                                return taffy::geometry::Size::default();
528                            };
529
530                            let known_dimensions = Size {
531                                width: known_dimensions.width.map(|e| Pixels(e / scale_factor)),
532                                height: known_dimensions.height.map(|e| Pixels(e / scale_factor)),
533                            };
534
535                            let available_space: Size<AvailableSpace> = available_space.into();
536                            let untransform = |ev: AvailableSpace| match ev {
537                                AvailableSpace::Definite(pixels) => {
538                                    AvailableSpace::Definite(Pixels(pixels.0 / scale_factor))
539                                }
540                                AvailableSpace::MinContent => AvailableSpace::MinContent,
541                                AvailableSpace::MaxContent => AvailableSpace::MaxContent,
542                            };
543                            let available_space = size(
544                                untransform(available_space.width),
545                                untransform(available_space.height),
546                            );
547
548                            let final_layout = input.run_mode == taffy::RunMode::PerformLayout;
549                            let measured_size = node_context.measure(
550                                known_dimensions,
551                                available_space,
552                                final_layout,
553                                window,
554                                cx,
555                            );
556                            snap_measured_size_to_device_pixels(measured_size, scale_factor).into()
557                        },
558                    )
559                },
560            )
561            .expect(EXPECT_MESSAGE);
562    }
563
564    // Pixel snapping
565    //
566    // Painting primitives at non-integer pixel coordinates produces blurry
567    // output. Pixel snapping converts layout coordinates into integer
568    // device-pixel coordinates so painted edges land exactly on physical
569    // pixel boundaries.
570    //
571    // Non-integer coordinates can arise for several reasons, including:
572    //   - flex distribution, percentages, centering, and text measurement
573    //     can produce fractional element sizes and positions;
574    //   - at fractional scale factors (for example 125% or 150%), integer
575    //     logical-pixel values can map to non-integer device-pixel values.
576    //
577    // We pixel-snap by rounding in device-pixel space, after multiplying
578    // by `scale_factor`, so that snapping targets physical pixels. Bounds
579    // are divided by `scale_factor` before being returned to GPUI.
580    //
581    // Midpoints are rounded toward zero. This is a stylistic choice: a
582    // 1-logical-pixel line at 150% scale should render as 1 dp rather than
583    // 2 dp.
584    //
585    // Pixel snapping is done in two phases:
586    //
587    //  1. Pre-layout metric snapping. Before Taffy computes layout, all
588    //     authored absolute lengths are rounded in `to_taffy`. This
589    //     includes borders, padding, gaps, and explicit sizes.
590    //     Custom-measured leaf nodes have their measured sizes rounded up
591    //     to integer device-pixel lengths.
592    //
593    //  2. Post-layout edge snapping. After Taffy resolves the tree, layout
594    //     relationships such as flex shares, grid tracks, percentages, and
595    //     centering can produce new fractional edge positions. Boxes now
596    //     have edges in absolute coordinates, and snapping must decide
597    //     where those edges land on the device-pixel grid.
598    //
599    // Ideally, post-layout snapping would satisfy:
600    //
601    //  - Edge closure. Two raw layout edges at the same absolute position
602    //    should snap to the same pixel column.
603    //  - Translation stability. A component's internal geometry should not
604    //    change when it moves to a new absolute position.
605    //
606    // These goals are in tension because rounding is not associative.
607    // The simple local schemes make different tradeoffs:
608    //
609    //  - Absolute edge rounding gives each window coordinate one answer,
610    //    so coincident edges always close globally. But a span's snapped
611    //    length is `round(far) - round(near)`, which may change by 1 dp
612    //    as its absolute origin moves.
613    //
614    //  - Parent-relative edge rounding rounds each child inside its
615    //    parent's coordinate space. This guarantees translation stability,
616    //    but a shared edge reached through different parents can
617    //    accumulate different rounding, causing non-closure between
618    //    cousins.
619    //
620    //  - Length rounding rounds each width, height, and thickness
621    //    independently and then places boxes from those rounded lengths.
622    //    Sizes stay stable under translation, but neighboring boxes derive
623    //    their shared boundary from different sources, so closure is not
624    //    guaranteed.
625    //
626    // We apply absolute edge rounding for each element's outer box in
627    // post-layout rounding to preserve closure. Border and padding widths
628    // are not touched by post-layout rounding; they keep their pre-layout
629    // rounded value so that they remain stable under translation.
630    //
631    // This gives both closure and translation stability in the case that
632    // all local metrics are integer device-pixel lengths. Pre-layout
633    // rounding covers that in most cases. The exception is metrics
634    // resolved by layout relationships, such as percentages. Outer box
635    // edges will still close globally, and painted border widths are still
636    // snapped independently, but the raw content-box origin can carry a
637    // 1dp residual into descendants.
638
639    pub fn layout_bounds(&mut self, id: LayoutId, scale_factor: f32) -> Bounds<Pixels> {
640        if let Some(layout) = self.absolute_layout_bounds.get(&id).cloned() {
641            return layout;
642        }
643
644        let layout = self.taffy.layout(id.into()).expect(EXPECT_MESSAGE);
645        let layout_location = layout.location;
646        let layout_size = layout.size;
647        let parent = self.taffy.parent(id.0);
648
649        let absolute_outer_origin = match parent {
650            Some(parent_id) => {
651                let parent_id = LayoutId::from(parent_id);
652                self.layout_bounds(parent_id, scale_factor);
653                let parent_origin = *self
654                    .absolute_outer_origins
655                    .get(&parent_id)
656                    .expect("parent absolute outer origin should be cached");
657                parent_origin + Point::from(layout_location)
658            }
659            None => Point::from(layout_location),
660        };
661        self.absolute_outer_origins
662            .insert(id, absolute_outer_origin);
663
664        let absolute_far = absolute_outer_origin + Point::from(Size::from(layout_size));
665        let snapped_bounds = Bounds::from_corners(
666            absolute_outer_origin.map(round_half_toward_zero),
667            absolute_far.map(round_half_toward_zero),
668        );
669
670        let bounds = (snapped_bounds / scale_factor).map(Pixels);
671        self.absolute_layout_bounds.insert(id, bounds);
672        bounds
673    }
674}
675
676impl LayoutCache {
677    fn evict_unrequested(
678        &mut self,
679        taffy: &mut TaffyTree,
680        contexts: &mut SecondaryMap<DefaultKey, NodeContext>,
681    ) {
682        for id in self.free_nodes.drain(..) {
683            self.nodes.remove(node_key(id));
684            taffy.remove(id).expect(EXPECT_MESSAGE);
685        }
686
687        let free_nodes = &mut self.free_nodes;
688        self.scopes.retain(|_, scope| {
689            let requested = std::mem::take(&mut scope.requested);
690            free_nodes.extend(scope.nodes.drain(requested..));
691            requested > 0
692        });
693
694        // Every node an element requested this frame had its children set to nodes also
695        // requested this frame, so an unrequested node's parent is unrequested too (or it
696        // has none). Clearing their children therefore detaches all of them without
697        // touching the live tree. Measure functions can hold on to anything, so they're
698        // dropped now rather than when the node is reused or removed.
699        for &id in &self.free_nodes {
700            contexts.remove(node_key(id));
701            if taffy.child_count(id) > 0 {
702                taffy.set_children(id, &[]).expect(EXPECT_MESSAGE);
703            }
704        }
705        debug_assert!(self.free_nodes.iter().all(|&id| taffy.parent(id).is_none()));
706        self.frame += 1;
707    }
708}
709
710/// A unique identifier for a layout node, generated when requesting a layout from Taffy
711#[derive(Copy, Clone, Eq, PartialEq, Debug)]
712#[repr(transparent)]
713pub struct LayoutId(NodeId);
714
715impl LayoutId {
716    fn to_taffy_slice(node_ids: &[Self]) -> &[taffy::NodeId] {
717        // SAFETY: LayoutId is repr(transparent) to taffy::tree::NodeId.
718        unsafe { std::mem::transmute::<&[LayoutId], &[taffy::NodeId]>(node_ids) }
719    }
720}
721
722impl std::hash::Hash for LayoutId {
723    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
724        u64::from(self.0).hash(state);
725    }
726}
727
728impl From<NodeId> for LayoutId {
729    fn from(node_id: NodeId) -> Self {
730        Self(node_id)
731    }
732}
733
734impl From<LayoutId> for NodeId {
735    fn from(layout_id: LayoutId) -> NodeId {
736        layout_id.0
737    }
738}
739
740fn snap_measured_size_to_device_pixels(size: Size<Pixels>, scale_factor: f32) -> Size<f32> {
741    size.map(|d| ceil_to_device_pixel(d.0.max(0.0), scale_factor))
742}
743
744fn border_widths_to_taffy(
745    widths: &Edges<AbsoluteLength>,
746    rem_size: Pixels,
747    scale_factor: f32,
748) -> TaffyRect<taffy::style::LengthPercentage> {
749    let snap = |w: &AbsoluteLength| {
750        taffy::style::LengthPercentage::length(round_stroke_to_device_pixel(
751            w.to_pixels(rem_size).0,
752            scale_factor,
753        ))
754    };
755    TaffyRect {
756        top: snap(&widths.top),
757        right: snap(&widths.right),
758        bottom: snap(&widths.bottom),
759        left: snap(&widths.left),
760    }
761}
762
763trait ToTaffy<Output> {
764    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> Output;
765}
766
767// Conversion reads the copied fields, not `Style`, so a field can't affect layout
768// without also being compared to decide whether to convert again.
769macro_rules! layout_style {
770    ($($field:ident: $field_type:ty),* $(,)?) => {
771        /// The fields of a [`Style`] that affect layout, and what their lengths are
772        /// resolved against.
773        #[derive(Clone, Debug)]
774        struct LayoutStyle {
775            rem_size: Pixels,
776            scale_factor: f32,
777            $($field: $field_type,)*
778        }
779
780        impl LayoutStyle {
781            fn new(style: &Style, rem_size: Pixels, scale_factor: f32) -> Self {
782                Self {
783                    rem_size,
784                    scale_factor,
785                    $($field: Clone::clone(&style.$field),)*
786                }
787            }
788
789            fn matches(&self, style: &Style, rem_size: Pixels, scale_factor: f32) -> bool {
790                self.rem_size == rem_size
791                    && self.scale_factor == scale_factor
792                    $(&& self.$field == style.$field)*
793            }
794        }
795    };
796}
797
798layout_style! {
799    display: crate::Display,
800    overflow: Point<crate::Overflow>,
801    scrollbar_width: AbsoluteLength,
802    position: crate::Position,
803    inset: Edges<Length>,
804    size: Size<Length>,
805    min_size: Size<Length>,
806    max_size: Size<Length>,
807    aspect_ratio: Option<f32>,
808    margin: Edges<Length>,
809    padding: Edges<DefiniteLength>,
810    border_widths: Edges<AbsoluteLength>,
811    align_items: Option<crate::AlignItems>,
812    align_self: Option<crate::AlignSelf>,
813    align_content: Option<crate::AlignContent>,
814    justify_content: Option<crate::JustifyContent>,
815    gap: Size<DefiniteLength>,
816    flex_direction: crate::FlexDirection,
817    flex_wrap: crate::FlexWrap,
818    flex_basis: Length,
819    flex_grow: f32,
820    flex_shrink: f32,
821    grid_rows: Option<GridTemplate>,
822    grid_cols: Option<GridTemplate>,
823    grid_location: Option<crate::GridLocation>,
824}
825
826impl LayoutStyle {
827    fn to_taffy(&self) -> taffy::style::Style {
828        use taffy::style_helpers::{fr, length, minmax, repeat};
829
830        let rem_size = self.rem_size;
831        let scale_factor = self.scale_factor;
832
833        fn to_grid_line(
834            placement: &Range<crate::GridPlacement>,
835        ) -> taffy::Line<taffy::GridPlacement> {
836            taffy::Line {
837                start: placement.start.into(),
838                end: placement.end.into(),
839            }
840        }
841
842        fn to_grid_repeat<T: taffy::style::CheapCloneStr>(
843            unit: &Option<GridTemplate>,
844        ) -> Vec<taffy::GridTemplateComponent<T>> {
845            unit.map(|template| {
846                match template.min_size {
847                    // grid-template-*: repeat(<number>, minmax(0, 1fr));
848                    crate::GridTemplateMinSize::Zero => {
849                        vec![repeat(
850                            template.repeat,
851                            vec![minmax(length(0.0_f32), fr(1.0_f32))],
852                        )]
853                    }
854                    // grid-template-*: repeat(<number>, minmax(min-content, 1fr));
855                    crate::GridTemplateMinSize::MinContent => {
856                        vec![repeat(
857                            template.repeat,
858                            vec![minmax(min_content(), fr(1.0_f32))],
859                        )]
860                    }
861                    // grid-template-*: repeat(<number>, minmax(0, max-content))
862                    crate::GridTemplateMinSize::MaxContent => {
863                        vec![repeat(
864                            template.repeat,
865                            vec![minmax(length(0.0_f32), max_content())],
866                        )]
867                    }
868                }
869            })
870            .unwrap_or_default()
871        }
872
873        taffy::style::Style {
874            display: self.display.into(),
875            overflow: self.overflow.into(),
876            scrollbar_width: self.scrollbar_width.to_taffy(rem_size, scale_factor),
877            position: self.position.into(),
878            inset: self.inset.to_taffy(rem_size, scale_factor),
879            size: self.size.to_taffy(rem_size, scale_factor),
880            min_size: self.min_size.to_taffy(rem_size, scale_factor),
881            max_size: self.max_size.to_taffy(rem_size, scale_factor),
882            aspect_ratio: self.aspect_ratio,
883            margin: self.margin.to_taffy(rem_size, scale_factor),
884            padding: self.padding.to_taffy(rem_size, scale_factor),
885            border: border_widths_to_taffy(&self.border_widths, rem_size, scale_factor),
886            align_items: self.align_items.map(Into::into).unwrap_or_default(),
887            align_self: self.align_self.map(|x| x.into()),
888            align_content: self.align_content.map(Into::into).unwrap_or_default(),
889            justify_content: self.justify_content.map(Into::into).unwrap_or_default(),
890            gap: self.gap.to_taffy(rem_size, scale_factor),
891            flex_direction: self.flex_direction.into(),
892            flex_wrap: self.flex_wrap.into(),
893            flex_basis: self.flex_basis.to_taffy(rem_size, scale_factor),
894            flex_grow: self.flex_grow,
895            flex_shrink: self.flex_shrink,
896            grid_template_rows: to_grid_repeat(&self.grid_rows),
897            grid_template_columns: to_grid_repeat(&self.grid_cols),
898            grid_row: self
899                .grid_location
900                .as_ref()
901                .map(|location| to_grid_line(&location.row))
902                .unwrap_or_default(),
903            grid_column: self
904                .grid_location
905                .as_ref()
906                .map(|location| to_grid_line(&location.column))
907                .unwrap_or_default(),
908            ..Default::default()
909        }
910    }
911}
912
913impl ToTaffy<f32> for AbsoluteLength {
914    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> f32 {
915        round_to_device_pixel(self.to_pixels(rem_size).0, scale_factor)
916    }
917}
918
919impl ToTaffy<taffy::style::LengthPercentageAuto> for Length {
920    fn to_taffy(
921        &self,
922        rem_size: Pixels,
923        scale_factor: f32,
924    ) -> taffy::prelude::LengthPercentageAuto {
925        match self {
926            Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
927            Length::Auto => taffy::prelude::LengthPercentageAuto::auto(),
928        }
929    }
930}
931
932impl ToTaffy<taffy::style::Dimension> for Length {
933    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::prelude::Dimension {
934        match self {
935            Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
936            Length::Auto => taffy::prelude::Dimension::auto(),
937        }
938    }
939}
940
941impl ToTaffy<taffy::style::LengthPercentage> for DefiniteLength {
942    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
943        match self {
944            DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
945            DefiniteLength::Fraction(fraction) => {
946                taffy::style::LengthPercentage::percent(*fraction)
947            }
948        }
949    }
950}
951
952impl ToTaffy<taffy::style::LengthPercentageAuto> for DefiniteLength {
953    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
954        match self {
955            DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
956            DefiniteLength::Fraction(fraction) => {
957                taffy::style::LengthPercentageAuto::percent(*fraction)
958            }
959        }
960    }
961}
962
963impl ToTaffy<taffy::style::Dimension> for DefiniteLength {
964    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
965        match self {
966            DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
967            DefiniteLength::Fraction(fraction) => taffy::style::Dimension::percent(*fraction),
968        }
969    }
970}
971
972impl ToTaffy<taffy::style::LengthPercentage> for AbsoluteLength {
973    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
974        taffy::style::LengthPercentage::length(self.to_taffy(rem_size, scale_factor))
975    }
976}
977
978impl ToTaffy<taffy::style::LengthPercentageAuto> for AbsoluteLength {
979    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
980        taffy::style::LengthPercentageAuto::length(self.to_taffy(rem_size, scale_factor))
981    }
982}
983
984impl ToTaffy<taffy::style::Dimension> for AbsoluteLength {
985    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
986        taffy::style::Dimension::length(self.to_taffy(rem_size, scale_factor))
987    }
988}
989
990impl<T, T2> From<TaffyPoint<T>> for Point<T2>
991where
992    T: Into<T2>,
993    T2: Clone + Debug + Default + PartialEq,
994{
995    fn from(point: TaffyPoint<T>) -> Point<T2> {
996        Point {
997            x: point.x.into(),
998            y: point.y.into(),
999        }
1000    }
1001}
1002
1003impl<T, T2> From<Point<T>> for TaffyPoint<T2>
1004where
1005    T: Into<T2> + Clone + Debug + Default + PartialEq,
1006{
1007    fn from(val: Point<T>) -> Self {
1008        TaffyPoint {
1009            x: val.x.into(),
1010            y: val.y.into(),
1011        }
1012    }
1013}
1014
1015impl<T, U> ToTaffy<TaffySize<U>> for Size<T>
1016where
1017    T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
1018{
1019    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffySize<U> {
1020        TaffySize {
1021            width: self.width.to_taffy(rem_size, scale_factor),
1022            height: self.height.to_taffy(rem_size, scale_factor),
1023        }
1024    }
1025}
1026
1027impl<T, U> ToTaffy<TaffyRect<U>> for Edges<T>
1028where
1029    T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
1030{
1031    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffyRect<U> {
1032        TaffyRect {
1033            top: self.top.to_taffy(rem_size, scale_factor),
1034            right: self.right.to_taffy(rem_size, scale_factor),
1035            bottom: self.bottom.to_taffy(rem_size, scale_factor),
1036            left: self.left.to_taffy(rem_size, scale_factor),
1037        }
1038    }
1039}
1040
1041impl<T, U> From<TaffySize<T>> for Size<U>
1042where
1043    T: Into<U>,
1044    U: Clone + Debug + Default + PartialEq,
1045{
1046    fn from(taffy_size: TaffySize<T>) -> Self {
1047        Size {
1048            width: taffy_size.width.into(),
1049            height: taffy_size.height.into(),
1050        }
1051    }
1052}
1053
1054impl<T, U> From<Size<T>> for TaffySize<U>
1055where
1056    T: Into<U> + Clone + Debug + Default + PartialEq,
1057{
1058    fn from(size: Size<T>) -> Self {
1059        TaffySize {
1060            width: size.width.into(),
1061            height: size.height.into(),
1062        }
1063    }
1064}
1065
1066/// The space available for an element to be laid out in
1067#[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
1068pub enum AvailableSpace {
1069    /// The amount of space available is the specified number of pixels
1070    Definite(Pixels),
1071    /// The amount of space available is indefinite and the node should be laid out under a min-content constraint
1072    #[default]
1073    MinContent,
1074    /// The amount of space available is indefinite and the node should be laid out under a max-content constraint
1075    MaxContent,
1076}
1077
1078impl AvailableSpace {
1079    /// Returns a `Size` with both width and height set to `AvailableSpace::MinContent`.
1080    ///
1081    /// This function is useful when you want to create a `Size` with the minimum content constraints
1082    /// for both dimensions.
1083    ///
1084    /// # Examples
1085    ///
1086    /// ```
1087    /// use gpui::AvailableSpace;
1088    /// let min_content_size = AvailableSpace::min_size();
1089    /// assert_eq!(min_content_size.width, AvailableSpace::MinContent);
1090    /// assert_eq!(min_content_size.height, AvailableSpace::MinContent);
1091    /// ```
1092    pub const fn min_size() -> Size<Self> {
1093        Size {
1094            width: Self::MinContent,
1095            height: Self::MinContent,
1096        }
1097    }
1098}
1099
1100impl From<AvailableSpace> for TaffyAvailableSpace {
1101    fn from(space: AvailableSpace) -> TaffyAvailableSpace {
1102        match space {
1103            AvailableSpace::Definite(Pixels(value)) => TaffyAvailableSpace::Definite(value),
1104            AvailableSpace::MinContent => TaffyAvailableSpace::MinContent,
1105            AvailableSpace::MaxContent => TaffyAvailableSpace::MaxContent,
1106        }
1107    }
1108}
1109
1110impl From<TaffyAvailableSpace> for AvailableSpace {
1111    fn from(space: TaffyAvailableSpace) -> AvailableSpace {
1112        match space {
1113            TaffyAvailableSpace::Definite(value) => AvailableSpace::Definite(Pixels(value)),
1114            TaffyAvailableSpace::MinContent => AvailableSpace::MinContent,
1115            TaffyAvailableSpace::MaxContent => AvailableSpace::MaxContent,
1116        }
1117    }
1118}
1119
1120impl From<Pixels> for AvailableSpace {
1121    fn from(pixels: Pixels) -> Self {
1122        AvailableSpace::Definite(pixels)
1123    }
1124}
1125
1126impl From<Size<Pixels>> for Size<AvailableSpace> {
1127    fn from(size: Size<Pixels>) -> Self {
1128        Size {
1129            width: AvailableSpace::Definite(size.width),
1130            height: AvailableSpace::Definite(size.height),
1131        }
1132    }
1133}
1134
1135#[cfg(test)]
1136mod tests {
1137    use super::*;
1138    use crate::{
1139        AnyElement, AnyWindowHandle, AppContext as _, Context, Element, ElementId, GlobalElementId,
1140        InspectorElementId, InteractiveElement as _, IntoElement, ParentElement as _, Render,
1141        Styled as _, TestAppContext, div, px,
1142        randomized_element_tree::{RandomizedElementTree, RandomizedElementTreeConfig},
1143        rems,
1144    };
1145    use std::{cell::Cell, rc::Rc};
1146
1147    type Frame = Box<dyn Fn(&mut Window) -> AnyElement>;
1148
1149    struct FrameView {
1150        frame: Rc<Cell<usize>>,
1151        frames: Rc<Vec<Frame>>,
1152    }
1153
1154    impl Render for FrameView {
1155        fn render(&mut self, window: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1156            (self.frames[self.frame.get()])(window)
1157        }
1158    }
1159
1160    /// Draws each frame in a window that keeps its layout nodes and in one that rebuilds
1161    /// them, checking that every element with a debug selector has the same bounds in
1162    /// both.
1163    fn assert_frames_match_uncached(cx: &mut TestAppContext, frames: Vec<Frame>) {
1164        assert_frames_match_uncached_with(cx, frames, |_| {}, |_| ());
1165    }
1166
1167    /// Like [`assert_frames_match_uncached`], running `before_cached` before and
1168    /// `after_cached` after each cached frame draw and returning the observations.
1169    fn assert_frames_match_uncached_with<T>(
1170        cx: &mut TestAppContext,
1171        frames: Vec<Frame>,
1172        mut before_cached: impl FnMut(&Window),
1173        mut after_cached: impl FnMut(&Window) -> T,
1174    ) -> Vec<T> {
1175        let frames = Rc::new(frames);
1176        let frame = Rc::new(Cell::new(0));
1177        let windows = [false, true].map(|rebuild| {
1178            let frames = frames.clone();
1179            let frame = frame.clone();
1180            let window = cx.open_window(size(px(800.), px(600.)), move |_, _| FrameView {
1181                frame,
1182                frames,
1183            });
1184            (AnyWindowHandle::from(window), rebuild)
1185        });
1186        let mut observations = Vec::new();
1187        for index in 0..frames.len() {
1188            frame.set(index);
1189            let [cached, uncached] = windows.map(|(window, rebuild)| {
1190                cx.update_window(window, |_, window, cx| {
1191                    if rebuild {
1192                        window.clear_layout_cache();
1193                    } else {
1194                        before_cached(window);
1195                    }
1196                    window.refresh();
1197                    window.draw(cx).clear(cx);
1198                    let observation = (!rebuild).then(|| after_cached(window));
1199                    let mut bounds = window
1200                        .rendered_frame
1201                        .debug_bounds
1202                        .iter()
1203                        .map(|(selector, bounds)| (selector.clone(), *bounds))
1204                        .collect::<Vec<_>>();
1205                    bounds.sort_by(|a, b| a.0.cmp(&b.0));
1206                    (bounds, observation)
1207                })
1208                .expect("window should remain open")
1209            });
1210            assert!(
1211                !uncached.0.is_empty(),
1212                "frame {index} has no debug selectors"
1213            );
1214            assert_eq!(cached.0, uncached.0, "frame {index}");
1215            observations.push(cached.1.expect("cached window observation"));
1216        }
1217        observations
1218    }
1219
1220    fn frame(render: impl Fn(&mut Window) -> AnyElement + 'static) -> Frame {
1221        Box::new(render)
1222    }
1223
1224    /// A leaf whose size comes from its measure function, which captures it and is keyed
1225    /// by it.
1226    struct MeasuredLeaf {
1227        size: Size<Pixels>,
1228        measurements: Option<Rc<Cell<usize>>>,
1229    }
1230
1231    impl MeasuredLeaf {
1232        fn new(size: Size<Pixels>) -> Self {
1233            Self {
1234                size,
1235                measurements: None,
1236            }
1237        }
1238
1239        fn with_counter(size: Size<Pixels>, measurements: Rc<Cell<usize>>) -> Self {
1240            Self {
1241                size,
1242                measurements: Some(measurements),
1243            }
1244        }
1245    }
1246
1247    impl Element for MeasuredLeaf {
1248        type RequestLayoutState = ();
1249        type PrepaintState = ();
1250
1251        fn id(&self) -> Option<ElementId> {
1252            None
1253        }
1254
1255        fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
1256            None
1257        }
1258
1259        fn request_layout(
1260            &mut self,
1261            _: Option<&GlobalElementId>,
1262            _: Option<&InspectorElementId>,
1263            window: &mut Window,
1264            _: &mut App,
1265        ) -> (LayoutId, ()) {
1266            let measured = self.size;
1267            let measurements = self.measurements.clone();
1268            let layout_id = window.request_keyed_measured_layout(
1269                Style::default(),
1270                measured,
1271                move |_, _, _, _| {
1272                    if let Some(measurements) = &measurements {
1273                        measurements.set(measurements.get() + 1);
1274                    }
1275                    measured
1276                },
1277            );
1278            (layout_id, ())
1279        }
1280
1281        fn prepaint(
1282            &mut self,
1283            _: Option<&GlobalElementId>,
1284            _: Option<&InspectorElementId>,
1285            _: Bounds<Pixels>,
1286            _: &mut (),
1287            _: &mut Window,
1288            _: &mut App,
1289        ) {
1290        }
1291
1292        fn paint(
1293            &mut self,
1294            _: Option<&GlobalElementId>,
1295            _: Option<&InspectorElementId>,
1296            _: Bounds<Pixels>,
1297            _: &mut (),
1298            _: &mut (),
1299            _: &mut Window,
1300            _: &mut App,
1301        ) {
1302        }
1303    }
1304
1305    #[crate::test]
1306    fn stretched_root_style_is_restored_when_its_node_is_reused(cx: &mut TestAppContext) {
1307        // Elements without IDs are matched by request order, and children request first,
1308        // so the second frame's child reuses the first frame's root node.
1309        assert_frames_match_uncached(
1310            cx,
1311            vec![
1312                frame(|_| div().debug_selector(|| "root".into()).into_any_element()),
1313                frame(|_| {
1314                    div()
1315                        .size(px(100.))
1316                        .child(div().debug_selector(|| "child".into()))
1317                        .into_any_element()
1318                }),
1319            ],
1320        );
1321    }
1322
1323    #[crate::test]
1324    fn root_is_detached_from_a_parent_no_longer_requested(cx: &mut TestAppContext) {
1325        // The second frame's root reuses the first frame's innermost node, whose parent
1326        // sat inside padding.
1327        assert_frames_match_uncached(
1328            cx,
1329            vec![
1330                frame(|_| {
1331                    div()
1332                        .p(px(10.))
1333                        .child(
1334                            div()
1335                                .p(px(7.))
1336                                .child(div().size(px(5.)).debug_selector(|| "leaf".into())),
1337                        )
1338                        .into_any_element()
1339                }),
1340                frame(|_| {
1341                    div()
1342                        .size(px(50.))
1343                        .debug_selector(|| "root".into())
1344                        .into_any_element()
1345                }),
1346            ],
1347        );
1348    }
1349
1350    #[crate::test]
1351    fn hidden_element_is_laid_out_again_when_shown(cx: &mut TestAppContext) {
1352        let with_child_shown = |shown: bool| {
1353            frame(move |_| {
1354                let mut child = div().size(px(20.)).debug_selector(|| "child".into());
1355                if !shown {
1356                    child.style().display = Some(crate::Display::None);
1357                }
1358                div()
1359                    .flex()
1360                    .child(div().debug_selector(|| "wrapper".into()).child(child))
1361                    .into_any_element()
1362            })
1363        };
1364        assert_frames_match_uncached(
1365            cx,
1366            vec![
1367                with_child_shown(false),
1368                with_child_shown(false),
1369                with_child_shown(true),
1370                with_child_shown(false),
1371                with_child_shown(true),
1372            ],
1373        );
1374    }
1375
1376    #[crate::test]
1377    fn measured_leaf_is_measured_again_only_when_its_key_changes(cx: &mut TestAppContext) {
1378        let counter = Rc::new(Cell::new(0));
1379        let measured = |width: f32, height: f32| {
1380            let counter = counter.clone();
1381            frame(move |_| {
1382                div()
1383                    .flex()
1384                    .child(div().debug_selector(|| "wrapper".into()).child(
1385                        MeasuredLeaf::with_counter(size(px(width), px(height)), counter.clone()),
1386                    ))
1387                    .into_any_element()
1388            })
1389        };
1390        let measurements = assert_frames_match_uncached_with(
1391            cx,
1392            vec![
1393                measured(10., 10.),
1394                measured(10., 10.),
1395                measured(30., 20.),
1396                measured(30., 20.),
1397                measured(5., 40.),
1398            ],
1399            |_| counter.set(0),
1400            |_| counter.get(),
1401        );
1402        // Opening the window draws the first frame, so drawing it again measures nothing.
1403        let measured = measurements
1404            .iter()
1405            .map(|count| *count > 0)
1406            .collect::<Vec<_>>();
1407        assert_eq!(
1408            measured,
1409            [false, false, true, false, true],
1410            "measurements per frame: {measurements:?}"
1411        );
1412    }
1413
1414    #[crate::test]
1415    fn rem_size_changes_resolve_lengths_again(cx: &mut TestAppContext) {
1416        let with_rem_size = |rem_size: f32| {
1417            frame(move |window| {
1418                window.set_rem_size(px(rem_size));
1419                div()
1420                    .flex()
1421                    .child(
1422                        div()
1423                            .w(rems(2.5))
1424                            .h(rems(1.25))
1425                            .debug_selector(|| "sized".into()),
1426                    )
1427                    .into_any_element()
1428            })
1429        };
1430        assert_frames_match_uncached(
1431            cx,
1432            vec![with_rem_size(16.), with_rem_size(13.), with_rem_size(13.)],
1433        );
1434    }
1435
1436    #[crate::test]
1437    fn element_ids_reused_by_different_elements(cx: &mut TestAppContext) {
1438        // One ID names a measured leaf, then nothing, then a container whose children
1439        // have no IDs, then a measured leaf again.
1440        let leaf = || {
1441            frame(|_| {
1442                div()
1443                    .flex()
1444                    .child(
1445                        div()
1446                            .id("reused")
1447                            .debug_selector(|| "reused".into())
1448                            .child(MeasuredLeaf::new(size(px(12.), px(9.)))),
1449                    )
1450                    .into_any_element()
1451            })
1452        };
1453        assert_frames_match_uncached(
1454            cx,
1455            vec![
1456                leaf(),
1457                frame(|_| {
1458                    div()
1459                        .flex()
1460                        .child(div().size(px(3.)).debug_selector(|| "other".into()))
1461                        .into_any_element()
1462                }),
1463                frame(|_| {
1464                    div()
1465                        .flex()
1466                        .child(
1467                            div()
1468                                .id("reused")
1469                                .flex_col()
1470                                .p(px(4.))
1471                                .debug_selector(|| "reused".into())
1472                                .child(div().size(px(20.)))
1473                                .child(div().size(px(8.)).debug_selector(|| "inner".into())),
1474                        )
1475                        .into_any_element()
1476                }),
1477                leaf(),
1478            ],
1479        );
1480    }
1481
1482    #[crate::test]
1483    fn text_is_measured_again_only_when_it_changes(cx: &mut TestAppContext) {
1484        let text = |width: f32, text: &'static str, font_size: f32| {
1485            frame(move |_| {
1486                div()
1487                    .flex()
1488                    .child(
1489                        div()
1490                            .w(px(width))
1491                            .text_size(px(font_size))
1492                            .debug_selector(|| "wrapper".into())
1493                            .child(text),
1494                    )
1495                    .child(div().size(px(10.)).debug_selector(|| "sibling".into()))
1496                    .into_any_element()
1497            })
1498        };
1499        let short = "Some text";
1500        let same_length = "Same text";
1501        let long = "Some longer text that wraps in narrow parents";
1502        // Opening the window draws the first frame, so drawing it again measures nothing.
1503        let frames = [
1504            (text(200., short, 14.), false),
1505            (text(200., short, 14.), false),
1506            (text(200., same_length, 14.), true),
1507            (text(200., long, 14.), true),
1508            (text(200., long, 14.), false),
1509            (text(60., long, 14.), true),
1510            (text(60., long, 18.), true),
1511            (text(60., long, 18.), false),
1512            (text(200., long, 14.), true),
1513        ];
1514        let expected = frames
1515            .iter()
1516            .map(|(_, measured)| *measured)
1517            .collect::<Vec<_>>();
1518        let measurements = assert_frames_match_uncached_with(
1519            cx,
1520            frames.into_iter().map(|(frame, _)| frame).collect(),
1521            |_| {},
1522            |window| window.text_system().last_frame_wrapped_line_count(),
1523        );
1524        let measured = measurements
1525            .iter()
1526            .map(|count| *count > 0)
1527            .collect::<Vec<_>>();
1528        assert_eq!(
1529            measured, expected,
1530            "text measurements per frame: {measurements:?}"
1531        );
1532    }
1533
1534    #[crate::test]
1535    fn measured_leaf_updates_when_scale_factor_changes(cx: &mut TestAppContext) {
1536        let at_scale = |scale_factor: f32| {
1537            frame(move |window| {
1538                window.set_scale_factor(scale_factor);
1539                div()
1540                    .flex()
1541                    .child(
1542                        div()
1543                            .debug_selector(|| "wrapper".into())
1544                            .child(MeasuredLeaf::new(size(px(100.), px(40.)))),
1545                    )
1546                    .into_any_element()
1547            })
1548        };
1549        assert_frames_match_uncached(cx, vec![at_scale(1.0), at_scale(2.0), at_scale(1.0)]);
1550    }
1551
1552    #[crate::test]
1553    fn text_is_measured_again_when_fonts_are_added(cx: &mut TestAppContext) {
1554        let with_text = || {
1555            frame(|_| {
1556                div()
1557                    .flex()
1558                    .child(
1559                        div()
1560                            .w(px(200.))
1561                            .debug_selector(|| "wrapper".into())
1562                            .child("Some text"),
1563                    )
1564                    .into_any_element()
1565            })
1566        };
1567        let mut frame_index = 0;
1568        let measurements = assert_frames_match_uncached_with(
1569            cx,
1570            vec![with_text(), with_text(), with_text()],
1571            |window| {
1572                if frame_index == 1 {
1573                    window
1574                        .text_system()
1575                        .add_fonts(Vec::new())
1576                        .expect("noop text system accepts empty font list");
1577                }
1578                frame_index += 1;
1579            },
1580            |window| window.text_system().last_frame_wrapped_line_count(),
1581        );
1582        let measured = measurements
1583            .iter()
1584            .map(|count| *count > 0)
1585            .collect::<Vec<_>>();
1586        assert_eq!(
1587            measured,
1588            [false, true, false],
1589            "text measurements per frame: {measurements:?}"
1590        );
1591    }
1592
1593    #[crate::test]
1594    fn evicted_nodes_do_not_accumulate_when_ids_change_every_frame(cx: &mut TestAppContext) {
1595        let window = cx.open_window(size(px(800.), px(600.)), |_, cx| {
1596            RandomizedElementTree::new_with_config(RandomizedElementTreeConfig::new(3, 64), cx)
1597        });
1598        let root = window.root(cx).expect("window should have a root");
1599        let mut node_counts = Vec::new();
1600        for _ in 0..20 {
1601            root.update(cx, |tree, cx| tree.churn_element_ids(cx));
1602            let node_count = cx
1603                .update_window(window.into(), |_, window, cx| {
1604                    window.draw(cx).clear(cx);
1605                    window.layout_node_count()
1606                })
1607                .expect("window should remain open");
1608            node_counts.push(node_count);
1609        }
1610        // Each frame's evicted nodes are kept for the next frame to reuse, and every node
1611        // a frame doesn't reuse is removed, so the tree stays the size of one frame.
1612        assert!(
1613            node_counts.windows(2).all(|pair| pair[0] == pair[1]),
1614            "{node_counts:?}"
1615        );
1616    }
1617
1618    #[test]
1619    fn border_widths_to_taffy_use_stroke_snapping() {
1620        let border_widths = Edges {
1621            top: Pixels(0.0).into(),
1622            right: Pixels(0.4).into(),
1623            bottom: Pixels(0.5).into(),
1624            left: Pixels(1.6).into(),
1625        };
1626        let taffy_border = border_widths_to_taffy(&border_widths, Pixels(16.0), 1.0);
1627
1628        assert_eq!(
1629            taffy_border.top,
1630            taffy::style::LengthPercentage::length(0.0)
1631        );
1632        assert_eq!(
1633            taffy_border.right,
1634            taffy::style::LengthPercentage::length(1.0)
1635        );
1636        assert_eq!(
1637            taffy_border.bottom,
1638            taffy::style::LengthPercentage::length(1.0)
1639        );
1640        assert_eq!(
1641            taffy_border.left,
1642            taffy::style::LengthPercentage::length(2.0)
1643        );
1644    }
1645}