Skip to main content

gpui/fast/
taffy.rs

1// Modified by Longbridge for gpui-fast.
2//! gpui-fast's `taffy.rs`, redirected from `gpui.rs` with
3//! `#[path = "fast/taffy.rs"]`; upstream's `crates/gpui/src/taffy.rs` stays as
4//! upstream has it, unused.
5//!
6//! Upstream keeps layout nodes between frames by element id path and keys
7//! measured leaves by what they depend on (zed#67222, zed#67223). gpui-fast
8//! has retained layout nodes of its own (`fast::layout`: layout keys, measure
9//! logs replayed before layout, carried text measurements), which every
10//! retained element, list row and scroll layer builds on, so this file keeps
11//! the engine forwarding to it and serves upstream's new entry points
12//! (`request_keyed_measure`, `clear_layout_cache`,
13//! `clear_if_scale_factor_changed`) from it. When syncing, port upstream's
14//! changes to `taffy.rs` outside its layout cache here by hand.
15
16use crate::{
17    AbsoluteLength, App, Bounds, DefiniteLength, Edges, GridTemplate, Length, Pixels, Point, Size,
18    Style, Window, size,
19    util::{
20        ceil_to_device_pixel, round_half_toward_zero, round_stroke_to_device_pixel,
21        round_to_device_pixel,
22    },
23};
24use collections::FxHashSet;
25use std::{fmt::Debug, ops::Range};
26use taffy::{
27    TaffyTree, TraversePartialTree as _,
28    geometry::{Point as TaffyPoint, Rect as TaffyRect, Size as TaffySize},
29    prelude::{max_content, min_content},
30    style::AvailableSpace as TaffyAvailableSpace,
31    tree::NodeId,
32};
33
34#[cfg(feature = "stacker")]
35pub(crate) type StackSafe<T> = stacksafe::StackSafe<T>;
36#[cfg(not(feature = "stacker"))]
37pub(crate) type StackSafe<T> = T;
38
39pub(crate) type MeasureFn =
40    dyn FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>;
41type NodeMeasureFn = StackSafe<Box<MeasureFn>>;
42
43pub(crate) struct NodeContext {
44    pub(crate) measure: NodeMeasureFn,
45}
46pub struct TaffyLayoutEngine {
47    pub(crate) taffy: TaffyTree<NodeContext>,
48    pub(crate) retention: crate::fast::layout::LayoutRetention,
49    pub(crate) absolute_layout_bounds: crate::fast::layout_bounds::LayoutIdMap<Bounds<Pixels>>,
50    /// Unrounded absolute border-box top-left per-node coordinate in device pixels.
51    pub(crate) absolute_outer_origins: crate::fast::layout_bounds::LayoutIdMap<Point<f32>>,
52    computed_layouts: FxHashSet<LayoutId>,
53    pub(crate) layout_bounds_scratch_space: Vec<LayoutId>,
54}
55
56const EXPECT_MESSAGE: &str = "we should avoid taffy layout errors by construction if possible";
57
58impl TaffyLayoutEngine {
59    pub fn new() -> Self {
60        let mut taffy = TaffyTree::new();
61        taffy.disable_rounding();
62        TaffyLayoutEngine {
63            taffy,
64            retention: crate::fast::layout::LayoutRetention::default(),
65            absolute_layout_bounds: crate::fast::layout_bounds::LayoutIdMap::default(),
66            absolute_outer_origins: crate::fast::layout_bounds::LayoutIdMap::default(),
67            computed_layouts: FxHashSet::default(),
68            layout_bounds_scratch_space: Vec::new(),
69        }
70    }
71
72    pub fn clear(&mut self) {
73        crate::fast::layout::release_unclaimed_nodes(self);
74        self.absolute_layout_bounds.clear();
75        self.absolute_outer_origins.clear();
76        self.computed_layouts.clear();
77    }
78
79    pub fn request_layout(
80        &mut self,
81        fast_key: Option<u64>,
82        style: &Style,
83        rem_size: Pixels,
84        scale_factor: f32,
85        children: &[LayoutId],
86    ) -> LayoutId {
87        crate::fast::layout::request_retained_layout(
88            self,
89            fast_key,
90            style,
91            rem_size,
92            scale_factor,
93            children,
94        )
95    }
96
97    /// Upstream's keyed measure (zed#67223), served by gpui-fast's retained
98    /// measured leaves: the node is the one retained under `fast_key`, and a
99    /// reused node's new closure is replayed against the constraints Taffy
100    /// measured it under, dirtying it only when a size changes (see
101    /// [`crate::fast::layout::request_retained_measured_layout`]). That
102    /// already keeps an unchanged measurement without comparing keys, so
103    /// `reuse` is not consulted, and every measurement is treated as final.
104    #[allow(clippy::too_many_arguments)]
105    pub(crate) fn request_keyed_measure<K, F>(
106        &mut self,
107        fast_key: Option<u64>,
108        style: &Style,
109        rem_size: Pixels,
110        scale_factor: f32,
111        key: K,
112        _reuse: fn(&mut K, &mut K) -> bool,
113        mut measure: F,
114    ) -> LayoutId
115    where
116        K: 'static,
117        F: FnMut(
118                &K,
119                Size<Option<Pixels>>,
120                Size<AvailableSpace>,
121                bool,
122                &mut Window,
123                &mut App,
124            ) -> Size<Pixels>
125            + 'static,
126    {
127        crate::fast::layout::request_retained_measured_layout(
128            self,
129            fast_key,
130            style,
131            rem_size,
132            scale_factor,
133            move |known_dimensions, available_space, window, cx| {
134                measure(&key, known_dimensions, available_space, true, window, cx)
135            },
136        )
137    }
138
139    /// Upstream drops its kept layout nodes when the scale factor changes
140    /// (zed#67222). gpui-fast's retained nodes are keyed by a fingerprint of
141    /// their style that includes the rem size and the scale factor, so a node
142    /// requested at a new scale factor is restyled and laid out again; there
143    /// is nothing to drop.
144    pub(crate) fn clear_layout_cache(&mut self) {}
145
146    /// See [`Self::clear_layout_cache`].
147    pub(crate) fn clear_if_scale_factor_changed(&mut self, _scale_factor: f32) {}
148
149    /// Treats any `auto` dimension of the given node's style as filling `size`.
150    ///
151    /// This is applied to window roots before layout so they behave like the
152    /// root element on the web, which stretches to fill the initial containing
153    /// block (the viewport) unless given an explicit size. Explicitly styled
154    /// dimensions are preserved.
155    pub fn stretch_auto_size_to_fill(
156        &mut self,
157        id: LayoutId,
158        size: Size<Pixels>,
159        scale_factor: f32,
160    ) {
161        crate::fast::layout::stretch_retained_auto_size_to_fill(self, id, size, scale_factor);
162    }
163
164    // Used to understand performance
165    #[allow(dead_code)]
166    fn count_all_children(&self, parent: LayoutId) -> anyhow::Result<u32> {
167        let mut count = 0;
168
169        for child in self.taffy.children(parent.0)? {
170            // Count this child.
171            count += 1;
172
173            // Count all of this child's children.
174            count += self.count_all_children(LayoutId(child))?
175        }
176
177        Ok(count)
178    }
179
180    // Used to understand performance
181    #[allow(dead_code)]
182    fn max_depth(&self, depth: u32, parent: LayoutId) -> anyhow::Result<u32> {
183        println!(
184            "{parent:?} at depth {depth} has {} children",
185            self.taffy.child_count(parent.0)
186        );
187
188        let mut max_child_depth = 0;
189
190        for child in self.taffy.children(parent.0)? {
191            max_child_depth = std::cmp::max(max_child_depth, self.max_depth(0, LayoutId(child))?);
192        }
193
194        Ok(depth + 1 + max_child_depth)
195    }
196
197    // Used to understand performance
198    #[allow(dead_code)]
199    fn get_edges(&self, parent: LayoutId) -> anyhow::Result<Vec<(LayoutId, LayoutId)>> {
200        let mut edges = Vec::new();
201
202        for child in self.taffy.children(parent.0)? {
203            edges.push((parent, LayoutId(child)));
204
205            edges.extend(self.get_edges(LayoutId(child))?);
206        }
207
208        Ok(edges)
209    }
210
211    #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
212    pub fn compute_layout(
213        &mut self,
214        id: LayoutId,
215        available_space: Size<AvailableSpace>,
216        window: &mut Window,
217        cx: &mut App,
218    ) {
219        // Leaving this here until we have a better instrumentation approach.
220        // println!("Laying out {} children", self.count_all_children(id)?);
221        // println!("Max layout depth: {}", self.max_depth(0, id)?);
222
223        // Output the edges (branches) of the tree in Mermaid format for visualization.
224        // println!("Edges:");
225        // for (a, b) in self.get_edges(id)? {
226        //     println!("N{} --> N{}", u64::from(a), u64::from(b));
227        // }
228        //
229
230        if !self.computed_layouts.insert(id) {
231            let stack = &mut self.layout_bounds_scratch_space;
232            stack.push(id);
233            while let Some(id) = stack.pop() {
234                self.absolute_layout_bounds.remove(&id);
235                self.absolute_outer_origins.remove(&id);
236                stack.extend(
237                    self.taffy
238                        .children(id.into())
239                        .expect(EXPECT_MESSAGE)
240                        .into_iter()
241                        .map(LayoutId::from),
242                );
243            }
244        }
245
246        let scale_factor = window.scale_factor();
247
248        let transform = |v: AvailableSpace| match v {
249            AvailableSpace::Definite(pixels) => {
250                AvailableSpace::Definite(Pixels(pixels.0 * scale_factor))
251            }
252            AvailableSpace::MinContent => AvailableSpace::MinContent,
253            AvailableSpace::MaxContent => AvailableSpace::MaxContent,
254        };
255        let available_space = size(
256            transform(available_space.width),
257            transform(available_space.height),
258        );
259
260        crate::fast::layout::replay_pending_measures(self, window, cx);
261        let mut measures = crate::fast::stats::begin_measure_tally(self);
262        self.taffy
263            .compute_layout_with_measure(
264                id.into(),
265                available_space.into(),
266                |input, _id, node_context, style| {
267                    taffy::compute_leaf_layout(
268                        input,
269                        style,
270                        |_, _| 0.0,
271                        |known_dimensions, available_space| {
272                            let Some(node_context) = node_context else {
273                                return taffy::geometry::Size::default();
274                            };
275                            let started = crate::fast::stats::MeasureTally::start(&measures);
276
277                            let known_dimensions = Size {
278                                width: known_dimensions.width.map(|e| Pixels(e / scale_factor)),
279                                height: known_dimensions.height.map(|e| Pixels(e / scale_factor)),
280                            };
281
282                            let available_space: Size<AvailableSpace> = available_space.into();
283                            let untransform = |ev: AvailableSpace| match ev {
284                                AvailableSpace::Definite(pixels) => {
285                                    AvailableSpace::Definite(Pixels(pixels.0 / scale_factor))
286                                }
287                                AvailableSpace::MinContent => AvailableSpace::MinContent,
288                                AvailableSpace::MaxContent => AvailableSpace::MaxContent,
289                            };
290                            let available_space = size(
291                                untransform(available_space.width),
292                                untransform(available_space.height),
293                            );
294
295                            let measured_size: Size<Pixels> = (node_context.measure)(
296                                known_dimensions,
297                                available_space,
298                                window,
299                                cx,
300                            );
301                            crate::fast::stats::MeasureTally::measured(
302                                &mut measures,
303                                started,
304                                _id,
305                                known_dimensions,
306                                available_space,
307                            );
308                            snap_measured_size_to_device_pixels(measured_size, scale_factor).into()
309                        },
310                    )
311                },
312            )
313            .expect(EXPECT_MESSAGE);
314        crate::fast::stats::finish_measure_tally(self, measures);
315        crate::fast::layout::settle_measured_leaves(self, window, cx);
316    }
317
318    // Pixel snapping
319    //
320    // Painting primitives at non-integer pixel coordinates produces blurry
321    // output. Pixel snapping converts layout coordinates into integer
322    // device-pixel coordinates so painted edges land exactly on physical
323    // pixel boundaries.
324    //
325    // Non-integer coordinates can arise for several reasons, including:
326    //   - flex distribution, percentages, centering, and text measurement
327    //     can produce fractional element sizes and positions;
328    //   - at fractional scale factors (for example 125% or 150%), integer
329    //     logical-pixel values can map to non-integer device-pixel values.
330    //
331    // We pixel-snap by rounding in device-pixel space, after multiplying
332    // by `scale_factor`, so that snapping targets physical pixels. Bounds
333    // are divided by `scale_factor` before being returned to GPUI.
334    //
335    // Midpoints are rounded toward zero. This is a stylistic choice: a
336    // 1-logical-pixel line at 150% scale should render as 1 dp rather than
337    // 2 dp.
338    //
339    // Pixel snapping is done in two phases:
340    //
341    //  1. Pre-layout metric snapping. Before Taffy computes layout, all
342    //     authored absolute lengths are rounded in `to_taffy`. This
343    //     includes borders, padding, gaps, and explicit sizes.
344    //     Custom-measured leaf nodes have their measured sizes rounded up
345    //     to integer device-pixel lengths.
346    //
347    //  2. Post-layout edge snapping. After Taffy resolves the tree, layout
348    //     relationships such as flex shares, grid tracks, percentages, and
349    //     centering can produce new fractional edge positions. Boxes now
350    //     have edges in absolute coordinates, and snapping must decide
351    //     where those edges land on the device-pixel grid.
352    //
353    // Ideally, post-layout snapping would satisfy:
354    //
355    //  - Edge closure. Two raw layout edges at the same absolute position
356    //    should snap to the same pixel column.
357    //  - Translation stability. A component's internal geometry should not
358    //    change when it moves to a new absolute position.
359    //
360    // These goals are in tension because rounding is not associative.
361    // The simple local schemes make different tradeoffs:
362    //
363    //  - Absolute edge rounding gives each window coordinate one answer,
364    //    so coincident edges always close globally. But a span's snapped
365    //    length is `round(far) - round(near)`, which may change by 1 dp
366    //    as its absolute origin moves.
367    //
368    //  - Parent-relative edge rounding rounds each child inside its
369    //    parent's coordinate space. This guarantees translation stability,
370    //    but a shared edge reached through different parents can
371    //    accumulate different rounding, causing non-closure between
372    //    cousins.
373    //
374    //  - Length rounding rounds each width, height, and thickness
375    //    independently and then places boxes from those rounded lengths.
376    //    Sizes stay stable under translation, but neighboring boxes derive
377    //    their shared boundary from different sources, so closure is not
378    //    guaranteed.
379    //
380    // We apply absolute edge rounding for each element's outer box in
381    // post-layout rounding to preserve closure. Border and padding widths
382    // are not touched by post-layout rounding; they keep their pre-layout
383    // rounded value so that they remain stable under translation.
384    //
385    // This gives both closure and translation stability in the case that
386    // all local metrics are integer device-pixel lengths. Pre-layout
387    // rounding covers that in most cases. The exception is metrics
388    // resolved by layout relationships, such as percentages. Outer box
389    // edges will still close globally, and painted border widths are still
390    // snapped independently, but the raw content-box origin can carry a
391    // 1dp residual into descendants.
392
393    pub fn layout_bounds(&mut self, id: LayoutId, scale_factor: f32) -> Bounds<Pixels> {
394        if let Some(layout) = self.absolute_layout_bounds.get(&id).cloned() {
395            return layout;
396        }
397
398        let layout = self.taffy.layout(id.into()).expect(EXPECT_MESSAGE);
399        let layout_location = layout.location;
400        let layout_size = layout.size;
401        let parent = self.taffy.parent(id.0);
402
403        let absolute_outer_origin = match parent {
404            Some(parent_id) => {
405                let parent_id = LayoutId::from(parent_id);
406                self.layout_bounds(parent_id, scale_factor);
407                let parent_origin = *self
408                    .absolute_outer_origins
409                    .get(&parent_id)
410                    .expect("parent absolute outer origin should be cached");
411                parent_origin + Point::from(layout_location)
412            }
413            None => Point::from(layout_location),
414        };
415        self.absolute_outer_origins
416            .insert(id, absolute_outer_origin);
417
418        let absolute_far = absolute_outer_origin + Point::from(Size::from(layout_size));
419        let snapped_bounds = Bounds::from_corners(
420            absolute_outer_origin.map(round_half_toward_zero),
421            absolute_far.map(round_half_toward_zero),
422        );
423
424        let bounds = (snapped_bounds / scale_factor).map(Pixels);
425        self.absolute_layout_bounds.insert(id, bounds);
426        bounds
427    }
428}
429
430/// A unique identifier for a layout node, generated when requesting a layout from Taffy
431#[derive(Copy, Clone, Eq, PartialEq, Debug)]
432#[repr(transparent)]
433pub struct LayoutId(NodeId);
434
435impl LayoutId {
436    pub(crate) fn to_taffy_slice(node_ids: &[Self]) -> &[taffy::NodeId] {
437        // SAFETY: LayoutId is repr(transparent) to taffy::tree::NodeId.
438        unsafe { std::mem::transmute::<&[LayoutId], &[taffy::NodeId]>(node_ids) }
439    }
440}
441
442impl std::hash::Hash for LayoutId {
443    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
444        u64::from(self.0).hash(state);
445    }
446}
447
448impl From<NodeId> for LayoutId {
449    fn from(node_id: NodeId) -> Self {
450        Self(node_id)
451    }
452}
453
454impl From<LayoutId> for NodeId {
455    fn from(layout_id: LayoutId) -> NodeId {
456        layout_id.0
457    }
458}
459
460fn snap_measured_size_to_device_pixels(size: Size<Pixels>, scale_factor: f32) -> Size<f32> {
461    size.map(|d| ceil_to_device_pixel(d.0.max(0.0), scale_factor))
462}
463
464fn border_widths_to_taffy(
465    widths: &Edges<AbsoluteLength>,
466    rem_size: Pixels,
467    scale_factor: f32,
468) -> TaffyRect<taffy::style::LengthPercentage> {
469    let snap = |w: &AbsoluteLength| {
470        taffy::style::LengthPercentage::length(round_stroke_to_device_pixel(
471            w.to_pixels(rem_size).0,
472            scale_factor,
473        ))
474    };
475    TaffyRect {
476        top: snap(&widths.top),
477        right: snap(&widths.right),
478        bottom: snap(&widths.bottom),
479        left: snap(&widths.left),
480    }
481}
482
483pub(crate) trait ToTaffy<Output> {
484    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> Output;
485}
486
487impl ToTaffy<taffy::style::Style> for Style {
488    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Style {
489        use taffy::style_helpers::{fr, length, minmax, repeat};
490
491        fn to_grid_line(
492            placement: &Range<crate::GridPlacement>,
493        ) -> taffy::Line<taffy::GridPlacement> {
494            taffy::Line {
495                start: placement.start.into(),
496                end: placement.end.into(),
497            }
498        }
499
500        fn to_grid_repeat<T: taffy::style::CheapCloneStr>(
501            unit: &Option<GridTemplate>,
502        ) -> Vec<taffy::GridTemplateComponent<T>> {
503            unit.map(|template| {
504                match template.min_size {
505                    // grid-template-*: repeat(<number>, minmax(0, 1fr));
506                    crate::GridTemplateMinSize::Zero => {
507                        vec![repeat(
508                            template.repeat,
509                            vec![minmax(length(0.0_f32), fr(1.0_f32))],
510                        )]
511                    }
512                    // grid-template-*: repeat(<number>, minmax(min-content, 1fr));
513                    crate::GridTemplateMinSize::MinContent => {
514                        vec![repeat(
515                            template.repeat,
516                            vec![minmax(min_content(), fr(1.0_f32))],
517                        )]
518                    }
519                    // grid-template-*: repeat(<number>, minmax(0, max-content))
520                    crate::GridTemplateMinSize::MaxContent => {
521                        vec![repeat(
522                            template.repeat,
523                            vec![minmax(length(0.0_f32), max_content())],
524                        )]
525                    }
526                }
527            })
528            .unwrap_or_default()
529        }
530
531        taffy::style::Style {
532            display: self.display.into(),
533            overflow: self.overflow.into(),
534            scrollbar_width: self.scrollbar_width.to_taffy(rem_size, scale_factor),
535            position: self.position.into(),
536            inset: self.inset.to_taffy(rem_size, scale_factor),
537            size: self.size.to_taffy(rem_size, scale_factor),
538            min_size: self.min_size.to_taffy(rem_size, scale_factor),
539            max_size: self.max_size.to_taffy(rem_size, scale_factor),
540            aspect_ratio: self.aspect_ratio,
541            margin: self.margin.to_taffy(rem_size, scale_factor),
542            padding: self.padding.to_taffy(rem_size, scale_factor),
543            border: border_widths_to_taffy(&self.border_widths, rem_size, scale_factor),
544            align_items: self.align_items.map(Into::into).unwrap_or_default(),
545            align_self: self.align_self.map(|x| x.into()),
546            align_content: self.align_content.map(Into::into).unwrap_or_default(),
547            justify_content: self.justify_content.map(Into::into).unwrap_or_default(),
548            gap: self.gap.to_taffy(rem_size, scale_factor),
549            flex_direction: self.flex_direction.into(),
550            flex_wrap: self.flex_wrap.into(),
551            flex_basis: self.flex_basis.to_taffy(rem_size, scale_factor),
552            flex_grow: self.flex_grow,
553            flex_shrink: self.flex_shrink,
554            grid_template_rows: to_grid_repeat(&self.grid_rows),
555            grid_template_columns: to_grid_repeat(&self.grid_cols),
556            grid_row: self
557                .grid_location
558                .as_ref()
559                .map(|location| to_grid_line(&location.row))
560                .unwrap_or_default(),
561            grid_column: self
562                .grid_location
563                .as_ref()
564                .map(|location| to_grid_line(&location.column))
565                .unwrap_or_default(),
566            ..Default::default()
567        }
568    }
569}
570
571impl ToTaffy<f32> for AbsoluteLength {
572    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> f32 {
573        round_to_device_pixel(self.to_pixels(rem_size).0, scale_factor)
574    }
575}
576
577impl ToTaffy<taffy::style::LengthPercentageAuto> for Length {
578    fn to_taffy(
579        &self,
580        rem_size: Pixels,
581        scale_factor: f32,
582    ) -> taffy::prelude::LengthPercentageAuto {
583        match self {
584            Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
585            Length::Auto => taffy::prelude::LengthPercentageAuto::auto(),
586        }
587    }
588}
589
590impl ToTaffy<taffy::style::Dimension> for Length {
591    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::prelude::Dimension {
592        match self {
593            Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
594            Length::Auto => taffy::prelude::Dimension::auto(),
595        }
596    }
597}
598
599impl ToTaffy<taffy::style::LengthPercentage> for DefiniteLength {
600    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
601        match self {
602            DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
603            DefiniteLength::Fraction(fraction) => {
604                taffy::style::LengthPercentage::percent(*fraction)
605            }
606        }
607    }
608}
609
610impl ToTaffy<taffy::style::LengthPercentageAuto> for DefiniteLength {
611    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
612        match self {
613            DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
614            DefiniteLength::Fraction(fraction) => {
615                taffy::style::LengthPercentageAuto::percent(*fraction)
616            }
617        }
618    }
619}
620
621impl ToTaffy<taffy::style::Dimension> for DefiniteLength {
622    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
623        match self {
624            DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
625            DefiniteLength::Fraction(fraction) => taffy::style::Dimension::percent(*fraction),
626        }
627    }
628}
629
630impl ToTaffy<taffy::style::LengthPercentage> for AbsoluteLength {
631    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
632        taffy::style::LengthPercentage::length(self.to_taffy(rem_size, scale_factor))
633    }
634}
635
636impl ToTaffy<taffy::style::LengthPercentageAuto> for AbsoluteLength {
637    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
638        taffy::style::LengthPercentageAuto::length(self.to_taffy(rem_size, scale_factor))
639    }
640}
641
642impl ToTaffy<taffy::style::Dimension> for AbsoluteLength {
643    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
644        taffy::style::Dimension::length(self.to_taffy(rem_size, scale_factor))
645    }
646}
647
648impl<T, T2> From<TaffyPoint<T>> for Point<T2>
649where
650    T: Into<T2>,
651    T2: Clone + Debug + Default + PartialEq,
652{
653    fn from(point: TaffyPoint<T>) -> Point<T2> {
654        Point {
655            x: point.x.into(),
656            y: point.y.into(),
657        }
658    }
659}
660
661impl<T, T2> From<Point<T>> for TaffyPoint<T2>
662where
663    T: Into<T2> + Clone + Debug + Default + PartialEq,
664{
665    fn from(val: Point<T>) -> Self {
666        TaffyPoint {
667            x: val.x.into(),
668            y: val.y.into(),
669        }
670    }
671}
672
673impl<T, U> ToTaffy<TaffySize<U>> for Size<T>
674where
675    T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
676{
677    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffySize<U> {
678        TaffySize {
679            width: self.width.to_taffy(rem_size, scale_factor),
680            height: self.height.to_taffy(rem_size, scale_factor),
681        }
682    }
683}
684
685impl<T, U> ToTaffy<TaffyRect<U>> for Edges<T>
686where
687    T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
688{
689    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffyRect<U> {
690        TaffyRect {
691            top: self.top.to_taffy(rem_size, scale_factor),
692            right: self.right.to_taffy(rem_size, scale_factor),
693            bottom: self.bottom.to_taffy(rem_size, scale_factor),
694            left: self.left.to_taffy(rem_size, scale_factor),
695        }
696    }
697}
698
699impl<T, U> From<TaffySize<T>> for Size<U>
700where
701    T: Into<U>,
702    U: Clone + Debug + Default + PartialEq,
703{
704    fn from(taffy_size: TaffySize<T>) -> Self {
705        Size {
706            width: taffy_size.width.into(),
707            height: taffy_size.height.into(),
708        }
709    }
710}
711
712impl<T, U> From<Size<T>> for TaffySize<U>
713where
714    T: Into<U> + Clone + Debug + Default + PartialEq,
715{
716    fn from(size: Size<T>) -> Self {
717        TaffySize {
718            width: size.width.into(),
719            height: size.height.into(),
720        }
721    }
722}
723
724/// The space available for an element to be laid out in
725#[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
726pub enum AvailableSpace {
727    /// The amount of space available is the specified number of pixels
728    Definite(Pixels),
729    /// The amount of space available is indefinite and the node should be laid out under a min-content constraint
730    #[default]
731    MinContent,
732    /// The amount of space available is indefinite and the node should be laid out under a max-content constraint
733    MaxContent,
734}
735
736impl AvailableSpace {
737    /// Returns a `Size` with both width and height set to `AvailableSpace::MinContent`.
738    ///
739    /// This function is useful when you want to create a `Size` with the minimum content constraints
740    /// for both dimensions.
741    ///
742    /// # Examples
743    ///
744    /// ```
745    /// use gpui::AvailableSpace;
746    /// let min_content_size = AvailableSpace::min_size();
747    /// assert_eq!(min_content_size.width, AvailableSpace::MinContent);
748    /// assert_eq!(min_content_size.height, AvailableSpace::MinContent);
749    /// ```
750    pub const fn min_size() -> Size<Self> {
751        Size {
752            width: Self::MinContent,
753            height: Self::MinContent,
754        }
755    }
756}
757
758impl From<AvailableSpace> for TaffyAvailableSpace {
759    fn from(space: AvailableSpace) -> TaffyAvailableSpace {
760        match space {
761            AvailableSpace::Definite(Pixels(value)) => TaffyAvailableSpace::Definite(value),
762            AvailableSpace::MinContent => TaffyAvailableSpace::MinContent,
763            AvailableSpace::MaxContent => TaffyAvailableSpace::MaxContent,
764        }
765    }
766}
767
768impl From<TaffyAvailableSpace> for AvailableSpace {
769    fn from(space: TaffyAvailableSpace) -> AvailableSpace {
770        match space {
771            TaffyAvailableSpace::Definite(value) => AvailableSpace::Definite(Pixels(value)),
772            TaffyAvailableSpace::MinContent => AvailableSpace::MinContent,
773            TaffyAvailableSpace::MaxContent => AvailableSpace::MaxContent,
774        }
775    }
776}
777
778impl From<Pixels> for AvailableSpace {
779    fn from(pixels: Pixels) -> Self {
780        AvailableSpace::Definite(pixels)
781    }
782}
783
784impl From<Size<Pixels>> for Size<AvailableSpace> {
785    fn from(size: Size<Pixels>) -> Self {
786        Size {
787            width: AvailableSpace::Definite(size.width),
788            height: AvailableSpace::Definite(size.height),
789        }
790    }
791}
792
793#[cfg(test)]
794mod tests {
795    use super::{Edges, Pixels, border_widths_to_taffy};
796
797    #[test]
798    fn border_widths_to_taffy_use_stroke_snapping() {
799        let border_widths = Edges {
800            top: Pixels(0.0).into(),
801            right: Pixels(0.4).into(),
802            bottom: Pixels(0.5).into(),
803            left: Pixels(1.6).into(),
804        };
805        let taffy_border = border_widths_to_taffy(&border_widths, Pixels(16.0), 1.0);
806
807        assert_eq!(
808            taffy_border.top,
809            taffy::style::LengthPercentage::length(0.0)
810        );
811        assert_eq!(
812            taffy_border.right,
813            taffy::style::LengthPercentage::length(1.0)
814        );
815        assert_eq!(
816            taffy_border.bottom,
817            taffy::style::LengthPercentage::length(1.0)
818        );
819        assert_eq!(
820            taffy_border.left,
821            taffy::style::LengthPercentage::length(2.0)
822        );
823    }
824}