1mod layout_bounds;
2mod retained;
3pub use retained::VnRetainedLayoutStats;
4
5use layout_bounds::LayoutIdMap;
6
7use crate::{
8 AbsoluteLength, App, Bounds, DefiniteLength, Display, Edges, GridTemplate, Length, Pixels,
9 Point, Size, Style, Window, size,
10 util::{
11 ceil_to_device_pixel, round_half_toward_zero, round_stroke_to_device_pixel,
12 round_to_device_pixel,
13 },
14};
15use collections::{FxHashMap, FxHashSet};
16use std::{fmt::Debug, ops::Range};
17use taffy::{
18 TaffyTree, TraversePartialTree as _,
19 geometry::{Point as TaffyPoint, Rect as TaffyRect, Size as TaffySize},
20 prelude::{max_content, min_content},
21 style::AvailableSpace as TaffyAvailableSpace,
22 tree::NodeId,
23};
24
25#[cfg(feature = "stacker")]
26type StackSafe<T> = stacksafe::StackSafe<T>;
27#[cfg(not(feature = "stacker"))]
28type StackSafe<T> = T;
29
30type MeasureFn =
31 dyn FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>;
32type NodeMeasureFn = StackSafe<Box<MeasureFn>>;
33
34struct NodeContext {
35 measure: NodeMeasureFn,
36}
37pub struct TaffyLayoutEngine {
38 taffy: TaffyTree<NodeContext>,
39 absolute_layout_bounds: LayoutIdMap<Bounds<Pixels>>,
40 absolute_outer_origins: LayoutIdMap<Point<f32>>,
42 retention: retained::Retention,
43 computed_layouts: FxHashSet<LayoutId>,
44 layout_bounds_scratch_space: Vec<LayoutId>,
45 orders: FxHashMap<LayoutId, i32>,
47}
48
49const EXPECT_MESSAGE: &str = "we should avoid taffy layout errors by construction if possible";
50
51impl TaffyLayoutEngine {
52 pub fn new() -> Self {
53 let mut taffy = TaffyTree::new();
54 taffy.disable_rounding();
55 TaffyLayoutEngine {
56 taffy,
57 absolute_layout_bounds: LayoutIdMap::default(),
58 absolute_outer_origins: LayoutIdMap::default(),
59 retention: retained::Retention::default(),
60 computed_layouts: FxHashSet::default(),
61 layout_bounds_scratch_space: Vec::new(),
62 orders: FxHashMap::default(),
63 }
64 }
65
66 pub fn clear(&mut self) {
67 if self.retention.enabled {
68 retained::finish_frame(self);
69 } else {
70 self.taffy.clear();
71 }
72 self.absolute_layout_bounds.clear();
73 self.absolute_outer_origins.clear();
74 self.computed_layouts.clear();
75 self.orders.clear();
76 }
77
78 pub(crate) fn retention_enabled(&self) -> bool {
79 self.retention.enabled
80 }
81
82 pub(crate) fn enable_retention(&mut self) {
83 if !self.retention.enabled {
84 assert_eq!(
85 self.taffy.total_node_count(),
86 0,
87 "enable retained layout before the first layout request"
88 );
89 self.retention.enabled = true;
90 }
91 }
92
93 pub(crate) fn profile_retention(&mut self, enabled: bool) {
94 self.retention.stats = enabled.then(Default::default);
95 }
96
97 pub(crate) fn take_retention_stats(&mut self) -> Option<VnRetainedLayoutStats> {
98 self.retention.stats.as_mut().map(std::mem::take)
99 }
100
101 pub fn request_layout(
102 &mut self,
103 style: Style,
104 rem_size: Pixels,
105 scale_factor: f32,
106 children: &[LayoutId],
107 ) -> LayoutId {
108 self.request_layout_in_scope(None, style, rem_size, scale_factor, children)
109 }
110
111 pub(crate) fn request_layout_in_scope(
112 &mut self,
113 scope: Option<crate::GlobalElementId>,
114 style: Style,
115 rem_size: Pixels,
116 scale_factor: f32,
117 children: &[LayoutId],
118 ) -> LayoutId {
119 let taffy_style = style.to_taffy(rem_size, scale_factor);
120 let reordered = self.order_modified(&style, children);
121 let children = reordered.as_deref().unwrap_or(children);
122 let id = if self.retention.enabled {
123 retained::request_layout(self, scope, taffy_style, children)
124 } else if children.is_empty() {
125 self.taffy
126 .new_leaf(taffy_style)
127 .expect(EXPECT_MESSAGE)
128 .into()
129 } else {
130 self.taffy
131 .new_with_children(taffy_style, LayoutId::to_taffy_slice(children))
133 .expect(EXPECT_MESSAGE)
134 .into()
135 };
136 self.note_order(id, &style);
137 id
138 }
139
140 fn note_order(&mut self, id: LayoutId, style: &Style) {
141 if style.vn_order != 0 {
142 self.orders.insert(id, style.vn_order);
143 }
144 }
145
146 fn order_modified(&self, style: &Style, children: &[LayoutId]) -> Option<Vec<LayoutId>> {
149 if self.orders.is_empty() || !matches!(style.display, Display::Flex | Display::Grid) {
150 return None;
151 }
152 let order = |id: &LayoutId| self.orders.get(id).copied().unwrap_or(0);
153 if children.windows(2).all(|w| order(&w[0]) <= order(&w[1])) {
154 return None;
155 }
156 let mut sorted = children.to_vec();
157 sorted.sort_by_key(order);
158 Some(sorted)
159 }
160
161 pub fn request_measured_layout(
162 &mut self,
163 style: Style,
164 rem_size: Pixels,
165 scale_factor: f32,
166 measure: impl FnMut(
167 Size<Option<Pixels>>,
168 Size<AvailableSpace>,
169 &mut Window,
170 &mut App,
171 ) -> Size<Pixels>
172 + 'static,
173 ) -> LayoutId {
174 self.request_measured_layout_in_scope(None, style, rem_size, scale_factor, measure)
175 }
176
177 pub(crate) fn request_measured_layout_in_scope(
178 &mut self,
179 scope: Option<crate::GlobalElementId>,
180 style: Style,
181 rem_size: Pixels,
182 scale_factor: f32,
183 measure: impl FnMut(
184 Size<Option<Pixels>>,
185 Size<AvailableSpace>,
186 &mut Window,
187 &mut App,
188 ) -> Size<Pixels>
189 + 'static,
190 ) -> LayoutId {
191 let taffy_style = style.to_taffy(rem_size, scale_factor);
192 let id = if self.retention.enabled {
193 retained::request_measured_layout(self, scope, taffy_style, measure)
194 } else {
195 let measure = Box::new(measure) as Box<MeasureFn>;
196 #[cfg(feature = "stacker")]
197 let measure = StackSafe::new(measure);
198
199 self.taffy
200 .new_leaf_with_context(taffy_style, NodeContext { measure })
201 .expect(EXPECT_MESSAGE)
202 .into()
203 };
204 self.note_order(id, &style);
205 id
206 }
207
208 pub fn stretch_auto_size_to_fill(
215 &mut self,
216 id: LayoutId,
217 size: Size<Pixels>,
218 scale_factor: f32,
219 ) {
220 if self.retention.enabled {
221 retained::stretch(self, id, size, scale_factor);
222 return;
223 }
224 let style = self.taffy.style(id.0).expect(EXPECT_MESSAGE);
225 let stretch_width = style.size.width.is_auto();
226 let stretch_height = style.size.height.is_auto();
227 if !stretch_width && !stretch_height {
228 return;
229 }
230 let mut style = style.clone();
231 if stretch_width {
232 style.size.width =
233 taffy::style::Dimension::length(round_to_device_pixel(size.width.0, scale_factor));
234 }
235 if stretch_height {
236 style.size.height =
237 taffy::style::Dimension::length(round_to_device_pixel(size.height.0, scale_factor));
238 }
239 self.taffy.set_style(id.0, style).expect(EXPECT_MESSAGE);
240 }
241
242 #[allow(dead_code)]
244 fn count_all_children(&self, parent: LayoutId) -> anyhow::Result<u32> {
245 let mut count = 0;
246
247 for child in self.taffy.children(parent.0)? {
248 count += 1;
250
251 count += self.count_all_children(LayoutId(child))?
253 }
254
255 Ok(count)
256 }
257
258 #[allow(dead_code)]
260 fn max_depth(&self, depth: u32, parent: LayoutId) -> anyhow::Result<u32> {
261 println!(
262 "{parent:?} at depth {depth} has {} children",
263 self.taffy.child_count(parent.0)
264 );
265
266 let mut max_child_depth = 0;
267
268 for child in self.taffy.children(parent.0)? {
269 max_child_depth = std::cmp::max(max_child_depth, self.max_depth(0, LayoutId(child))?);
270 }
271
272 Ok(depth + 1 + max_child_depth)
273 }
274
275 #[allow(dead_code)]
277 fn get_edges(&self, parent: LayoutId) -> anyhow::Result<Vec<(LayoutId, LayoutId)>> {
278 let mut edges = Vec::new();
279
280 for child in self.taffy.children(parent.0)? {
281 edges.push((parent, LayoutId(child)));
282
283 edges.extend(self.get_edges(LayoutId(child))?);
284 }
285
286 Ok(edges)
287 }
288
289 pub(crate) fn detach_root(&mut self, id: LayoutId) {
297 if let Some(parent) = self.taffy.parent(id.0) {
298 self.taffy.remove_child(parent, id.0).expect(EXPECT_MESSAGE);
299 }
300 }
301
302 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
303 pub fn compute_layout(
304 &mut self,
305 id: LayoutId,
306 available_space: Size<AvailableSpace>,
307 window: &mut Window,
308 cx: &mut App,
309 ) {
310 if self.retention.enabled {
322 self.detach_root(id);
323 }
324
325 if !self.computed_layouts.insert(id) {
326 let stack = &mut self.layout_bounds_scratch_space;
327 stack.push(id);
328 while let Some(id) = stack.pop() {
329 self.absolute_layout_bounds.remove(&id);
330 self.absolute_outer_origins.remove(&id);
331 stack.extend(
332 self.taffy
333 .children(id.into())
334 .expect(EXPECT_MESSAGE)
335 .into_iter()
336 .map(LayoutId::from),
337 );
338 }
339 }
340
341 let scale_factor = window.scale_factor();
342
343 let transform = |v: AvailableSpace| match v {
344 AvailableSpace::Definite(pixels) => {
345 AvailableSpace::Definite(Pixels(pixels.0 * scale_factor))
346 }
347 AvailableSpace::MinContent => AvailableSpace::MinContent,
348 AvailableSpace::MaxContent => AvailableSpace::MaxContent,
349 };
350 let available_space = size(
351 transform(available_space.width),
352 transform(available_space.height),
353 );
354
355 if self.retention.enabled {
356 retained::prepare_compute(self, scale_factor);
357 retained::replay(self, window, cx);
358 }
359 let retention = &mut self.retention;
360 self.taffy
361 .compute_layout_with_measure(
362 id.into(),
363 available_space.into(),
364 |input, id, node_context, style| {
365 taffy::compute_leaf_layout(
366 input,
367 style,
368 resolve_calc_handle,
372 |known_dimensions, available_space| {
373 let Some(node_context) = node_context else {
374 return taffy::geometry::Size::default();
375 };
376
377 let known_dimensions = Size {
378 width: known_dimensions.width.map(|e| Pixels(e / scale_factor)),
379 height: known_dimensions.height.map(|e| Pixels(e / scale_factor)),
380 };
381
382 let available_space: Size<AvailableSpace> = available_space.into();
383 let untransform = |ev: AvailableSpace| match ev {
384 AvailableSpace::Definite(pixels) => {
385 AvailableSpace::Definite(Pixels(pixels.0 / scale_factor))
386 }
387 AvailableSpace::MinContent => AvailableSpace::MinContent,
388 AvailableSpace::MaxContent => AvailableSpace::MaxContent,
389 };
390 let available_space = size(
391 untransform(available_space.width),
392 untransform(available_space.height),
393 );
394
395 if retention.enabled {
396 retained::note_measure(
397 retention,
398 id,
399 known_dimensions,
400 available_space,
401 );
402 }
403 let measured_size: Size<Pixels> = (node_context.measure)(
404 known_dimensions,
405 available_space,
406 window,
407 cx,
408 );
409 snap_measured_size_to_device_pixels(measured_size, scale_factor).into()
410 },
411 )
412 },
413 )
414 .expect(EXPECT_MESSAGE);
415 if self.retention.enabled {
416 retained::settle(self, window, cx);
417 }
418 }
419
420 pub fn is_absolute(&self, id: LayoutId) -> bool {
498 self.taffy
499 .style(id.0)
500 .is_ok_and(|style| style.position == taffy::style::Position::Absolute)
501 }
502
503 pub fn layout_bounds(&mut self, id: LayoutId, scale_factor: f32) -> Bounds<Pixels> {
504 if let Some(layout) = self.absolute_layout_bounds.get(&id).cloned() {
505 return layout;
506 }
507
508 let layout = self.taffy.layout(id.into()).expect(EXPECT_MESSAGE);
509 let layout_location = layout.location;
510 let layout_size = layout.size;
511 let parent = self.taffy.parent(id.0);
512
513 let absolute_outer_origin = match parent {
514 Some(parent_id) => {
515 let parent_id = LayoutId::from(parent_id);
516 self.layout_bounds(parent_id, scale_factor);
517 let parent_origin = *self
518 .absolute_outer_origins
519 .get(&parent_id)
520 .expect("parent absolute outer origin should be cached");
521 parent_origin + Point::from(layout_location)
522 }
523 None => Point::from(layout_location),
524 };
525 self.absolute_outer_origins
526 .insert(id, absolute_outer_origin);
527
528 let absolute_far = absolute_outer_origin + Point::from(Size::from(layout_size));
529 let snapped_bounds = Bounds::from_corners(
530 absolute_outer_origin.map(round_half_toward_zero),
531 absolute_far.map(round_half_toward_zero),
532 );
533
534 let bounds = (snapped_bounds / scale_factor).map(Pixels);
535 self.absolute_layout_bounds.insert(id, bounds);
536 bounds
537 }
538}
539
540#[derive(Copy, Clone, Eq, PartialEq, Debug)]
542#[repr(transparent)]
543pub struct LayoutId(NodeId);
544
545impl LayoutId {
546 fn to_taffy_slice(node_ids: &[Self]) -> &[taffy::NodeId] {
547 unsafe { std::mem::transmute::<&[LayoutId], &[taffy::NodeId]>(node_ids) }
549 }
550}
551
552impl std::hash::Hash for LayoutId {
553 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
554 u64::from(self.0).hash(state);
555 }
556}
557
558impl From<NodeId> for LayoutId {
559 fn from(node_id: NodeId) -> Self {
560 Self(node_id)
561 }
562}
563
564impl From<LayoutId> for NodeId {
565 fn from(layout_id: LayoutId) -> NodeId {
566 layout_id.0
567 }
568}
569
570fn snap_measured_size_to_device_pixels(size: Size<Pixels>, scale_factor: f32) -> Size<f32> {
571 size.map(|d| ceil_to_device_pixel(d.0.max(0.0), scale_factor))
572}
573
574fn border_widths_to_taffy(
575 widths: &Edges<AbsoluteLength>,
576 rem_size: Pixels,
577 scale_factor: f32,
578) -> TaffyRect<taffy::style::LengthPercentage> {
579 let snap = |w: &AbsoluteLength| {
580 taffy::style::LengthPercentage::length(round_stroke_to_device_pixel(
581 w.to_pixels(rem_size).0,
582 scale_factor,
583 ))
584 };
585 TaffyRect {
586 top: snap(&widths.top),
587 right: snap(&widths.right),
588 bottom: snap(&widths.bottom),
589 left: snap(&widths.left),
590 }
591}
592
593trait ToTaffy<Output> {
594 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> Output;
595}
596
597impl ToTaffy<taffy::style::Style> for Style {
598 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Style {
599 use taffy::style_helpers::{fr, length, minmax, repeat};
600
601 fn to_grid_line(
602 placement: &Range<crate::GridPlacement>,
603 ) -> taffy::Line<taffy::GridPlacement> {
604 taffy::Line {
605 start: placement.start.into(),
606 end: placement.end.into(),
607 }
608 }
609
610 fn to_grid_repeat<T: taffy::style::CheapCloneStr>(
611 unit: &Option<GridTemplate>,
612 ) -> Vec<taffy::GridTemplateComponent<T>> {
613 unit.map(|template| {
614 match template.min_size {
615 crate::GridTemplateMinSize::Zero => {
617 vec![repeat(
618 template.repeat,
619 vec![minmax(length(0.0_f32), fr(1.0_f32))],
620 )]
621 }
622 crate::GridTemplateMinSize::MinContent => {
624 vec![repeat(
625 template.repeat,
626 vec![minmax(min_content(), fr(1.0_f32))],
627 )]
628 }
629 crate::GridTemplateMinSize::MaxContent => {
631 vec![repeat(
632 template.repeat,
633 vec![minmax(length(0.0_f32), max_content())],
634 )]
635 }
636 }
637 })
638 .unwrap_or_default()
639 }
640
641 fn to_track_size_min(size: crate::GridTrackSize) -> taffy::MinTrackSizingFunction {
645 use crate::GridTrackSize as G;
646 use taffy::MinTrackSizingFunction as M;
647 match size {
648 G::Auto => M::auto(),
649 G::MinContent => M::min_content(),
650 G::MaxContent => M::max_content(),
651 G::Px(v) => M::length(v),
652 G::Percent(v) => M::percent(v),
653 G::Fr(_) => M::auto(),
656 }
657 }
658 fn to_track_size_max(size: crate::GridTrackSize) -> taffy::MaxTrackSizingFunction {
659 use crate::GridTrackSize as G;
660 use taffy::MaxTrackSizingFunction as M;
661 match size {
662 G::Auto => M::auto(),
663 G::MinContent => M::min_content(),
664 G::MaxContent => M::max_content(),
665 G::Px(v) => M::length(v),
666 G::Percent(v) => M::percent(v),
667 G::Fr(v) => M::fr(v),
668 }
669 }
670 fn to_grid_tracks<T: taffy::style::CheapCloneStr>(
671 tracks: &Option<Vec<crate::GridTrack>>,
672 auto: Option<crate::GridAutoRepeat>,
673 ) -> Option<Vec<taffy::GridTemplateComponent<T>>> {
674 let track =
675 |t: &crate::GridTrack| minmax(to_track_size_min(t.min), to_track_size_max(t.max));
676 tracks.as_ref().map(|list| {
677 let run = auto
680 .map(|a| a.start as usize..(a.start as usize + a.len as usize))
681 .filter(|run| !run.is_empty() && run.end <= list.len());
682 let mut out = Vec::with_capacity(list.len());
683 for (index, t) in list.iter().enumerate() {
684 match (&run, auto) {
685 (Some(run), Some(a)) if run.contains(&index) => {
686 if index == run.start {
687 let count = if a.fit {
688 taffy::RepetitionCount::AutoFit
689 } else {
690 taffy::RepetitionCount::AutoFill
691 };
692 out.push(repeat(
693 count,
694 list[run.clone()].iter().map(track).collect(),
695 ));
696 }
697 }
698 _ => out.push(taffy::GridTemplateComponent::Single(track(t))),
699 }
700 }
701 out
702 })
703 }
704
705 taffy::style::Style {
706 display: self.display.into(),
707 overflow: self.overflow.into(),
708 scrollbar_width: self.scrollbar_width.to_taffy(rem_size, scale_factor),
709 position: self.position.into(),
710 inset: self.inset.to_taffy(rem_size, scale_factor),
711 size: self.size.to_taffy(rem_size, scale_factor),
712 min_size: self.min_size.to_taffy(rem_size, scale_factor),
713 max_size: self.max_size.to_taffy(rem_size, scale_factor),
714 aspect_ratio: self.aspect_ratio,
715 margin: self.margin.to_taffy(rem_size, scale_factor),
716 padding: self.padding.to_taffy(rem_size, scale_factor),
717 border: border_widths_to_taffy(&self.border_widths, rem_size, scale_factor),
718 align_items: self.align_items.map(Into::into).unwrap_or_default(),
719 align_self: self.align_self.map(|x| x.into()),
720 align_content: self.align_content.map(Into::into).unwrap_or_default(),
721 justify_content: self.justify_content.map(Into::into).unwrap_or_default(),
722 gap: self.gap.to_taffy(rem_size, scale_factor),
723 flex_direction: self.flex_direction.into(),
724 flex_wrap: self.flex_wrap.into(),
725 flex_basis: self.flex_basis.to_taffy(rem_size, scale_factor),
726 flex_grow: self.flex_grow,
727 flex_shrink: self.flex_shrink,
728 grid_template_rows: to_grid_tracks(&self.vn_grid_rows, self.vn_grid_rows_auto)
730 .unwrap_or_else(|| to_grid_repeat(&self.grid_rows)),
731 grid_template_columns: to_grid_tracks(&self.vn_grid_cols, self.vn_grid_cols_auto)
732 .unwrap_or_else(|| to_grid_repeat(&self.grid_cols)),
733 grid_auto_columns: self.vn_grid_auto_cols.as_ref().map(|tracks| tracks.iter()
734 .map(|track| minmax(to_track_size_min(track.min), to_track_size_max(track.max)))
735 .collect()).unwrap_or_default(),
736 grid_auto_rows: self.vn_grid_auto_rows.as_ref().map(|tracks| tracks.iter()
737 .map(|track| minmax(to_track_size_min(track.min), to_track_size_max(track.max)))
738 .collect()).unwrap_or_default(),
739 grid_auto_flow: match self.vn_grid_auto_flow.unwrap_or_default() {
740 crate::GridAutoFlow::Row => taffy::GridAutoFlow::Row,
741 crate::GridAutoFlow::Column => taffy::GridAutoFlow::Column,
742 crate::GridAutoFlow::RowDense => taffy::GridAutoFlow::RowDense,
743 crate::GridAutoFlow::ColumnDense => taffy::GridAutoFlow::ColumnDense,
744 },
745 justify_items: self.vn_justify_items.map(Into::into).unwrap_or_default(),
746 justify_self: self.vn_justify_self.map(|x| x.into()),
747 grid_row: self
748 .grid_location
749 .as_ref()
750 .map(|location| to_grid_line(&location.row))
751 .unwrap_or_default(),
752 grid_column: self
753 .grid_location
754 .as_ref()
755 .map(|location| to_grid_line(&location.column))
756 .unwrap_or_default(),
757 ..Default::default()
758 }
759 }
760}
761
762impl ToTaffy<f32> for AbsoluteLength {
763 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> f32 {
764 round_to_device_pixel(self.to_pixels(rem_size).0, scale_factor)
765 }
766}
767
768impl ToTaffy<taffy::style::LengthPercentageAuto> for Length {
769 fn to_taffy(
770 &self,
771 rem_size: Pixels,
772 scale_factor: f32,
773 ) -> taffy::prelude::LengthPercentageAuto {
774 match self {
775 Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
776 Length::Auto => taffy::prelude::LengthPercentageAuto::auto(),
777 }
778 }
779}
780
781impl ToTaffy<taffy::style::Dimension> for Length {
782 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::prelude::Dimension {
783 match self {
784 Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
785 Length::Auto => taffy::prelude::Dimension::auto(),
786 }
787 }
788}
789
790impl ToTaffy<taffy::style::LengthPercentage> for DefiniteLength {
791 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
792 match self {
793 DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
794 DefiniteLength::Fraction(fraction) => {
795 taffy::style::LengthPercentage::percent(*fraction)
796 }
797 DefiniteLength::Calc { fraction, pixels } => {
798 match calc_handle(*fraction, *pixels, scale_factor) {
799 Ok(handle) => taffy::style::LengthPercentage::calc(handle),
800 Err(pixels) => taffy::style::LengthPercentage::length(pixels),
801 }
802 }
803 }
804 }
805}
806
807impl ToTaffy<taffy::style::LengthPercentageAuto> for DefiniteLength {
808 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
809 match self {
810 DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
811 DefiniteLength::Fraction(fraction) => {
812 taffy::style::LengthPercentageAuto::percent(*fraction)
813 }
814 DefiniteLength::Calc { fraction, pixels } => {
815 match calc_handle(*fraction, *pixels, scale_factor) {
816 Ok(handle) => taffy::style::LengthPercentageAuto::calc(handle),
817 Err(pixels) => taffy::style::LengthPercentageAuto::length(pixels),
818 }
819 }
820 }
821 }
822}
823
824impl ToTaffy<taffy::style::Dimension> for DefiniteLength {
825 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
826 match self {
827 DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
828 DefiniteLength::Fraction(fraction) => taffy::style::Dimension::percent(*fraction),
829 DefiniteLength::Calc { fraction, pixels } => {
830 match calc_handle(*fraction, *pixels, scale_factor) {
831 Ok(handle) => taffy::style::Dimension::calc(handle),
832 Err(pixels) => taffy::style::Dimension::length(pixels),
833 }
834 }
835 }
836 }
837}
838
839fn calc_handle(fraction: f32, pixels: Pixels, scale_factor: f32) -> Result<*const (), f32> {
857 let length = round_to_device_pixel(pixels.0, scale_factor);
858 if fraction == 0. {
859 return Err(length);
860 }
861 #[cfg(target_pointer_width = "64")]
862 {
863 let bits = ((length.to_bits() as u64) << 32) | (fraction.to_bits() & !0b111) as u64;
864 if bits == 0 {
865 return Err(length);
866 }
867 Ok(bits as usize as *const ())
868 }
869 #[cfg(not(target_pointer_width = "64"))]
870 {
871 Err(length)
872 }
873}
874
875#[inline(always)]
880fn resolve_calc_handle(val: *const (), basis: f32) -> f32 {
881 #[cfg(target_pointer_width = "64")]
882 {
883 let bits = val as usize as u64;
884 let length = f32::from_bits((bits >> 32) as u32);
885 let fraction = f32::from_bits(bits as u32 & !0b111);
886 fraction * basis + length
887 }
888 #[cfg(not(target_pointer_width = "64"))]
889 {
890 let _ = (val, basis);
891 0.0
892 }
893}
894
895impl ToTaffy<taffy::style::LengthPercentage> for AbsoluteLength {
896 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
897 taffy::style::LengthPercentage::length(self.to_taffy(rem_size, scale_factor))
898 }
899}
900
901impl ToTaffy<taffy::style::LengthPercentageAuto> for AbsoluteLength {
902 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
903 taffy::style::LengthPercentageAuto::length(self.to_taffy(rem_size, scale_factor))
904 }
905}
906
907impl ToTaffy<taffy::style::Dimension> for AbsoluteLength {
908 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
909 taffy::style::Dimension::length(self.to_taffy(rem_size, scale_factor))
910 }
911}
912
913impl<T, T2> From<TaffyPoint<T>> for Point<T2>
914where
915 T: Into<T2>,
916 T2: Clone + Debug + Default + PartialEq,
917{
918 fn from(point: TaffyPoint<T>) -> Point<T2> {
919 Point {
920 x: point.x.into(),
921 y: point.y.into(),
922 }
923 }
924}
925
926impl<T, T2> From<Point<T>> for TaffyPoint<T2>
927where
928 T: Into<T2> + Clone + Debug + Default + PartialEq,
929{
930 fn from(val: Point<T>) -> Self {
931 TaffyPoint {
932 x: val.x.into(),
933 y: val.y.into(),
934 }
935 }
936}
937
938impl<T, U> ToTaffy<TaffySize<U>> for Size<T>
939where
940 T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
941{
942 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffySize<U> {
943 TaffySize {
944 width: self.width.to_taffy(rem_size, scale_factor),
945 height: self.height.to_taffy(rem_size, scale_factor),
946 }
947 }
948}
949
950impl<T, U> ToTaffy<TaffyRect<U>> for Edges<T>
951where
952 T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
953{
954 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffyRect<U> {
955 TaffyRect {
956 top: self.top.to_taffy(rem_size, scale_factor),
957 right: self.right.to_taffy(rem_size, scale_factor),
958 bottom: self.bottom.to_taffy(rem_size, scale_factor),
959 left: self.left.to_taffy(rem_size, scale_factor),
960 }
961 }
962}
963
964impl<T, U> From<TaffySize<T>> for Size<U>
965where
966 T: Into<U>,
967 U: Clone + Debug + Default + PartialEq,
968{
969 fn from(taffy_size: TaffySize<T>) -> Self {
970 Size {
971 width: taffy_size.width.into(),
972 height: taffy_size.height.into(),
973 }
974 }
975}
976
977impl<T, U> From<Size<T>> for TaffySize<U>
978where
979 T: Into<U> + Clone + Debug + Default + PartialEq,
980{
981 fn from(size: Size<T>) -> Self {
982 TaffySize {
983 width: size.width.into(),
984 height: size.height.into(),
985 }
986 }
987}
988
989#[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
991pub enum AvailableSpace {
992 Definite(Pixels),
994 #[default]
996 MinContent,
997 MaxContent,
999}
1000
1001impl AvailableSpace {
1002 pub const fn min_size() -> Size<Self> {
1016 Size {
1017 width: Self::MinContent,
1018 height: Self::MinContent,
1019 }
1020 }
1021}
1022
1023impl From<AvailableSpace> for TaffyAvailableSpace {
1024 fn from(space: AvailableSpace) -> TaffyAvailableSpace {
1025 match space {
1026 AvailableSpace::Definite(Pixels(value)) => TaffyAvailableSpace::Definite(value),
1027 AvailableSpace::MinContent => TaffyAvailableSpace::MinContent,
1028 AvailableSpace::MaxContent => TaffyAvailableSpace::MaxContent,
1029 }
1030 }
1031}
1032
1033impl From<TaffyAvailableSpace> for AvailableSpace {
1034 fn from(space: TaffyAvailableSpace) -> AvailableSpace {
1035 match space {
1036 TaffyAvailableSpace::Definite(value) => AvailableSpace::Definite(Pixels(value)),
1037 TaffyAvailableSpace::MinContent => AvailableSpace::MinContent,
1038 TaffyAvailableSpace::MaxContent => AvailableSpace::MaxContent,
1039 }
1040 }
1041}
1042
1043impl From<Pixels> for AvailableSpace {
1044 fn from(pixels: Pixels) -> Self {
1045 AvailableSpace::Definite(pixels)
1046 }
1047}
1048
1049impl From<Size<Pixels>> for Size<AvailableSpace> {
1050 fn from(size: Size<Pixels>) -> Self {
1051 Size {
1052 width: AvailableSpace::Definite(size.width),
1053 height: AvailableSpace::Definite(size.height),
1054 }
1055 }
1056}
1057
1058#[cfg(test)]
1059mod tests {
1060 use super::*;
1061
1062 #[test]
1063 fn flex_and_grid_lay_their_children_out_in_order_modified_document_order() {
1064 let mut engine = TaffyLayoutEngine::new();
1065 let leaf = |engine: &mut TaffyLayoutEngine, order: i32| {
1066 let style = Style { vn_order: order, ..Default::default() };
1067 engine.request_layout(style, Pixels(16.0), 1.0, &[])
1068 };
1069 let kids = [leaf(&mut engine, 2), leaf(&mut engine, -1), leaf(&mut engine, 0), leaf(&mut engine, 2)];
1070 let laid_out = |engine: &mut TaffyLayoutEngine, display: Display| {
1071 let style = Style { display, ..Default::default() };
1072 let root = engine.request_layout(style, Pixels(16.0), 1.0, &kids);
1073 engine.taffy.child_ids(root.into()).map(LayoutId::from).collect::<Vec<_>>()
1074 };
1075 let modified = vec![kids[1], kids[2], kids[0], kids[3]];
1076 assert_eq!(laid_out(&mut engine, Display::Flex), modified);
1077 assert_eq!(laid_out(&mut engine, Display::Grid), modified);
1078 assert_eq!(laid_out(&mut engine, Display::Block), kids.to_vec());
1079 engine.clear();
1080 let fresh = [leaf(&mut engine, 0), leaf(&mut engine, 0)];
1081 let root = engine.request_layout(Style { display: Display::Flex, ..Default::default() }, Pixels(16.0), 1.0, &fresh);
1082 assert!(engine.taffy.child_ids(root.into()).map(LayoutId::from).eq(fresh));
1083 }
1084
1085 #[test]
1086 fn implicit_fractional_columns_share_the_container_width() {
1087 let mut tree = TaffyTree::<()>::new();
1088 let children: Vec<_> = (0..3).map(|_| tree.new_leaf(Default::default()).unwrap()).collect();
1089 let style = Style {
1090 display: crate::Display::Grid,
1091 size: Size {
1092 width: Length::Definite(Pixels(300.0).into()),
1093 height: Length::Definite(Pixels(40.0).into()),
1094 },
1095 vn_grid_auto_flow: Some(crate::GridAutoFlow::Column),
1096 vn_grid_auto_cols: Some(vec![crate::GridTrack::fr(1.0)]),
1097 ..Default::default()
1098 };
1099 let root = tree.new_with_children(style.to_taffy(Pixels(16.0), 1.0), &children).unwrap();
1100 tree.compute_layout(root, TaffySize {
1101 width: TaffyAvailableSpace::Definite(300.0), height: TaffyAvailableSpace::Definite(40.0),
1102 }).unwrap();
1103 for (index, child) in children.into_iter().enumerate() {
1104 let layout = tree.layout(child).unwrap();
1105 assert_eq!(layout.size.width, 100.0);
1106 assert_eq!(layout.location.x, index as f32 * 100.0);
1107 }
1108 }
1109
1110 #[test]
1111 fn implicit_row_patterns_repeat_in_layout() {
1112 use crate::GridTrackSize as Track;
1113 let mut tree = TaffyTree::<()>::new();
1114 let children: Vec<_> = (0..5).map(|_| tree.new_leaf(Default::default()).unwrap()).collect();
1115 let style = Style {
1116 display: crate::Display::Grid,
1117 vn_grid_cols: Some(vec![crate::GridTrack::fixed(Track::Px(100.0))]),
1118 vn_grid_auto_rows: Some(vec![crate::GridTrack::fixed(Track::Px(20.0)), crate::GridTrack::fixed(Track::Px(35.0))]),
1119 ..Default::default()
1120 };
1121 let root = tree.new_with_children(style.to_taffy(Pixels(16.0), 1.0), &children).unwrap();
1122 tree.compute_layout(root, TaffySize {
1123 width: TaffyAvailableSpace::MaxContent, height: TaffyAvailableSpace::MaxContent,
1124 }).unwrap();
1125 for ((height, top), child) in [(20.0, 0.0), (35.0, 20.0), (20.0, 55.0), (35.0, 75.0), (20.0, 110.0)].into_iter().zip(children) {
1126 let layout = tree.layout(child).unwrap();
1127 assert_eq!(layout.size.height, height);
1128 assert_eq!(layout.location.y, top);
1129 }
1130 }
1131
1132 #[test]
1133 fn implicit_auto_reset_replaces_a_fixed_row_pattern() {
1134 use crate::{GridTrack, GridTrackSize, Refineable, StyleRefinement};
1135 let mut style = Style {
1136 display: crate::Display::Grid,
1137 vn_grid_cols: Some(vec![GridTrack::fixed(GridTrackSize::Px(100.0))]),
1138 vn_grid_auto_rows: Some(vec![GridTrack::fixed(GridTrackSize::Px(50.0))]),
1139 ..Default::default()
1140 };
1141 style.refine(&StyleRefinement { vn_grid_auto_rows: Some(Vec::new()), ..Default::default() });
1142 let mut tree = TaffyTree::<()>::new();
1143 let children: Vec<_> = [17.0, 29.0].into_iter().map(|height| {
1144 let mut leaf_style = taffy::style::Style::default();
1145 leaf_style.size.height = taffy::style::Dimension::length(height);
1146 tree.new_leaf(leaf_style).unwrap()
1147 }).collect();
1148 let root = tree.new_with_children(style.to_taffy(Pixels(16.0), 1.0), &children).unwrap();
1149 tree.compute_layout(root, TaffySize {
1150 width: TaffyAvailableSpace::MaxContent, height: TaffyAvailableSpace::MaxContent,
1151 }).unwrap();
1152 assert_eq!(tree.layout(children[1]).unwrap().location.y, 17.0);
1153 assert_eq!(tree.layout(root).unwrap().size.height, 46.0);
1154 }
1155
1156 #[test]
1157 fn border_widths_to_taffy_use_stroke_snapping() {
1158 let border_widths = Edges {
1159 top: Pixels(0.0).into(),
1160 right: Pixels(0.4).into(),
1161 bottom: Pixels(0.5).into(),
1162 left: Pixels(1.6).into(),
1163 };
1164 let taffy_border = border_widths_to_taffy(&border_widths, Pixels(16.0), 1.0);
1165
1166 assert_eq!(
1167 taffy_border.top,
1168 taffy::style::LengthPercentage::length(0.0)
1169 );
1170 assert_eq!(
1171 taffy_border.right,
1172 taffy::style::LengthPercentage::length(1.0)
1173 );
1174 assert_eq!(
1175 taffy_border.bottom,
1176 taffy::style::LengthPercentage::length(1.0)
1177 );
1178 assert_eq!(
1179 taffy_border.left,
1180 taffy::style::LengthPercentage::length(2.0)
1181 );
1182 }
1183}