taffy.rs

  1use crate::{
  2    AbsoluteLength, App, Bounds, DefiniteLength, Edges, Length, Pixels, Point, Size, Style, Window,
  3    point, size,
  4};
  5use collections::{FxHashMap, FxHashSet};
  6use stacksafe::{StackSafe, stacksafe};
  7use std::{fmt::Debug, ops::Range};
  8use taffy::{
  9    TaffyTree, TraversePartialTree as _,
 10    geometry::{Point as TaffyPoint, Rect as TaffyRect, Size as TaffySize},
 11    prelude::min_content,
 12    style::AvailableSpace as TaffyAvailableSpace,
 13    tree::NodeId,
 14};
 15
 16type NodeMeasureFn = StackSafe<
 17    Box<
 18        dyn FnMut(
 19            Size<Option<Pixels>>,
 20            Size<AvailableSpace>,
 21            &mut Window,
 22            &mut App,
 23        ) -> Size<Pixels>,
 24    >,
 25>;
 26
 27struct NodeContext {
 28    measure: NodeMeasureFn,
 29}
 30pub struct TaffyLayoutEngine {
 31    taffy: TaffyTree<NodeContext>,
 32    absolute_layout_bounds: FxHashMap<LayoutId, Bounds<Pixels>>,
 33    computed_layouts: FxHashSet<LayoutId>,
 34    layout_bounds_scratch_space: Vec<LayoutId>,
 35}
 36
 37const EXPECT_MESSAGE: &str = "we should avoid taffy layout errors by construction if possible";
 38
 39impl TaffyLayoutEngine {
 40    pub fn new() -> Self {
 41        let mut taffy = TaffyTree::new();
 42        taffy.enable_rounding();
 43        TaffyLayoutEngine {
 44            taffy,
 45            absolute_layout_bounds: FxHashMap::default(),
 46            computed_layouts: FxHashSet::default(),
 47            layout_bounds_scratch_space: Vec::new(),
 48        }
 49    }
 50
 51    pub fn clear(&mut self) {
 52        self.taffy.clear();
 53        self.absolute_layout_bounds.clear();
 54        self.computed_layouts.clear();
 55    }
 56
 57    pub fn request_layout(
 58        &mut self,
 59        style: Style,
 60        rem_size: Pixels,
 61        scale_factor: f32,
 62        children: &[LayoutId],
 63    ) -> LayoutId {
 64        let taffy_style = style.to_taffy(rem_size, scale_factor);
 65
 66        if children.is_empty() {
 67            self.taffy
 68                .new_leaf(taffy_style)
 69                .expect(EXPECT_MESSAGE)
 70                .into()
 71        } else {
 72            self.taffy
 73                // This is safe because LayoutId is repr(transparent) to taffy::tree::NodeId.
 74                .new_with_children(taffy_style, LayoutId::to_taffy_slice(children))
 75                .expect(EXPECT_MESSAGE)
 76                .into()
 77        }
 78    }
 79
 80    pub fn request_measured_layout(
 81        &mut self,
 82        style: Style,
 83        rem_size: Pixels,
 84        scale_factor: f32,
 85        measure: impl FnMut(
 86            Size<Option<Pixels>>,
 87            Size<AvailableSpace>,
 88            &mut Window,
 89            &mut App,
 90        ) -> Size<Pixels>
 91        + 'static,
 92    ) -> LayoutId {
 93        let taffy_style = style.to_taffy(rem_size, scale_factor);
 94
 95        self.taffy
 96            .new_leaf_with_context(
 97                taffy_style,
 98                NodeContext {
 99                    measure: StackSafe::new(Box::new(measure)),
100                },
101            )
102            .expect(EXPECT_MESSAGE)
103            .into()
104    }
105
106    // Used to understand performance
107    #[allow(dead_code)]
108    fn count_all_children(&self, parent: LayoutId) -> anyhow::Result<u32> {
109        let mut count = 0;
110
111        for child in self.taffy.children(parent.0)? {
112            // Count this child.
113            count += 1;
114
115            // Count all of this child's children.
116            count += self.count_all_children(LayoutId(child))?
117        }
118
119        Ok(count)
120    }
121
122    // Used to understand performance
123    #[allow(dead_code)]
124    fn max_depth(&self, depth: u32, parent: LayoutId) -> anyhow::Result<u32> {
125        println!(
126            "{parent:?} at depth {depth} has {} children",
127            self.taffy.child_count(parent.0)
128        );
129
130        let mut max_child_depth = 0;
131
132        for child in self.taffy.children(parent.0)? {
133            max_child_depth = std::cmp::max(max_child_depth, self.max_depth(0, LayoutId(child))?);
134        }
135
136        Ok(depth + 1 + max_child_depth)
137    }
138
139    // Used to understand performance
140    #[allow(dead_code)]
141    fn get_edges(&self, parent: LayoutId) -> anyhow::Result<Vec<(LayoutId, LayoutId)>> {
142        let mut edges = Vec::new();
143
144        for child in self.taffy.children(parent.0)? {
145            edges.push((parent, LayoutId(child)));
146
147            edges.extend(self.get_edges(LayoutId(child))?);
148        }
149
150        Ok(edges)
151    }
152
153    #[stacksafe]
154    pub fn compute_layout(
155        &mut self,
156        id: LayoutId,
157        available_space: Size<AvailableSpace>,
158        window: &mut Window,
159        cx: &mut App,
160    ) {
161        // Leaving this here until we have a better instrumentation approach.
162        // println!("Laying out {} children", self.count_all_children(id)?);
163        // println!("Max layout depth: {}", self.max_depth(0, id)?);
164
165        // Output the edges (branches) of the tree in Mermaid format for visualization.
166        // println!("Edges:");
167        // for (a, b) in self.get_edges(id)? {
168        //     println!("N{} --> N{}", u64::from(a), u64::from(b));
169        // }
170        //
171
172        if !self.computed_layouts.insert(id) {
173            let mut stack = &mut self.layout_bounds_scratch_space;
174            stack.push(id);
175            while let Some(id) = stack.pop() {
176                self.absolute_layout_bounds.remove(&id);
177                stack.extend(
178                    self.taffy
179                        .children(id.into())
180                        .expect(EXPECT_MESSAGE)
181                        .into_iter()
182                        .map(LayoutId::from),
183                );
184            }
185        }
186
187        let scale_factor = window.scale_factor();
188
189        let transform = |v: AvailableSpace| match v {
190            AvailableSpace::Definite(pixels) => {
191                AvailableSpace::Definite(Pixels(pixels.0 * scale_factor))
192            }
193            AvailableSpace::MinContent => AvailableSpace::MinContent,
194            AvailableSpace::MaxContent => AvailableSpace::MaxContent,
195        };
196        let available_space = size(
197            transform(available_space.width),
198            transform(available_space.height),
199        );
200
201        self.taffy
202            .compute_layout_with_measure(
203                id.into(),
204                available_space.into(),
205                |known_dimensions, available_space, _id, node_context, _style| {
206                    let Some(node_context) = node_context else {
207                        return taffy::geometry::Size::default();
208                    };
209
210                    let known_dimensions = Size {
211                        width: known_dimensions.width.map(|e| Pixels(e / scale_factor)),
212                        height: known_dimensions.height.map(|e| Pixels(e / scale_factor)),
213                    };
214
215                    let available_space: Size<AvailableSpace> = available_space.into();
216                    let untransform = |ev: AvailableSpace| match ev {
217                        AvailableSpace::Definite(pixels) => {
218                            AvailableSpace::Definite(Pixels(pixels.0 / scale_factor))
219                        }
220                        AvailableSpace::MinContent => AvailableSpace::MinContent,
221                        AvailableSpace::MaxContent => AvailableSpace::MaxContent,
222                    };
223                    let available_space = size(
224                        untransform(available_space.width),
225                        untransform(available_space.height),
226                    );
227
228                    let a: Size<Pixels> =
229                        (node_context.measure)(known_dimensions, available_space, window, cx);
230                    size(a.width.0 * scale_factor, a.height.0 * scale_factor).into()
231                },
232            )
233            .expect(EXPECT_MESSAGE);
234    }
235
236    pub fn layout_bounds(&mut self, id: LayoutId, scale_factor: f32) -> Bounds<Pixels> {
237        if let Some(layout) = self.absolute_layout_bounds.get(&id).cloned() {
238            return layout;
239        }
240
241        let layout = self.taffy.layout(id.into()).expect(EXPECT_MESSAGE);
242        let mut bounds = Bounds {
243            origin: point(
244                Pixels(layout.location.x / scale_factor),
245                Pixels(layout.location.y / scale_factor),
246            ),
247            size: size(
248                Pixels(layout.size.width / scale_factor),
249                Pixels(layout.size.height / scale_factor),
250            ),
251        };
252
253        if let Some(parent_id) = self.taffy.parent(id.0) {
254            let parent_bounds = self.layout_bounds(parent_id.into(), scale_factor);
255            bounds.origin += parent_bounds.origin;
256        }
257        self.absolute_layout_bounds.insert(id, bounds);
258
259        bounds
260    }
261}
262
263/// A unique identifier for a layout node, generated when requesting a layout from Taffy
264#[derive(Copy, Clone, Eq, PartialEq, Debug)]
265#[repr(transparent)]
266pub struct LayoutId(NodeId);
267
268impl LayoutId {
269    fn to_taffy_slice(node_ids: &[Self]) -> &[taffy::NodeId] {
270        // SAFETY: LayoutId is repr(transparent) to taffy::tree::NodeId.
271        unsafe { std::mem::transmute::<&[LayoutId], &[taffy::NodeId]>(node_ids) }
272    }
273}
274
275impl std::hash::Hash for LayoutId {
276    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
277        u64::from(self.0).hash(state);
278    }
279}
280
281impl From<NodeId> for LayoutId {
282    fn from(node_id: NodeId) -> Self {
283        Self(node_id)
284    }
285}
286
287impl From<LayoutId> for NodeId {
288    fn from(layout_id: LayoutId) -> NodeId {
289        layout_id.0
290    }
291}
292
293trait ToTaffy<Output> {
294    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> Output;
295}
296
297impl ToTaffy<taffy::style::Style> for Style {
298    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Style {
299        use taffy::style_helpers::{fr, length, minmax, repeat};
300
301        fn to_grid_line(
302            placement: &Range<crate::GridPlacement>,
303        ) -> taffy::Line<taffy::GridPlacement> {
304            taffy::Line {
305                start: placement.start.into(),
306                end: placement.end.into(),
307            }
308        }
309
310        fn to_grid_repeat<T: taffy::style::CheapCloneStr>(
311            unit: &Option<u16>,
312        ) -> Vec<taffy::GridTemplateComponent<T>> {
313            // grid-template-columns: repeat(<number>, minmax(0, 1fr));
314            unit.map(|count| vec![repeat(count, vec![minmax(length(0.0), fr(1.0))])])
315                .unwrap_or_default()
316        }
317
318        fn to_grid_repeat_min_content<T: taffy::style::CheapCloneStr>(
319            unit: &Option<u16>,
320        ) -> Vec<taffy::GridTemplateComponent<T>> {
321            // grid-template-columns: repeat(<number>, minmax(min-content, 1fr));
322            unit.map(|count| vec![repeat(count, vec![minmax(min_content(), fr(1.0))])])
323                .unwrap_or_default()
324        }
325
326        taffy::style::Style {
327            display: self.display.into(),
328            overflow: self.overflow.into(),
329            scrollbar_width: self.scrollbar_width.to_taffy(rem_size, scale_factor),
330            position: self.position.into(),
331            inset: self.inset.to_taffy(rem_size, scale_factor),
332            size: self.size.to_taffy(rem_size, scale_factor),
333            min_size: self.min_size.to_taffy(rem_size, scale_factor),
334            max_size: self.max_size.to_taffy(rem_size, scale_factor),
335            aspect_ratio: self.aspect_ratio,
336            margin: self.margin.to_taffy(rem_size, scale_factor),
337            padding: self.padding.to_taffy(rem_size, scale_factor),
338            border: self.border_widths.to_taffy(rem_size, scale_factor),
339            align_items: self.align_items.map(|x| x.into()),
340            align_self: self.align_self.map(|x| x.into()),
341            align_content: self.align_content.map(|x| x.into()),
342            justify_content: self.justify_content.map(|x| x.into()),
343            gap: self.gap.to_taffy(rem_size, scale_factor),
344            flex_direction: self.flex_direction.into(),
345            flex_wrap: self.flex_wrap.into(),
346            flex_basis: self.flex_basis.to_taffy(rem_size, scale_factor),
347            flex_grow: self.flex_grow,
348            flex_shrink: self.flex_shrink,
349            grid_template_rows: to_grid_repeat(&self.grid_rows),
350            grid_template_columns: if self.grid_cols_min_content.is_some() {
351                to_grid_repeat_min_content(&self.grid_cols_min_content)
352            } else {
353                to_grid_repeat(&self.grid_cols)
354            },
355            grid_row: self
356                .grid_location
357                .as_ref()
358                .map(|location| to_grid_line(&location.row))
359                .unwrap_or_default(),
360            grid_column: self
361                .grid_location
362                .as_ref()
363                .map(|location| to_grid_line(&location.column))
364                .unwrap_or_default(),
365            ..Default::default()
366        }
367    }
368}
369
370impl ToTaffy<f32> for AbsoluteLength {
371    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> f32 {
372        match self {
373            AbsoluteLength::Pixels(pixels) => {
374                let pixels: f32 = pixels.into();
375                pixels * scale_factor
376            }
377            AbsoluteLength::Rems(rems) => {
378                let pixels: f32 = (*rems * rem_size).into();
379                pixels * scale_factor
380            }
381        }
382    }
383}
384
385impl ToTaffy<taffy::style::LengthPercentageAuto> for Length {
386    fn to_taffy(
387        &self,
388        rem_size: Pixels,
389        scale_factor: f32,
390    ) -> taffy::prelude::LengthPercentageAuto {
391        match self {
392            Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
393            Length::Auto => taffy::prelude::LengthPercentageAuto::auto(),
394        }
395    }
396}
397
398impl ToTaffy<taffy::style::Dimension> for Length {
399    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::prelude::Dimension {
400        match self {
401            Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
402            Length::Auto => taffy::prelude::Dimension::auto(),
403        }
404    }
405}
406
407impl ToTaffy<taffy::style::LengthPercentage> for DefiniteLength {
408    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
409        match self {
410            DefiniteLength::Absolute(length) => match length {
411                AbsoluteLength::Pixels(pixels) => {
412                    let pixels: f32 = pixels.into();
413                    taffy::style::LengthPercentage::length(pixels * scale_factor)
414                }
415                AbsoluteLength::Rems(rems) => {
416                    let pixels: f32 = (*rems * rem_size).into();
417                    taffy::style::LengthPercentage::length(pixels * scale_factor)
418                }
419            },
420            DefiniteLength::Fraction(fraction) => {
421                taffy::style::LengthPercentage::percent(*fraction)
422            }
423        }
424    }
425}
426
427impl ToTaffy<taffy::style::LengthPercentageAuto> for DefiniteLength {
428    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
429        match self {
430            DefiniteLength::Absolute(length) => match length {
431                AbsoluteLength::Pixels(pixels) => {
432                    let pixels: f32 = pixels.into();
433                    taffy::style::LengthPercentageAuto::length(pixels * scale_factor)
434                }
435                AbsoluteLength::Rems(rems) => {
436                    let pixels: f32 = (*rems * rem_size).into();
437                    taffy::style::LengthPercentageAuto::length(pixels * scale_factor)
438                }
439            },
440            DefiniteLength::Fraction(fraction) => {
441                taffy::style::LengthPercentageAuto::percent(*fraction)
442            }
443        }
444    }
445}
446
447impl ToTaffy<taffy::style::Dimension> for DefiniteLength {
448    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
449        match self {
450            DefiniteLength::Absolute(length) => match length {
451                AbsoluteLength::Pixels(pixels) => {
452                    let pixels: f32 = pixels.into();
453                    taffy::style::Dimension::length(pixels * scale_factor)
454                }
455                AbsoluteLength::Rems(rems) => {
456                    taffy::style::Dimension::length((*rems * rem_size * scale_factor).into())
457                }
458            },
459            DefiniteLength::Fraction(fraction) => taffy::style::Dimension::percent(*fraction),
460        }
461    }
462}
463
464impl ToTaffy<taffy::style::LengthPercentage> for AbsoluteLength {
465    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
466        match self {
467            AbsoluteLength::Pixels(pixels) => {
468                let pixels: f32 = pixels.into();
469                taffy::style::LengthPercentage::length(pixels * scale_factor)
470            }
471            AbsoluteLength::Rems(rems) => {
472                let pixels: f32 = (*rems * rem_size).into();
473                taffy::style::LengthPercentage::length(pixels * scale_factor)
474            }
475        }
476    }
477}
478
479impl<T, T2> From<TaffyPoint<T>> for Point<T2>
480where
481    T: Into<T2>,
482    T2: Clone + Debug + Default + PartialEq,
483{
484    fn from(point: TaffyPoint<T>) -> Point<T2> {
485        Point {
486            x: point.x.into(),
487            y: point.y.into(),
488        }
489    }
490}
491
492impl<T, T2> From<Point<T>> for TaffyPoint<T2>
493where
494    T: Into<T2> + Clone + Debug + Default + PartialEq,
495{
496    fn from(val: Point<T>) -> Self {
497        TaffyPoint {
498            x: val.x.into(),
499            y: val.y.into(),
500        }
501    }
502}
503
504impl<T, U> ToTaffy<TaffySize<U>> for Size<T>
505where
506    T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
507{
508    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffySize<U> {
509        TaffySize {
510            width: self.width.to_taffy(rem_size, scale_factor),
511            height: self.height.to_taffy(rem_size, scale_factor),
512        }
513    }
514}
515
516impl<T, U> ToTaffy<TaffyRect<U>> for Edges<T>
517where
518    T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
519{
520    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffyRect<U> {
521        TaffyRect {
522            top: self.top.to_taffy(rem_size, scale_factor),
523            right: self.right.to_taffy(rem_size, scale_factor),
524            bottom: self.bottom.to_taffy(rem_size, scale_factor),
525            left: self.left.to_taffy(rem_size, scale_factor),
526        }
527    }
528}
529
530impl<T, U> From<TaffySize<T>> for Size<U>
531where
532    T: Into<U>,
533    U: Clone + Debug + Default + PartialEq,
534{
535    fn from(taffy_size: TaffySize<T>) -> Self {
536        Size {
537            width: taffy_size.width.into(),
538            height: taffy_size.height.into(),
539        }
540    }
541}
542
543impl<T, U> From<Size<T>> for TaffySize<U>
544where
545    T: Into<U> + Clone + Debug + Default + PartialEq,
546{
547    fn from(size: Size<T>) -> Self {
548        TaffySize {
549            width: size.width.into(),
550            height: size.height.into(),
551        }
552    }
553}
554
555/// The space available for an element to be laid out in
556#[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
557pub enum AvailableSpace {
558    /// The amount of space available is the specified number of pixels
559    Definite(Pixels),
560    /// The amount of space available is indefinite and the node should be laid out under a min-content constraint
561    #[default]
562    MinContent,
563    /// The amount of space available is indefinite and the node should be laid out under a max-content constraint
564    MaxContent,
565}
566
567impl AvailableSpace {
568    /// Returns a `Size` with both width and height set to `AvailableSpace::MinContent`.
569    ///
570    /// This function is useful when you want to create a `Size` with the minimum content constraints
571    /// for both dimensions.
572    ///
573    /// # Examples
574    ///
575    /// ```
576    /// use gpui::AvailableSpace;
577    /// let min_content_size = AvailableSpace::min_size();
578    /// assert_eq!(min_content_size.width, AvailableSpace::MinContent);
579    /// assert_eq!(min_content_size.height, AvailableSpace::MinContent);
580    /// ```
581    pub const fn min_size() -> Size<Self> {
582        Size {
583            width: Self::MinContent,
584            height: Self::MinContent,
585        }
586    }
587}
588
589impl From<AvailableSpace> for TaffyAvailableSpace {
590    fn from(space: AvailableSpace) -> TaffyAvailableSpace {
591        match space {
592            AvailableSpace::Definite(Pixels(value)) => TaffyAvailableSpace::Definite(value),
593            AvailableSpace::MinContent => TaffyAvailableSpace::MinContent,
594            AvailableSpace::MaxContent => TaffyAvailableSpace::MaxContent,
595        }
596    }
597}
598
599impl From<TaffyAvailableSpace> for AvailableSpace {
600    fn from(space: TaffyAvailableSpace) -> AvailableSpace {
601        match space {
602            TaffyAvailableSpace::Definite(value) => AvailableSpace::Definite(Pixels(value)),
603            TaffyAvailableSpace::MinContent => AvailableSpace::MinContent,
604            TaffyAvailableSpace::MaxContent => AvailableSpace::MaxContent,
605        }
606    }
607}
608
609impl From<Pixels> for AvailableSpace {
610    fn from(pixels: Pixels) -> Self {
611        AvailableSpace::Definite(pixels)
612    }
613}
614
615impl From<Size<Pixels>> for Size<AvailableSpace> {
616    fn from(size: Size<Pixels>) -> Self {
617        Size {
618            width: AvailableSpace::Definite(size.width),
619            height: AvailableSpace::Definite(size.height),
620        }
621    }
622}