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(basis), Some(_)) = (node.flex_basis, self.main_axis(node.id)) {
492 probe.flex_basis = basis_dimension(basis.basis);
493 probe.flex_grow = 0.;
494 probe.flex_shrink = 0.;
495 }
496 if probe != requested {
497 self.taffy.set_style(node.id.0, probe).expect(EXPECT_MESSAGE);
498 }
499 requested
500 })
501 .collect()
502 }
503
504 fn resolve_calc_sizes(
507 &mut self,
508 nodes: &[CalcSizeNode],
509 requested: Vec<taffy::style::Style>,
510 rem_size: Pixels,
511 scale_factor: f32,
512 ) {
513 for (node, mut style) in nodes.iter().zip(requested) {
514 let layout = *self.taffy.layout(node.id.0).expect(EXPECT_MESSAGE);
515 let content_box = style.box_sizing == taffy::style::BoxSizing::ContentBox;
516 let inner = |outer: f32, a: f32, b: f32, c: f32, d: f32| {
517 if content_box {
518 (outer - a - b - c - d).max(0.)
519 } else {
520 outer
521 }
522 };
523 let measured = [
524 inner(
525 layout.size.width,
526 layout.padding.left,
527 layout.padding.right,
528 layout.border.left,
529 layout.border.right,
530 ),
531 inner(
532 layout.size.height,
533 layout.padding.top,
534 layout.padding.bottom,
535 layout.border.top,
536 layout.border.bottom,
537 ),
538 ];
539 let resolve = |c: &crate::VnCalcSize, axis: usize| {
540 calc_size_value(c, measured[axis] / scale_factor, rem_size, scale_factor)
541 };
542 let dimension = |v: Result<*const (), f32>| match v {
543 Ok(handle) => taffy::style::Dimension::calc(handle),
544 Err(length) => taffy::style::Dimension::length(length),
545 };
546 let bound = |v: Result<*const (), f32>| match v {
547 Ok(handle) => taffy::style::LengthPercentageAuto::calc(handle),
548 Err(length) => taffy::style::LengthPercentageAuto::length(length),
549 };
550 for axis in 0..2 {
551 let [size, min, max] = if axis == 0 { node.width } else { node.height };
552 let (s, lo, hi) = if axis == 0 {
553 (
554 &mut style.size.width,
555 &mut style.min_size.width,
556 &mut style.max_size.width,
557 )
558 } else {
559 (
560 &mut style.size.height,
561 &mut style.min_size.height,
562 &mut style.max_size.height,
563 )
564 };
565 if let Some(c) = size {
566 *s = dimension(resolve(&c, axis));
567 }
568 if let Some(c) = min {
569 *lo = bound(resolve(&c, axis));
570 }
571 if let Some(c) = max {
572 *hi = bound(resolve(&c, axis));
573 }
574 }
575 if let (Some(c), Some(axis)) = (node.flex_basis, self.main_axis(node.id)) {
576 style.flex_basis = dimension(resolve(&c, axis));
577 }
578 if self.taffy.style(node.id.0).expect(EXPECT_MESSAGE) != &style {
579 self.taffy.set_style(node.id.0, style).expect(EXPECT_MESSAGE);
580 }
581 }
582 }
583
584 fn main_axis(&self, id: LayoutId) -> Option<usize> {
586 let parent = self.taffy.parent(id.0)?;
587 let style = self.taffy.style(parent).ok()?;
588 use taffy::style::FlexDirection as F;
589 (style.display == taffy::style::Display::Flex).then(|| match style.flex_direction {
590 F::Row | F::RowReverse => 0,
591 F::Column | F::ColumnReverse => 1,
592 })
593 }
594
595 pub fn is_absolute(&self, id: LayoutId) -> bool {
673 self.taffy
674 .style(id.0)
675 .is_ok_and(|style| style.position == taffy::style::Position::Absolute)
676 }
677
678 pub fn layout_bounds(&mut self, id: LayoutId, scale_factor: f32) -> Bounds<Pixels> {
679 if let Some(layout) = self.absolute_layout_bounds.get(&id).cloned() {
680 return layout;
681 }
682
683 let layout = self.taffy.layout(id.into()).expect(EXPECT_MESSAGE);
684 let layout_location = layout.location;
685 let layout_size = layout.size;
686 let parent = self.taffy.parent(id.0);
687
688 let absolute_outer_origin = match parent {
689 Some(parent_id) => {
690 let parent_id = LayoutId::from(parent_id);
691 self.layout_bounds(parent_id, scale_factor);
692 let parent_origin = *self
693 .absolute_outer_origins
694 .get(&parent_id)
695 .expect("parent absolute outer origin should be cached");
696 parent_origin + Point::from(layout_location)
697 }
698 None => Point::from(layout_location),
699 };
700 self.absolute_outer_origins
701 .insert(id, absolute_outer_origin);
702
703 let absolute_far = absolute_outer_origin + Point::from(Size::from(layout_size));
704 let snapped_bounds = Bounds::from_corners(
705 absolute_outer_origin.map(round_half_toward_zero),
706 absolute_far.map(round_half_toward_zero),
707 );
708
709 let bounds = (snapped_bounds / scale_factor).map(Pixels);
710 self.absolute_layout_bounds.insert(id, bounds);
711 bounds
712 }
713}
714
715#[derive(Copy, Clone, Eq, PartialEq, Debug)]
717#[repr(transparent)]
718pub struct LayoutId(NodeId);
719
720impl LayoutId {
721 fn to_taffy_slice(node_ids: &[Self]) -> &[taffy::NodeId] {
722 unsafe { std::mem::transmute::<&[LayoutId], &[taffy::NodeId]>(node_ids) }
724 }
725}
726
727impl std::hash::Hash for LayoutId {
728 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
729 u64::from(self.0).hash(state);
730 }
731}
732
733impl From<NodeId> for LayoutId {
734 fn from(node_id: NodeId) -> Self {
735 Self(node_id)
736 }
737}
738
739impl From<LayoutId> for NodeId {
740 fn from(layout_id: LayoutId) -> NodeId {
741 layout_id.0
742 }
743}
744
745fn snap_measured_size_to_device_pixels(size: Size<Pixels>, scale_factor: f32) -> Size<f32> {
746 size.map(|d| ceil_to_device_pixel(d.0.max(0.0), scale_factor))
747}
748
749fn border_widths_to_taffy(
750 widths: &Edges<AbsoluteLength>,
751 rem_size: Pixels,
752 scale_factor: f32,
753) -> TaffyRect<taffy::style::LengthPercentage> {
754 let snap = |w: &AbsoluteLength| {
755 taffy::style::LengthPercentage::length(round_stroke_to_device_pixel(
756 w.to_pixels(rem_size).0,
757 scale_factor,
758 ))
759 };
760 TaffyRect {
761 top: snap(&widths.top),
762 right: snap(&widths.right),
763 bottom: snap(&widths.bottom),
764 left: snap(&widths.left),
765 }
766}
767
768trait ToTaffy<Output> {
769 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> Output;
770}
771
772impl ToTaffy<taffy::style::Style> for Style {
773 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Style {
774 use taffy::style_helpers::{fr, length, minmax, repeat};
775
776 fn to_grid_line(
777 placement: &Range<crate::GridPlacement>,
778 ) -> taffy::Line<taffy::GridPlacement> {
779 taffy::Line {
780 start: placement.start.into(),
781 end: placement.end.into(),
782 }
783 }
784
785 fn to_grid_repeat<T: taffy::style::CheapCloneStr>(
786 unit: &Option<GridTemplate>,
787 ) -> Vec<taffy::GridTemplateComponent<T>> {
788 unit.map(|template| {
789 match template.min_size {
790 crate::GridTemplateMinSize::Zero => {
792 vec![repeat(
793 template.repeat,
794 vec![minmax(length(0.0_f32), fr(1.0_f32))],
795 )]
796 }
797 crate::GridTemplateMinSize::MinContent => {
799 vec![repeat(
800 template.repeat,
801 vec![minmax(min_content(), fr(1.0_f32))],
802 )]
803 }
804 crate::GridTemplateMinSize::MaxContent => {
806 vec![repeat(
807 template.repeat,
808 vec![minmax(length(0.0_f32), max_content())],
809 )]
810 }
811 }
812 })
813 .unwrap_or_default()
814 }
815
816 fn to_track_size_min(size: crate::GridTrackSize) -> taffy::MinTrackSizingFunction {
820 use crate::GridTrackSize as G;
821 use taffy::MinTrackSizingFunction as M;
822 match size {
823 G::Auto => M::auto(),
824 G::MinContent => M::min_content(),
825 G::MaxContent => M::max_content(),
826 G::Px(v) => M::length(v),
827 G::Percent(v) => M::percent(v),
828 G::Fr(_) => M::auto(),
831 }
832 }
833 fn to_track_size_max(size: crate::GridTrackSize) -> taffy::MaxTrackSizingFunction {
834 use crate::GridTrackSize as G;
835 use taffy::MaxTrackSizingFunction as M;
836 match size {
837 G::Auto => M::auto(),
838 G::MinContent => M::min_content(),
839 G::MaxContent => M::max_content(),
840 G::Px(v) => M::length(v),
841 G::Percent(v) => M::percent(v),
842 G::Fr(v) => M::fr(v),
843 }
844 }
845 fn to_grid_tracks<T: taffy::style::CheapCloneStr>(
846 tracks: &Option<Vec<crate::GridTrack>>,
847 auto: Option<crate::GridAutoRepeat>,
848 ) -> Option<Vec<taffy::GridTemplateComponent<T>>> {
849 let track =
850 |t: &crate::GridTrack| minmax(to_track_size_min(t.min), to_track_size_max(t.max));
851 tracks.as_ref().map(|list| {
852 let run = auto
855 .map(|a| a.start as usize..(a.start as usize + a.len as usize))
856 .filter(|run| !run.is_empty() && run.end <= list.len());
857 let mut out = Vec::with_capacity(list.len());
858 for (index, t) in list.iter().enumerate() {
859 match (&run, auto) {
860 (Some(run), Some(a)) if run.contains(&index) => {
861 if index == run.start {
862 let count = if a.fit {
863 taffy::RepetitionCount::AutoFit
864 } else {
865 taffy::RepetitionCount::AutoFill
866 };
867 out.push(repeat(
868 count,
869 list[run.clone()].iter().map(track).collect(),
870 ));
871 }
872 }
873 _ => out.push(taffy::GridTemplateComponent::Single(track(t))),
874 }
875 }
876 out
877 })
878 }
879
880 taffy::style::Style {
881 display: self.display.into(),
882 overflow: self.overflow.into(),
883 scrollbar_width: self.scrollbar_width.to_taffy(rem_size, scale_factor),
884 position: self.position.into(),
885 inset: self.inset.to_taffy(rem_size, scale_factor),
886 size: self.size.to_taffy(rem_size, scale_factor),
887 min_size: self.min_size.to_taffy(rem_size, scale_factor),
888 max_size: self.max_size.to_taffy(rem_size, scale_factor),
889 aspect_ratio: self
890 .aspect_ratio
891 .map(f32::abs)
892 .filter(|ratio| ratio.is_finite() && *ratio > 0.0),
893 margin: self.margin.to_taffy(rem_size, scale_factor),
894 padding: self.padding.to_taffy(rem_size, scale_factor),
895 border: border_widths_to_taffy(&self.border_widths, rem_size, scale_factor),
896 align_items: self.align_items.map(Into::into).unwrap_or_default(),
897 align_self: self.align_self.map(|x| x.into()),
898 align_content: self.align_content.map(Into::into).unwrap_or_default(),
899 justify_content: self.justify_content.map(Into::into).unwrap_or_default(),
900 gap: self.gap.to_taffy(rem_size, scale_factor),
901 flex_direction: self.flex_direction.into(),
902 flex_wrap: self.flex_wrap.into(),
903 flex_basis: self.flex_basis.to_taffy(rem_size, scale_factor),
904 flex_grow: self.flex_grow,
905 flex_shrink: self.flex_shrink,
906 grid_template_rows: to_grid_tracks(&self.vn_grid_rows, self.vn_grid_rows_auto)
908 .unwrap_or_else(|| to_grid_repeat(&self.grid_rows)),
909 grid_template_columns: to_grid_tracks(&self.vn_grid_cols, self.vn_grid_cols_auto)
910 .unwrap_or_else(|| to_grid_repeat(&self.grid_cols)),
911 grid_auto_columns: self.vn_grid_auto_cols.as_ref().map(|tracks| tracks.iter()
912 .map(|track| minmax(to_track_size_min(track.min), to_track_size_max(track.max)))
913 .collect()).unwrap_or_default(),
914 grid_auto_rows: self.vn_grid_auto_rows.as_ref().map(|tracks| tracks.iter()
915 .map(|track| minmax(to_track_size_min(track.min), to_track_size_max(track.max)))
916 .collect()).unwrap_or_default(),
917 grid_auto_flow: match self.vn_grid_auto_flow.unwrap_or_default() {
918 crate::GridAutoFlow::Row => taffy::GridAutoFlow::Row,
919 crate::GridAutoFlow::Column => taffy::GridAutoFlow::Column,
920 crate::GridAutoFlow::RowDense => taffy::GridAutoFlow::RowDense,
921 crate::GridAutoFlow::ColumnDense => taffy::GridAutoFlow::ColumnDense,
922 },
923 justify_items: self.vn_justify_items.map(Into::into).unwrap_or_default(),
924 justify_self: self.vn_justify_self.map(|x| x.into()),
925 grid_row: self
926 .grid_location
927 .as_ref()
928 .map(|location| to_grid_line(&location.row))
929 .unwrap_or_default(),
930 grid_column: self
931 .grid_location
932 .as_ref()
933 .map(|location| to_grid_line(&location.column))
934 .unwrap_or_default(),
935 contain: {
936 let mut contain = taffy::Contain::NONE;
937 if self.vn_contain_size & Style::CONTAIN_INLINE_SIZE != 0 {
938 contain |= taffy::Contain::INLINE_SIZE;
939 }
940 if self.vn_contain_size & Style::CONTAIN_BLOCK_SIZE != 0 {
941 contain |= taffy::Contain::BLOCK_SIZE;
942 }
943 contain
944 },
945 ..Default::default()
946 }
947 }
948}
949
950impl ToTaffy<f32> for AbsoluteLength {
951 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> f32 {
952 round_to_device_pixel(self.to_pixels(rem_size).0, scale_factor)
953 }
954}
955
956impl ToTaffy<taffy::style::LengthPercentageAuto> for Length {
957 fn to_taffy(
958 &self,
959 rem_size: Pixels,
960 scale_factor: f32,
961 ) -> taffy::prelude::LengthPercentageAuto {
962 match self {
963 Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
964 Length::Auto | Length::VnCalcSize(_) => taffy::prelude::LengthPercentageAuto::auto(),
965 }
966 }
967}
968
969impl ToTaffy<taffy::style::Dimension> for Length {
970 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::prelude::Dimension {
971 match self {
972 Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
973 Length::Auto => taffy::prelude::Dimension::auto(),
974 Length::VnCalcSize(c) => basis_dimension(c.basis),
975 }
976 }
977}
978
979struct CalcSizeNode {
982 id: LayoutId,
983 width: [Option<crate::VnCalcSize>; 3],
984 height: [Option<crate::VnCalcSize>; 3],
985 flex_basis: Option<crate::VnCalcSize>,
986}
987
988impl CalcSizeNode {
989 fn of(id: LayoutId, style: &Style) -> Option<Self> {
990 let calc = |l: &Length| match l {
991 Length::VnCalcSize(c) if !c.is_basis() => Some(*c),
992 _ => None,
993 };
994 let node = CalcSizeNode {
995 id,
996 width: [
997 calc(&style.size.width),
998 calc(&style.min_size.width),
999 calc(&style.max_size.width),
1000 ],
1001 height: [
1002 calc(&style.size.height),
1003 calc(&style.min_size.height),
1004 calc(&style.max_size.height),
1005 ],
1006 flex_basis: calc(&style.flex_basis),
1007 };
1008 (node.width.iter().chain(&node.height).any(Option::is_some) || node.flex_basis.is_some())
1009 .then_some(node)
1010 }
1011}
1012
1013fn calc_size_value(
1016 c: &crate::VnCalcSize,
1017 size: f32,
1018 rem_size: Pixels,
1019 scale_factor: f32,
1020) -> Result<*const (), f32> {
1021 let scaled = c.scale * size;
1022 let (fraction, pixels) = match c.offset {
1023 DefiniteLength::Absolute(a) => (0., scaled + a.to_pixels(rem_size).0),
1024 DefiniteLength::Fraction(f) => (f, scaled),
1025 DefiniteLength::Calc { fraction, pixels } => (fraction, scaled + pixels.0),
1026 };
1027 if fraction == 0. {
1028 return Err(round_to_device_pixel(pixels.max(0.), scale_factor));
1029 }
1030 calc_handle(fraction, Pixels(pixels), scale_factor)
1031}
1032
1033fn basis_dimension(basis: crate::VnSizeBasis) -> taffy::style::Dimension {
1036 use crate::VnSizeBasis as B;
1037 use taffy::style::Dimension as D;
1038 match basis {
1039 B::Auto => D::auto(),
1040 B::MinContent => D::min_content(),
1041 B::MaxContent => D::max_content(),
1042 B::FitContent => D::fit_content(),
1043 B::Content => D::content(),
1044 }
1045}
1046
1047impl ToTaffy<taffy::style::LengthPercentage> for DefiniteLength {
1048 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
1049 match self {
1050 DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
1051 DefiniteLength::Fraction(fraction) => {
1052 taffy::style::LengthPercentage::percent(*fraction)
1053 }
1054 DefiniteLength::Calc { fraction, pixels } => {
1055 match calc_handle(*fraction, *pixels, scale_factor) {
1056 Ok(handle) => taffy::style::LengthPercentage::calc(handle),
1057 Err(pixels) => taffy::style::LengthPercentage::length(pixels),
1058 }
1059 }
1060 }
1061 }
1062}
1063
1064impl ToTaffy<taffy::style::LengthPercentageAuto> for DefiniteLength {
1065 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
1066 match self {
1067 DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
1068 DefiniteLength::Fraction(fraction) => {
1069 taffy::style::LengthPercentageAuto::percent(*fraction)
1070 }
1071 DefiniteLength::Calc { fraction, pixels } => {
1072 match calc_handle(*fraction, *pixels, scale_factor) {
1073 Ok(handle) => taffy::style::LengthPercentageAuto::calc(handle),
1074 Err(pixels) => taffy::style::LengthPercentageAuto::length(pixels),
1075 }
1076 }
1077 }
1078 }
1079}
1080
1081impl ToTaffy<taffy::style::Dimension> for DefiniteLength {
1082 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
1083 match self {
1084 DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
1085 DefiniteLength::Fraction(fraction) => taffy::style::Dimension::percent(*fraction),
1086 DefiniteLength::Calc { fraction, pixels } => {
1087 match calc_handle(*fraction, *pixels, scale_factor) {
1088 Ok(handle) => taffy::style::Dimension::calc(handle),
1089 Err(pixels) => taffy::style::Dimension::length(pixels),
1090 }
1091 }
1092 }
1093 }
1094}
1095
1096fn calc_handle(fraction: f32, pixels: Pixels, scale_factor: f32) -> Result<*const (), f32> {
1114 let length = round_to_device_pixel(pixels.0, scale_factor);
1115 if fraction == 0. {
1116 return Err(length);
1117 }
1118 #[cfg(target_pointer_width = "64")]
1119 {
1120 let bits = ((length.to_bits() as u64) << 32) | (fraction.to_bits() & !0b111) as u64;
1121 if bits == 0 {
1122 return Err(length);
1123 }
1124 Ok(bits as usize as *const ())
1125 }
1126 #[cfg(not(target_pointer_width = "64"))]
1127 {
1128 Err(length)
1129 }
1130}
1131
1132#[inline(always)]
1137fn resolve_calc_handle(val: *const (), basis: f32) -> f32 {
1138 #[cfg(target_pointer_width = "64")]
1139 {
1140 let bits = val as usize as u64;
1141 let length = f32::from_bits((bits >> 32) as u32);
1142 let fraction = f32::from_bits(bits as u32 & !0b111);
1143 fraction * basis + length
1144 }
1145 #[cfg(not(target_pointer_width = "64"))]
1146 {
1147 let _ = (val, basis);
1148 0.0
1149 }
1150}
1151
1152impl ToTaffy<taffy::style::LengthPercentage> for AbsoluteLength {
1153 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
1154 taffy::style::LengthPercentage::length(self.to_taffy(rem_size, scale_factor))
1155 }
1156}
1157
1158impl ToTaffy<taffy::style::LengthPercentageAuto> for AbsoluteLength {
1159 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
1160 taffy::style::LengthPercentageAuto::length(self.to_taffy(rem_size, scale_factor))
1161 }
1162}
1163
1164impl ToTaffy<taffy::style::Dimension> for AbsoluteLength {
1165 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
1166 taffy::style::Dimension::length(self.to_taffy(rem_size, scale_factor))
1167 }
1168}
1169
1170impl<T, T2> From<TaffyPoint<T>> for Point<T2>
1171where
1172 T: Into<T2>,
1173 T2: Clone + Debug + Default + PartialEq,
1174{
1175 fn from(point: TaffyPoint<T>) -> Point<T2> {
1176 Point {
1177 x: point.x.into(),
1178 y: point.y.into(),
1179 }
1180 }
1181}
1182
1183impl<T, T2> From<Point<T>> for TaffyPoint<T2>
1184where
1185 T: Into<T2> + Clone + Debug + Default + PartialEq,
1186{
1187 fn from(val: Point<T>) -> Self {
1188 TaffyPoint {
1189 x: val.x.into(),
1190 y: val.y.into(),
1191 }
1192 }
1193}
1194
1195impl<T, U> ToTaffy<TaffySize<U>> for Size<T>
1196where
1197 T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
1198{
1199 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffySize<U> {
1200 TaffySize {
1201 width: self.width.to_taffy(rem_size, scale_factor),
1202 height: self.height.to_taffy(rem_size, scale_factor),
1203 }
1204 }
1205}
1206
1207impl<T, U> ToTaffy<TaffyRect<U>> for Edges<T>
1208where
1209 T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
1210{
1211 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffyRect<U> {
1212 TaffyRect {
1213 top: self.top.to_taffy(rem_size, scale_factor),
1214 right: self.right.to_taffy(rem_size, scale_factor),
1215 bottom: self.bottom.to_taffy(rem_size, scale_factor),
1216 left: self.left.to_taffy(rem_size, scale_factor),
1217 }
1218 }
1219}
1220
1221impl<T, U> From<TaffySize<T>> for Size<U>
1222where
1223 T: Into<U>,
1224 U: Clone + Debug + Default + PartialEq,
1225{
1226 fn from(taffy_size: TaffySize<T>) -> Self {
1227 Size {
1228 width: taffy_size.width.into(),
1229 height: taffy_size.height.into(),
1230 }
1231 }
1232}
1233
1234impl<T, U> From<Size<T>> for TaffySize<U>
1235where
1236 T: Into<U> + Clone + Debug + Default + PartialEq,
1237{
1238 fn from(size: Size<T>) -> Self {
1239 TaffySize {
1240 width: size.width.into(),
1241 height: size.height.into(),
1242 }
1243 }
1244}
1245
1246#[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
1248pub enum AvailableSpace {
1249 Definite(Pixels),
1251 #[default]
1253 MinContent,
1254 MaxContent,
1256}
1257
1258impl AvailableSpace {
1259 pub const fn min_size() -> Size<Self> {
1273 Size {
1274 width: Self::MinContent,
1275 height: Self::MinContent,
1276 }
1277 }
1278}
1279
1280impl From<AvailableSpace> for TaffyAvailableSpace {
1281 fn from(space: AvailableSpace) -> TaffyAvailableSpace {
1282 match space {
1283 AvailableSpace::Definite(Pixels(value)) => TaffyAvailableSpace::Definite(value),
1284 AvailableSpace::MinContent => TaffyAvailableSpace::MinContent,
1285 AvailableSpace::MaxContent => TaffyAvailableSpace::MaxContent,
1286 }
1287 }
1288}
1289
1290impl From<TaffyAvailableSpace> for AvailableSpace {
1291 fn from(space: TaffyAvailableSpace) -> AvailableSpace {
1292 match space {
1293 TaffyAvailableSpace::Definite(value) => AvailableSpace::Definite(Pixels(value)),
1294 TaffyAvailableSpace::MinContent => AvailableSpace::MinContent,
1295 TaffyAvailableSpace::MaxContent => AvailableSpace::MaxContent,
1296 }
1297 }
1298}
1299
1300impl From<Pixels> for AvailableSpace {
1301 fn from(pixels: Pixels) -> Self {
1302 AvailableSpace::Definite(pixels)
1303 }
1304}
1305
1306impl From<Size<Pixels>> for Size<AvailableSpace> {
1307 fn from(size: Size<Pixels>) -> Self {
1308 Size {
1309 width: AvailableSpace::Definite(size.width),
1310 height: AvailableSpace::Definite(size.height),
1311 }
1312 }
1313}
1314
1315#[cfg(test)]
1316mod tests {
1317 use super::*;
1318
1319 #[test]
1320 fn flex_and_grid_lay_their_children_out_in_order_modified_document_order() {
1321 let mut engine = TaffyLayoutEngine::new();
1322 let leaf = |engine: &mut TaffyLayoutEngine, order: i32| {
1323 let style = Style { vn_order: order, ..Default::default() };
1324 engine.request_layout(style, Pixels(16.0), 1.0, &[])
1325 };
1326 let kids = [leaf(&mut engine, 2), leaf(&mut engine, -1), leaf(&mut engine, 0), leaf(&mut engine, 2)];
1327 let laid_out = |engine: &mut TaffyLayoutEngine, display: Display| {
1328 let style = Style { display, ..Default::default() };
1329 let root = engine.request_layout(style, Pixels(16.0), 1.0, &kids);
1330 engine.taffy.child_ids(root.into()).map(LayoutId::from).collect::<Vec<_>>()
1331 };
1332 let modified = vec![kids[1], kids[2], kids[0], kids[3]];
1333 assert_eq!(laid_out(&mut engine, Display::Flex), modified);
1334 assert_eq!(laid_out(&mut engine, Display::Grid), modified);
1335 assert_eq!(laid_out(&mut engine, Display::Block), kids.to_vec());
1336 engine.clear();
1337 let fresh = [leaf(&mut engine, 0), leaf(&mut engine, 0)];
1338 let root = engine.request_layout(Style { display: Display::Flex, ..Default::default() }, Pixels(16.0), 1.0, &fresh);
1339 assert!(engine.taffy.child_ids(root.into()).map(LayoutId::from).eq(fresh));
1340 }
1341
1342 #[test]
1343 fn implicit_fractional_columns_share_the_container_width() {
1344 let mut tree = TaffyTree::<()>::new();
1345 let children: Vec<_> = (0..3).map(|_| tree.new_leaf(Default::default()).unwrap()).collect();
1346 let style = Style {
1347 display: crate::Display::Grid,
1348 size: Size {
1349 width: Length::Definite(Pixels(300.0).into()),
1350 height: Length::Definite(Pixels(40.0).into()),
1351 },
1352 vn_grid_auto_flow: Some(crate::GridAutoFlow::Column),
1353 vn_grid_auto_cols: Some(vec![crate::GridTrack::fr(1.0)]),
1354 ..Default::default()
1355 };
1356 let root = tree.new_with_children(style.to_taffy(Pixels(16.0), 1.0), &children).unwrap();
1357 tree.compute_layout(root, TaffySize {
1358 width: TaffyAvailableSpace::Definite(300.0), height: TaffyAvailableSpace::Definite(40.0),
1359 }).unwrap();
1360 for (index, child) in children.into_iter().enumerate() {
1361 let layout = tree.layout(child).unwrap();
1362 assert_eq!(layout.size.width, 100.0);
1363 assert_eq!(layout.location.x, index as f32 * 100.0);
1364 }
1365 }
1366
1367 #[test]
1368 fn implicit_row_patterns_repeat_in_layout() {
1369 use crate::GridTrackSize as Track;
1370 let mut tree = TaffyTree::<()>::new();
1371 let children: Vec<_> = (0..5).map(|_| tree.new_leaf(Default::default()).unwrap()).collect();
1372 let style = Style {
1373 display: crate::Display::Grid,
1374 vn_grid_cols: Some(vec![crate::GridTrack::fixed(Track::Px(100.0))]),
1375 vn_grid_auto_rows: Some(vec![crate::GridTrack::fixed(Track::Px(20.0)), crate::GridTrack::fixed(Track::Px(35.0))]),
1376 ..Default::default()
1377 };
1378 let root = tree.new_with_children(style.to_taffy(Pixels(16.0), 1.0), &children).unwrap();
1379 tree.compute_layout(root, TaffySize {
1380 width: TaffyAvailableSpace::MaxContent, height: TaffyAvailableSpace::MaxContent,
1381 }).unwrap();
1382 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) {
1383 let layout = tree.layout(child).unwrap();
1384 assert_eq!(layout.size.height, height);
1385 assert_eq!(layout.location.y, top);
1386 }
1387 }
1388
1389 #[test]
1390 fn implicit_auto_reset_replaces_a_fixed_row_pattern() {
1391 use crate::{GridTrack, GridTrackSize, Refineable, StyleRefinement};
1392 let mut style = Style {
1393 display: crate::Display::Grid,
1394 vn_grid_cols: Some(vec![GridTrack::fixed(GridTrackSize::Px(100.0))]),
1395 vn_grid_auto_rows: Some(vec![GridTrack::fixed(GridTrackSize::Px(50.0))]),
1396 ..Default::default()
1397 };
1398 style.refine(&StyleRefinement { vn_grid_auto_rows: Some(Vec::new()), ..Default::default() });
1399 let mut tree = TaffyTree::<()>::new();
1400 let children: Vec<_> = [17.0, 29.0].into_iter().map(|height| {
1401 let mut leaf_style = taffy::style::Style::default();
1402 leaf_style.size.height = taffy::style::Dimension::length(height);
1403 tree.new_leaf(leaf_style).unwrap()
1404 }).collect();
1405 let root = tree.new_with_children(style.to_taffy(Pixels(16.0), 1.0), &children).unwrap();
1406 tree.compute_layout(root, TaffySize {
1407 width: TaffyAvailableSpace::MaxContent, height: TaffyAvailableSpace::MaxContent,
1408 }).unwrap();
1409 assert_eq!(tree.layout(children[1]).unwrap().location.y, 17.0);
1410 assert_eq!(tree.layout(root).unwrap().size.height, 46.0);
1411 }
1412
1413 #[test]
1414 fn border_widths_to_taffy_use_stroke_snapping() {
1415 let border_widths = Edges {
1416 top: Pixels(0.0).into(),
1417 right: Pixels(0.4).into(),
1418 bottom: Pixels(0.5).into(),
1419 left: Pixels(1.6).into(),
1420 };
1421 let taffy_border = border_widths_to_taffy(&border_widths, Pixels(16.0), 1.0);
1422
1423 assert_eq!(
1424 taffy_border.top,
1425 taffy::style::LengthPercentage::length(0.0)
1426 );
1427 assert_eq!(
1428 taffy_border.right,
1429 taffy::style::LengthPercentage::length(1.0)
1430 );
1431 assert_eq!(
1432 taffy_border.bottom,
1433 taffy::style::LengthPercentage::length(1.0)
1434 );
1435 assert_eq!(
1436 taffy_border.left,
1437 taffy::style::LengthPercentage::length(2.0)
1438 );
1439 }
1440}