Skip to main content

gpui/
taffy.rs

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