1use crate::{
3 AbsoluteLength, App, Bounds, DefiniteLength, Edges, GridTemplate, Length, Pixels, Point, Size,
4 Style, Window, size,
5 util::{
6 ceil_to_device_pixel, round_half_toward_zero, round_stroke_to_device_pixel,
7 round_to_device_pixel,
8 },
9};
10use collections::FxHashSet;
11use std::{fmt::Debug, ops::Range};
12use taffy::{
13 TaffyTree, TraversePartialTree as _,
14 geometry::{Point as TaffyPoint, Rect as TaffyRect, Size as TaffySize},
15 prelude::{max_content, min_content},
16 style::AvailableSpace as TaffyAvailableSpace,
17 tree::NodeId,
18};
19
20#[cfg(feature = "stacker")]
21pub(crate) type StackSafe<T> = stacksafe::StackSafe<T>;
22#[cfg(not(feature = "stacker"))]
23pub(crate) type StackSafe<T> = T;
24
25pub(crate) type MeasureFn =
26 dyn FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>;
27type NodeMeasureFn = StackSafe<Box<MeasureFn>>;
28
29pub(crate) struct NodeContext {
30 pub(crate) measure: NodeMeasureFn,
31}
32pub struct TaffyLayoutEngine {
33 pub(crate) taffy: TaffyTree<NodeContext>,
34 pub(crate) retention: crate::fast::layout::LayoutRetention,
35 pub(crate) absolute_layout_bounds: crate::fast::layout_bounds::LayoutIdMap<Bounds<Pixels>>,
36 pub(crate) absolute_outer_origins: crate::fast::layout_bounds::LayoutIdMap<Point<f32>>,
38 computed_layouts: FxHashSet<LayoutId>,
39 pub(crate) layout_bounds_scratch_space: Vec<LayoutId>,
40}
41
42const EXPECT_MESSAGE: &str = "we should avoid taffy layout errors by construction if possible";
43
44impl TaffyLayoutEngine {
45 pub fn new() -> Self {
46 let mut taffy = TaffyTree::new();
47 taffy.disable_rounding();
48 TaffyLayoutEngine {
49 taffy,
50 retention: crate::fast::layout::LayoutRetention::default(),
51 absolute_layout_bounds: crate::fast::layout_bounds::LayoutIdMap::default(),
52 absolute_outer_origins: crate::fast::layout_bounds::LayoutIdMap::default(),
53 computed_layouts: FxHashSet::default(),
54 layout_bounds_scratch_space: Vec::new(),
55 }
56 }
57
58 pub fn clear(&mut self) {
59 crate::fast::layout::release_unclaimed_nodes(self);
60 self.absolute_layout_bounds.clear();
61 self.absolute_outer_origins.clear();
62 self.computed_layouts.clear();
63 }
64
65 pub fn request_layout(
66 &mut self,
67 fast_key: Option<u64>,
68 style: Style,
69 rem_size: Pixels,
70 scale_factor: f32,
71 children: &[LayoutId],
72 ) -> LayoutId {
73 crate::fast::layout::request_retained_layout(
74 self,
75 fast_key,
76 &style,
77 rem_size,
78 scale_factor,
79 children,
80 )
81 }
82
83 pub fn request_measured_layout(
84 &mut self,
85 fast_key: Option<u64>,
86 style: Style,
87 rem_size: Pixels,
88 scale_factor: f32,
89 measure: impl FnMut(
90 Size<Option<Pixels>>,
91 Size<AvailableSpace>,
92 &mut Window,
93 &mut App,
94 ) -> Size<Pixels>
95 + 'static,
96 ) -> LayoutId {
97 crate::fast::layout::request_retained_measured_layout(
98 self,
99 fast_key,
100 &style,
101 rem_size,
102 scale_factor,
103 measure,
104 )
105 }
106
107 pub fn stretch_auto_size_to_fill(
114 &mut self,
115 id: LayoutId,
116 size: Size<Pixels>,
117 scale_factor: f32,
118 ) {
119 crate::fast::layout::stretch_retained_auto_size_to_fill(self, id, size, scale_factor);
120 }
121
122 #[allow(dead_code)]
124 fn count_all_children(&self, parent: LayoutId) -> anyhow::Result<u32> {
125 let mut count = 0;
126
127 for child in self.taffy.children(parent.0)? {
128 count += 1;
130
131 count += self.count_all_children(LayoutId(child))?
133 }
134
135 Ok(count)
136 }
137
138 #[allow(dead_code)]
140 fn max_depth(&self, depth: u32, parent: LayoutId) -> anyhow::Result<u32> {
141 println!(
142 "{parent:?} at depth {depth} has {} children",
143 self.taffy.child_count(parent.0)
144 );
145
146 let mut max_child_depth = 0;
147
148 for child in self.taffy.children(parent.0)? {
149 max_child_depth = std::cmp::max(max_child_depth, self.max_depth(0, LayoutId(child))?);
150 }
151
152 Ok(depth + 1 + max_child_depth)
153 }
154
155 #[allow(dead_code)]
157 fn get_edges(&self, parent: LayoutId) -> anyhow::Result<Vec<(LayoutId, LayoutId)>> {
158 let mut edges = Vec::new();
159
160 for child in self.taffy.children(parent.0)? {
161 edges.push((parent, LayoutId(child)));
162
163 edges.extend(self.get_edges(LayoutId(child))?);
164 }
165
166 Ok(edges)
167 }
168
169 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
170 pub fn compute_layout(
171 &mut self,
172 id: LayoutId,
173 available_space: Size<AvailableSpace>,
174 window: &mut Window,
175 cx: &mut App,
176 ) {
177 if !self.computed_layouts.insert(id) {
189 let stack = &mut self.layout_bounds_scratch_space;
190 stack.push(id);
191 while let Some(id) = stack.pop() {
192 self.absolute_layout_bounds.remove(&id);
193 self.absolute_outer_origins.remove(&id);
194 stack.extend(
195 self.taffy
196 .children(id.into())
197 .expect(EXPECT_MESSAGE)
198 .into_iter()
199 .map(LayoutId::from),
200 );
201 }
202 }
203
204 let scale_factor = window.scale_factor();
205
206 let transform = |v: AvailableSpace| match v {
207 AvailableSpace::Definite(pixels) => {
208 AvailableSpace::Definite(Pixels(pixels.0 * scale_factor))
209 }
210 AvailableSpace::MinContent => AvailableSpace::MinContent,
211 AvailableSpace::MaxContent => AvailableSpace::MaxContent,
212 };
213 let available_space = size(
214 transform(available_space.width),
215 transform(available_space.height),
216 );
217
218 let mut measures = crate::fast::stats::begin_measure_tally(self);
219 self.taffy
220 .compute_layout_with_measure(
221 id.into(),
222 available_space.into(),
223 |known_dimensions, available_space, _id, node_context, _style| {
224 let Some(node_context) = node_context else {
225 return taffy::geometry::Size::default();
226 };
227 let measure_started_at = crate::fast::stats::MeasureTally::start(&mut measures);
228
229 let known_dimensions = Size {
230 width: known_dimensions.width.map(|e| Pixels(e / scale_factor)),
231 height: known_dimensions.height.map(|e| Pixels(e / scale_factor)),
232 };
233
234 let available_space: Size<AvailableSpace> = available_space.into();
235 let untransform = |ev: AvailableSpace| match ev {
236 AvailableSpace::Definite(pixels) => {
237 AvailableSpace::Definite(Pixels(pixels.0 / scale_factor))
238 }
239 AvailableSpace::MinContent => AvailableSpace::MinContent,
240 AvailableSpace::MaxContent => AvailableSpace::MaxContent,
241 };
242 let available_space = size(
243 untransform(available_space.width),
244 untransform(available_space.height),
245 );
246
247 let measured_size: Size<Pixels> =
248 (node_context.measure)(known_dimensions, available_space, window, cx);
249 crate::fast::stats::MeasureTally::finish(&mut measures, measure_started_at);
250 crate::fast::layout::MeasuredLeaves::note(
251 &mut measures.leaves,
252 _id,
253 known_dimensions,
254 available_space,
255 );
256 snap_measured_size_to_device_pixels(measured_size, scale_factor).into()
257 },
258 )
259 .expect(EXPECT_MESSAGE);
260 crate::fast::stats::finish_measure_tally(self, measures);
261 crate::fast::layout::settle_measured_leaves(self, window, cx);
262 }
263
264 pub fn layout_bounds(&mut self, id: LayoutId, scale_factor: f32) -> Bounds<Pixels> {
340 if let Some(layout) = self.absolute_layout_bounds.get(&id).cloned() {
341 return layout;
342 }
343
344 let layout = self.taffy.layout(id.into()).expect(EXPECT_MESSAGE);
345 let layout_location = layout.location;
346 let layout_size = layout.size;
347 let parent = self.taffy.parent(id.0);
348
349 let absolute_outer_origin = match parent {
350 Some(parent_id) => {
351 let parent_id = LayoutId::from(parent_id);
352 self.layout_bounds(parent_id, scale_factor);
353 let parent_origin = *self
354 .absolute_outer_origins
355 .get(&parent_id)
356 .expect("parent absolute outer origin should be cached");
357 parent_origin + Point::from(layout_location)
358 }
359 None => Point::from(layout_location),
360 };
361 self.absolute_outer_origins
362 .insert(id, absolute_outer_origin);
363
364 let absolute_far = absolute_outer_origin + Point::from(Size::from(layout_size));
365 let snapped_bounds = Bounds::from_corners(
366 absolute_outer_origin.map(round_half_toward_zero),
367 absolute_far.map(round_half_toward_zero),
368 );
369
370 let bounds = (snapped_bounds / scale_factor).map(Pixels);
371 self.absolute_layout_bounds.insert(id, bounds);
372 bounds
373 }
374}
375
376#[derive(Copy, Clone, Eq, PartialEq, Debug)]
378#[repr(transparent)]
379pub struct LayoutId(NodeId);
380
381impl LayoutId {
382 pub(crate) fn to_taffy_slice(node_ids: &[Self]) -> &[taffy::NodeId] {
383 unsafe { std::mem::transmute::<&[LayoutId], &[taffy::NodeId]>(node_ids) }
385 }
386}
387
388impl std::hash::Hash for LayoutId {
389 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
390 u64::from(self.0).hash(state);
391 }
392}
393
394impl From<NodeId> for LayoutId {
395 fn from(node_id: NodeId) -> Self {
396 Self(node_id)
397 }
398}
399
400impl From<LayoutId> for NodeId {
401 fn from(layout_id: LayoutId) -> NodeId {
402 layout_id.0
403 }
404}
405
406fn snap_measured_size_to_device_pixels(size: Size<Pixels>, scale_factor: f32) -> Size<f32> {
407 size.map(|d| ceil_to_device_pixel(d.0.max(0.0), scale_factor))
408}
409
410fn border_widths_to_taffy(
411 widths: &Edges<AbsoluteLength>,
412 rem_size: Pixels,
413 scale_factor: f32,
414) -> TaffyRect<taffy::style::LengthPercentage> {
415 let snap = |w: &AbsoluteLength| {
416 taffy::style::LengthPercentage::length(round_stroke_to_device_pixel(
417 w.to_pixels(rem_size).0,
418 scale_factor,
419 ))
420 };
421 TaffyRect {
422 top: snap(&widths.top),
423 right: snap(&widths.right),
424 bottom: snap(&widths.bottom),
425 left: snap(&widths.left),
426 }
427}
428
429pub(crate) trait ToTaffy<Output> {
430 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> Output;
431}
432
433impl ToTaffy<taffy::style::Style> for Style {
434 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Style {
435 use taffy::style_helpers::{fr, length, minmax, repeat};
436
437 fn to_grid_line(
438 placement: &Range<crate::GridPlacement>,
439 ) -> taffy::Line<taffy::GridPlacement> {
440 taffy::Line {
441 start: placement.start.into(),
442 end: placement.end.into(),
443 }
444 }
445
446 fn to_grid_repeat<T: taffy::style::CheapCloneStr>(
447 unit: &Option<GridTemplate>,
448 ) -> Vec<taffy::GridTemplateComponent<T>> {
449 unit.map(|template| {
450 match template.min_size {
451 crate::GridTemplateMinSize::Zero => {
453 vec![repeat(
454 template.repeat,
455 vec![minmax(length(0.0_f32), fr(1.0_f32))],
456 )]
457 }
458 crate::GridTemplateMinSize::MinContent => {
460 vec![repeat(
461 template.repeat,
462 vec![minmax(min_content(), fr(1.0_f32))],
463 )]
464 }
465 crate::GridTemplateMinSize::MaxContent => {
467 vec![repeat(
468 template.repeat,
469 vec![minmax(length(0.0_f32), max_content())],
470 )]
471 }
472 }
473 })
474 .unwrap_or_default()
475 }
476
477 taffy::style::Style {
478 display: self.display.into(),
479 overflow: self.overflow.into(),
480 scrollbar_width: self.scrollbar_width.to_taffy(rem_size, scale_factor),
481 position: self.position.into(),
482 inset: self.inset.to_taffy(rem_size, scale_factor),
483 size: self.size.to_taffy(rem_size, scale_factor),
484 min_size: self.min_size.to_taffy(rem_size, scale_factor),
485 max_size: self.max_size.to_taffy(rem_size, scale_factor),
486 aspect_ratio: self.aspect_ratio,
487 margin: self.margin.to_taffy(rem_size, scale_factor),
488 padding: self.padding.to_taffy(rem_size, scale_factor),
489 border: border_widths_to_taffy(&self.border_widths, rem_size, scale_factor),
490 align_items: self.align_items.map(|x| x.into()),
491 align_self: self.align_self.map(|x| x.into()),
492 align_content: self.align_content.map(|x| x.into()),
493 justify_content: self.justify_content.map(|x| x.into()),
494 gap: self.gap.to_taffy(rem_size, scale_factor),
495 flex_direction: self.flex_direction.into(),
496 flex_wrap: self.flex_wrap.into(),
497 flex_basis: self.flex_basis.to_taffy(rem_size, scale_factor),
498 flex_grow: self.flex_grow,
499 flex_shrink: self.flex_shrink,
500 grid_template_rows: to_grid_repeat(&self.grid_rows),
501 grid_template_columns: to_grid_repeat(&self.grid_cols),
502 grid_row: self
503 .grid_location
504 .as_ref()
505 .map(|location| to_grid_line(&location.row))
506 .unwrap_or_default(),
507 grid_column: self
508 .grid_location
509 .as_ref()
510 .map(|location| to_grid_line(&location.column))
511 .unwrap_or_default(),
512 ..Default::default()
513 }
514 }
515}
516
517impl ToTaffy<f32> for AbsoluteLength {
518 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> f32 {
519 round_to_device_pixel(self.to_pixels(rem_size).0, scale_factor)
520 }
521}
522
523impl ToTaffy<taffy::style::LengthPercentageAuto> for Length {
524 fn to_taffy(
525 &self,
526 rem_size: Pixels,
527 scale_factor: f32,
528 ) -> taffy::prelude::LengthPercentageAuto {
529 match self {
530 Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
531 Length::Auto => taffy::prelude::LengthPercentageAuto::auto(),
532 }
533 }
534}
535
536impl ToTaffy<taffy::style::Dimension> for Length {
537 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::prelude::Dimension {
538 match self {
539 Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
540 Length::Auto => taffy::prelude::Dimension::auto(),
541 }
542 }
543}
544
545impl ToTaffy<taffy::style::LengthPercentage> for DefiniteLength {
546 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
547 match self {
548 DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
549 DefiniteLength::Fraction(fraction) => {
550 taffy::style::LengthPercentage::percent(*fraction)
551 }
552 }
553 }
554}
555
556impl ToTaffy<taffy::style::LengthPercentageAuto> for DefiniteLength {
557 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
558 match self {
559 DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
560 DefiniteLength::Fraction(fraction) => {
561 taffy::style::LengthPercentageAuto::percent(*fraction)
562 }
563 }
564 }
565}
566
567impl ToTaffy<taffy::style::Dimension> for DefiniteLength {
568 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
569 match self {
570 DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
571 DefiniteLength::Fraction(fraction) => taffy::style::Dimension::percent(*fraction),
572 }
573 }
574}
575
576impl ToTaffy<taffy::style::LengthPercentage> for AbsoluteLength {
577 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
578 taffy::style::LengthPercentage::length(self.to_taffy(rem_size, scale_factor))
579 }
580}
581
582impl ToTaffy<taffy::style::LengthPercentageAuto> for AbsoluteLength {
583 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
584 taffy::style::LengthPercentageAuto::length(self.to_taffy(rem_size, scale_factor))
585 }
586}
587
588impl ToTaffy<taffy::style::Dimension> for AbsoluteLength {
589 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
590 taffy::style::Dimension::length(self.to_taffy(rem_size, scale_factor))
591 }
592}
593
594impl<T, T2> From<TaffyPoint<T>> for Point<T2>
595where
596 T: Into<T2>,
597 T2: Clone + Debug + Default + PartialEq,
598{
599 fn from(point: TaffyPoint<T>) -> Point<T2> {
600 Point {
601 x: point.x.into(),
602 y: point.y.into(),
603 }
604 }
605}
606
607impl<T, T2> From<Point<T>> for TaffyPoint<T2>
608where
609 T: Into<T2> + Clone + Debug + Default + PartialEq,
610{
611 fn from(val: Point<T>) -> Self {
612 TaffyPoint {
613 x: val.x.into(),
614 y: val.y.into(),
615 }
616 }
617}
618
619impl<T, U> ToTaffy<TaffySize<U>> for Size<T>
620where
621 T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
622{
623 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffySize<U> {
624 TaffySize {
625 width: self.width.to_taffy(rem_size, scale_factor),
626 height: self.height.to_taffy(rem_size, scale_factor),
627 }
628 }
629}
630
631impl<T, U> ToTaffy<TaffyRect<U>> for Edges<T>
632where
633 T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
634{
635 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffyRect<U> {
636 TaffyRect {
637 top: self.top.to_taffy(rem_size, scale_factor),
638 right: self.right.to_taffy(rem_size, scale_factor),
639 bottom: self.bottom.to_taffy(rem_size, scale_factor),
640 left: self.left.to_taffy(rem_size, scale_factor),
641 }
642 }
643}
644
645impl<T, U> From<TaffySize<T>> for Size<U>
646where
647 T: Into<U>,
648 U: Clone + Debug + Default + PartialEq,
649{
650 fn from(taffy_size: TaffySize<T>) -> Self {
651 Size {
652 width: taffy_size.width.into(),
653 height: taffy_size.height.into(),
654 }
655 }
656}
657
658impl<T, U> From<Size<T>> for TaffySize<U>
659where
660 T: Into<U> + Clone + Debug + Default + PartialEq,
661{
662 fn from(size: Size<T>) -> Self {
663 TaffySize {
664 width: size.width.into(),
665 height: size.height.into(),
666 }
667 }
668}
669
670#[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
672pub enum AvailableSpace {
673 Definite(Pixels),
675 #[default]
677 MinContent,
678 MaxContent,
680}
681
682impl AvailableSpace {
683 pub const fn min_size() -> Size<Self> {
697 Size {
698 width: Self::MinContent,
699 height: Self::MinContent,
700 }
701 }
702}
703
704impl From<AvailableSpace> for TaffyAvailableSpace {
705 fn from(space: AvailableSpace) -> TaffyAvailableSpace {
706 match space {
707 AvailableSpace::Definite(Pixels(value)) => TaffyAvailableSpace::Definite(value),
708 AvailableSpace::MinContent => TaffyAvailableSpace::MinContent,
709 AvailableSpace::MaxContent => TaffyAvailableSpace::MaxContent,
710 }
711 }
712}
713
714impl From<TaffyAvailableSpace> for AvailableSpace {
715 fn from(space: TaffyAvailableSpace) -> AvailableSpace {
716 match space {
717 TaffyAvailableSpace::Definite(value) => AvailableSpace::Definite(Pixels(value)),
718 TaffyAvailableSpace::MinContent => AvailableSpace::MinContent,
719 TaffyAvailableSpace::MaxContent => AvailableSpace::MaxContent,
720 }
721 }
722}
723
724impl From<Pixels> for AvailableSpace {
725 fn from(pixels: Pixels) -> Self {
726 AvailableSpace::Definite(pixels)
727 }
728}
729
730impl From<Size<Pixels>> for Size<AvailableSpace> {
731 fn from(size: Size<Pixels>) -> Self {
732 Size {
733 width: AvailableSpace::Definite(size.width),
734 height: AvailableSpace::Definite(size.height),
735 }
736 }
737}
738
739#[cfg(test)]
740mod tests {
741 use super::*;
742
743 #[test]
744 fn border_widths_to_taffy_use_stroke_snapping() {
745 let border_widths = Edges {
746 top: Pixels(0.0).into(),
747 right: Pixels(0.4).into(),
748 bottom: Pixels(0.5).into(),
749 left: Pixels(1.6).into(),
750 };
751 let taffy_border = border_widths_to_taffy(&border_widths, Pixels(16.0), 1.0);
752
753 assert_eq!(
754 taffy_border.top,
755 taffy::style::LengthPercentage::length(0.0)
756 );
757 assert_eq!(
758 taffy_border.right,
759 taffy::style::LengthPercentage::length(1.0)
760 );
761 assert_eq!(
762 taffy_border.bottom,
763 taffy::style::LengthPercentage::length(1.0)
764 );
765 assert_eq!(
766 taffy_border.left,
767 taffy::style::LengthPercentage::length(2.0)
768 );
769 }
770}