1use crate::{
2 AbsoluteLength, App, Bounds, DefiniteLength, Edges, Length, Pixels, Point, Size, Style, Window,
3 point, size, util::round_half_toward_zero,
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
243 // Taffy already rounds positions and sizes via a cumulative edge-based
244 // post-pass (see `round_layout` in taffy). That pass uses absolute
245 // positions to guarantee gap-free abutment between siblings. We must
246 // NOT re-round here — doing so would destroy the cumulative rounding
247 // invariant and could introduce 1-device-pixel gaps or size mismatches.
248 let mut bounds = Bounds {
249 origin: point(
250 Pixels(layout.location.x / scale_factor),
251 Pixels(layout.location.y / scale_factor),
252 ),
253 size: size(
254 Pixels(layout.size.width / scale_factor),
255 Pixels(layout.size.height / scale_factor),
256 ),
257 };
258
259 if let Some(parent_id) = self.taffy.parent(id.0) {
260 let parent_bounds = self.layout_bounds(parent_id.into(), scale_factor);
261 bounds.origin += parent_bounds.origin;
262 }
263 self.absolute_layout_bounds.insert(id, bounds);
264
265 bounds
266 }
267}
268
269/// A unique identifier for a layout node, generated when requesting a layout from Taffy
270#[derive(Copy, Clone, Eq, PartialEq, Debug)]
271#[repr(transparent)]
272pub struct LayoutId(NodeId);
273
274impl LayoutId {
275 fn to_taffy_slice(node_ids: &[Self]) -> &[taffy::NodeId] {
276 // SAFETY: LayoutId is repr(transparent) to taffy::tree::NodeId.
277 unsafe { std::mem::transmute::<&[LayoutId], &[taffy::NodeId]>(node_ids) }
278 }
279}
280
281impl std::hash::Hash for LayoutId {
282 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
283 u64::from(self.0).hash(state);
284 }
285}
286
287impl From<NodeId> for LayoutId {
288 fn from(node_id: NodeId) -> Self {
289 Self(node_id)
290 }
291}
292
293impl From<LayoutId> for NodeId {
294 fn from(layout_id: LayoutId) -> NodeId {
295 layout_id.0
296 }
297}
298
299trait ToTaffy<Output> {
300 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> Output;
301}
302
303impl ToTaffy<taffy::style::Style> for Style {
304 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Style {
305 use taffy::style_helpers::{fr, length, minmax, repeat};
306
307 fn to_grid_line(
308 placement: &Range<crate::GridPlacement>,
309 ) -> taffy::Line<taffy::GridPlacement> {
310 taffy::Line {
311 start: placement.start.into(),
312 end: placement.end.into(),
313 }
314 }
315
316 fn to_grid_repeat<T: taffy::style::CheapCloneStr>(
317 unit: &Option<u16>,
318 ) -> Vec<taffy::GridTemplateComponent<T>> {
319 // grid-template-columns: repeat(<number>, minmax(0, 1fr));
320 unit.map(|count| vec![repeat(count, vec![minmax(length(0.0), fr(1.0))])])
321 .unwrap_or_default()
322 }
323
324 fn to_grid_repeat_min_content<T: taffy::style::CheapCloneStr>(
325 unit: &Option<u16>,
326 ) -> Vec<taffy::GridTemplateComponent<T>> {
327 // grid-template-columns: repeat(<number>, minmax(min-content, 1fr));
328 unit.map(|count| vec![repeat(count, vec![minmax(min_content(), fr(1.0))])])
329 .unwrap_or_default()
330 }
331
332 taffy::style::Style {
333 display: self.display.into(),
334 overflow: self.overflow.into(),
335 scrollbar_width: self.scrollbar_width.to_taffy(rem_size, scale_factor),
336 position: self.position.into(),
337 inset: self.inset.to_taffy(rem_size, scale_factor),
338 size: self.size.to_taffy(rem_size, scale_factor),
339 min_size: self.min_size.to_taffy(rem_size, scale_factor),
340 max_size: self.max_size.to_taffy(rem_size, scale_factor),
341 aspect_ratio: self.aspect_ratio,
342 margin: self.margin.to_taffy(rem_size, scale_factor),
343 padding: self.padding.to_taffy(rem_size, scale_factor),
344 border: self.border_widths.to_taffy(rem_size, scale_factor),
345 align_items: self.align_items.map(|x| x.into()),
346 align_self: self.align_self.map(|x| x.into()),
347 align_content: self.align_content.map(|x| x.into()),
348 justify_content: self.justify_content.map(|x| x.into()),
349 gap: self.gap.to_taffy(rem_size, scale_factor),
350 flex_direction: self.flex_direction.into(),
351 flex_wrap: self.flex_wrap.into(),
352 flex_basis: self.flex_basis.to_taffy(rem_size, scale_factor),
353 flex_grow: self.flex_grow,
354 flex_shrink: self.flex_shrink,
355 grid_template_rows: to_grid_repeat(&self.grid_rows),
356 grid_template_columns: if self.grid_cols_min_content.is_some() {
357 to_grid_repeat_min_content(&self.grid_cols_min_content)
358 } else {
359 to_grid_repeat(&self.grid_cols)
360 },
361 grid_row: self
362 .grid_location
363 .as_ref()
364 .map(|location| to_grid_line(&location.row))
365 .unwrap_or_default(),
366 grid_column: self
367 .grid_location
368 .as_ref()
369 .map(|location| to_grid_line(&location.column))
370 .unwrap_or_default(),
371 ..Default::default()
372 }
373 }
374}
375
376impl ToTaffy<f32> for AbsoluteLength {
377 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> f32 {
378 // Pre-round to integer device pixels so that Taffy's flex algorithm
379 // works with snapped values. Taffy's cumulative edge-based post-pass
380 // then ensures gap-free abutment between siblings.
381 // NOTE: no `.max(0.0)` here — negative values are valid (e.g. margins).
382 round_half_toward_zero(self.to_pixels(rem_size).0 * scale_factor)
383 }
384}
385
386impl ToTaffy<taffy::style::LengthPercentageAuto> for Length {
387 fn to_taffy(
388 &self,
389 rem_size: Pixels,
390 scale_factor: f32,
391 ) -> taffy::prelude::LengthPercentageAuto {
392 match self {
393 Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
394 Length::Auto => taffy::prelude::LengthPercentageAuto::auto(),
395 }
396 }
397}
398
399impl ToTaffy<taffy::style::Dimension> for Length {
400 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::prelude::Dimension {
401 match self {
402 Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
403 Length::Auto => taffy::prelude::Dimension::auto(),
404 }
405 }
406}
407
408impl ToTaffy<taffy::style::LengthPercentage> for DefiniteLength {
409 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
410 match self {
411 DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
412 DefiniteLength::Fraction(fraction) => {
413 taffy::style::LengthPercentage::percent(*fraction)
414 }
415 }
416 }
417}
418
419impl ToTaffy<taffy::style::LengthPercentageAuto> for DefiniteLength {
420 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
421 match self {
422 DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
423 DefiniteLength::Fraction(fraction) => {
424 taffy::style::LengthPercentageAuto::percent(*fraction)
425 }
426 }
427 }
428}
429
430impl ToTaffy<taffy::style::Dimension> for DefiniteLength {
431 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
432 match self {
433 DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
434 DefiniteLength::Fraction(fraction) => taffy::style::Dimension::percent(*fraction),
435 }
436 }
437}
438
439impl ToTaffy<taffy::style::LengthPercentage> for AbsoluteLength {
440 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
441 taffy::style::LengthPercentage::length(self.to_taffy(rem_size, scale_factor))
442 }
443}
444
445impl ToTaffy<taffy::style::LengthPercentageAuto> for AbsoluteLength {
446 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
447 taffy::style::LengthPercentageAuto::length(self.to_taffy(rem_size, scale_factor))
448 }
449}
450
451impl ToTaffy<taffy::style::Dimension> for AbsoluteLength {
452 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
453 taffy::style::Dimension::length(self.to_taffy(rem_size, scale_factor))
454 }
455}
456
457impl<T, T2> From<TaffyPoint<T>> for Point<T2>
458where
459 T: Into<T2>,
460 T2: Clone + Debug + Default + PartialEq,
461{
462 fn from(point: TaffyPoint<T>) -> Point<T2> {
463 Point {
464 x: point.x.into(),
465 y: point.y.into(),
466 }
467 }
468}
469
470impl<T, T2> From<Point<T>> for TaffyPoint<T2>
471where
472 T: Into<T2> + Clone + Debug + Default + PartialEq,
473{
474 fn from(val: Point<T>) -> Self {
475 TaffyPoint {
476 x: val.x.into(),
477 y: val.y.into(),
478 }
479 }
480}
481
482impl<T, U> ToTaffy<TaffySize<U>> for Size<T>
483where
484 T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
485{
486 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffySize<U> {
487 TaffySize {
488 width: self.width.to_taffy(rem_size, scale_factor),
489 height: self.height.to_taffy(rem_size, scale_factor),
490 }
491 }
492}
493
494impl<T, U> ToTaffy<TaffyRect<U>> for Edges<T>
495where
496 T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
497{
498 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffyRect<U> {
499 TaffyRect {
500 top: self.top.to_taffy(rem_size, scale_factor),
501 right: self.right.to_taffy(rem_size, scale_factor),
502 bottom: self.bottom.to_taffy(rem_size, scale_factor),
503 left: self.left.to_taffy(rem_size, scale_factor),
504 }
505 }
506}
507
508impl<T, U> From<TaffySize<T>> for Size<U>
509where
510 T: Into<U>,
511 U: Clone + Debug + Default + PartialEq,
512{
513 fn from(taffy_size: TaffySize<T>) -> Self {
514 Size {
515 width: taffy_size.width.into(),
516 height: taffy_size.height.into(),
517 }
518 }
519}
520
521impl<T, U> From<Size<T>> for TaffySize<U>
522where
523 T: Into<U> + Clone + Debug + Default + PartialEq,
524{
525 fn from(size: Size<T>) -> Self {
526 TaffySize {
527 width: size.width.into(),
528 height: size.height.into(),
529 }
530 }
531}
532
533/// The space available for an element to be laid out in
534#[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
535pub enum AvailableSpace {
536 /// The amount of space available is the specified number of pixels
537 Definite(Pixels),
538 /// The amount of space available is indefinite and the node should be laid out under a min-content constraint
539 #[default]
540 MinContent,
541 /// The amount of space available is indefinite and the node should be laid out under a max-content constraint
542 MaxContent,
543}
544
545impl AvailableSpace {
546 /// Returns a `Size` with both width and height set to `AvailableSpace::MinContent`.
547 ///
548 /// This function is useful when you want to create a `Size` with the minimum content constraints
549 /// for both dimensions.
550 ///
551 /// # Examples
552 ///
553 /// ```
554 /// use gpui::AvailableSpace;
555 /// let min_content_size = AvailableSpace::min_size();
556 /// assert_eq!(min_content_size.width, AvailableSpace::MinContent);
557 /// assert_eq!(min_content_size.height, AvailableSpace::MinContent);
558 /// ```
559 pub const fn min_size() -> Size<Self> {
560 Size {
561 width: Self::MinContent,
562 height: Self::MinContent,
563 }
564 }
565}
566
567impl From<AvailableSpace> for TaffyAvailableSpace {
568 fn from(space: AvailableSpace) -> TaffyAvailableSpace {
569 match space {
570 AvailableSpace::Definite(Pixels(value)) => TaffyAvailableSpace::Definite(value),
571 AvailableSpace::MinContent => TaffyAvailableSpace::MinContent,
572 AvailableSpace::MaxContent => TaffyAvailableSpace::MaxContent,
573 }
574 }
575}
576
577impl From<TaffyAvailableSpace> for AvailableSpace {
578 fn from(space: TaffyAvailableSpace) -> AvailableSpace {
579 match space {
580 TaffyAvailableSpace::Definite(value) => AvailableSpace::Definite(Pixels(value)),
581 TaffyAvailableSpace::MinContent => AvailableSpace::MinContent,
582 TaffyAvailableSpace::MaxContent => AvailableSpace::MaxContent,
583 }
584 }
585}
586
587impl From<Pixels> for AvailableSpace {
588 fn from(pixels: Pixels) -> Self {
589 AvailableSpace::Definite(pixels)
590 }
591}
592
593impl From<Size<Pixels>> for Size<AvailableSpace> {
594 fn from(size: Size<Pixels>) -> Self {
595 Size {
596 width: AvailableSpace::Definite(size.width),
597 height: AvailableSpace::Definite(size.height),
598 }
599 }
600}