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 calc_sizes: Vec<CalcSizeNode>,
48}
49
50const EXPECT_MESSAGE: &str = "we should avoid taffy layout errors by construction if possible";
51
52impl TaffyLayoutEngine {
53 pub fn new() -> Self {
54 let mut taffy = TaffyTree::new();
55 taffy.disable_rounding();
56 TaffyLayoutEngine {
57 taffy,
58 absolute_layout_bounds: LayoutIdMap::default(),
59 absolute_outer_origins: LayoutIdMap::default(),
60 retention: retained::Retention::default(),
61 computed_layouts: FxHashSet::default(),
62 layout_bounds_scratch_space: Vec::new(),
63 orders: FxHashMap::default(),
64 calc_sizes: Vec::new(),
65 }
66 }
67
68 pub fn clear(&mut self) {
69 if self.retention.enabled {
70 retained::finish_frame(self);
71 } else {
72 self.taffy.clear();
73 }
74 self.absolute_layout_bounds.clear();
75 self.absolute_outer_origins.clear();
76 self.computed_layouts.clear();
77 self.orders.clear();
78 self.calc_sizes.clear();
79 }
80
81 pub(crate) fn retention_enabled(&self) -> bool {
82 self.retention.enabled
83 }
84
85 pub(crate) fn enable_retention(&mut self) {
86 if !self.retention.enabled {
87 assert_eq!(
88 self.taffy.total_node_count(),
89 0,
90 "enable retained layout before the first layout request"
91 );
92 self.retention.enabled = true;
93 }
94 }
95
96 pub(crate) fn profile_retention(&mut self, enabled: bool) {
97 self.retention.stats = enabled.then(Default::default);
98 }
99
100 pub(crate) fn take_retention_stats(&mut self) -> Option<VnRetainedLayoutStats> {
101 self.retention.stats.as_mut().map(std::mem::take)
102 }
103
104 pub fn request_layout(
105 &mut self,
106 style: Style,
107 rem_size: Pixels,
108 scale_factor: f32,
109 children: &[LayoutId],
110 ) -> LayoutId {
111 self.request_layout_in_scope(None, style, rem_size, scale_factor, children)
112 }
113
114 pub(crate) fn request_layout_in_scope(
115 &mut self,
116 scope: Option<crate::GlobalElementId>,
117 style: Style,
118 rem_size: Pixels,
119 scale_factor: f32,
120 children: &[LayoutId],
121 ) -> LayoutId {
122 let taffy_style = style.to_taffy(rem_size, scale_factor);
123 let reordered = self.order_modified(&style, children);
124 let children = reordered.as_deref().unwrap_or(children);
125 let id = if self.retention.enabled {
126 retained::request_layout(self, scope, taffy_style, children)
127 } else if children.is_empty() {
128 self.taffy
129 .new_leaf(taffy_style)
130 .expect(EXPECT_MESSAGE)
131 .into()
132 } else {
133 self.taffy
134 .new_with_children(taffy_style, LayoutId::to_taffy_slice(children))
136 .expect(EXPECT_MESSAGE)
137 .into()
138 };
139 self.note_order(id, &style);
140 id
141 }
142
143 fn note_order(&mut self, id: LayoutId, style: &Style) {
144 if style.vn_order != 0 {
145 self.orders.insert(id, style.vn_order);
146 }
147 if let Some(node) = CalcSizeNode::of(id, style) {
148 self.calc_sizes.push(node);
149 }
150 }
151
152 fn order_modified(&self, style: &Style, children: &[LayoutId]) -> Option<Vec<LayoutId>> {
155 if self.orders.is_empty() || !matches!(style.display, Display::Flex | Display::Grid) {
156 return None;
157 }
158 let order = |id: &LayoutId| self.orders.get(id).copied().unwrap_or(0);
159 if children.windows(2).all(|w| order(&w[0]) <= order(&w[1])) {
160 return None;
161 }
162 let mut sorted = children.to_vec();
163 sorted.sort_by_key(order);
164 Some(sorted)
165 }
166
167 pub fn request_measured_layout(
168 &mut self,
169 style: Style,
170 rem_size: Pixels,
171 scale_factor: f32,
172 measure: impl FnMut(
173 Size<Option<Pixels>>,
174 Size<AvailableSpace>,
175 &mut Window,
176 &mut App,
177 ) -> Size<Pixels>
178 + 'static,
179 ) -> LayoutId {
180 self.request_measured_layout_in_scope(None, style, rem_size, scale_factor, measure)
181 }
182
183 pub(crate) fn request_measured_layout_in_scope(
184 &mut self,
185 scope: Option<crate::GlobalElementId>,
186 style: Style,
187 rem_size: Pixels,
188 scale_factor: f32,
189 measure: impl FnMut(
190 Size<Option<Pixels>>,
191 Size<AvailableSpace>,
192 &mut Window,
193 &mut App,
194 ) -> Size<Pixels>
195 + 'static,
196 ) -> LayoutId {
197 let taffy_style = style.to_taffy(rem_size, scale_factor);
198 let id = if self.retention.enabled {
199 retained::request_measured_layout(self, scope, taffy_style, measure)
200 } else {
201 let measure = Box::new(measure) as Box<MeasureFn>;
202 #[cfg(feature = "stacker")]
203 let measure = StackSafe::new(measure);
204
205 self.taffy
206 .new_leaf_with_context(taffy_style, NodeContext { measure })
207 .expect(EXPECT_MESSAGE)
208 .into()
209 };
210 self.note_order(id, &style);
211 id
212 }
213
214 pub fn stretch_auto_size_to_fill(
221 &mut self,
222 id: LayoutId,
223 size: Size<Pixels>,
224 scale_factor: f32,
225 ) {
226 if self.retention.enabled {
227 retained::stretch(self, id, size, scale_factor);
228 return;
229 }
230 let style = self.taffy.style(id.0).expect(EXPECT_MESSAGE);
231 let stretch_width = style.size.width.is_auto();
232 let stretch_height = style.size.height.is_auto();
233 if !stretch_width && !stretch_height {
234 return;
235 }
236 let mut style = style.clone();
237 if stretch_width {
238 style.size.width =
239 taffy::style::Dimension::length(round_to_device_pixel(size.width.0, scale_factor));
240 }
241 if stretch_height {
242 style.size.height =
243 taffy::style::Dimension::length(round_to_device_pixel(size.height.0, scale_factor));
244 }
245 self.taffy.set_style(id.0, style).expect(EXPECT_MESSAGE);
246 }
247
248 #[allow(dead_code)]
250 fn count_all_children(&self, parent: LayoutId) -> anyhow::Result<u32> {
251 let mut count = 0;
252
253 for child in self.taffy.children(parent.0)? {
254 count += 1;
256
257 count += self.count_all_children(LayoutId(child))?
259 }
260
261 Ok(count)
262 }
263
264 #[allow(dead_code)]
266 fn max_depth(&self, depth: u32, parent: LayoutId) -> anyhow::Result<u32> {
267 println!(
268 "{parent:?} at depth {depth} has {} children",
269 self.taffy.child_count(parent.0)
270 );
271
272 let mut max_child_depth = 0;
273
274 for child in self.taffy.children(parent.0)? {
275 max_child_depth = std::cmp::max(max_child_depth, self.max_depth(0, LayoutId(child))?);
276 }
277
278 Ok(depth + 1 + max_child_depth)
279 }
280
281 #[allow(dead_code)]
283 fn get_edges(&self, parent: LayoutId) -> anyhow::Result<Vec<(LayoutId, LayoutId)>> {
284 let mut edges = Vec::new();
285
286 for child in self.taffy.children(parent.0)? {
287 edges.push((parent, LayoutId(child)));
288
289 edges.extend(self.get_edges(LayoutId(child))?);
290 }
291
292 Ok(edges)
293 }
294
295 pub(crate) fn detach_root(&mut self, id: LayoutId) {
303 if let Some(parent) = self.taffy.parent(id.0) {
304 self.taffy.remove_child(parent, id.0).expect(EXPECT_MESSAGE);
305 }
306 }
307
308 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
309 pub fn compute_layout(
310 &mut self,
311 id: LayoutId,
312 available_space: Size<AvailableSpace>,
313 window: &mut Window,
314 cx: &mut App,
315 ) {
316 if self.retention.enabled {
328 self.detach_root(id);
329 }
330
331 if !self.computed_layouts.insert(id) {
332 let stack = &mut self.layout_bounds_scratch_space;
333 stack.push(id);
334 while let Some(id) = stack.pop() {
335 self.absolute_layout_bounds.remove(&id);
336 self.absolute_outer_origins.remove(&id);
337 stack.extend(
338 self.taffy
339 .children(id.into())
340 .expect(EXPECT_MESSAGE)
341 .into_iter()
342 .map(LayoutId::from),
343 );
344 }
345 }
346
347 let scale_factor = window.scale_factor();
348
349 let transform = |v: AvailableSpace| match v {
350 AvailableSpace::Definite(pixels) => {
351 AvailableSpace::Definite(Pixels(pixels.0 * scale_factor))
352 }
353 AvailableSpace::MinContent => AvailableSpace::MinContent,
354 AvailableSpace::MaxContent => AvailableSpace::MaxContent,
355 };
356 let available_space = size(
357 transform(available_space.width),
358 transform(available_space.height),
359 );
360
361 if self.retention.enabled {
362 retained::prepare_compute(self, scale_factor);
363 retained::replay(self, window, cx);
364 }
365 let calc_sizes = self.take_calc_sizes(id);
366 if !calc_sizes.is_empty() {
367 let requested = self.probe_calc_sizes(&calc_sizes);
368 self.run_taffy(id, available_space, scale_factor, window, cx);
369 let rem_size = window.rem_size();
370 self.resolve_calc_sizes(&calc_sizes, requested, rem_size, scale_factor);
371 }
372 self.run_taffy(id, available_space, scale_factor, window, cx);
373 if self.retention.enabled {
374 retained::settle(self, window, cx);
375 }
376 }
377
378 fn run_taffy(
379 &mut self,
380 id: LayoutId,
381 available_space: Size<AvailableSpace>,
382 scale_factor: f32,
383 window: &mut Window,
384 cx: &mut App,
385 ) {
386 let retention = &mut self.retention;
387 self.taffy
388 .compute_layout_with_measure(
389 id.into(),
390 available_space.into(),
391 |input, id, node_context, style| {
392 taffy::compute_leaf_layout(
393 input,
394 style,
395 resolve_calc_handle,
399 |known_dimensions, available_space| {
400 let Some(node_context) = node_context else {
401 return taffy::geometry::Size::default();
402 };
403
404 let known_dimensions = Size {
405 width: known_dimensions.width.map(|e| Pixels(e / scale_factor)),
406 height: known_dimensions.height.map(|e| Pixels(e / scale_factor)),
407 };
408
409 let available_space: Size<AvailableSpace> = available_space.into();
410 let untransform = |ev: AvailableSpace| match ev {
411 AvailableSpace::Definite(pixels) => {
412 AvailableSpace::Definite(Pixels(pixels.0 / scale_factor))
413 }
414 AvailableSpace::MinContent => AvailableSpace::MinContent,
415 AvailableSpace::MaxContent => AvailableSpace::MaxContent,
416 };
417 let available_space = size(
418 untransform(available_space.width),
419 untransform(available_space.height),
420 );
421
422 if retention.enabled {
423 retained::note_measure(
424 retention,
425 id,
426 known_dimensions,
427 available_space,
428 );
429 }
430 let measured_size: Size<Pixels> = (node_context.measure)(
431 known_dimensions,
432 available_space,
433 window,
434 cx,
435 );
436 snap_measured_size_to_device_pixels(measured_size, scale_factor).into()
437 },
438 )
439 },
440 )
441 .expect(EXPECT_MESSAGE);
442 }
443
444 fn take_calc_sizes(&mut self, root: LayoutId) -> Vec<CalcSizeNode> {
446 if self.calc_sizes.is_empty() {
447 return Vec::new();
448 }
449 let taffy = &self.taffy;
450 let under = |mut node: NodeId| loop {
451 if node == root.0 {
452 return true;
453 }
454 match taffy.parent(node) {
455 Some(parent) => node = parent,
456 None => return false,
457 }
458 };
459 let (mine, rest) = std::mem::take(&mut self.calc_sizes)
460 .into_iter()
461 .partition(|n| under(n.id.0));
462 self.calc_sizes = rest;
463 mine
464 }
465
466 fn probe_calc_sizes(&mut self, nodes: &[CalcSizeNode]) -> Vec<taffy::style::Style> {
470 nodes
471 .iter()
472 .map(|node| {
473 let requested = self.taffy.style(node.id.0).expect(EXPECT_MESSAGE).clone();
474 let mut probe = requested.clone();
475 for (axis, props) in [(0, &node.width), (1, &node.height)] {
476 let Some(first) = props.iter().flatten().next() else {
477 continue;
478 };
479 let size = basis_dimension(first.basis);
480 let none = taffy::style::LengthPercentageAuto::auto();
481 if axis == 0 {
482 probe.size.width = size;
483 probe.min_size.width = none;
484 probe.max_size.width = none;
485 } else {
486 probe.size.height = size;
487 probe.min_size.height = none;
488 probe.max_size.height = none;
489 }
490 }
491 if let Some(main) = self.main_axis(node.id) {
492 let sized = [&node.width, &node.height][main].iter().any(Option::is_some);
495 if let Some(basis) = node.flex_basis {
496 probe.flex_basis = basis_dimension(basis.basis);
497 } else if sized {
498 probe.flex_basis = taffy::style::Dimension::auto();
499 }
500 if node.flex_basis.is_some() || sized {
501 probe.flex_grow = 0.;
502 probe.flex_shrink = 0.;
503 }
504 }
505 if probe != requested {
506 self.taffy.set_style(node.id.0, probe).expect(EXPECT_MESSAGE);
507 }
508 requested
509 })
510 .collect()
511 }
512
513 fn resolve_calc_sizes(
516 &mut self,
517 nodes: &[CalcSizeNode],
518 requested: Vec<taffy::style::Style>,
519 rem_size: Pixels,
520 scale_factor: f32,
521 ) {
522 for (node, mut style) in nodes.iter().zip(requested) {
523 let layout = *self.taffy.layout(node.id.0).expect(EXPECT_MESSAGE);
524 let content_box = style.box_sizing == taffy::style::BoxSizing::ContentBox;
525 let inner = |outer: f32, a: f32, b: f32, c: f32, d: f32| {
526 if content_box {
527 (outer - a - b - c - d).max(0.)
528 } else {
529 outer
530 }
531 };
532 let measured = [
533 inner(
534 layout.size.width,
535 layout.padding.left,
536 layout.padding.right,
537 layout.border.left,
538 layout.border.right,
539 ),
540 inner(
541 layout.size.height,
542 layout.padding.top,
543 layout.padding.bottom,
544 layout.border.top,
545 layout.border.bottom,
546 ),
547 ];
548 let resolve = |c: &crate::VnCalcSize, axis: usize| {
549 calc_size_value(c, measured[axis] / scale_factor, rem_size, scale_factor)
550 };
551 let dimension = |v: Result<*const (), f32>| match v {
552 Ok(handle) => taffy::style::Dimension::calc(handle),
553 Err(length) => taffy::style::Dimension::length(length),
554 };
555 let bound = |v: Result<*const (), f32>| match v {
556 Ok(handle) => taffy::style::LengthPercentageAuto::calc(handle),
557 Err(length) => taffy::style::LengthPercentageAuto::length(length),
558 };
559 for axis in 0..2 {
560 let [size, min, max] = if axis == 0 { node.width } else { node.height };
561 let (s, lo, hi) = if axis == 0 {
562 (
563 &mut style.size.width,
564 &mut style.min_size.width,
565 &mut style.max_size.width,
566 )
567 } else {
568 (
569 &mut style.size.height,
570 &mut style.min_size.height,
571 &mut style.max_size.height,
572 )
573 };
574 if let Some(c) = size {
575 *s = dimension(resolve(&c, axis));
576 }
577 if let Some(c) = min {
578 *lo = bound(resolve(&c, axis));
579 }
580 if let Some(c) = max {
581 *hi = bound(resolve(&c, axis));
582 }
583 }
584 if let (Some(c), Some(axis)) = (node.flex_basis, self.main_axis(node.id)) {
585 style.flex_basis = dimension(resolve(&c, axis));
586 }
587 if self.taffy.style(node.id.0).expect(EXPECT_MESSAGE) != &style {
588 self.taffy.set_style(node.id.0, style).expect(EXPECT_MESSAGE);
589 }
590 }
591 }
592
593 fn main_axis(&self, id: LayoutId) -> Option<usize> {
595 let parent = self.taffy.parent(id.0)?;
596 let style = self.taffy.style(parent).ok()?;
597 use taffy::style::FlexDirection as F;
598 (style.display == taffy::style::Display::Flex).then(|| match style.flex_direction {
599 F::Row | F::RowReverse => 0,
600 F::Column | F::ColumnReverse => 1,
601 })
602 }
603
604 pub fn is_absolute(&self, id: LayoutId) -> bool {
682 self.taffy
683 .style(id.0)
684 .is_ok_and(|style| style.position == taffy::style::Position::Absolute)
685 }
686
687 pub fn layout_bounds(&mut self, id: LayoutId, scale_factor: f32) -> Bounds<Pixels> {
688 if let Some(layout) = self.absolute_layout_bounds.get(&id).cloned() {
689 return layout;
690 }
691
692 let layout = self.taffy.layout(id.into()).expect(EXPECT_MESSAGE);
693 let layout_location = layout.location;
694 let layout_size = layout.size;
695 let parent = self.taffy.parent(id.0);
696
697 let absolute_outer_origin = match parent {
698 Some(parent_id) => {
699 let parent_id = LayoutId::from(parent_id);
700 self.layout_bounds(parent_id, scale_factor);
701 let parent_origin = *self
702 .absolute_outer_origins
703 .get(&parent_id)
704 .expect("parent absolute outer origin should be cached");
705 parent_origin + Point::from(layout_location)
706 }
707 None => Point::from(layout_location),
708 };
709 self.absolute_outer_origins
710 .insert(id, absolute_outer_origin);
711
712 let absolute_far = absolute_outer_origin + Point::from(Size::from(layout_size));
713 let snapped_bounds = Bounds::from_corners(
714 absolute_outer_origin.map(round_half_toward_zero),
715 absolute_far.map(round_half_toward_zero),
716 );
717
718 let bounds = (snapped_bounds / scale_factor).map(Pixels);
719 self.absolute_layout_bounds.insert(id, bounds);
720 bounds
721 }
722}
723
724#[derive(Copy, Clone, Eq, PartialEq, Debug)]
726#[repr(transparent)]
727pub struct LayoutId(NodeId);
728
729impl LayoutId {
730 fn to_taffy_slice(node_ids: &[Self]) -> &[taffy::NodeId] {
731 unsafe { std::mem::transmute::<&[LayoutId], &[taffy::NodeId]>(node_ids) }
733 }
734}
735
736impl std::hash::Hash for LayoutId {
737 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
738 u64::from(self.0).hash(state);
739 }
740}
741
742impl From<NodeId> for LayoutId {
743 fn from(node_id: NodeId) -> Self {
744 Self(node_id)
745 }
746}
747
748impl From<LayoutId> for NodeId {
749 fn from(layout_id: LayoutId) -> NodeId {
750 layout_id.0
751 }
752}
753
754fn snap_measured_size_to_device_pixels(size: Size<Pixels>, scale_factor: f32) -> Size<f32> {
755 size.map(|d| ceil_to_device_pixel(d.0.max(0.0), scale_factor))
756}
757
758fn border_widths_to_taffy(
759 widths: &Edges<AbsoluteLength>,
760 rem_size: Pixels,
761 scale_factor: f32,
762) -> TaffyRect<taffy::style::LengthPercentage> {
763 let snap = |w: &AbsoluteLength| {
764 taffy::style::LengthPercentage::length(round_stroke_to_device_pixel(
765 w.to_pixels(rem_size).0,
766 scale_factor,
767 ))
768 };
769 TaffyRect {
770 top: snap(&widths.top),
771 right: snap(&widths.right),
772 bottom: snap(&widths.bottom),
773 left: snap(&widths.left),
774 }
775}
776
777trait ToTaffy<Output> {
778 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> Output;
779}
780
781impl ToTaffy<taffy::style::Style> for Style {
782 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Style {
783 use taffy::style_helpers::{fr, length, minmax, repeat};
784
785 fn to_grid_line(
786 placement: &Range<crate::GridPlacement>,
787 ) -> taffy::Line<taffy::GridPlacement> {
788 taffy::Line {
789 start: placement.start.into(),
790 end: placement.end.into(),
791 }
792 }
793
794 fn to_grid_repeat<T: taffy::style::CheapCloneStr>(
795 unit: &Option<GridTemplate>,
796 ) -> Vec<taffy::GridTemplateComponent<T>> {
797 unit.map(|template| {
798 match template.min_size {
799 crate::GridTemplateMinSize::Zero => {
801 vec![repeat(
802 template.repeat,
803 vec![minmax(length(0.0_f32), fr(1.0_f32))],
804 )]
805 }
806 crate::GridTemplateMinSize::MinContent => {
808 vec![repeat(
809 template.repeat,
810 vec![minmax(min_content(), fr(1.0_f32))],
811 )]
812 }
813 crate::GridTemplateMinSize::MaxContent => {
815 vec![repeat(
816 template.repeat,
817 vec![minmax(length(0.0_f32), max_content())],
818 )]
819 }
820 }
821 })
822 .unwrap_or_default()
823 }
824
825 fn to_track_size_min(size: crate::GridTrackSize) -> taffy::MinTrackSizingFunction {
829 use crate::GridTrackSize as G;
830 use taffy::MinTrackSizingFunction as M;
831 match size {
832 G::Auto => M::auto(),
833 G::MinContent => M::min_content(),
834 G::MaxContent => M::max_content(),
835 G::Px(v) => M::length(v),
836 G::Percent(v) => M::percent(v),
837 G::Fr(_) => M::auto(),
840 }
841 }
842 fn to_track_size_max(size: crate::GridTrackSize) -> taffy::MaxTrackSizingFunction {
843 use crate::GridTrackSize as G;
844 use taffy::MaxTrackSizingFunction as M;
845 match size {
846 G::Auto => M::auto(),
847 G::MinContent => M::min_content(),
848 G::MaxContent => M::max_content(),
849 G::Px(v) => M::length(v),
850 G::Percent(v) => M::percent(v),
851 G::Fr(v) => M::fr(v),
852 }
853 }
854 fn to_grid_tracks<T: taffy::style::CheapCloneStr>(
855 tracks: &Option<Vec<crate::GridTrack>>,
856 auto: Option<crate::GridAutoRepeat>,
857 ) -> Option<Vec<taffy::GridTemplateComponent<T>>> {
858 let track =
859 |t: &crate::GridTrack| minmax(to_track_size_min(t.min), to_track_size_max(t.max));
860 tracks.as_ref().map(|list| {
861 let run = auto
864 .map(|a| a.start as usize..(a.start as usize + a.len as usize))
865 .filter(|run| !run.is_empty() && run.end <= list.len());
866 let mut out = Vec::with_capacity(list.len());
867 for (index, t) in list.iter().enumerate() {
868 match (&run, auto) {
869 (Some(run), Some(a)) if run.contains(&index) => {
870 if index == run.start {
871 let count = if a.fit {
872 taffy::RepetitionCount::AutoFit
873 } else {
874 taffy::RepetitionCount::AutoFill
875 };
876 out.push(repeat(
877 count,
878 list[run.clone()].iter().map(track).collect(),
879 ));
880 }
881 }
882 _ => out.push(taffy::GridTemplateComponent::Single(track(t))),
883 }
884 }
885 out
886 })
887 }
888
889 taffy::style::Style {
890 display: self.display.into(),
891 overflow: self.overflow.into(),
892 scrollbar_width: self.scrollbar_width.to_taffy(rem_size, scale_factor),
893 position: self.position.into(),
894 inset: self.inset.to_taffy(rem_size, scale_factor),
895 size: self.size.to_taffy(rem_size, scale_factor),
896 min_size: self.min_size.to_taffy(rem_size, scale_factor),
897 max_size: self.max_size.to_taffy(rem_size, scale_factor),
898 aspect_ratio: self
899 .aspect_ratio
900 .map(f32::abs)
901 .filter(|ratio| ratio.is_finite() && *ratio > 0.0),
902 margin: self.margin.to_taffy(rem_size, scale_factor),
903 padding: self.padding.to_taffy(rem_size, scale_factor),
904 border: border_widths_to_taffy(&self.border_widths, rem_size, scale_factor),
905 align_items: self.align_items.map(Into::into).unwrap_or_default(),
906 align_self: self.align_self.map(|x| x.into()),
907 align_content: self.align_content.map(Into::into).unwrap_or_default(),
908 justify_content: self.justify_content.map(Into::into).unwrap_or_default(),
909 gap: self.gap.to_taffy(rem_size, scale_factor),
910 flex_direction: self.flex_direction.into(),
911 flex_wrap: self.flex_wrap.into(),
912 flex_basis: self.flex_basis.to_taffy(rem_size, scale_factor),
913 flex_grow: self.flex_grow,
914 flex_shrink: self.flex_shrink,
915 grid_template_rows: to_grid_tracks(&self.vn_grid_rows, self.vn_grid_rows_auto)
917 .unwrap_or_else(|| to_grid_repeat(&self.grid_rows)),
918 grid_template_columns: to_grid_tracks(&self.vn_grid_cols, self.vn_grid_cols_auto)
919 .unwrap_or_else(|| to_grid_repeat(&self.grid_cols)),
920 grid_auto_columns: self.vn_grid_auto_cols.as_ref().map(|tracks| tracks.iter()
921 .map(|track| minmax(to_track_size_min(track.min), to_track_size_max(track.max)))
922 .collect()).unwrap_or_default(),
923 grid_auto_rows: self.vn_grid_auto_rows.as_ref().map(|tracks| tracks.iter()
924 .map(|track| minmax(to_track_size_min(track.min), to_track_size_max(track.max)))
925 .collect()).unwrap_or_default(),
926 grid_auto_flow: match self.vn_grid_auto_flow.unwrap_or_default() {
927 crate::GridAutoFlow::Row => taffy::GridAutoFlow::Row,
928 crate::GridAutoFlow::Column => taffy::GridAutoFlow::Column,
929 crate::GridAutoFlow::RowDense => taffy::GridAutoFlow::RowDense,
930 crate::GridAutoFlow::ColumnDense => taffy::GridAutoFlow::ColumnDense,
931 },
932 justify_items: self.vn_justify_items.map(Into::into).unwrap_or_default(),
933 justify_self: self.vn_justify_self.map(|x| x.into()),
934 grid_row: self
935 .grid_location
936 .as_ref()
937 .map(|location| to_grid_line(&location.row))
938 .unwrap_or_default(),
939 grid_column: self
940 .grid_location
941 .as_ref()
942 .map(|location| to_grid_line(&location.column))
943 .unwrap_or_default(),
944 contain: {
945 let mut contain = taffy::Contain::NONE;
946 if self.vn_contain_size & Style::CONTAIN_INLINE_SIZE != 0 {
947 contain |= taffy::Contain::INLINE_SIZE;
948 }
949 if self.vn_contain_size & Style::CONTAIN_BLOCK_SIZE != 0 {
950 contain |= taffy::Contain::BLOCK_SIZE;
951 }
952 contain
953 },
954 ..Default::default()
955 }
956 }
957}
958
959impl ToTaffy<f32> for AbsoluteLength {
960 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> f32 {
961 round_to_device_pixel(self.to_pixels(rem_size).0, scale_factor)
962 }
963}
964
965impl ToTaffy<taffy::style::LengthPercentageAuto> for Length {
966 fn to_taffy(
967 &self,
968 rem_size: Pixels,
969 scale_factor: f32,
970 ) -> taffy::prelude::LengthPercentageAuto {
971 match self {
972 Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
973 Length::Auto | Length::VnCalcSize(_) => taffy::prelude::LengthPercentageAuto::auto(),
974 }
975 }
976}
977
978impl ToTaffy<taffy::style::Dimension> for Length {
979 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::prelude::Dimension {
980 match self {
981 Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
982 Length::Auto => taffy::prelude::Dimension::auto(),
983 Length::VnCalcSize(c) => basis_dimension(c.basis),
984 }
985 }
986}
987
988struct CalcSizeNode {
991 id: LayoutId,
992 width: [Option<crate::VnCalcSize>; 3],
993 height: [Option<crate::VnCalcSize>; 3],
994 flex_basis: Option<crate::VnCalcSize>,
995}
996
997impl CalcSizeNode {
998 fn of(id: LayoutId, style: &Style) -> Option<Self> {
999 let calc = |l: &Length| match l {
1000 Length::VnCalcSize(c) if !c.is_basis() => Some(*c),
1001 _ => None,
1002 };
1003 let node = CalcSizeNode {
1004 id,
1005 width: [
1006 calc(&style.size.width),
1007 calc(&style.min_size.width),
1008 calc(&style.max_size.width),
1009 ],
1010 height: [
1011 calc(&style.size.height),
1012 calc(&style.min_size.height),
1013 calc(&style.max_size.height),
1014 ],
1015 flex_basis: calc(&style.flex_basis),
1016 };
1017 (node.width.iter().chain(&node.height).any(Option::is_some) || node.flex_basis.is_some())
1018 .then_some(node)
1019 }
1020}
1021
1022fn calc_size_value(
1025 c: &crate::VnCalcSize,
1026 size: f32,
1027 rem_size: Pixels,
1028 scale_factor: f32,
1029) -> Result<*const (), f32> {
1030 let scaled = c.scale * size;
1031 let (fraction, pixels) = match c.offset {
1032 DefiniteLength::Absolute(a) => (0., scaled + a.to_pixels(rem_size).0),
1033 DefiniteLength::Fraction(f) => (f, scaled),
1034 DefiniteLength::Calc { fraction, pixels } => (fraction, scaled + pixels.0),
1035 };
1036 if fraction == 0. {
1037 return Err(round_to_device_pixel(pixels.max(0.), scale_factor));
1038 }
1039 calc_handle(fraction, Pixels(pixels), scale_factor)
1040}
1041
1042fn basis_dimension(basis: crate::VnSizeBasis) -> taffy::style::Dimension {
1045 use crate::VnSizeBasis as B;
1046 use taffy::style::Dimension as D;
1047 match basis {
1048 B::Auto => D::auto(),
1049 B::MinContent => D::min_content(),
1050 B::MaxContent => D::max_content(),
1051 B::FitContent => D::fit_content(),
1052 B::Content => D::content(),
1053 }
1054}
1055
1056impl ToTaffy<taffy::style::LengthPercentage> for DefiniteLength {
1057 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
1058 match self {
1059 DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
1060 DefiniteLength::Fraction(fraction) => {
1061 taffy::style::LengthPercentage::percent(*fraction)
1062 }
1063 DefiniteLength::Calc { fraction, pixels } => {
1064 match calc_handle(*fraction, *pixels, scale_factor) {
1065 Ok(handle) => taffy::style::LengthPercentage::calc(handle),
1066 Err(pixels) => taffy::style::LengthPercentage::length(pixels),
1067 }
1068 }
1069 }
1070 }
1071}
1072
1073impl ToTaffy<taffy::style::LengthPercentageAuto> for DefiniteLength {
1074 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
1075 match self {
1076 DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
1077 DefiniteLength::Fraction(fraction) => {
1078 taffy::style::LengthPercentageAuto::percent(*fraction)
1079 }
1080 DefiniteLength::Calc { fraction, pixels } => {
1081 match calc_handle(*fraction, *pixels, scale_factor) {
1082 Ok(handle) => taffy::style::LengthPercentageAuto::calc(handle),
1083 Err(pixels) => taffy::style::LengthPercentageAuto::length(pixels),
1084 }
1085 }
1086 }
1087 }
1088}
1089
1090impl ToTaffy<taffy::style::Dimension> for DefiniteLength {
1091 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
1092 match self {
1093 DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
1094 DefiniteLength::Fraction(fraction) => taffy::style::Dimension::percent(*fraction),
1095 DefiniteLength::Calc { fraction, pixels } => {
1096 match calc_handle(*fraction, *pixels, scale_factor) {
1097 Ok(handle) => taffy::style::Dimension::calc(handle),
1098 Err(pixels) => taffy::style::Dimension::length(pixels),
1099 }
1100 }
1101 }
1102 }
1103}
1104
1105fn calc_handle(fraction: f32, pixels: Pixels, scale_factor: f32) -> Result<*const (), f32> {
1123 let length = round_to_device_pixel(pixels.0, scale_factor);
1124 if fraction == 0. {
1125 return Err(length);
1126 }
1127 #[cfg(target_pointer_width = "64")]
1128 {
1129 let bits = ((length.to_bits() as u64) << 32) | (fraction.to_bits() & !0b111) as u64;
1130 if bits == 0 {
1131 return Err(length);
1132 }
1133 Ok(bits as usize as *const ())
1134 }
1135 #[cfg(not(target_pointer_width = "64"))]
1136 {
1137 Err(length)
1138 }
1139}
1140
1141#[inline(always)]
1146fn resolve_calc_handle(val: *const (), basis: f32) -> f32 {
1147 #[cfg(target_pointer_width = "64")]
1148 {
1149 let bits = val as usize as u64;
1150 let length = f32::from_bits((bits >> 32) as u32);
1151 let fraction = f32::from_bits(bits as u32 & !0b111);
1152 fraction * basis + length
1153 }
1154 #[cfg(not(target_pointer_width = "64"))]
1155 {
1156 let _ = (val, basis);
1157 0.0
1158 }
1159}
1160
1161impl ToTaffy<taffy::style::LengthPercentage> for AbsoluteLength {
1162 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
1163 taffy::style::LengthPercentage::length(self.to_taffy(rem_size, scale_factor))
1164 }
1165}
1166
1167impl ToTaffy<taffy::style::LengthPercentageAuto> for AbsoluteLength {
1168 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
1169 taffy::style::LengthPercentageAuto::length(self.to_taffy(rem_size, scale_factor))
1170 }
1171}
1172
1173impl ToTaffy<taffy::style::Dimension> for AbsoluteLength {
1174 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
1175 taffy::style::Dimension::length(self.to_taffy(rem_size, scale_factor))
1176 }
1177}
1178
1179impl<T, T2> From<TaffyPoint<T>> for Point<T2>
1180where
1181 T: Into<T2>,
1182 T2: Clone + Debug + Default + PartialEq,
1183{
1184 fn from(point: TaffyPoint<T>) -> Point<T2> {
1185 Point {
1186 x: point.x.into(),
1187 y: point.y.into(),
1188 }
1189 }
1190}
1191
1192impl<T, T2> From<Point<T>> for TaffyPoint<T2>
1193where
1194 T: Into<T2> + Clone + Debug + Default + PartialEq,
1195{
1196 fn from(val: Point<T>) -> Self {
1197 TaffyPoint {
1198 x: val.x.into(),
1199 y: val.y.into(),
1200 }
1201 }
1202}
1203
1204impl<T, U> ToTaffy<TaffySize<U>> for Size<T>
1205where
1206 T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
1207{
1208 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffySize<U> {
1209 TaffySize {
1210 width: self.width.to_taffy(rem_size, scale_factor),
1211 height: self.height.to_taffy(rem_size, scale_factor),
1212 }
1213 }
1214}
1215
1216impl<T, U> ToTaffy<TaffyRect<U>> for Edges<T>
1217where
1218 T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
1219{
1220 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffyRect<U> {
1221 TaffyRect {
1222 top: self.top.to_taffy(rem_size, scale_factor),
1223 right: self.right.to_taffy(rem_size, scale_factor),
1224 bottom: self.bottom.to_taffy(rem_size, scale_factor),
1225 left: self.left.to_taffy(rem_size, scale_factor),
1226 }
1227 }
1228}
1229
1230impl<T, U> From<TaffySize<T>> for Size<U>
1231where
1232 T: Into<U>,
1233 U: Clone + Debug + Default + PartialEq,
1234{
1235 fn from(taffy_size: TaffySize<T>) -> Self {
1236 Size {
1237 width: taffy_size.width.into(),
1238 height: taffy_size.height.into(),
1239 }
1240 }
1241}
1242
1243impl<T, U> From<Size<T>> for TaffySize<U>
1244where
1245 T: Into<U> + Clone + Debug + Default + PartialEq,
1246{
1247 fn from(size: Size<T>) -> Self {
1248 TaffySize {
1249 width: size.width.into(),
1250 height: size.height.into(),
1251 }
1252 }
1253}
1254
1255#[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
1257pub enum AvailableSpace {
1258 Definite(Pixels),
1260 #[default]
1262 MinContent,
1263 MaxContent,
1265}
1266
1267impl AvailableSpace {
1268 pub const fn min_size() -> Size<Self> {
1282 Size {
1283 width: Self::MinContent,
1284 height: Self::MinContent,
1285 }
1286 }
1287}
1288
1289impl From<AvailableSpace> for TaffyAvailableSpace {
1290 fn from(space: AvailableSpace) -> TaffyAvailableSpace {
1291 match space {
1292 AvailableSpace::Definite(Pixels(value)) => TaffyAvailableSpace::Definite(value),
1293 AvailableSpace::MinContent => TaffyAvailableSpace::MinContent,
1294 AvailableSpace::MaxContent => TaffyAvailableSpace::MaxContent,
1295 }
1296 }
1297}
1298
1299impl From<TaffyAvailableSpace> for AvailableSpace {
1300 fn from(space: TaffyAvailableSpace) -> AvailableSpace {
1301 match space {
1302 TaffyAvailableSpace::Definite(value) => AvailableSpace::Definite(Pixels(value)),
1303 TaffyAvailableSpace::MinContent => AvailableSpace::MinContent,
1304 TaffyAvailableSpace::MaxContent => AvailableSpace::MaxContent,
1305 }
1306 }
1307}
1308
1309impl From<Pixels> for AvailableSpace {
1310 fn from(pixels: Pixels) -> Self {
1311 AvailableSpace::Definite(pixels)
1312 }
1313}
1314
1315impl From<Size<Pixels>> for Size<AvailableSpace> {
1316 fn from(size: Size<Pixels>) -> Self {
1317 Size {
1318 width: AvailableSpace::Definite(size.width),
1319 height: AvailableSpace::Definite(size.height),
1320 }
1321 }
1322}
1323
1324#[cfg(test)]
1325mod tests {
1326 use super::*;
1327
1328 #[test]
1329 fn flex_and_grid_lay_their_children_out_in_order_modified_document_order() {
1330 let mut engine = TaffyLayoutEngine::new();
1331 let leaf = |engine: &mut TaffyLayoutEngine, order: i32| {
1332 let style = Style { vn_order: order, ..Default::default() };
1333 engine.request_layout(style, Pixels(16.0), 1.0, &[])
1334 };
1335 let kids = [leaf(&mut engine, 2), leaf(&mut engine, -1), leaf(&mut engine, 0), leaf(&mut engine, 2)];
1336 let laid_out = |engine: &mut TaffyLayoutEngine, display: Display| {
1337 let style = Style { display, ..Default::default() };
1338 let root = engine.request_layout(style, Pixels(16.0), 1.0, &kids);
1339 engine.taffy.child_ids(root.into()).map(LayoutId::from).collect::<Vec<_>>()
1340 };
1341 let modified = vec![kids[1], kids[2], kids[0], kids[3]];
1342 assert_eq!(laid_out(&mut engine, Display::Flex), modified);
1343 assert_eq!(laid_out(&mut engine, Display::Grid), modified);
1344 assert_eq!(laid_out(&mut engine, Display::Block), kids.to_vec());
1345 engine.clear();
1346 let fresh = [leaf(&mut engine, 0), leaf(&mut engine, 0)];
1347 let root = engine.request_layout(Style { display: Display::Flex, ..Default::default() }, Pixels(16.0), 1.0, &fresh);
1348 assert!(engine.taffy.child_ids(root.into()).map(LayoutId::from).eq(fresh));
1349 }
1350
1351 #[test]
1352 fn implicit_fractional_columns_share_the_container_width() {
1353 let mut tree = TaffyTree::<()>::new();
1354 let children: Vec<_> = (0..3).map(|_| tree.new_leaf(Default::default()).unwrap()).collect();
1355 let style = Style {
1356 display: crate::Display::Grid,
1357 size: Size {
1358 width: Length::Definite(Pixels(300.0).into()),
1359 height: Length::Definite(Pixels(40.0).into()),
1360 },
1361 vn_grid_auto_flow: Some(crate::GridAutoFlow::Column),
1362 vn_grid_auto_cols: Some(vec![crate::GridTrack::fr(1.0)]),
1363 ..Default::default()
1364 };
1365 let root = tree.new_with_children(style.to_taffy(Pixels(16.0), 1.0), &children).unwrap();
1366 tree.compute_layout(root, TaffySize {
1367 width: TaffyAvailableSpace::Definite(300.0), height: TaffyAvailableSpace::Definite(40.0),
1368 }).unwrap();
1369 for (index, child) in children.into_iter().enumerate() {
1370 let layout = tree.layout(child).unwrap();
1371 assert_eq!(layout.size.width, 100.0);
1372 assert_eq!(layout.location.x, index as f32 * 100.0);
1373 }
1374 }
1375
1376 #[test]
1377 fn implicit_row_patterns_repeat_in_layout() {
1378 use crate::GridTrackSize as Track;
1379 let mut tree = TaffyTree::<()>::new();
1380 let children: Vec<_> = (0..5).map(|_| tree.new_leaf(Default::default()).unwrap()).collect();
1381 let style = Style {
1382 display: crate::Display::Grid,
1383 vn_grid_cols: Some(vec![crate::GridTrack::fixed(Track::Px(100.0))]),
1384 vn_grid_auto_rows: Some(vec![crate::GridTrack::fixed(Track::Px(20.0)), crate::GridTrack::fixed(Track::Px(35.0))]),
1385 ..Default::default()
1386 };
1387 let root = tree.new_with_children(style.to_taffy(Pixels(16.0), 1.0), &children).unwrap();
1388 tree.compute_layout(root, TaffySize {
1389 width: TaffyAvailableSpace::MaxContent, height: TaffyAvailableSpace::MaxContent,
1390 }).unwrap();
1391 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) {
1392 let layout = tree.layout(child).unwrap();
1393 assert_eq!(layout.size.height, height);
1394 assert_eq!(layout.location.y, top);
1395 }
1396 }
1397
1398 #[test]
1399 fn implicit_auto_reset_replaces_a_fixed_row_pattern() {
1400 use crate::{GridTrack, GridTrackSize, Refineable, StyleRefinement};
1401 let mut style = Style {
1402 display: crate::Display::Grid,
1403 vn_grid_cols: Some(vec![GridTrack::fixed(GridTrackSize::Px(100.0))]),
1404 vn_grid_auto_rows: Some(vec![GridTrack::fixed(GridTrackSize::Px(50.0))]),
1405 ..Default::default()
1406 };
1407 style.refine(&StyleRefinement { vn_grid_auto_rows: Some(Vec::new()), ..Default::default() });
1408 let mut tree = TaffyTree::<()>::new();
1409 let children: Vec<_> = [17.0, 29.0].into_iter().map(|height| {
1410 let mut leaf_style = taffy::style::Style::default();
1411 leaf_style.size.height = taffy::style::Dimension::length(height);
1412 tree.new_leaf(leaf_style).unwrap()
1413 }).collect();
1414 let root = tree.new_with_children(style.to_taffy(Pixels(16.0), 1.0), &children).unwrap();
1415 tree.compute_layout(root, TaffySize {
1416 width: TaffyAvailableSpace::MaxContent, height: TaffyAvailableSpace::MaxContent,
1417 }).unwrap();
1418 assert_eq!(tree.layout(children[1]).unwrap().location.y, 17.0);
1419 assert_eq!(tree.layout(root).unwrap().size.height, 46.0);
1420 }
1421
1422 #[test]
1423 fn border_widths_to_taffy_use_stroke_snapping() {
1424 let border_widths = Edges {
1425 top: Pixels(0.0).into(),
1426 right: Pixels(0.4).into(),
1427 bottom: Pixels(0.5).into(),
1428 left: Pixels(1.6).into(),
1429 };
1430 let taffy_border = border_widths_to_taffy(&border_widths, Pixels(16.0), 1.0);
1431
1432 assert_eq!(
1433 taffy_border.top,
1434 taffy::style::LengthPercentage::length(0.0)
1435 );
1436 assert_eq!(
1437 taffy_border.right,
1438 taffy::style::LengthPercentage::length(1.0)
1439 );
1440 assert_eq!(
1441 taffy_border.bottom,
1442 taffy::style::LengthPercentage::length(1.0)
1443 );
1444 assert_eq!(
1445 taffy_border.left,
1446 taffy::style::LengthPercentage::length(2.0)
1447 );
1448 }
1449}