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 crate::fast::layout::replay_pending_measures(self, window, cx);
219 let mut measures = crate::fast::stats::begin_measure_tally(self);
220 self.taffy
221 .compute_layout_with_measure(
222 id.into(),
223 available_space.into(),
224 |input, _id, node_context, style| {
225 taffy::compute_leaf_layout(
226 input,
227 style,
228 |_, _| 0.0,
229 |known_dimensions, available_space| {
230 let Some(node_context) = node_context else {
231 return taffy::geometry::Size::default();
232 };
233 let started = crate::fast::stats::MeasureTally::start(&measures);
234
235 let known_dimensions = Size {
236 width: known_dimensions.width.map(|e| Pixels(e / scale_factor)),
237 height: known_dimensions.height.map(|e| Pixels(e / scale_factor)),
238 };
239
240 let available_space: Size<AvailableSpace> = available_space.into();
241 let untransform = |ev: AvailableSpace| match ev {
242 AvailableSpace::Definite(pixels) => {
243 AvailableSpace::Definite(Pixels(pixels.0 / scale_factor))
244 }
245 AvailableSpace::MinContent => AvailableSpace::MinContent,
246 AvailableSpace::MaxContent => AvailableSpace::MaxContent,
247 };
248 let available_space = size(
249 untransform(available_space.width),
250 untransform(available_space.height),
251 );
252
253 let measured_size: Size<Pixels> = (node_context.measure)(
254 known_dimensions,
255 available_space,
256 window,
257 cx,
258 );
259 crate::fast::stats::MeasureTally::measured(
260 &mut measures,
261 started,
262 _id,
263 known_dimensions,
264 available_space,
265 );
266 snap_measured_size_to_device_pixels(measured_size, scale_factor).into()
267 },
268 )
269 },
270 )
271 .expect(EXPECT_MESSAGE);
272 crate::fast::stats::finish_measure_tally(self, measures);
273 crate::fast::layout::settle_measured_leaves(self, window, cx);
274 }
275
276 pub fn layout_bounds(&mut self, id: LayoutId, scale_factor: f32) -> Bounds<Pixels> {
352 if let Some(layout) = self.absolute_layout_bounds.get(&id).cloned() {
353 return layout;
354 }
355
356 let layout = self.taffy.layout(id.into()).expect(EXPECT_MESSAGE);
357 let layout_location = layout.location;
358 let layout_size = layout.size;
359 let parent = self.taffy.parent(id.0);
360
361 let absolute_outer_origin = match parent {
362 Some(parent_id) => {
363 let parent_id = LayoutId::from(parent_id);
364 self.layout_bounds(parent_id, scale_factor);
365 let parent_origin = *self
366 .absolute_outer_origins
367 .get(&parent_id)
368 .expect("parent absolute outer origin should be cached");
369 parent_origin + Point::from(layout_location)
370 }
371 None => Point::from(layout_location),
372 };
373 self.absolute_outer_origins
374 .insert(id, absolute_outer_origin);
375
376 let absolute_far = absolute_outer_origin + Point::from(Size::from(layout_size));
377 let snapped_bounds = Bounds::from_corners(
378 absolute_outer_origin.map(round_half_toward_zero),
379 absolute_far.map(round_half_toward_zero),
380 );
381
382 let bounds = (snapped_bounds / scale_factor).map(Pixels);
383 self.absolute_layout_bounds.insert(id, bounds);
384 bounds
385 }
386}
387
388#[derive(Copy, Clone, Eq, PartialEq, Debug)]
390#[repr(transparent)]
391pub struct LayoutId(NodeId);
392
393impl LayoutId {
394 pub(crate) fn to_taffy_slice(node_ids: &[Self]) -> &[taffy::NodeId] {
395 unsafe { std::mem::transmute::<&[LayoutId], &[taffy::NodeId]>(node_ids) }
397 }
398}
399
400impl std::hash::Hash for LayoutId {
401 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
402 u64::from(self.0).hash(state);
403 }
404}
405
406impl From<NodeId> for LayoutId {
407 fn from(node_id: NodeId) -> Self {
408 Self(node_id)
409 }
410}
411
412impl From<LayoutId> for NodeId {
413 fn from(layout_id: LayoutId) -> NodeId {
414 layout_id.0
415 }
416}
417
418fn snap_measured_size_to_device_pixels(size: Size<Pixels>, scale_factor: f32) -> Size<f32> {
419 size.map(|d| ceil_to_device_pixel(d.0.max(0.0), scale_factor))
420}
421
422fn border_widths_to_taffy(
423 widths: &Edges<AbsoluteLength>,
424 rem_size: Pixels,
425 scale_factor: f32,
426) -> TaffyRect<taffy::style::LengthPercentage> {
427 let snap = |w: &AbsoluteLength| {
428 taffy::style::LengthPercentage::length(round_stroke_to_device_pixel(
429 w.to_pixels(rem_size).0,
430 scale_factor,
431 ))
432 };
433 TaffyRect {
434 top: snap(&widths.top),
435 right: snap(&widths.right),
436 bottom: snap(&widths.bottom),
437 left: snap(&widths.left),
438 }
439}
440
441pub(crate) trait ToTaffy<Output> {
442 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> Output;
443}
444
445impl ToTaffy<taffy::style::Style> for Style {
446 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Style {
447 use taffy::style_helpers::{fr, length, minmax, repeat};
448
449 fn to_grid_line(
450 placement: &Range<crate::GridPlacement>,
451 ) -> taffy::Line<taffy::GridPlacement> {
452 taffy::Line {
453 start: placement.start.into(),
454 end: placement.end.into(),
455 }
456 }
457
458 fn to_grid_repeat<T: taffy::style::CheapCloneStr>(
459 unit: &Option<GridTemplate>,
460 ) -> Vec<taffy::GridTemplateComponent<T>> {
461 unit.map(|template| {
462 match template.min_size {
463 crate::GridTemplateMinSize::Zero => {
465 vec![repeat(
466 template.repeat,
467 vec![minmax(length(0.0_f32), fr(1.0_f32))],
468 )]
469 }
470 crate::GridTemplateMinSize::MinContent => {
472 vec![repeat(
473 template.repeat,
474 vec![minmax(min_content(), fr(1.0_f32))],
475 )]
476 }
477 crate::GridTemplateMinSize::MaxContent => {
479 vec![repeat(
480 template.repeat,
481 vec![minmax(length(0.0_f32), max_content())],
482 )]
483 }
484 }
485 })
486 .unwrap_or_default()
487 }
488
489 taffy::style::Style {
490 display: self.display.into(),
491 overflow: self.overflow.into(),
492 scrollbar_width: self.scrollbar_width.to_taffy(rem_size, scale_factor),
493 position: self.position.into(),
494 inset: self.inset.to_taffy(rem_size, scale_factor),
495 size: self.size.to_taffy(rem_size, scale_factor),
496 min_size: self.min_size.to_taffy(rem_size, scale_factor),
497 max_size: self.max_size.to_taffy(rem_size, scale_factor),
498 aspect_ratio: self.aspect_ratio,
499 margin: self.margin.to_taffy(rem_size, scale_factor),
500 padding: self.padding.to_taffy(rem_size, scale_factor),
501 border: border_widths_to_taffy(&self.border_widths, rem_size, scale_factor),
502 align_items: self.align_items.map(Into::into).unwrap_or_default(),
503 align_self: self.align_self.map(|x| x.into()),
504 align_content: self.align_content.map(Into::into).unwrap_or_default(),
505 justify_content: self.justify_content.map(Into::into).unwrap_or_default(),
506 gap: self.gap.to_taffy(rem_size, scale_factor),
507 flex_direction: self.flex_direction.into(),
508 flex_wrap: self.flex_wrap.into(),
509 flex_basis: self.flex_basis.to_taffy(rem_size, scale_factor),
510 flex_grow: self.flex_grow,
511 flex_shrink: self.flex_shrink,
512 grid_template_rows: to_grid_repeat(&self.grid_rows),
513 grid_template_columns: to_grid_repeat(&self.grid_cols),
514 grid_row: self
515 .grid_location
516 .as_ref()
517 .map(|location| to_grid_line(&location.row))
518 .unwrap_or_default(),
519 grid_column: self
520 .grid_location
521 .as_ref()
522 .map(|location| to_grid_line(&location.column))
523 .unwrap_or_default(),
524 ..Default::default()
525 }
526 }
527}
528
529impl ToTaffy<f32> for AbsoluteLength {
530 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> f32 {
531 round_to_device_pixel(self.to_pixels(rem_size).0, scale_factor)
532 }
533}
534
535impl ToTaffy<taffy::style::LengthPercentageAuto> for Length {
536 fn to_taffy(
537 &self,
538 rem_size: Pixels,
539 scale_factor: f32,
540 ) -> taffy::prelude::LengthPercentageAuto {
541 match self {
542 Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
543 Length::Auto => taffy::prelude::LengthPercentageAuto::auto(),
544 }
545 }
546}
547
548impl ToTaffy<taffy::style::Dimension> for Length {
549 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::prelude::Dimension {
550 match self {
551 Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
552 Length::Auto => taffy::prelude::Dimension::auto(),
553 }
554 }
555}
556
557impl ToTaffy<taffy::style::LengthPercentage> for DefiniteLength {
558 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
559 match self {
560 DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
561 DefiniteLength::Fraction(fraction) => {
562 taffy::style::LengthPercentage::percent(*fraction)
563 }
564 }
565 }
566}
567
568impl ToTaffy<taffy::style::LengthPercentageAuto> for DefiniteLength {
569 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
570 match self {
571 DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
572 DefiniteLength::Fraction(fraction) => {
573 taffy::style::LengthPercentageAuto::percent(*fraction)
574 }
575 }
576 }
577}
578
579impl ToTaffy<taffy::style::Dimension> for DefiniteLength {
580 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
581 match self {
582 DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
583 DefiniteLength::Fraction(fraction) => taffy::style::Dimension::percent(*fraction),
584 }
585 }
586}
587
588impl ToTaffy<taffy::style::LengthPercentage> for AbsoluteLength {
589 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
590 taffy::style::LengthPercentage::length(self.to_taffy(rem_size, scale_factor))
591 }
592}
593
594impl ToTaffy<taffy::style::LengthPercentageAuto> for AbsoluteLength {
595 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
596 taffy::style::LengthPercentageAuto::length(self.to_taffy(rem_size, scale_factor))
597 }
598}
599
600impl ToTaffy<taffy::style::Dimension> for AbsoluteLength {
601 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
602 taffy::style::Dimension::length(self.to_taffy(rem_size, scale_factor))
603 }
604}
605
606impl<T, T2> From<TaffyPoint<T>> for Point<T2>
607where
608 T: Into<T2>,
609 T2: Clone + Debug + Default + PartialEq,
610{
611 fn from(point: TaffyPoint<T>) -> Point<T2> {
612 Point {
613 x: point.x.into(),
614 y: point.y.into(),
615 }
616 }
617}
618
619impl<T, T2> From<Point<T>> for TaffyPoint<T2>
620where
621 T: Into<T2> + Clone + Debug + Default + PartialEq,
622{
623 fn from(val: Point<T>) -> Self {
624 TaffyPoint {
625 x: val.x.into(),
626 y: val.y.into(),
627 }
628 }
629}
630
631impl<T, U> ToTaffy<TaffySize<U>> for Size<T>
632where
633 T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
634{
635 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffySize<U> {
636 TaffySize {
637 width: self.width.to_taffy(rem_size, scale_factor),
638 height: self.height.to_taffy(rem_size, scale_factor),
639 }
640 }
641}
642
643impl<T, U> ToTaffy<TaffyRect<U>> for Edges<T>
644where
645 T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
646{
647 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffyRect<U> {
648 TaffyRect {
649 top: self.top.to_taffy(rem_size, scale_factor),
650 right: self.right.to_taffy(rem_size, scale_factor),
651 bottom: self.bottom.to_taffy(rem_size, scale_factor),
652 left: self.left.to_taffy(rem_size, scale_factor),
653 }
654 }
655}
656
657impl<T, U> From<TaffySize<T>> for Size<U>
658where
659 T: Into<U>,
660 U: Clone + Debug + Default + PartialEq,
661{
662 fn from(taffy_size: TaffySize<T>) -> Self {
663 Size {
664 width: taffy_size.width.into(),
665 height: taffy_size.height.into(),
666 }
667 }
668}
669
670impl<T, U> From<Size<T>> for TaffySize<U>
671where
672 T: Into<U> + Clone + Debug + Default + PartialEq,
673{
674 fn from(size: Size<T>) -> Self {
675 TaffySize {
676 width: size.width.into(),
677 height: size.height.into(),
678 }
679 }
680}
681
682#[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
684pub enum AvailableSpace {
685 Definite(Pixels),
687 #[default]
689 MinContent,
690 MaxContent,
692}
693
694impl AvailableSpace {
695 pub const fn min_size() -> Size<Self> {
709 Size {
710 width: Self::MinContent,
711 height: Self::MinContent,
712 }
713 }
714}
715
716impl From<AvailableSpace> for TaffyAvailableSpace {
717 fn from(space: AvailableSpace) -> TaffyAvailableSpace {
718 match space {
719 AvailableSpace::Definite(Pixels(value)) => TaffyAvailableSpace::Definite(value),
720 AvailableSpace::MinContent => TaffyAvailableSpace::MinContent,
721 AvailableSpace::MaxContent => TaffyAvailableSpace::MaxContent,
722 }
723 }
724}
725
726impl From<TaffyAvailableSpace> for AvailableSpace {
727 fn from(space: TaffyAvailableSpace) -> AvailableSpace {
728 match space {
729 TaffyAvailableSpace::Definite(value) => AvailableSpace::Definite(Pixels(value)),
730 TaffyAvailableSpace::MinContent => AvailableSpace::MinContent,
731 TaffyAvailableSpace::MaxContent => AvailableSpace::MaxContent,
732 }
733 }
734}
735
736impl From<Pixels> for AvailableSpace {
737 fn from(pixels: Pixels) -> Self {
738 AvailableSpace::Definite(pixels)
739 }
740}
741
742impl From<Size<Pixels>> for Size<AvailableSpace> {
743 fn from(size: Size<Pixels>) -> Self {
744 Size {
745 width: AvailableSpace::Definite(size.width),
746 height: AvailableSpace::Definite(size.height),
747 }
748 }
749}
750
751#[cfg(test)]
752mod tests {
753 use super::*;
754
755 #[test]
756 fn border_widths_to_taffy_use_stroke_snapping() {
757 let border_widths = Edges {
758 top: Pixels(0.0).into(),
759 right: Pixels(0.4).into(),
760 bottom: Pixels(0.5).into(),
761 left: Pixels(1.6).into(),
762 };
763 let taffy_border = border_widths_to_taffy(&border_widths, Pixels(16.0), 1.0);
764
765 assert_eq!(
766 taffy_border.top,
767 taffy::style::LengthPercentage::length(0.0)
768 );
769 assert_eq!(
770 taffy_border.right,
771 taffy::style::LengthPercentage::length(1.0)
772 );
773 assert_eq!(
774 taffy_border.bottom,
775 taffy::style::LengthPercentage::length(1.0)
776 );
777 assert_eq!(
778 taffy_border.left,
779 taffy::style::LengthPercentage::length(2.0)
780 );
781 }
782}