1use crate::{
17 AbsoluteLength, App, Bounds, DefiniteLength, Edges, GridTemplate, Length, Pixels, Point, Size,
18 Style, Window, size,
19 util::{
20 ceil_to_device_pixel, round_half_toward_zero, round_stroke_to_device_pixel,
21 round_to_device_pixel,
22 },
23};
24use collections::FxHashSet;
25use std::{fmt::Debug, ops::Range};
26use taffy::{
27 TaffyTree, TraversePartialTree as _,
28 geometry::{Point as TaffyPoint, Rect as TaffyRect, Size as TaffySize},
29 prelude::{max_content, min_content},
30 style::AvailableSpace as TaffyAvailableSpace,
31 tree::NodeId,
32};
33
34#[cfg(feature = "stacker")]
35pub(crate) type StackSafe<T> = stacksafe::StackSafe<T>;
36#[cfg(not(feature = "stacker"))]
37pub(crate) type StackSafe<T> = T;
38
39pub(crate) type MeasureFn =
40 dyn FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>;
41type NodeMeasureFn = StackSafe<Box<MeasureFn>>;
42
43pub(crate) struct NodeContext {
44 pub(crate) measure: NodeMeasureFn,
45}
46pub struct TaffyLayoutEngine {
47 pub(crate) taffy: TaffyTree<NodeContext>,
48 pub(crate) retention: crate::fast::layout::LayoutRetention,
49 pub(crate) absolute_layout_bounds: crate::fast::layout_bounds::LayoutIdMap<Bounds<Pixels>>,
50 pub(crate) absolute_outer_origins: crate::fast::layout_bounds::LayoutIdMap<Point<f32>>,
52 computed_layouts: FxHashSet<LayoutId>,
53 pub(crate) layout_bounds_scratch_space: Vec<LayoutId>,
54}
55
56const EXPECT_MESSAGE: &str = "we should avoid taffy layout errors by construction if possible";
57
58impl TaffyLayoutEngine {
59 pub fn new() -> Self {
60 let mut taffy = TaffyTree::new();
61 taffy.disable_rounding();
62 TaffyLayoutEngine {
63 taffy,
64 retention: crate::fast::layout::LayoutRetention::default(),
65 absolute_layout_bounds: crate::fast::layout_bounds::LayoutIdMap::default(),
66 absolute_outer_origins: crate::fast::layout_bounds::LayoutIdMap::default(),
67 computed_layouts: FxHashSet::default(),
68 layout_bounds_scratch_space: Vec::new(),
69 }
70 }
71
72 pub fn clear(&mut self) {
73 crate::fast::layout::release_unclaimed_nodes(self);
74 self.absolute_layout_bounds.clear();
75 self.absolute_outer_origins.clear();
76 self.computed_layouts.clear();
77 }
78
79 pub fn request_layout(
80 &mut self,
81 fast_key: Option<u64>,
82 style: &Style,
83 rem_size: Pixels,
84 scale_factor: f32,
85 children: &[LayoutId],
86 ) -> LayoutId {
87 crate::fast::layout::request_retained_layout(
88 self,
89 fast_key,
90 style,
91 rem_size,
92 scale_factor,
93 children,
94 )
95 }
96
97 #[allow(clippy::too_many_arguments)]
105 pub(crate) fn request_keyed_measure<K, F>(
106 &mut self,
107 fast_key: Option<u64>,
108 style: &Style,
109 rem_size: Pixels,
110 scale_factor: f32,
111 key: K,
112 _reuse: fn(&mut K, &mut K) -> bool,
113 mut measure: F,
114 ) -> LayoutId
115 where
116 K: 'static,
117 F: FnMut(
118 &K,
119 Size<Option<Pixels>>,
120 Size<AvailableSpace>,
121 bool,
122 &mut Window,
123 &mut App,
124 ) -> Size<Pixels>
125 + 'static,
126 {
127 crate::fast::layout::request_retained_measured_layout(
128 self,
129 fast_key,
130 style,
131 rem_size,
132 scale_factor,
133 move |known_dimensions, available_space, window, cx| {
134 measure(&key, known_dimensions, available_space, true, window, cx)
135 },
136 )
137 }
138
139 pub(crate) fn clear_layout_cache(&mut self) {}
145
146 pub(crate) fn clear_if_scale_factor_changed(&mut self, _scale_factor: f32) {}
148
149 pub fn stretch_auto_size_to_fill(
156 &mut self,
157 id: LayoutId,
158 size: Size<Pixels>,
159 scale_factor: f32,
160 ) {
161 crate::fast::layout::stretch_retained_auto_size_to_fill(self, id, size, scale_factor);
162 }
163
164 #[allow(dead_code)]
166 fn count_all_children(&self, parent: LayoutId) -> anyhow::Result<u32> {
167 let mut count = 0;
168
169 for child in self.taffy.children(parent.0)? {
170 count += 1;
172
173 count += self.count_all_children(LayoutId(child))?
175 }
176
177 Ok(count)
178 }
179
180 #[allow(dead_code)]
182 fn max_depth(&self, depth: u32, parent: LayoutId) -> anyhow::Result<u32> {
183 println!(
184 "{parent:?} at depth {depth} has {} children",
185 self.taffy.child_count(parent.0)
186 );
187
188 let mut max_child_depth = 0;
189
190 for child in self.taffy.children(parent.0)? {
191 max_child_depth = std::cmp::max(max_child_depth, self.max_depth(0, LayoutId(child))?);
192 }
193
194 Ok(depth + 1 + max_child_depth)
195 }
196
197 #[allow(dead_code)]
199 fn get_edges(&self, parent: LayoutId) -> anyhow::Result<Vec<(LayoutId, LayoutId)>> {
200 let mut edges = Vec::new();
201
202 for child in self.taffy.children(parent.0)? {
203 edges.push((parent, LayoutId(child)));
204
205 edges.extend(self.get_edges(LayoutId(child))?);
206 }
207
208 Ok(edges)
209 }
210
211 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
212 pub fn compute_layout(
213 &mut self,
214 id: LayoutId,
215 available_space: Size<AvailableSpace>,
216 window: &mut Window,
217 cx: &mut App,
218 ) {
219 if !self.computed_layouts.insert(id) {
231 let stack = &mut self.layout_bounds_scratch_space;
232 stack.push(id);
233 while let Some(id) = stack.pop() {
234 self.absolute_layout_bounds.remove(&id);
235 self.absolute_outer_origins.remove(&id);
236 stack.extend(
237 self.taffy
238 .children(id.into())
239 .expect(EXPECT_MESSAGE)
240 .into_iter()
241 .map(LayoutId::from),
242 );
243 }
244 }
245
246 let scale_factor = window.scale_factor();
247
248 let transform = |v: AvailableSpace| match v {
249 AvailableSpace::Definite(pixels) => {
250 AvailableSpace::Definite(Pixels(pixels.0 * scale_factor))
251 }
252 AvailableSpace::MinContent => AvailableSpace::MinContent,
253 AvailableSpace::MaxContent => AvailableSpace::MaxContent,
254 };
255 let available_space = size(
256 transform(available_space.width),
257 transform(available_space.height),
258 );
259
260 crate::fast::layout::replay_pending_measures(self, window, cx);
261 let mut measures = crate::fast::stats::begin_measure_tally(self);
262 self.taffy
263 .compute_layout_with_measure(
264 id.into(),
265 available_space.into(),
266 |input, _id, node_context, style| {
267 taffy::compute_leaf_layout(
268 input,
269 style,
270 |_, _| 0.0,
271 |known_dimensions, available_space| {
272 let Some(node_context) = node_context else {
273 return taffy::geometry::Size::default();
274 };
275 let started = crate::fast::stats::MeasureTally::start(&measures);
276
277 let known_dimensions = Size {
278 width: known_dimensions.width.map(|e| Pixels(e / scale_factor)),
279 height: known_dimensions.height.map(|e| Pixels(e / scale_factor)),
280 };
281
282 let available_space: Size<AvailableSpace> = available_space.into();
283 let untransform = |ev: AvailableSpace| match ev {
284 AvailableSpace::Definite(pixels) => {
285 AvailableSpace::Definite(Pixels(pixels.0 / scale_factor))
286 }
287 AvailableSpace::MinContent => AvailableSpace::MinContent,
288 AvailableSpace::MaxContent => AvailableSpace::MaxContent,
289 };
290 let available_space = size(
291 untransform(available_space.width),
292 untransform(available_space.height),
293 );
294
295 let measured_size: Size<Pixels> = (node_context.measure)(
296 known_dimensions,
297 available_space,
298 window,
299 cx,
300 );
301 crate::fast::stats::MeasureTally::measured(
302 &mut measures,
303 started,
304 _id,
305 known_dimensions,
306 available_space,
307 );
308 snap_measured_size_to_device_pixels(measured_size, scale_factor).into()
309 },
310 )
311 },
312 )
313 .expect(EXPECT_MESSAGE);
314 crate::fast::stats::finish_measure_tally(self, measures);
315 crate::fast::layout::settle_measured_leaves(self, window, cx);
316 }
317
318 pub fn layout_bounds(&mut self, id: LayoutId, scale_factor: f32) -> Bounds<Pixels> {
394 if let Some(layout) = self.absolute_layout_bounds.get(&id).cloned() {
395 return layout;
396 }
397
398 let layout = self.taffy.layout(id.into()).expect(EXPECT_MESSAGE);
399 let layout_location = layout.location;
400 let layout_size = layout.size;
401 let parent = self.taffy.parent(id.0);
402
403 let absolute_outer_origin = match parent {
404 Some(parent_id) => {
405 let parent_id = LayoutId::from(parent_id);
406 self.layout_bounds(parent_id, scale_factor);
407 let parent_origin = *self
408 .absolute_outer_origins
409 .get(&parent_id)
410 .expect("parent absolute outer origin should be cached");
411 parent_origin + Point::from(layout_location)
412 }
413 None => Point::from(layout_location),
414 };
415 self.absolute_outer_origins
416 .insert(id, absolute_outer_origin);
417
418 let absolute_far = absolute_outer_origin + Point::from(Size::from(layout_size));
419 let snapped_bounds = Bounds::from_corners(
420 absolute_outer_origin.map(round_half_toward_zero),
421 absolute_far.map(round_half_toward_zero),
422 );
423
424 let bounds = (snapped_bounds / scale_factor).map(Pixels);
425 self.absolute_layout_bounds.insert(id, bounds);
426 bounds
427 }
428}
429
430#[derive(Copy, Clone, Eq, PartialEq, Debug)]
432#[repr(transparent)]
433pub struct LayoutId(NodeId);
434
435impl LayoutId {
436 pub(crate) fn to_taffy_slice(node_ids: &[Self]) -> &[taffy::NodeId] {
437 unsafe { std::mem::transmute::<&[LayoutId], &[taffy::NodeId]>(node_ids) }
439 }
440}
441
442impl std::hash::Hash for LayoutId {
443 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
444 u64::from(self.0).hash(state);
445 }
446}
447
448impl From<NodeId> for LayoutId {
449 fn from(node_id: NodeId) -> Self {
450 Self(node_id)
451 }
452}
453
454impl From<LayoutId> for NodeId {
455 fn from(layout_id: LayoutId) -> NodeId {
456 layout_id.0
457 }
458}
459
460fn snap_measured_size_to_device_pixels(size: Size<Pixels>, scale_factor: f32) -> Size<f32> {
461 size.map(|d| ceil_to_device_pixel(d.0.max(0.0), scale_factor))
462}
463
464fn border_widths_to_taffy(
465 widths: &Edges<AbsoluteLength>,
466 rem_size: Pixels,
467 scale_factor: f32,
468) -> TaffyRect<taffy::style::LengthPercentage> {
469 let snap = |w: &AbsoluteLength| {
470 taffy::style::LengthPercentage::length(round_stroke_to_device_pixel(
471 w.to_pixels(rem_size).0,
472 scale_factor,
473 ))
474 };
475 TaffyRect {
476 top: snap(&widths.top),
477 right: snap(&widths.right),
478 bottom: snap(&widths.bottom),
479 left: snap(&widths.left),
480 }
481}
482
483pub(crate) trait ToTaffy<Output> {
484 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> Output;
485}
486
487impl ToTaffy<taffy::style::Style> for Style {
488 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Style {
489 use taffy::style_helpers::{fr, length, minmax, repeat};
490
491 fn to_grid_line(
492 placement: &Range<crate::GridPlacement>,
493 ) -> taffy::Line<taffy::GridPlacement> {
494 taffy::Line {
495 start: placement.start.into(),
496 end: placement.end.into(),
497 }
498 }
499
500 fn to_grid_repeat<T: taffy::style::CheapCloneStr>(
501 unit: &Option<GridTemplate>,
502 ) -> Vec<taffy::GridTemplateComponent<T>> {
503 unit.map(|template| {
504 match template.min_size {
505 crate::GridTemplateMinSize::Zero => {
507 vec![repeat(
508 template.repeat,
509 vec![minmax(length(0.0_f32), fr(1.0_f32))],
510 )]
511 }
512 crate::GridTemplateMinSize::MinContent => {
514 vec![repeat(
515 template.repeat,
516 vec![minmax(min_content(), fr(1.0_f32))],
517 )]
518 }
519 crate::GridTemplateMinSize::MaxContent => {
521 vec![repeat(
522 template.repeat,
523 vec![minmax(length(0.0_f32), max_content())],
524 )]
525 }
526 }
527 })
528 .unwrap_or_default()
529 }
530
531 taffy::style::Style {
532 display: self.display.into(),
533 overflow: self.overflow.into(),
534 scrollbar_width: self.scrollbar_width.to_taffy(rem_size, scale_factor),
535 position: self.position.into(),
536 inset: self.inset.to_taffy(rem_size, scale_factor),
537 size: self.size.to_taffy(rem_size, scale_factor),
538 min_size: self.min_size.to_taffy(rem_size, scale_factor),
539 max_size: self.max_size.to_taffy(rem_size, scale_factor),
540 aspect_ratio: self.aspect_ratio,
541 margin: self.margin.to_taffy(rem_size, scale_factor),
542 padding: self.padding.to_taffy(rem_size, scale_factor),
543 border: border_widths_to_taffy(&self.border_widths, rem_size, scale_factor),
544 align_items: self.align_items.map(Into::into).unwrap_or_default(),
545 align_self: self.align_self.map(|x| x.into()),
546 align_content: self.align_content.map(Into::into).unwrap_or_default(),
547 justify_content: self.justify_content.map(Into::into).unwrap_or_default(),
548 gap: self.gap.to_taffy(rem_size, scale_factor),
549 flex_direction: self.flex_direction.into(),
550 flex_wrap: self.flex_wrap.into(),
551 flex_basis: self.flex_basis.to_taffy(rem_size, scale_factor),
552 flex_grow: self.flex_grow,
553 flex_shrink: self.flex_shrink,
554 grid_template_rows: to_grid_repeat(&self.grid_rows),
555 grid_template_columns: to_grid_repeat(&self.grid_cols),
556 grid_row: self
557 .grid_location
558 .as_ref()
559 .map(|location| to_grid_line(&location.row))
560 .unwrap_or_default(),
561 grid_column: self
562 .grid_location
563 .as_ref()
564 .map(|location| to_grid_line(&location.column))
565 .unwrap_or_default(),
566 ..Default::default()
567 }
568 }
569}
570
571impl ToTaffy<f32> for AbsoluteLength {
572 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> f32 {
573 round_to_device_pixel(self.to_pixels(rem_size).0, scale_factor)
574 }
575}
576
577impl ToTaffy<taffy::style::LengthPercentageAuto> for Length {
578 fn to_taffy(
579 &self,
580 rem_size: Pixels,
581 scale_factor: f32,
582 ) -> taffy::prelude::LengthPercentageAuto {
583 match self {
584 Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
585 Length::Auto => taffy::prelude::LengthPercentageAuto::auto(),
586 }
587 }
588}
589
590impl ToTaffy<taffy::style::Dimension> for Length {
591 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::prelude::Dimension {
592 match self {
593 Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
594 Length::Auto => taffy::prelude::Dimension::auto(),
595 }
596 }
597}
598
599impl ToTaffy<taffy::style::LengthPercentage> for DefiniteLength {
600 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
601 match self {
602 DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
603 DefiniteLength::Fraction(fraction) => {
604 taffy::style::LengthPercentage::percent(*fraction)
605 }
606 }
607 }
608}
609
610impl ToTaffy<taffy::style::LengthPercentageAuto> for DefiniteLength {
611 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
612 match self {
613 DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
614 DefiniteLength::Fraction(fraction) => {
615 taffy::style::LengthPercentageAuto::percent(*fraction)
616 }
617 }
618 }
619}
620
621impl ToTaffy<taffy::style::Dimension> for DefiniteLength {
622 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
623 match self {
624 DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
625 DefiniteLength::Fraction(fraction) => taffy::style::Dimension::percent(*fraction),
626 }
627 }
628}
629
630impl ToTaffy<taffy::style::LengthPercentage> for AbsoluteLength {
631 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
632 taffy::style::LengthPercentage::length(self.to_taffy(rem_size, scale_factor))
633 }
634}
635
636impl ToTaffy<taffy::style::LengthPercentageAuto> for AbsoluteLength {
637 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
638 taffy::style::LengthPercentageAuto::length(self.to_taffy(rem_size, scale_factor))
639 }
640}
641
642impl ToTaffy<taffy::style::Dimension> for AbsoluteLength {
643 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
644 taffy::style::Dimension::length(self.to_taffy(rem_size, scale_factor))
645 }
646}
647
648impl<T, T2> From<TaffyPoint<T>> for Point<T2>
649where
650 T: Into<T2>,
651 T2: Clone + Debug + Default + PartialEq,
652{
653 fn from(point: TaffyPoint<T>) -> Point<T2> {
654 Point {
655 x: point.x.into(),
656 y: point.y.into(),
657 }
658 }
659}
660
661impl<T, T2> From<Point<T>> for TaffyPoint<T2>
662where
663 T: Into<T2> + Clone + Debug + Default + PartialEq,
664{
665 fn from(val: Point<T>) -> Self {
666 TaffyPoint {
667 x: val.x.into(),
668 y: val.y.into(),
669 }
670 }
671}
672
673impl<T, U> ToTaffy<TaffySize<U>> for Size<T>
674where
675 T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
676{
677 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffySize<U> {
678 TaffySize {
679 width: self.width.to_taffy(rem_size, scale_factor),
680 height: self.height.to_taffy(rem_size, scale_factor),
681 }
682 }
683}
684
685impl<T, U> ToTaffy<TaffyRect<U>> for Edges<T>
686where
687 T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
688{
689 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffyRect<U> {
690 TaffyRect {
691 top: self.top.to_taffy(rem_size, scale_factor),
692 right: self.right.to_taffy(rem_size, scale_factor),
693 bottom: self.bottom.to_taffy(rem_size, scale_factor),
694 left: self.left.to_taffy(rem_size, scale_factor),
695 }
696 }
697}
698
699impl<T, U> From<TaffySize<T>> for Size<U>
700where
701 T: Into<U>,
702 U: Clone + Debug + Default + PartialEq,
703{
704 fn from(taffy_size: TaffySize<T>) -> Self {
705 Size {
706 width: taffy_size.width.into(),
707 height: taffy_size.height.into(),
708 }
709 }
710}
711
712impl<T, U> From<Size<T>> for TaffySize<U>
713where
714 T: Into<U> + Clone + Debug + Default + PartialEq,
715{
716 fn from(size: Size<T>) -> Self {
717 TaffySize {
718 width: size.width.into(),
719 height: size.height.into(),
720 }
721 }
722}
723
724#[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
726pub enum AvailableSpace {
727 Definite(Pixels),
729 #[default]
731 MinContent,
732 MaxContent,
734}
735
736impl AvailableSpace {
737 pub const fn min_size() -> Size<Self> {
751 Size {
752 width: Self::MinContent,
753 height: Self::MinContent,
754 }
755 }
756}
757
758impl From<AvailableSpace> for TaffyAvailableSpace {
759 fn from(space: AvailableSpace) -> TaffyAvailableSpace {
760 match space {
761 AvailableSpace::Definite(Pixels(value)) => TaffyAvailableSpace::Definite(value),
762 AvailableSpace::MinContent => TaffyAvailableSpace::MinContent,
763 AvailableSpace::MaxContent => TaffyAvailableSpace::MaxContent,
764 }
765 }
766}
767
768impl From<TaffyAvailableSpace> for AvailableSpace {
769 fn from(space: TaffyAvailableSpace) -> AvailableSpace {
770 match space {
771 TaffyAvailableSpace::Definite(value) => AvailableSpace::Definite(Pixels(value)),
772 TaffyAvailableSpace::MinContent => AvailableSpace::MinContent,
773 TaffyAvailableSpace::MaxContent => AvailableSpace::MaxContent,
774 }
775 }
776}
777
778impl From<Pixels> for AvailableSpace {
779 fn from(pixels: Pixels) -> Self {
780 AvailableSpace::Definite(pixels)
781 }
782}
783
784impl From<Size<Pixels>> for Size<AvailableSpace> {
785 fn from(size: Size<Pixels>) -> Self {
786 Size {
787 width: AvailableSpace::Definite(size.width),
788 height: AvailableSpace::Definite(size.height),
789 }
790 }
791}
792
793#[cfg(test)]
794mod tests {
795 use super::{Edges, Pixels, border_widths_to_taffy};
796
797 #[test]
798 fn border_widths_to_taffy_use_stroke_snapping() {
799 let border_widths = Edges {
800 top: Pixels(0.0).into(),
801 right: Pixels(0.4).into(),
802 bottom: Pixels(0.5).into(),
803 left: Pixels(1.6).into(),
804 };
805 let taffy_border = border_widths_to_taffy(&border_widths, Pixels(16.0), 1.0);
806
807 assert_eq!(
808 taffy_border.top,
809 taffy::style::LengthPercentage::length(0.0)
810 );
811 assert_eq!(
812 taffy_border.right,
813 taffy::style::LengthPercentage::length(1.0)
814 );
815 assert_eq!(
816 taffy_border.bottom,
817 taffy::style::LengthPercentage::length(1.0)
818 );
819 assert_eq!(
820 taffy_border.left,
821 taffy::style::LengthPercentage::length(2.0)
822 );
823 }
824}