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