1use crate::{
2 AbsoluteLength, App, Bounds, DefiniteLength, Edges, GridTemplate, Length, Pixels, Point, Size,
3 Style, Window, 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::{max_content, 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<GridTemplate>,
312 ) -> Vec<taffy::GridTemplateComponent<T>> {
313 unit.map(|template| {
314 match template.min_size {
315 // grid-template-*: repeat(<number>, minmax(0, 1fr));
316 crate::TemplateColumnMinSize::Zero => {
317 vec![repeat(template.repeat, vec![minmax(length(0.0), fr(1.0))])]
318 }
319 // grid-template-*: repeat(<number>, minmax(min-content, 1fr));
320 crate::TemplateColumnMinSize::MinContent => {
321 vec![repeat(
322 template.repeat,
323 vec![minmax(min_content(), fr(1.0))],
324 )]
325 }
326 // grid-template-*: repeat(<number>, minmax(0, max-content))
327 crate::TemplateColumnMinSize::MaxContent => {
328 vec![repeat(
329 template.repeat,
330 vec![minmax(length(0.0), max_content())],
331 )]
332 }
333 }
334 })
335 .unwrap_or_default()
336 }
337
338 taffy::style::Style {
339 display: self.display.into(),
340 overflow: self.overflow.into(),
341 scrollbar_width: self.scrollbar_width.to_taffy(rem_size, scale_factor),
342 position: self.position.into(),
343 inset: self.inset.to_taffy(rem_size, scale_factor),
344 size: self.size.to_taffy(rem_size, scale_factor),
345 min_size: self.min_size.to_taffy(rem_size, scale_factor),
346 max_size: self.max_size.to_taffy(rem_size, scale_factor),
347 aspect_ratio: self.aspect_ratio,
348 margin: self.margin.to_taffy(rem_size, scale_factor),
349 padding: self.padding.to_taffy(rem_size, scale_factor),
350 border: self.border_widths.to_taffy(rem_size, scale_factor),
351 align_items: self.align_items.map(|x| x.into()),
352 align_self: self.align_self.map(|x| x.into()),
353 align_content: self.align_content.map(|x| x.into()),
354 justify_content: self.justify_content.map(|x| x.into()),
355 gap: self.gap.to_taffy(rem_size, scale_factor),
356 flex_direction: self.flex_direction.into(),
357 flex_wrap: self.flex_wrap.into(),
358 flex_basis: self.flex_basis.to_taffy(rem_size, scale_factor),
359 flex_grow: self.flex_grow,
360 flex_shrink: self.flex_shrink,
361 grid_template_rows: to_grid_repeat(&self.grid_rows),
362 grid_template_columns: to_grid_repeat(&self.grid_cols),
363 grid_row: self
364 .grid_location
365 .as_ref()
366 .map(|location| to_grid_line(&location.row))
367 .unwrap_or_default(),
368 grid_column: self
369 .grid_location
370 .as_ref()
371 .map(|location| to_grid_line(&location.column))
372 .unwrap_or_default(),
373 ..Default::default()
374 }
375 }
376}
377
378impl ToTaffy<f32> for AbsoluteLength {
379 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> f32 {
380 match self {
381 AbsoluteLength::Pixels(pixels) => {
382 let pixels: f32 = pixels.into();
383 pixels * scale_factor
384 }
385 AbsoluteLength::Rems(rems) => {
386 let pixels: f32 = (*rems * rem_size).into();
387 pixels * scale_factor
388 }
389 }
390 }
391}
392
393impl ToTaffy<taffy::style::LengthPercentageAuto> for Length {
394 fn to_taffy(
395 &self,
396 rem_size: Pixels,
397 scale_factor: f32,
398 ) -> taffy::prelude::LengthPercentageAuto {
399 match self {
400 Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
401 Length::Auto => taffy::prelude::LengthPercentageAuto::auto(),
402 }
403 }
404}
405
406impl ToTaffy<taffy::style::Dimension> for Length {
407 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::prelude::Dimension {
408 match self {
409 Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
410 Length::Auto => taffy::prelude::Dimension::auto(),
411 }
412 }
413}
414
415impl ToTaffy<taffy::style::LengthPercentage> for DefiniteLength {
416 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
417 match self {
418 DefiniteLength::Absolute(length) => match length {
419 AbsoluteLength::Pixels(pixels) => {
420 let pixels: f32 = pixels.into();
421 taffy::style::LengthPercentage::length(pixels * scale_factor)
422 }
423 AbsoluteLength::Rems(rems) => {
424 let pixels: f32 = (*rems * rem_size).into();
425 taffy::style::LengthPercentage::length(pixels * scale_factor)
426 }
427 },
428 DefiniteLength::Fraction(fraction) => {
429 taffy::style::LengthPercentage::percent(*fraction)
430 }
431 }
432 }
433}
434
435impl ToTaffy<taffy::style::LengthPercentageAuto> for DefiniteLength {
436 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
437 match self {
438 DefiniteLength::Absolute(length) => match length {
439 AbsoluteLength::Pixels(pixels) => {
440 let pixels: f32 = pixels.into();
441 taffy::style::LengthPercentageAuto::length(pixels * scale_factor)
442 }
443 AbsoluteLength::Rems(rems) => {
444 let pixels: f32 = (*rems * rem_size).into();
445 taffy::style::LengthPercentageAuto::length(pixels * scale_factor)
446 }
447 },
448 DefiniteLength::Fraction(fraction) => {
449 taffy::style::LengthPercentageAuto::percent(*fraction)
450 }
451 }
452 }
453}
454
455impl ToTaffy<taffy::style::Dimension> for DefiniteLength {
456 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
457 match self {
458 DefiniteLength::Absolute(length) => match length {
459 AbsoluteLength::Pixels(pixels) => {
460 let pixels: f32 = pixels.into();
461 taffy::style::Dimension::length(pixels * scale_factor)
462 }
463 AbsoluteLength::Rems(rems) => {
464 taffy::style::Dimension::length((*rems * rem_size * scale_factor).into())
465 }
466 },
467 DefiniteLength::Fraction(fraction) => taffy::style::Dimension::percent(*fraction),
468 }
469 }
470}
471
472impl ToTaffy<taffy::style::LengthPercentage> for AbsoluteLength {
473 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
474 match self {
475 AbsoluteLength::Pixels(pixels) => {
476 let pixels: f32 = pixels.into();
477 taffy::style::LengthPercentage::length(pixels * scale_factor)
478 }
479 AbsoluteLength::Rems(rems) => {
480 let pixels: f32 = (*rems * rem_size).into();
481 taffy::style::LengthPercentage::length(pixels * scale_factor)
482 }
483 }
484 }
485}
486
487impl<T, T2> From<TaffyPoint<T>> for Point<T2>
488where
489 T: Into<T2>,
490 T2: Clone + Debug + Default + PartialEq,
491{
492 fn from(point: TaffyPoint<T>) -> Point<T2> {
493 Point {
494 x: point.x.into(),
495 y: point.y.into(),
496 }
497 }
498}
499
500impl<T, T2> From<Point<T>> for TaffyPoint<T2>
501where
502 T: Into<T2> + Clone + Debug + Default + PartialEq,
503{
504 fn from(val: Point<T>) -> Self {
505 TaffyPoint {
506 x: val.x.into(),
507 y: val.y.into(),
508 }
509 }
510}
511
512impl<T, U> ToTaffy<TaffySize<U>> for Size<T>
513where
514 T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
515{
516 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffySize<U> {
517 TaffySize {
518 width: self.width.to_taffy(rem_size, scale_factor),
519 height: self.height.to_taffy(rem_size, scale_factor),
520 }
521 }
522}
523
524impl<T, U> ToTaffy<TaffyRect<U>> for Edges<T>
525where
526 T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
527{
528 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffyRect<U> {
529 TaffyRect {
530 top: self.top.to_taffy(rem_size, scale_factor),
531 right: self.right.to_taffy(rem_size, scale_factor),
532 bottom: self.bottom.to_taffy(rem_size, scale_factor),
533 left: self.left.to_taffy(rem_size, scale_factor),
534 }
535 }
536}
537
538impl<T, U> From<TaffySize<T>> for Size<U>
539where
540 T: Into<U>,
541 U: Clone + Debug + Default + PartialEq,
542{
543 fn from(taffy_size: TaffySize<T>) -> Self {
544 Size {
545 width: taffy_size.width.into(),
546 height: taffy_size.height.into(),
547 }
548 }
549}
550
551impl<T, U> From<Size<T>> for TaffySize<U>
552where
553 T: Into<U> + Clone + Debug + Default + PartialEq,
554{
555 fn from(size: Size<T>) -> Self {
556 TaffySize {
557 width: size.width.into(),
558 height: size.height.into(),
559 }
560 }
561}
562
563/// The space available for an element to be laid out in
564#[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
565pub enum AvailableSpace {
566 /// The amount of space available is the specified number of pixels
567 Definite(Pixels),
568 /// The amount of space available is indefinite and the node should be laid out under a min-content constraint
569 #[default]
570 MinContent,
571 /// The amount of space available is indefinite and the node should be laid out under a max-content constraint
572 MaxContent,
573}
574
575impl AvailableSpace {
576 /// Returns a `Size` with both width and height set to `AvailableSpace::MinContent`.
577 ///
578 /// This function is useful when you want to create a `Size` with the minimum content constraints
579 /// for both dimensions.
580 ///
581 /// # Examples
582 ///
583 /// ```
584 /// use gpui::AvailableSpace;
585 /// let min_content_size = AvailableSpace::min_size();
586 /// assert_eq!(min_content_size.width, AvailableSpace::MinContent);
587 /// assert_eq!(min_content_size.height, AvailableSpace::MinContent);
588 /// ```
589 pub const fn min_size() -> Size<Self> {
590 Size {
591 width: Self::MinContent,
592 height: Self::MinContent,
593 }
594 }
595}
596
597impl From<AvailableSpace> for TaffyAvailableSpace {
598 fn from(space: AvailableSpace) -> TaffyAvailableSpace {
599 match space {
600 AvailableSpace::Definite(Pixels(value)) => TaffyAvailableSpace::Definite(value),
601 AvailableSpace::MinContent => TaffyAvailableSpace::MinContent,
602 AvailableSpace::MaxContent => TaffyAvailableSpace::MaxContent,
603 }
604 }
605}
606
607impl From<TaffyAvailableSpace> for AvailableSpace {
608 fn from(space: TaffyAvailableSpace) -> AvailableSpace {
609 match space {
610 TaffyAvailableSpace::Definite(value) => AvailableSpace::Definite(Pixels(value)),
611 TaffyAvailableSpace::MinContent => AvailableSpace::MinContent,
612 TaffyAvailableSpace::MaxContent => AvailableSpace::MaxContent,
613 }
614 }
615}
616
617impl From<Pixels> for AvailableSpace {
618 fn from(pixels: Pixels) -> Self {
619 AvailableSpace::Definite(pixels)
620 }
621}
622
623impl From<Size<Pixels>> for Size<AvailableSpace> {
624 fn from(size: Size<Pixels>) -> Self {
625 Size {
626 width: AvailableSpace::Definite(size.width),
627 height: AvailableSpace::Definite(size.height),
628 }
629 }
630}