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