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