taffy.rs

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