1use crate::{
2 AbsoluteLength, App, Bounds, DefiniteLength, Edges, GridTemplate, Length, Pixels, Point, Size,
3 Style, Window, point, size,
4 util::{
5 ceil_to_device_pixel, round_half_toward_zero, round_stroke_to_device_pixel,
6 round_to_device_pixel,
7 },
8};
9use collections::{FxHashMap, FxHashSet};
10use smallvec::SmallVec;
11use stacksafe::{StackSafe, stacksafe};
12use std::{fmt::Debug, ops::Range};
13use taffy::{
14 TaffyTree,
15 geometry::{Point as TaffyPoint, Rect as TaffyRect, Size as TaffySize},
16 prelude::{max_content, min_content},
17 style::AvailableSpace as TaffyAvailableSpace,
18 tree::{LayoutInput, NodeId},
19};
20
21type NodeMeasureFn = StackSafe<
22 Box<
23 dyn FnMut(
24 Size<Option<Pixels>>,
25 Size<AvailableSpace>,
26 &mut Window,
27 &mut App,
28 ) -> Size<Pixels>,
29 >,
30>;
31
32struct NodeContext {
33 measure: NodeMeasureFn,
34}
35pub struct TaffyLayoutEngine {
36 taffy: TaffyTree<NodeContext>,
37 absolute_layout_bounds: FxHashMap<LayoutId, Bounds<Pixels>>,
38 absolute_outer_origins: FxHashMap<LayoutId, Point<f32>>,
39 computed_layouts: FxHashSet<LayoutId>,
40}
41
42const EXPECT_MESSAGE: &str = "we should avoid taffy layout errors by construction if possible";
43
44impl TaffyLayoutEngine {
45 pub fn new() -> Self {
46 let mut taffy = TaffyTree::new();
47 taffy.disable_rounding();
48 TaffyLayoutEngine {
49 taffy,
50 absolute_layout_bounds: FxHashMap::default(),
51 absolute_outer_origins: FxHashMap::default(),
52 computed_layouts: FxHashSet::default(),
53 }
54 }
55
56 pub fn clear(&mut self) {
57 self.taffy.clear();
58 self.absolute_layout_bounds.clear();
59 self.absolute_outer_origins.clear();
60 self.computed_layouts.clear();
61 }
62
63 pub fn request_layout(
64 &mut self,
65 style: Style,
66 rem_size: Pixels,
67 scale_factor: f32,
68 children: &[LayoutId],
69 ) -> LayoutId {
70 let taffy_style = style.to_taffy(rem_size, scale_factor);
71
72 if children.is_empty() {
73 self.taffy
74 .new_leaf(taffy_style)
75 .expect(EXPECT_MESSAGE)
76 .into()
77 } else {
78 self.taffy
79 .new_with_children(taffy_style, unsafe {
81 std::mem::transmute::<&[LayoutId], &[taffy::NodeId]>(children)
82 })
83 .expect(EXPECT_MESSAGE)
84 .into()
85 }
86 }
87
88 pub fn request_measured_layout(
89 &mut self,
90 style: Style,
91 rem_size: Pixels,
92 scale_factor: f32,
93 measure: impl FnMut(
94 Size<Option<Pixels>>,
95 Size<AvailableSpace>,
96 &mut Window,
97 &mut App,
98 ) -> Size<Pixels>
99 + 'static,
100 ) -> LayoutId {
101 let taffy_style = style.to_taffy(rem_size, scale_factor);
102
103 self.taffy
104 .new_leaf_with_context(
105 taffy_style,
106 NodeContext {
107 measure: StackSafe::new(Box::new(measure)),
108 },
109 )
110 .expect(EXPECT_MESSAGE)
111 .into()
112 }
113
114 pub fn stretch_auto_size_to_fill(
117 &mut self,
118 id: LayoutId,
119 size: Size<Pixels>,
120 scale_factor: f32,
121 ) {
122 let style = self.taffy.style(id.0).expect(EXPECT_MESSAGE);
123 let stretch_width = style.size.width.is_auto();
124 let stretch_height = style.size.height.is_auto();
125 if !stretch_width && !stretch_height {
126 return;
127 }
128
129 let mut style = style.clone();
130 if stretch_width {
131 style.size.width =
132 taffy::style::Dimension::length(round_to_device_pixel(size.width.0, scale_factor));
133 }
134 if stretch_height {
135 style.size.height =
136 taffy::style::Dimension::length(round_to_device_pixel(size.height.0, scale_factor));
137 }
138 self.taffy.set_style(id.0, style).expect(EXPECT_MESSAGE);
139 }
140
141 #[stacksafe]
142 pub fn compute_layout(
143 &mut self,
144 id: LayoutId,
145 available_space: Size<AvailableSpace>,
146 window: &mut Window,
147 cx: &mut App,
148 ) {
149 if !self.computed_layouts.insert(id) {
150 let mut stack = SmallVec::<[LayoutId; 64]>::new();
151 stack.push(id);
152 while let Some(id) = stack.pop() {
153 self.absolute_layout_bounds.remove(&id);
154 self.absolute_outer_origins.remove(&id);
155 stack.extend(
156 self.taffy
157 .children(id.into())
158 .expect(EXPECT_MESSAGE)
159 .into_iter()
160 .map(Into::into),
161 );
162 }
163 }
164
165 let scale_factor = window.scale_factor();
166
167 let transform = |v: AvailableSpace| match v {
168 AvailableSpace::Definite(pixels) => {
169 AvailableSpace::Definite(Pixels(pixels.0 * scale_factor))
170 }
171 AvailableSpace::MinContent => AvailableSpace::MinContent,
172 AvailableSpace::MaxContent => AvailableSpace::MaxContent,
173 };
174 let available_space = size(
175 transform(available_space.width),
176 transform(available_space.height),
177 );
178
179 self.taffy
180 .compute_layout_with_measure(
181 id.into(),
182 available_space.into(),
183 |inputs: LayoutInput, _id, node_context, style| {
184 taffy::compute_leaf_layout(
185 inputs,
186 style,
187 |_, _| 0.0,
188 |known_dimensions, available_space| {
189 let Some(node_context) = node_context else {
190 return TaffySize::ZERO;
191 };
192
193 let known_dimensions = Size {
194 width: known_dimensions.width.map(|e| Pixels(e / scale_factor)),
195 height: known_dimensions.height.map(|e| Pixels(e / scale_factor)),
196 };
197
198 let available_space: Size<AvailableSpace> = available_space.into();
199 let untransform = |ev: AvailableSpace| match ev {
200 AvailableSpace::Definite(pixels) => {
201 AvailableSpace::Definite(Pixels(pixels.0 / scale_factor))
202 }
203 AvailableSpace::MinContent => AvailableSpace::MinContent,
204 AvailableSpace::MaxContent => AvailableSpace::MaxContent,
205 };
206 let available_space = size(
207 untransform(available_space.width),
208 untransform(available_space.height),
209 );
210
211 let measured_size: Size<Pixels> = (node_context.measure)(
212 known_dimensions,
213 available_space,
214 window,
215 cx,
216 );
217 snap_measured_size_to_device_pixels(measured_size, scale_factor).into()
218 },
219 )
220 },
221 )
222 .expect(EXPECT_MESSAGE);
223 }
224
225 pub fn layout_bounds(&mut self, id: LayoutId, scale_factor: f32) -> Bounds<Pixels> {
230 if let Some(layout) = self.absolute_layout_bounds.get(&id).cloned() {
231 return layout;
232 }
233
234 let layout = self.taffy.layout(id.into()).expect(EXPECT_MESSAGE);
235 let layout_location = layout.location;
236 let layout_size = layout.size;
237 let parent = self.taffy.parent(id.0);
238
239 let absolute_outer_origin = match parent {
240 Some(parent_id) => {
241 let parent_id = LayoutId::from(parent_id);
242 self.layout_bounds(parent_id, scale_factor);
243 let parent_origin = *self
244 .absolute_outer_origins
245 .get(&parent_id)
246 .expect("parent absolute outer origin should be cached");
247 parent_origin + Point::from(layout_location)
248 }
249 None => Point::from(layout_location),
250 };
251 self.absolute_outer_origins
252 .insert(id, absolute_outer_origin);
253
254 let layout_size = Size::from(layout_size);
255 let absolute_far = absolute_outer_origin + point(layout_size.width, layout_size.height);
256 let snapped_bounds = Bounds::from_corners(
257 absolute_outer_origin.map(round_half_toward_zero),
258 absolute_far.map(round_half_toward_zero),
259 );
260
261 let bounds = (snapped_bounds / scale_factor).map(Pixels);
262 self.absolute_layout_bounds.insert(id, bounds);
263
264 bounds
265 }
266}
267
268#[derive(Copy, Clone, Eq, PartialEq, Debug)]
270#[repr(transparent)]
271pub struct LayoutId(NodeId);
272
273impl std::hash::Hash for LayoutId {
274 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
275 u64::from(self.0).hash(state);
276 }
277}
278
279impl From<NodeId> for LayoutId {
280 fn from(node_id: NodeId) -> Self {
281 Self(node_id)
282 }
283}
284
285impl From<LayoutId> for NodeId {
286 fn from(layout_id: LayoutId) -> NodeId {
287 layout_id.0
288 }
289}
290
291trait ToTaffy<Output> {
292 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> Output;
293}
294
295fn snap_measured_size_to_device_pixels(size: Size<Pixels>, scale_factor: f32) -> Size<f32> {
296 size.map(|d| ceil_to_device_pixel(d.0.max(0.0), scale_factor))
297}
298
299fn border_widths_to_taffy(
300 widths: &Edges<AbsoluteLength>,
301 rem_size: Pixels,
302 scale_factor: f32,
303) -> TaffyRect<taffy::style::LengthPercentage> {
304 let snap = |w: &AbsoluteLength| {
305 taffy::style::LengthPercentage::length(round_stroke_to_device_pixel(
306 w.to_pixels(rem_size).0,
307 scale_factor,
308 ))
309 };
310 TaffyRect {
311 top: snap(&widths.top),
312 right: snap(&widths.right),
313 bottom: snap(&widths.bottom),
314 left: snap(&widths.left),
315 }
316}
317
318impl ToTaffy<taffy::style::Style> for Style {
319 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Style {
320 use taffy::style_helpers::{fr, length, minmax, repeat};
321
322 fn to_grid_line(
323 placement: &Range<crate::GridPlacement>,
324 ) -> taffy::Line<taffy::GridPlacement> {
325 taffy::Line {
326 start: placement.start.into(),
327 end: placement.end.into(),
328 }
329 }
330
331 fn to_grid_repeat<T: taffy::style::CheapCloneStr>(
332 unit: &Option<GridTemplate>,
333 ) -> Vec<taffy::GridTemplateComponent<T>> {
334 unit.map(|template| match template.min_size {
335 crate::TemplateColumnMinSize::Zero => {
336 vec![repeat(
337 template.repeat,
338 vec![minmax(length(0.0_f32), fr(1.0_f32))],
339 )]
340 }
341 crate::TemplateColumnMinSize::MinContent => {
342 vec![repeat(
343 template.repeat,
344 vec![minmax(min_content(), fr(1.0_f32))],
345 )]
346 }
347 crate::TemplateColumnMinSize::MaxContent => {
348 vec![repeat(
349 template.repeat,
350 vec![minmax(length(0.0_f32), max_content())],
351 )]
352 }
353 })
354 .unwrap_or_default()
355 }
356
357 taffy::style::Style {
358 display: self.display.into(),
359 overflow: self.overflow.into(),
360 scrollbar_width: self.scrollbar_width.to_taffy(rem_size, scale_factor),
361 position: self.position.into(),
362 inset: self.inset.to_taffy(rem_size, scale_factor),
363 size: self.size.to_taffy(rem_size, scale_factor),
364 min_size: self.min_size.to_taffy(rem_size, scale_factor),
365 max_size: self.max_size.to_taffy(rem_size, scale_factor),
366 aspect_ratio: self.aspect_ratio,
367 margin: self.margin.to_taffy(rem_size, scale_factor),
368 padding: self.padding.to_taffy(rem_size, scale_factor),
369 border: border_widths_to_taffy(&self.border_widths, rem_size, scale_factor),
370 align_items: self.align_items.map(Into::into).unwrap_or_default(),
371 align_self: self.align_self.map(|x| x.into()),
372 align_content: self.align_content.map(Into::into).unwrap_or_default(),
373 justify_content: self.justify_content.map(Into::into).unwrap_or_default(),
374 gap: self.gap.to_taffy(rem_size, scale_factor),
375 flex_direction: self.flex_direction.into(),
376 flex_wrap: self.flex_wrap.into(),
377 flex_basis: self.flex_basis.to_taffy(rem_size, scale_factor),
378 flex_grow: self.flex_grow,
379 flex_shrink: self.flex_shrink,
380 grid_template_rows: to_grid_repeat(&self.grid_rows),
381 grid_template_columns: to_grid_repeat(&self.grid_cols),
382 grid_row: self
383 .grid_location
384 .as_ref()
385 .map(|location| to_grid_line(&location.row))
386 .unwrap_or_default(),
387 grid_column: self
388 .grid_location
389 .as_ref()
390 .map(|location| to_grid_line(&location.column))
391 .unwrap_or_default(),
392 ..Default::default()
393 }
394 }
395}
396
397impl ToTaffy<f32> for AbsoluteLength {
398 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> f32 {
399 round_to_device_pixel(self.to_pixels(rem_size).0, scale_factor)
400 }
401}
402
403impl ToTaffy<taffy::style::LengthPercentageAuto> for Length {
404 fn to_taffy(
405 &self,
406 rem_size: Pixels,
407 scale_factor: f32,
408 ) -> taffy::prelude::LengthPercentageAuto {
409 match self {
410 Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
411 Length::Auto => taffy::prelude::LengthPercentageAuto::auto(),
412 }
413 }
414}
415
416impl ToTaffy<taffy::style::Dimension> for Length {
417 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::prelude::Dimension {
418 match self {
419 Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
420 Length::Auto => taffy::prelude::Dimension::auto(),
421 }
422 }
423}
424
425impl ToTaffy<taffy::style::LengthPercentage> for DefiniteLength {
426 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
427 match self {
428 DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
429 DefiniteLength::Fraction(fraction) => {
430 taffy::style::LengthPercentage::percent(*fraction)
431 }
432 }
433 }
434}
435
436impl ToTaffy<taffy::style::LengthPercentageAuto> for DefiniteLength {
437 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
438 match self {
439 DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
440 DefiniteLength::Fraction(fraction) => {
441 taffy::style::LengthPercentageAuto::percent(*fraction)
442 }
443 }
444 }
445}
446
447impl ToTaffy<taffy::style::Dimension> for DefiniteLength {
448 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
449 match self {
450 DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
451 DefiniteLength::Fraction(fraction) => taffy::style::Dimension::percent(*fraction),
452 }
453 }
454}
455
456impl ToTaffy<taffy::style::LengthPercentage> for AbsoluteLength {
457 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
458 taffy::style::LengthPercentage::length(self.to_taffy(rem_size, scale_factor))
459 }
460}
461
462impl ToTaffy<taffy::style::LengthPercentageAuto> for AbsoluteLength {
463 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
464 taffy::style::LengthPercentageAuto::length(self.to_taffy(rem_size, scale_factor))
465 }
466}
467
468impl ToTaffy<taffy::style::Dimension> for AbsoluteLength {
469 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
470 taffy::style::Dimension::length(self.to_taffy(rem_size, scale_factor))
471 }
472}
473
474impl<T, T2> From<TaffyPoint<T>> for Point<T2>
475where
476 T: Into<T2>,
477 T2: Clone + Debug + Default + PartialEq,
478{
479 fn from(point: TaffyPoint<T>) -> Point<T2> {
480 Point {
481 x: point.x.into(),
482 y: point.y.into(),
483 }
484 }
485}
486
487impl<T, T2> From<Point<T>> for TaffyPoint<T2>
488where
489 T: Into<T2> + Clone + Debug + Default + PartialEq,
490{
491 fn from(val: Point<T>) -> Self {
492 TaffyPoint {
493 x: val.x.into(),
494 y: val.y.into(),
495 }
496 }
497}
498
499impl<T, U> ToTaffy<TaffySize<U>> for Size<T>
500where
501 T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
502{
503 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffySize<U> {
504 TaffySize {
505 width: self.width.to_taffy(rem_size, scale_factor),
506 height: self.height.to_taffy(rem_size, scale_factor),
507 }
508 }
509}
510
511impl<T, U> ToTaffy<TaffyRect<U>> for Edges<T>
512where
513 T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
514{
515 fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffyRect<U> {
516 TaffyRect {
517 top: self.top.to_taffy(rem_size, scale_factor),
518 right: self.right.to_taffy(rem_size, scale_factor),
519 bottom: self.bottom.to_taffy(rem_size, scale_factor),
520 left: self.left.to_taffy(rem_size, scale_factor),
521 }
522 }
523}
524
525impl<T, U> From<TaffySize<T>> for Size<U>
526where
527 T: Into<U>,
528 U: Clone + Debug + Default + PartialEq,
529{
530 fn from(taffy_size: TaffySize<T>) -> Self {
531 Size {
532 width: taffy_size.width.into(),
533 height: taffy_size.height.into(),
534 }
535 }
536}
537
538impl<T, U> From<Size<T>> for TaffySize<U>
539where
540 T: Into<U> + Clone + Debug + Default + PartialEq,
541{
542 fn from(size: Size<T>) -> Self {
543 TaffySize {
544 width: size.width.into(),
545 height: size.height.into(),
546 }
547 }
548}
549
550#[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
552pub enum AvailableSpace {
553 Definite(Pixels),
555 #[default]
557 MinContent,
558 MaxContent,
560}
561
562pub(crate) fn available_space_for_optional_width(width: Option<Pixels>) -> AvailableSpace {
563 width.map_or(AvailableSpace::MaxContent, AvailableSpace::Definite)
564}
565
566impl AvailableSpace {
567 pub const fn min_size() -> Size<Self> {
581 Size {
582 width: Self::MinContent,
583 height: Self::MinContent,
584 }
585 }
586}
587
588impl From<AvailableSpace> for TaffyAvailableSpace {
589 fn from(space: AvailableSpace) -> TaffyAvailableSpace {
590 match space {
591 AvailableSpace::Definite(Pixels(value)) => TaffyAvailableSpace::Definite(value),
592 AvailableSpace::MinContent => TaffyAvailableSpace::MinContent,
593 AvailableSpace::MaxContent => TaffyAvailableSpace::MaxContent,
594 }
595 }
596}
597
598impl From<TaffyAvailableSpace> for AvailableSpace {
599 fn from(space: TaffyAvailableSpace) -> AvailableSpace {
600 match space {
601 TaffyAvailableSpace::Definite(value) => AvailableSpace::Definite(Pixels(value)),
602 TaffyAvailableSpace::MinContent => AvailableSpace::MinContent,
603 TaffyAvailableSpace::MaxContent => AvailableSpace::MaxContent,
604 }
605 }
606}
607
608impl From<Pixels> for AvailableSpace {
609 fn from(pixels: Pixels) -> Self {
610 AvailableSpace::Definite(pixels)
611 }
612}
613
614impl From<Size<Pixels>> for Size<AvailableSpace> {
615 fn from(size: Size<Pixels>) -> Self {
616 Size {
617 width: AvailableSpace::Definite(size.width),
618 height: AvailableSpace::Definite(size.height),
619 }
620 }
621}
622
623#[cfg(test)]
624mod tests {
625 use super::*;
626 use crate::px;
627
628 #[test]
629 fn optional_width_uses_max_content_when_unbounded() {
630 assert_eq!(
631 available_space_for_optional_width(None),
632 AvailableSpace::MaxContent
633 );
634 assert_eq!(
635 available_space_for_optional_width(Some(px(320.0))),
636 AvailableSpace::Definite(px(320.0))
637 );
638 }
639}