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 smallvec::SmallVec;
  7use stacksafe::{StackSafe, stacksafe};
  8use std::{fmt::Debug, ops::Range};
  9use taffy::{
 10    TaffyTree, TraversePartialTree as _,
 11    geometry::{Point as TaffyPoint, Rect as TaffyRect, Size as TaffySize},
 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}
 35
 36const EXPECT_MESSAGE: &str = "we should avoid taffy layout errors by construction if possible";
 37
 38impl TaffyLayoutEngine {
 39    pub fn new() -> Self {
 40        let mut taffy = TaffyTree::new();
 41        taffy.enable_rounding();
 42        TaffyLayoutEngine {
 43            taffy,
 44            absolute_layout_bounds: FxHashMap::default(),
 45            computed_layouts: FxHashSet::default(),
 46        }
 47    }
 48
 49    pub fn clear(&mut self) {
 50        self.taffy.clear();
 51        self.absolute_layout_bounds.clear();
 52        self.computed_layouts.clear();
 53    }
 54
 55    pub fn request_layout(
 56        &mut self,
 57        style: Style,
 58        rem_size: Pixels,
 59        scale_factor: f32,
 60        children: &[LayoutId],
 61    ) -> LayoutId {
 62        let taffy_style = style.to_taffy(rem_size, scale_factor);
 63
 64        if children.is_empty() {
 65            self.taffy
 66                .new_leaf(taffy_style)
 67                .expect(EXPECT_MESSAGE)
 68                .into()
 69        } else {
 70            self.taffy
 71                // This is safe because LayoutId is repr(transparent) to taffy::tree::NodeId.
 72                .new_with_children(taffy_style, unsafe {
 73                    std::mem::transmute::<&[LayoutId], &[taffy::NodeId]>(children)
 74                })
 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 = SmallVec::<[LayoutId; 64]>::new();
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(Into::into),
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 std::hash::Hash for LayoutId {
269    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
270        u64::from(self.0).hash(state);
271    }
272}
273
274impl From<NodeId> for LayoutId {
275    fn from(node_id: NodeId) -> Self {
276        Self(node_id)
277    }
278}
279
280impl From<LayoutId> for NodeId {
281    fn from(layout_id: LayoutId) -> NodeId {
282        layout_id.0
283    }
284}
285
286trait ToTaffy<Output> {
287    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> Output;
288}
289
290impl ToTaffy<taffy::style::Style> for Style {
291    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Style {
292        use taffy::style_helpers::{fr, length, minmax, repeat};
293
294        fn to_grid_line(
295            placement: &Range<crate::GridPlacement>,
296        ) -> taffy::Line<taffy::GridPlacement> {
297            taffy::Line {
298                start: placement.start.into(),
299                end: placement.end.into(),
300            }
301        }
302
303        fn to_grid_repeat<T: taffy::style::CheapCloneStr>(
304            unit: &Option<u16>,
305        ) -> Vec<taffy::GridTemplateComponent<T>> {
306            // grid-template-columns: repeat(<number>, minmax(0, 1fr));
307            unit.map(|count| vec![repeat(count, vec![minmax(length(0.0), fr(1.0))])])
308                .unwrap_or_default()
309        }
310
311        taffy::style::Style {
312            display: self.display.into(),
313            overflow: self.overflow.into(),
314            scrollbar_width: self.scrollbar_width.to_taffy(rem_size, scale_factor),
315            position: self.position.into(),
316            inset: self.inset.to_taffy(rem_size, scale_factor),
317            size: self.size.to_taffy(rem_size, scale_factor),
318            min_size: self.min_size.to_taffy(rem_size, scale_factor),
319            max_size: self.max_size.to_taffy(rem_size, scale_factor),
320            aspect_ratio: self.aspect_ratio,
321            margin: self.margin.to_taffy(rem_size, scale_factor),
322            padding: self.padding.to_taffy(rem_size, scale_factor),
323            border: self.border_widths.to_taffy(rem_size, scale_factor),
324            align_items: self.align_items.map(|x| x.into()),
325            align_self: self.align_self.map(|x| x.into()),
326            align_content: self.align_content.map(|x| x.into()),
327            justify_content: self.justify_content.map(|x| x.into()),
328            gap: self.gap.to_taffy(rem_size, scale_factor),
329            flex_direction: self.flex_direction.into(),
330            flex_wrap: self.flex_wrap.into(),
331            flex_basis: self.flex_basis.to_taffy(rem_size, scale_factor),
332            flex_grow: self.flex_grow,
333            flex_shrink: self.flex_shrink,
334            grid_template_rows: to_grid_repeat(&self.grid_rows),
335            grid_template_columns: to_grid_repeat(&self.grid_cols),
336            grid_row: self
337                .grid_location
338                .as_ref()
339                .map(|location| to_grid_line(&location.row))
340                .unwrap_or_default(),
341            grid_column: self
342                .grid_location
343                .as_ref()
344                .map(|location| to_grid_line(&location.column))
345                .unwrap_or_default(),
346            ..Default::default()
347        }
348    }
349}
350
351impl ToTaffy<f32> for AbsoluteLength {
352    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> f32 {
353        match self {
354            AbsoluteLength::Pixels(pixels) => {
355                let pixels: f32 = pixels.into();
356                pixels * scale_factor
357            }
358            AbsoluteLength::Rems(rems) => {
359                let pixels: f32 = (*rems * rem_size).into();
360                pixels * scale_factor
361            }
362        }
363    }
364}
365
366impl ToTaffy<taffy::style::LengthPercentageAuto> for Length {
367    fn to_taffy(
368        &self,
369        rem_size: Pixels,
370        scale_factor: f32,
371    ) -> taffy::prelude::LengthPercentageAuto {
372        match self {
373            Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
374            Length::Auto => taffy::prelude::LengthPercentageAuto::auto(),
375        }
376    }
377}
378
379impl ToTaffy<taffy::style::Dimension> for Length {
380    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::prelude::Dimension {
381        match self {
382            Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
383            Length::Auto => taffy::prelude::Dimension::auto(),
384        }
385    }
386}
387
388impl ToTaffy<taffy::style::LengthPercentage> for DefiniteLength {
389    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
390        match self {
391            DefiniteLength::Absolute(length) => match length {
392                AbsoluteLength::Pixels(pixels) => {
393                    let pixels: f32 = pixels.into();
394                    taffy::style::LengthPercentage::length(pixels * scale_factor)
395                }
396                AbsoluteLength::Rems(rems) => {
397                    let pixels: f32 = (*rems * rem_size).into();
398                    taffy::style::LengthPercentage::length(pixels * scale_factor)
399                }
400            },
401            DefiniteLength::Fraction(fraction) => {
402                taffy::style::LengthPercentage::percent(*fraction)
403            }
404        }
405    }
406}
407
408impl ToTaffy<taffy::style::LengthPercentageAuto> for DefiniteLength {
409    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
410        match self {
411            DefiniteLength::Absolute(length) => match length {
412                AbsoluteLength::Pixels(pixels) => {
413                    let pixels: f32 = pixels.into();
414                    taffy::style::LengthPercentageAuto::length(pixels * scale_factor)
415                }
416                AbsoluteLength::Rems(rems) => {
417                    let pixels: f32 = (*rems * rem_size).into();
418                    taffy::style::LengthPercentageAuto::length(pixels * scale_factor)
419                }
420            },
421            DefiniteLength::Fraction(fraction) => {
422                taffy::style::LengthPercentageAuto::percent(*fraction)
423            }
424        }
425    }
426}
427
428impl ToTaffy<taffy::style::Dimension> for DefiniteLength {
429    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
430        match self {
431            DefiniteLength::Absolute(length) => match length {
432                AbsoluteLength::Pixels(pixels) => {
433                    let pixels: f32 = pixels.into();
434                    taffy::style::Dimension::length(pixels * scale_factor)
435                }
436                AbsoluteLength::Rems(rems) => {
437                    taffy::style::Dimension::length((*rems * rem_size * scale_factor).into())
438                }
439            },
440            DefiniteLength::Fraction(fraction) => taffy::style::Dimension::percent(*fraction),
441        }
442    }
443}
444
445impl ToTaffy<taffy::style::LengthPercentage> for AbsoluteLength {
446    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
447        match self {
448            AbsoluteLength::Pixels(pixels) => {
449                let pixels: f32 = pixels.into();
450                taffy::style::LengthPercentage::length(pixels * scale_factor)
451            }
452            AbsoluteLength::Rems(rems) => {
453                let pixels: f32 = (*rems * rem_size).into();
454                taffy::style::LengthPercentage::length(pixels * scale_factor)
455            }
456        }
457    }
458}
459
460impl<T, T2> From<TaffyPoint<T>> for Point<T2>
461where
462    T: Into<T2>,
463    T2: Clone + Debug + Default + PartialEq,
464{
465    fn from(point: TaffyPoint<T>) -> Point<T2> {
466        Point {
467            x: point.x.into(),
468            y: point.y.into(),
469        }
470    }
471}
472
473impl<T, T2> From<Point<T>> for TaffyPoint<T2>
474where
475    T: Into<T2> + Clone + Debug + Default + PartialEq,
476{
477    fn from(val: Point<T>) -> Self {
478        TaffyPoint {
479            x: val.x.into(),
480            y: val.y.into(),
481        }
482    }
483}
484
485impl<T, U> ToTaffy<TaffySize<U>> for Size<T>
486where
487    T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
488{
489    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffySize<U> {
490        TaffySize {
491            width: self.width.to_taffy(rem_size, scale_factor),
492            height: self.height.to_taffy(rem_size, scale_factor),
493        }
494    }
495}
496
497impl<T, U> ToTaffy<TaffyRect<U>> for Edges<T>
498where
499    T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
500{
501    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffyRect<U> {
502        TaffyRect {
503            top: self.top.to_taffy(rem_size, scale_factor),
504            right: self.right.to_taffy(rem_size, scale_factor),
505            bottom: self.bottom.to_taffy(rem_size, scale_factor),
506            left: self.left.to_taffy(rem_size, scale_factor),
507        }
508    }
509}
510
511impl<T, U> From<TaffySize<T>> for Size<U>
512where
513    T: Into<U>,
514    U: Clone + Debug + Default + PartialEq,
515{
516    fn from(taffy_size: TaffySize<T>) -> Self {
517        Size {
518            width: taffy_size.width.into(),
519            height: taffy_size.height.into(),
520        }
521    }
522}
523
524impl<T, U> From<Size<T>> for TaffySize<U>
525where
526    T: Into<U> + Clone + Debug + Default + PartialEq,
527{
528    fn from(size: Size<T>) -> Self {
529        TaffySize {
530            width: size.width.into(),
531            height: size.height.into(),
532        }
533    }
534}
535
536/// The space available for an element to be laid out in
537#[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
538pub enum AvailableSpace {
539    /// The amount of space available is the specified number of pixels
540    Definite(Pixels),
541    /// The amount of space available is indefinite and the node should be laid out under a min-content constraint
542    #[default]
543    MinContent,
544    /// The amount of space available is indefinite and the node should be laid out under a max-content constraint
545    MaxContent,
546}
547
548impl AvailableSpace {
549    /// Returns a `Size` with both width and height set to `AvailableSpace::MinContent`.
550    ///
551    /// This function is useful when you want to create a `Size` with the minimum content constraints
552    /// for both dimensions.
553    ///
554    /// # Examples
555    ///
556    /// ```
557    /// use gpui::AvailableSpace;
558    /// let min_content_size = AvailableSpace::min_size();
559    /// assert_eq!(min_content_size.width, AvailableSpace::MinContent);
560    /// assert_eq!(min_content_size.height, AvailableSpace::MinContent);
561    /// ```
562    pub const fn min_size() -> Size<Self> {
563        Size {
564            width: Self::MinContent,
565            height: Self::MinContent,
566        }
567    }
568}
569
570impl From<AvailableSpace> for TaffyAvailableSpace {
571    fn from(space: AvailableSpace) -> TaffyAvailableSpace {
572        match space {
573            AvailableSpace::Definite(Pixels(value)) => TaffyAvailableSpace::Definite(value),
574            AvailableSpace::MinContent => TaffyAvailableSpace::MinContent,
575            AvailableSpace::MaxContent => TaffyAvailableSpace::MaxContent,
576        }
577    }
578}
579
580impl From<TaffyAvailableSpace> for AvailableSpace {
581    fn from(space: TaffyAvailableSpace) -> AvailableSpace {
582        match space {
583            TaffyAvailableSpace::Definite(value) => AvailableSpace::Definite(Pixels(value)),
584            TaffyAvailableSpace::MinContent => AvailableSpace::MinContent,
585            TaffyAvailableSpace::MaxContent => AvailableSpace::MaxContent,
586        }
587    }
588}
589
590impl From<Pixels> for AvailableSpace {
591    fn from(pixels: Pixels) -> Self {
592        AvailableSpace::Definite(pixels)
593    }
594}
595
596impl From<Size<Pixels>> for Size<AvailableSpace> {
597    fn from(size: Size<Pixels>) -> Self {
598        Size {
599            width: AvailableSpace::Definite(size.width),
600            height: AvailableSpace::Definite(size.height),
601        }
602    }
603}