1use std::collections::HashMap;
8use std::fmt;
9
10use crate::error::{GuiError, GuiResult};
11use crate::layout::{AvailableSpace, Display, LayoutRect, Point, Position, Size, Style};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16pub struct LayoutNodeId {
17 pub index: usize,
18 pub generation: u32,
19}
20
21impl LayoutNodeId {
22 pub const fn new(index: usize, generation: u32) -> Self {
24 Self { index, generation }
25 }
26
27 pub fn index(&self) -> usize {
29 self.index
30 }
31
32 pub fn generation(&self) -> u32 {
34 self.generation
35 }
36}
37
38impl fmt::Display for LayoutNodeId {
39 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40 write!(f, "LayoutNodeId({}:{})", self.index, self.generation)
41 }
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
46#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
47pub struct LayoutMetrics {
48 pub node_creations: usize,
49 pub attachments: usize,
50 pub removals: usize,
51 pub style_updates: usize,
52 pub dirty_markings: usize,
53 pub cache_hits: usize,
54 pub cache_misses: usize,
55 pub solves: usize,
56}
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
60pub enum AvailableSpaceKey {
61 Definite(u32),
62 MinContent,
63 MaxContent,
64}
65
66impl From<AvailableSpace> for AvailableSpaceKey {
67 fn from(space: AvailableSpace) -> Self {
68 match space {
69 AvailableSpace::Definite(px) => {
70 let norm = if px == 0.0 { 0.0 } else { px };
71 AvailableSpaceKey::Definite(norm.to_bits())
72 }
73 AvailableSpace::MinContent => AvailableSpaceKey::MinContent,
74 AvailableSpace::MaxContent => AvailableSpaceKey::MaxContent,
75 }
76 }
77}
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
81pub struct LayoutCacheKey {
82 pub node_id: LayoutNodeId,
83 pub available_width: AvailableSpaceKey,
84 pub available_height: AvailableSpaceKey,
85 pub measurement_revision: u64,
86 pub style_revision: u64,
87}
88
89#[derive(Debug, Clone, Copy, PartialEq, Default)]
91#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
92pub struct CachedLayout {
93 pub layout: LayoutRect,
94 pub unrounded: LayoutRect,
95 pub content_size: Size<f32>,
96}
97
98#[derive(Debug, Clone)]
100pub struct LayoutNode {
101 id: LayoutNodeId,
102 style: Style,
103 parent: Option<LayoutNodeId>,
104 children: Vec<LayoutNodeId>,
105 revision: u64,
106 style_revision: u64,
107 measurement_revision: u64,
108 dirty: bool,
109 layout: LayoutRect,
110 unrounded_layout: LayoutRect,
111}
112
113impl LayoutNode {
114 pub fn id(&self) -> LayoutNodeId {
116 self.id
117 }
118
119 pub fn style(&self) -> &Style {
121 &self.style
122 }
123
124 pub fn parent(&self) -> Option<LayoutNodeId> {
126 self.parent
127 }
128
129 pub fn children(&self) -> &[LayoutNodeId] {
131 &self.children
132 }
133
134 pub fn revision(&self) -> u64 {
136 self.revision
137 }
138
139 pub fn style_revision(&self) -> u64 {
141 self.style_revision
142 }
143
144 pub fn measurement_revision(&self) -> u64 {
146 self.measurement_revision
147 }
148
149 pub fn is_dirty(&self) -> bool {
151 self.dirty
152 }
153
154 pub fn layout(&self) -> LayoutRect {
156 self.layout
157 }
158
159 pub fn unrounded_layout(&self) -> LayoutRect {
161 self.unrounded_layout
162 }
163}
164
165#[derive(Debug, Clone)]
166struct Slot {
167 generation: u32,
168 node: Option<LayoutNode>,
169}
170
171#[derive(Debug, Clone, Default)]
174pub struct LayoutTree {
175 slots: Vec<Slot>,
176 free_indices: Vec<usize>,
177 roots: Vec<LayoutNodeId>,
178 cache: HashMap<LayoutCacheKey, CachedLayout>,
179 metrics: LayoutMetrics,
180}
181
182impl LayoutTree {
183 pub fn new() -> Self {
185 Self::default()
186 }
187
188 pub fn validate_node_id(&self, id: LayoutNodeId) -> GuiResult<()> {
190 let slot = self.slots.get(id.index).ok_or_else(|| {
191 GuiError::Backend(format!("stale or invalid layout node id: {:?}", id))
192 })?;
193 if slot.generation != id.generation || slot.node.is_none() {
194 return Err(GuiError::Backend(format!(
195 "stale or invalid layout node id: {:?}",
196 id
197 )));
198 }
199 Ok(())
200 }
201
202 pub fn node(&self, id: LayoutNodeId) -> GuiResult<&LayoutNode> {
204 self.validate_node_id(id)?;
205 Ok(self.slots[id.index].node.as_ref().unwrap())
206 }
207
208 pub fn node_mut(&mut self, id: LayoutNodeId) -> GuiResult<&mut LayoutNode> {
210 self.validate_node_id(id)?;
211 Ok(self.slots[id.index].node.as_mut().unwrap())
212 }
213
214 pub fn create_node(&mut self, style: Style) -> LayoutNodeId {
216 let index = if let Some(free_idx) = self.free_indices.pop() {
217 free_idx
218 } else {
219 let idx = self.slots.len();
220 self.slots.push(Slot {
221 generation: 1,
222 node: None,
223 });
224 idx
225 };
226
227 let generation = self.slots[index].generation;
228 let id = LayoutNodeId::new(index, generation);
229 let node = LayoutNode {
230 id,
231 style,
232 parent: None,
233 children: Vec::new(),
234 revision: 1,
235 style_revision: 1,
236 measurement_revision: 1,
237 dirty: true,
238 layout: LayoutRect::ZERO,
239 unrounded_layout: LayoutRect::ZERO,
240 };
241
242 self.slots[index].node = Some(node);
243 self.roots.push(id);
244 self.metrics.node_creations += 1;
245 self.metrics.dirty_markings += 1;
246 id
247 }
248
249 pub fn attach_child(&mut self, parent: LayoutNodeId, child: LayoutNodeId) -> GuiResult<()> {
254 self.validate_node_id(parent)?;
255 self.validate_node_id(child)?;
256 self.check_cycle(parent, child)?;
257
258 let old_parent = self.node(child)?.parent;
259 if old_parent == Some(parent) {
260 return Ok(());
261 }
262
263 if let Some(old_p_id) = old_parent {
264 let old_p = self.slots[old_p_id.index].node.as_mut().unwrap();
265 old_p.children.retain(|&c| c != child);
266 old_p.revision += 1;
267 self.propagate_dirty(old_p_id);
268 } else {
269 self.roots.retain(|&r| r != child);
270 self.cache.retain(|k, _| k.node_id != child);
272 }
273
274 let p_node = self.slots[parent.index].node.as_mut().unwrap();
275 if !p_node.children.contains(&child) {
276 p_node.children.push(child);
277 }
278 p_node.revision += 1;
279
280 let c_node = self.slots[child.index].node.as_mut().unwrap();
281 c_node.parent = Some(parent);
282 c_node.revision += 1;
283
284 self.propagate_dirty(parent);
285 self.propagate_dirty(child);
286
287 self.metrics.attachments += 1;
288 Ok(())
289 }
290
291 pub fn reparent_child(
293 &mut self,
294 new_parent: LayoutNodeId,
295 child: LayoutNodeId,
296 ) -> GuiResult<()> {
297 self.attach_child(new_parent, child)
298 }
299
300 pub fn detach_child(&mut self, child: LayoutNodeId) -> GuiResult<()> {
302 self.validate_node_id(child)?;
303 let old_parent = self.node(child)?.parent;
304 if let Some(old_p_id) = old_parent {
305 let old_p = self.slots[old_p_id.index].node.as_mut().unwrap();
306 if let Some(pos) = old_p.children.iter().position(|&c| c == child) {
307 old_p.children.remove(pos);
308 }
309 old_p.revision += 1;
310 self.propagate_dirty(old_p_id);
311
312 let c_node = self.slots[child.index].node.as_mut().unwrap();
313 c_node.parent = None;
314 c_node.revision += 1;
315 self.propagate_dirty(child);
316
317 if !self.roots.contains(&child) {
318 self.roots.push(child);
319 }
320 }
321 Ok(())
322 }
323
324 pub fn detach_all_children(&mut self, parent: LayoutNodeId) -> GuiResult<Vec<LayoutNodeId>> {
326 self.validate_node_id(parent)?;
327 let p = self.slots[parent.index].node.as_mut().unwrap();
328 let children = std::mem::take(&mut p.children);
329 p.revision += 1;
330 self.propagate_dirty(parent);
331 for &child in &children {
332 if let Some(c_node) = self.slots[child.index].node.as_mut() {
333 c_node.parent = None;
334 c_node.revision += 1;
335 }
336 }
337 Ok(children)
338 }
339
340 pub fn remove_node(&mut self, node: LayoutNodeId) -> GuiResult<()> {
342 self.validate_node_id(node)?;
343
344 let subtree = self.collect_subtree(node)?;
345
346 let parent = self.node(node)?.parent;
347 if let Some(p_id) = parent {
348 let p_node = self.slots[p_id.index].node.as_mut().unwrap();
349 if let Some(pos) = p_node.children.iter().position(|&c| c == node) {
350 p_node.children.remove(pos);
351 }
352 p_node.revision += 1;
353 self.propagate_dirty(p_id);
354 } else {
355 if let Some(pos) = self.roots.iter().position(|&r| r == node) {
356 self.roots.swap_remove(pos);
357 }
358 self.cache.retain(|k, _| k.node_id != node);
362 }
363
364 for id in subtree {
365 let slot = &mut self.slots[id.index];
366 slot.generation = slot.generation.wrapping_add(1);
367 slot.node = None;
368 self.free_indices.push(id.index);
369 if let Some(pos) = self.roots.iter().position(|&r| r == id) {
370 self.roots.swap_remove(pos);
371 }
372 self.metrics.removals += 1;
373 }
374
375 Ok(())
376 }
377
378 pub fn set_style(&mut self, node: LayoutNodeId, style: Style) -> GuiResult<()> {
382 self.validate_node_id(node)?;
383 style.validate()?;
384
385 let n = self.slots[node.index].node.as_mut().unwrap();
386 n.style = style;
387 n.style_revision += 1;
388 n.revision += 1;
389 self.propagate_dirty(node);
390 self.metrics.style_updates += 1;
391 Ok(())
392 }
393
394 pub fn style(&self, node: LayoutNodeId) -> GuiResult<&Style> {
396 Ok(&self.node(node)?.style)
397 }
398
399 pub fn children(&self, node: LayoutNodeId) -> GuiResult<&[LayoutNodeId]> {
401 Ok(&self.node(node)?.children)
402 }
403
404 pub fn parent(&self, node: LayoutNodeId) -> GuiResult<Option<LayoutNodeId>> {
406 Ok(self.node(node)?.parent)
407 }
408
409 pub fn is_dirty(&self, node: LayoutNodeId) -> GuiResult<bool> {
411 Ok(self.node(node)?.dirty)
412 }
413
414 pub fn mark_dirty(&mut self, node: LayoutNodeId) -> GuiResult<()> {
416 self.validate_node_id(node)?;
417 self.propagate_dirty(node);
418 Ok(())
419 }
420
421 pub fn set_measurement_revision(&mut self, node: LayoutNodeId, revision: u64) -> GuiResult<()> {
423 self.validate_node_id(node)?;
424 let n = self.slots[node.index].node.as_mut().unwrap();
425 if n.measurement_revision != revision {
426 n.measurement_revision = revision;
427 n.revision += 1;
428 self.propagate_dirty(node);
429 }
430 Ok(())
431 }
432
433 pub fn layout(&self, node: LayoutNodeId) -> GuiResult<LayoutRect> {
435 Ok(self.node(node)?.layout)
436 }
437
438 pub fn unrounded_layout(&self, node: LayoutNodeId) -> GuiResult<LayoutRect> {
440 Ok(self.node(node)?.unrounded_layout)
441 }
442
443 pub fn node_count(&self) -> usize {
445 self.slots.iter().filter(|s| s.node.is_some()).count()
446 }
447
448 pub fn contains(&self, node: LayoutNodeId) -> bool {
450 self.validate_node_id(node).is_ok()
451 }
452
453 pub fn roots(&self) -> &[LayoutNodeId] {
455 &self.roots
456 }
457
458 pub fn is_root(&self, node: LayoutNodeId) -> GuiResult<bool> {
460 self.validate_node_id(node)?;
461 Ok(self.node(node)?.parent.is_none())
462 }
463
464 pub fn root_for(&self, node: LayoutNodeId) -> GuiResult<LayoutNodeId> {
466 self.validate_node_id(node)?;
467 let mut current = node;
468 while let Some(p) = self.node(current)?.parent {
469 current = p;
470 }
471 Ok(current)
472 }
473
474 pub fn metrics(&self) -> &LayoutMetrics {
476 &self.metrics
477 }
478
479 pub fn reset_metrics(&mut self) {
481 self.metrics = LayoutMetrics::default();
482 }
483
484 pub fn clear_cache(&mut self) {
486 self.cache.clear();
487 }
488
489 pub fn cache_len(&self) -> usize {
491 self.cache.len()
492 }
493
494 pub fn compute_layout(
496 &mut self,
497 root: LayoutNodeId,
498 available_space: Size<AvailableSpace>,
499 ) -> GuiResult<LayoutRect> {
500 self.compute_layout_with_measure(root, available_space, |_, _, _| None)
501 }
502
503 pub fn compute_layout_with_measure<F>(
512 &mut self,
513 root: LayoutNodeId,
514 available_space: Size<AvailableSpace>,
515 mut measure_fn: F,
516 ) -> GuiResult<LayoutRect>
517 where
518 F: FnMut(LayoutNodeId, Size<Option<f32>>, Size<AvailableSpace>) -> Option<Size<f32>>,
519 {
520 self.validate_node_id(root)?;
521
522 let root_node = self.node(root)?;
523 let is_root = root_node.parent.is_none();
524 let is_dirty = root_node.dirty;
525 let meas_rev = root_node.measurement_revision;
526 let style_rev = root_node.style_revision;
527
528 let key = LayoutCacheKey {
529 node_id: root,
530 available_width: available_space.width.into(),
531 available_height: available_space.height.into(),
532 measurement_revision: meas_rev,
533 style_revision: style_rev,
534 };
535
536 if is_root && !is_dirty {
537 if let Some(cached) = self.cache.get(&key) {
538 self.metrics.cache_hits += 1;
539 self.metrics.solves += 1;
540 return Ok(cached.layout);
541 }
542 }
543
544 self.metrics.cache_misses += 1;
545 self.metrics.solves += 1;
546
547 let rect = self.solve_node(root, Point::ZERO, available_space, &mut measure_fn)?;
548 if is_root {
549 self.cache.retain(|k, _| k.node_id != root);
552 self.cache.insert(
553 key,
554 CachedLayout {
555 layout: rect,
556 unrounded: rect,
557 content_size: Size::new(rect.width, rect.height),
558 },
559 );
560 }
561 Ok(rect)
562 }
563
564 fn check_cycle(&self, parent: LayoutNodeId, child: LayoutNodeId) -> GuiResult<()> {
569 if parent == child {
570 return Err(GuiError::Backend(format!(
571 "cannot create a widget parent cycle: node {:?} attached to itself",
572 parent
573 )));
574 }
575 let mut current = Some(parent);
576 while let Some(curr_id) = current {
577 if curr_id == child {
578 return Err(GuiError::Backend(format!(
579 "cannot create a widget parent cycle: child {:?} is an ancestor of parent {:?}",
580 child, parent
581 )));
582 }
583 let node = self.node(curr_id)?;
584 current = node.parent;
585 }
586 Ok(())
587 }
588
589 fn propagate_dirty(&mut self, node_id: LayoutNodeId) {
590 let mut current = Some(node_id);
591 while let Some(curr_id) = current {
592 if let Some(slot) = self.slots.get_mut(curr_id.index) {
593 if let Some(node) = slot.node.as_mut() {
594 if !node.dirty {
595 node.dirty = true;
596 self.metrics.dirty_markings += 1;
597 }
598 current = node.parent;
599 } else {
600 break;
601 }
602 } else {
603 break;
604 }
605 }
606 }
607
608 fn collect_subtree(&self, root: LayoutNodeId) -> GuiResult<Vec<LayoutNodeId>> {
609 let mut result = Vec::new();
610 let mut stack = vec![root];
611 while let Some(current) = stack.pop() {
612 result.push(current);
613 let node = self.node(current)?;
614 for &child in node.children.iter().rev() {
615 stack.push(child);
616 }
617 }
618 Ok(result)
619 }
620
621 fn solve_node<F>(
622 &mut self,
623 node_id: LayoutNodeId,
624 origin: Point<f32>,
625 available_space: Size<AvailableSpace>,
626 measure_fn: &mut F,
627 ) -> GuiResult<LayoutRect>
628 where
629 F: FnMut(LayoutNodeId, Size<Option<f32>>, Size<AvailableSpace>) -> Option<Size<f32>>,
630 {
631 self.solve_node_depth(node_id, origin, available_space, measure_fn, 0)
632 }
633
634 fn intrinsic_extent<F>(
645 &self,
646 node_id: LayoutNodeId,
647 along_width: bool,
648 available_main: Option<f32>,
649 measure_fn: &mut F,
650 depth: usize,
651 ) -> GuiResult<f32>
652 where
653 F: FnMut(LayoutNodeId, Size<Option<f32>>, Size<AvailableSpace>) -> Option<Size<f32>>,
654 {
655 use crate::layout::{
656 Dimension, FlexDirection, FlexWrap, LengthPercentage, LengthPercentageAuto,
657 };
658 if depth >= crate::layout::box_sizing::MAX_LAYOUT_DEPTH {
659 return Ok(0.0);
660 }
661 let node = self.node(node_id)?;
662 let style = &node.style;
663 if style.display == Display::None {
664 return Ok(0.0);
665 }
666 let pick = |size: &Size<Dimension>| if along_width { size.width } else { size.height };
667 let length = |dim: Dimension| match dim {
668 Dimension::Length(px) => Some(px.max(0.0)),
669 _ => None,
670 };
671 let min = length(pick(&style.min_size)).unwrap_or(0.0);
672 let max = length(pick(&style.max_size)).unwrap_or(f32::INFINITY);
673 let clamp = |value: f32| {
674 if min > max {
675 min
676 } else {
677 value.clamp(min, max)
678 }
679 };
680 if let Some(px) = length(pick(&style.size)) {
681 return Ok(clamp(px));
682 }
683 let content = if node.children.is_empty() {
684 let measured = measure_fn(
685 node_id,
686 Size::new(None, None),
687 Size::new(AvailableSpace::MaxContent, AvailableSpace::MaxContent),
688 );
689 measured.map_or(
690 0.0,
691 |size| if along_width { size.width } else { size.height },
692 )
693 } else if style.display == Display::Grid {
694 0.0
695 } else {
696 let is_row = matches!(
697 style.flex_direction,
698 FlexDirection::Row | FlexDirection::RowReverse
699 );
700 let along_main = is_row == along_width;
701 let lp = |value: LengthPercentageAuto| match value {
702 LengthPercentageAuto::Length(px) => px.max(0.0),
703 _ => 0.0,
704 };
705 let mut total = 0.0f32;
706 let mut largest = 0.0f32;
707 let mut count = 0usize;
708 let is_wrapping = !along_main && style.flex_wrap != FlexWrap::NoWrap;
709 let mut child_extents = Vec::new();
710
711 for &child in &node.children {
712 let child_node = self.node(child)?;
713 if child_node.style.position == Position::Absolute
714 || child_node.style.display == Display::None
715 {
716 continue;
717 }
718 let margins = if along_width {
719 lp(child_node.style.margin.left) + lp(child_node.style.margin.right)
720 } else {
721 lp(child_node.style.margin.top) + lp(child_node.style.margin.bottom)
722 };
723 let extent =
724 self.intrinsic_extent(child, along_width, None, measure_fn, depth + 1)?
725 + margins;
726 total += extent;
727 largest = largest.max(extent);
728 count += 1;
729
730 if is_wrapping {
731 let main_margins = if is_row {
732 lp(child_node.style.margin.left) + lp(child_node.style.margin.right)
733 } else {
734 lp(child_node.style.margin.top) + lp(child_node.style.margin.bottom)
735 };
736 let child_main =
737 self.intrinsic_extent(child, is_row, None, measure_fn, depth + 1)?
738 + main_margins;
739 child_extents.push((child_main, extent));
740 }
741 }
742 if along_main {
743 let gap = match if along_width {
744 style.gap.width
745 } else {
746 style.gap.height
747 } {
748 LengthPercentage::Length(px) => px.max(0.0),
749 LengthPercentage::Percent(_) => 0.0,
750 };
751 total + gap * count.saturating_sub(1) as f32
752 } else if is_wrapping {
753 let padding_func = |value: LengthPercentage| match value {
754 LengthPercentage::Length(px) => px.max(0.0),
755 LengthPercentage::Percent(_) => 0.0,
756 };
757 let pad_main = if is_row {
758 padding_func(style.padding.left) + padding_func(style.padding.right)
759 } else {
760 padding_func(style.padding.top) + padding_func(style.padding.bottom)
761 };
762
763 let main_dim = if is_row {
764 style.size.width
765 } else {
766 style.size.height
767 };
768 let mut main_limit = length(main_dim);
769 if main_limit.is_none() {
770 main_limit = available_main;
771 }
772 let max_main_dim = if is_row {
773 style.max_size.width
774 } else {
775 style.max_size.height
776 };
777 if let Some(max_px) = length(max_main_dim) {
778 main_limit = Some(main_limit.map_or(max_px, |v| v.min(max_px)));
779 }
780 let min_main_dim = if is_row {
781 style.min_size.width
782 } else {
783 style.min_size.height
784 };
785 if let Some(min_px) = length(min_main_dim) {
786 main_limit = Some(main_limit.map_or(min_px, |v| v.max(min_px)));
787 }
788
789 if let Some(limit) = main_limit {
790 let inner_main = (limit - pad_main).max(0.0);
791 let gap_main = match if is_row {
792 style.gap.width
793 } else {
794 style.gap.height
795 } {
796 LengthPercentage::Length(px) => px.max(0.0),
797 LengthPercentage::Percent(_) => 0.0,
798 };
799 let gap_cross = match if is_row {
800 style.gap.height
801 } else {
802 style.gap.width
803 } {
804 LengthPercentage::Length(px) => px.max(0.0),
805 LengthPercentage::Percent(_) => 0.0,
806 };
807
808 let mut lines_cross: Vec<f32> = Vec::new();
809 let mut cur_main = 0.0f32;
810 let mut cur_cross = 0.0f32;
811 let mut line_has_items = false;
812
813 for (c_main, c_cross) in child_extents {
814 if !line_has_items {
815 cur_main = c_main;
816 cur_cross = c_cross;
817 line_has_items = true;
818 } else {
819 let needed = gap_main + c_main;
820 if cur_main + needed <= inner_main + 1e-4 {
821 cur_main += needed;
822 cur_cross = cur_cross.max(c_cross);
823 } else {
824 lines_cross.push(cur_cross);
825 cur_main = c_main;
826 cur_cross = c_cross;
827 }
828 }
829 }
830 if line_has_items {
831 lines_cross.push(cur_cross);
832 }
833
834 lines_cross.iter().sum::<f32>()
835 + gap_cross * lines_cross.len().saturating_sub(1) as f32
836 } else {
837 largest
838 }
839 } else {
840 largest
841 }
842 };
843 let padding = |value: LengthPercentage| match value {
844 LengthPercentage::Length(px) => px.max(0.0),
845 LengthPercentage::Percent(_) => 0.0,
846 };
847 let pad = if along_width {
848 padding(style.padding.left) + padding(style.padding.right)
849 } else {
850 padding(style.padding.top) + padding(style.padding.bottom)
851 };
852 Ok(clamp(content + pad))
853 }
854
855 fn solve_node_depth<F>(
856 &mut self,
857 node_id: LayoutNodeId,
858 origin: Point<f32>,
859 available_space: Size<AvailableSpace>,
860 measure_fn: &mut F,
861 depth: usize,
862 ) -> GuiResult<LayoutRect>
863 where
864 F: FnMut(LayoutNodeId, Size<Option<f32>>, Size<AvailableSpace>) -> Option<Size<f32>>,
865 {
866 if depth >= crate::layout::box_sizing::MAX_LAYOUT_DEPTH {
867 return Err(GuiError::Backend(
868 "maximum layout recursion depth exceeded".to_string(),
869 ));
870 }
871
872 let (is_leaf, style) = {
873 let n = self.node(node_id)?;
874 (n.children.is_empty(), n.style.clone())
875 };
876 let display = style.display;
877 let auto_w = style.size.width.is_auto();
878 let auto_h = style.size.height.is_auto();
879
880 if display == Display::None {
881 let rect = LayoutRect::new(origin.x, origin.y, 0.0, 0.0);
882 let n = self.slots[node_id.index].node.as_mut().unwrap();
883 n.layout = rect;
884 n.unrounded_layout = rect;
885 n.dirty = false;
886 return Ok(rect);
887 }
888
889 let mut intrinsic_size = None;
891 if is_leaf && (auto_w || auto_h) {
892 let known = {
893 let n = self.node(node_id)?;
894 Size::new(
895 crate::layout::box_sizing::resolve_dimension(
896 n.style.size.width,
897 available_space.width,
898 ),
899 crate::layout::box_sizing::resolve_dimension(
900 n.style.size.height,
901 available_space.height,
902 ),
903 )
904 };
905 if let Some(measured) = measure_fn(node_id, known, available_space) {
906 intrinsic_size = Some(measured);
907 }
908 }
909
910 let box_dims = {
911 let n = self.node(node_id)?;
912 crate::layout::box_sizing::compute_box_sizing(
913 &n.style,
914 available_space,
915 intrinsic_size,
916 )?
917 };
918
919 let mut resolved_width = box_dims.border_box().width;
920 let mut resolved_height = box_dims.border_box().height;
921
922 if !is_leaf {
923 let inner_avail_w = if resolved_width > 0.0 && !auto_w {
924 AvailableSpace::Definite(box_dims.content.width)
925 } else {
926 available_space.width
927 };
928 let inner_avail_h = if resolved_height > 0.0 && !auto_h {
929 AvailableSpace::Definite(box_dims.content.height)
930 } else {
931 available_space.height
932 };
933 let inner_avail = Size::new(inner_avail_w, inner_avail_h);
934
935 let mut in_flow_children = Vec::new();
937 let mut out_of_flow_children = Vec::new();
938 for &child_id in &self.slots[node_id.index].node.as_ref().unwrap().children {
939 let child_node = self.node(child_id)?;
940 if child_node.style.position == Position::Absolute {
941 out_of_flow_children.push(child_id);
942 } else {
943 in_flow_children.push(child_id);
944 }
945 }
946
947 let mut child_info = Vec::with_capacity(in_flow_children.len());
949 for &child_id in &in_flow_children {
950 let (child_style, child_is_leaf) = {
951 let child_node = self.node(child_id)?;
952 (child_node.style.clone(), child_node.children.is_empty())
953 };
954 let mut measured_size = None;
955 if !child_is_leaf
962 && style.display != Display::Grid
963 && child_style.aspect_ratio.is_none()
964 && child_style.flex_basis.is_auto()
965 {
966 let parent_is_row = matches!(
967 style.flex_direction,
968 crate::layout::FlexDirection::Row
969 | crate::layout::FlexDirection::RowReverse
970 );
971 let main_is_auto = if parent_is_row {
972 child_style.size.width.is_auto()
973 } else {
974 child_style.size.height.is_auto()
975 };
976 if main_is_auto {
977 let lp_margin = |value: crate::layout::LengthPercentageAuto| match value {
978 crate::layout::LengthPercentageAuto::Length(px) => px.max(0.0),
979 _ => 0.0,
980 };
981 let child_is_row = matches!(
982 child_style.flex_direction,
983 crate::layout::FlexDirection::Row
984 | crate::layout::FlexDirection::RowReverse
985 );
986 let available_main = if parent_is_row {
987 if !child_is_row {
988 let mut avail = match child_style.size.height {
989 crate::layout::Dimension::Length(h) => Some(h.max(0.0)),
990 crate::layout::Dimension::Percent(pct) => match inner_avail
991 .height
992 {
993 AvailableSpace::Definite(ph) => Some((ph * pct).max(0.0)),
994 _ => None,
995 },
996 crate::layout::Dimension::Auto => match inner_avail.height {
997 AvailableSpace::Definite(ph) => {
998 let margin_h = lp_margin(child_style.margin.top)
999 + lp_margin(child_style.margin.bottom);
1000 Some((ph - margin_h).max(0.0))
1001 }
1002 _ => None,
1003 },
1004 };
1005 if let crate::layout::Dimension::Length(max_h) =
1006 child_style.max_size.height
1007 {
1008 avail = Some(
1009 avail.map_or(max_h.max(0.0), |v| v.min(max_h.max(0.0))),
1010 );
1011 }
1012 if let crate::layout::Dimension::Length(min_h) =
1013 child_style.min_size.height
1014 {
1015 avail = Some(
1016 avail.map_or(min_h.max(0.0), |v| v.max(min_h.max(0.0))),
1017 );
1018 }
1019 avail
1020 } else {
1021 match child_style.size.width {
1022 crate::layout::Dimension::Length(w) => Some(w.max(0.0)),
1023 _ => None,
1024 }
1025 }
1026 } else if child_is_row {
1027 let mut avail = match child_style.size.width {
1028 crate::layout::Dimension::Length(w) => Some(w.max(0.0)),
1029 crate::layout::Dimension::Percent(pct) => match inner_avail.width {
1030 AvailableSpace::Definite(pw) => Some((pw * pct).max(0.0)),
1031 _ => None,
1032 },
1033 crate::layout::Dimension::Auto => match inner_avail.width {
1034 AvailableSpace::Definite(pw) => {
1035 let margin_w = lp_margin(child_style.margin.left)
1036 + lp_margin(child_style.margin.right);
1037 Some((pw - margin_w).max(0.0))
1038 }
1039 _ => None,
1040 },
1041 };
1042 if let crate::layout::Dimension::Length(max_w) =
1043 child_style.max_size.width
1044 {
1045 avail =
1046 Some(avail.map_or(max_w.max(0.0), |v| v.min(max_w.max(0.0))));
1047 }
1048 if let crate::layout::Dimension::Length(min_w) =
1049 child_style.min_size.width
1050 {
1051 avail =
1052 Some(avail.map_or(min_w.max(0.0), |v| v.max(min_w.max(0.0))));
1053 }
1054 avail
1055 } else {
1056 match child_style.size.height {
1057 crate::layout::Dimension::Length(h) => Some(h.max(0.0)),
1058 _ => None,
1059 }
1060 };
1061 let extent = self.intrinsic_extent(
1062 child_id,
1063 parent_is_row,
1064 available_main,
1065 measure_fn,
1066 depth + 1,
1067 )?;
1068 if extent > 0.0 {
1069 measured_size = Some(if parent_is_row {
1070 Size::new(extent, 0.0)
1071 } else {
1072 Size::new(0.0, extent)
1073 });
1074 }
1075 }
1076 }
1077 if child_is_leaf
1078 && (child_style.size.width.is_auto() || child_style.size.height.is_auto())
1079 {
1080 let known = Size::new(
1081 crate::layout::box_sizing::resolve_dimension(
1082 child_style.size.width,
1083 inner_avail.width,
1084 ),
1085 crate::layout::box_sizing::resolve_dimension(
1086 child_style.size.height,
1087 inner_avail.height,
1088 ),
1089 );
1090 if let Some(measured) = measure_fn(child_id, known, inner_avail) {
1091 measured_size = Some(measured);
1092 }
1093 }
1094 let child_box = crate::layout::box_sizing::compute_box_sizing(
1095 &child_style,
1096 inner_avail,
1097 measured_size,
1098 )?;
1099 let hypo_w = child_box.border_box().width;
1100 let hypo_h = child_box.border_box().height;
1101 child_info.push((child_id, child_style, Size::new(hypo_w, hypo_h)));
1102 }
1103
1104 let content_origin = Point::new(
1105 origin.x + box_dims.padding.left,
1106 origin.y + box_dims.padding.top,
1107 );
1108 let constraints =
1109 crate::layout::box_sizing::resolve_box_constraints(&style, available_space);
1110 let keep_box_w = !auto_w
1111 || (style.aspect_ratio.is_some() && !auto_h && box_dims.content.width > 0.0);
1112 let inner_content_w = if keep_box_w {
1113 box_dims.content.width
1114 } else {
1115 match available_space.width {
1116 AvailableSpace::Definite(w) => {
1117 let clamped = crate::layout::box_sizing::BoxConstraints::clamp_dimension(
1118 w,
1119 constraints.min_size.width,
1120 constraints.max_size.width,
1121 );
1122 (clamped - box_dims.padding.left - box_dims.padding.right).max(0.0)
1123 }
1124 _ => box_dims.content.width,
1125 }
1126 };
1127 let keep_box_h = !auto_h
1128 || (style.aspect_ratio.is_some() && !auto_w && box_dims.content.height > 0.0);
1129 let inner_content_h = if keep_box_h {
1130 box_dims.content.height
1131 } else {
1132 match available_space.height {
1133 AvailableSpace::Definite(h) => {
1134 let clamped = crate::layout::box_sizing::BoxConstraints::clamp_dimension(
1135 h,
1136 constraints.min_size.height,
1137 constraints.max_size.height,
1138 );
1139 (clamped - box_dims.padding.top - box_dims.padding.bottom).max(0.0)
1140 }
1141 _ => box_dims.content.height,
1142 }
1143 };
1144 let inner_content_size = Size::new(inner_content_w, inner_content_h);
1145
1146 let flex_placements = {
1147 let n = self.node(node_id)?;
1148 if display == Display::Grid {
1149 crate::layout::grid::compute_grid(
1150 &n.style,
1151 inner_content_size,
1152 inner_avail,
1153 &child_info,
1154 content_origin,
1155 )?
1156 } else {
1157 crate::layout::flex::compute_flex(
1158 &n.style,
1159 inner_content_size,
1160 inner_avail,
1161 &child_info,
1162 content_origin,
1163 )?
1164 }
1165 };
1166
1167 let mut max_x = content_origin.x;
1168 let mut max_y = content_origin.y;
1169
1170 for (child_id, placed_rect) in flex_placements {
1171 let (child_position, child_inset, child_display, is_child_leaf) = {
1172 let child_node = self.node(child_id)?;
1173 (
1174 child_node.style.position,
1175 child_node.style.inset,
1176 child_node.style.display,
1177 child_node.children.is_empty(),
1178 )
1179 };
1180
1181 let mut solved_rect = if is_child_leaf {
1182 placed_rect
1183 } else {
1184 let child_avail = Size::new(
1185 AvailableSpace::Definite(placed_rect.width),
1186 AvailableSpace::Definite(placed_rect.height),
1187 );
1188 let mut r = self.solve_node_depth(
1189 child_id,
1190 Point::new(placed_rect.x, placed_rect.y),
1191 child_avail,
1192 measure_fn,
1193 depth + 1,
1194 )?;
1195 r.width = placed_rect.width;
1196 r.height = placed_rect.height;
1197 r
1198 };
1199
1200 if child_position == Position::Relative {
1202 let inset = crate::layout::box_sizing::resolve_inset(&child_inset, inner_avail);
1203 let new_loc = crate::layout::box_sizing::apply_relative_offset(
1204 Point::new(solved_rect.x, solved_rect.y),
1205 &inset,
1206 );
1207 solved_rect.x = new_loc.x;
1208 solved_rect.y = new_loc.y;
1209 }
1210
1211 if child_display != Display::None {
1212 max_x = max_x.max(solved_rect.x + solved_rect.width);
1213 max_y = max_y.max(solved_rect.y + solved_rect.height);
1214 }
1215
1216 let c_slot = self.slots[child_id.index].node.as_mut().unwrap();
1217 c_slot.layout = solved_rect;
1218 c_slot.unrounded_layout = solved_rect;
1219 c_slot.dirty = false;
1220 }
1221
1222 if auto_w {
1224 let content_extent =
1225 (max_x - origin.x + box_dims.padding.right).max(resolved_width);
1226 resolved_width = match available_space.width {
1227 AvailableSpace::Definite(w)
1228 if in_flow_children.iter().any(|&c| {
1229 self.node(c)
1230 .map(|n| n.style.flex_grow > 0.0)
1231 .unwrap_or(false)
1232 }) =>
1233 {
1234 w
1235 }
1236 _ => content_extent,
1237 };
1238 }
1239 if auto_h {
1240 let content_extent =
1241 (max_y - origin.y + box_dims.padding.bottom).max(resolved_height);
1242 resolved_height = match available_space.height {
1243 AvailableSpace::Definite(h) => h,
1244 _ => content_extent,
1245 };
1246 }
1247
1248 let constraints = {
1250 let n = self.node(node_id)?;
1251 crate::layout::box_sizing::resolve_box_constraints(&n.style, available_space)
1252 };
1253 resolved_width = crate::layout::box_sizing::BoxConstraints::clamp_dimension(
1254 resolved_width,
1255 constraints.min_size.width,
1256 constraints.max_size.width,
1257 );
1258 resolved_height = crate::layout::box_sizing::BoxConstraints::clamp_dimension(
1259 resolved_height,
1260 constraints.min_size.height,
1261 constraints.max_size.height,
1262 );
1263
1264 let final_content_w =
1266 (resolved_width - box_dims.padding.left - box_dims.padding.right).max(0.0);
1267 let final_content_h =
1268 (resolved_height - box_dims.padding.top - box_dims.padding.bottom).max(0.0);
1269
1270 let parent_padding_origin = Point::new(
1272 origin.x + box_dims.padding.left,
1273 origin.y + box_dims.padding.top,
1274 );
1275 let parent_padding_size = Size::new(final_content_w, final_content_h);
1276
1277 for child_id in out_of_flow_children {
1278 let child_rect = self.solve_node_depth(
1279 child_id,
1280 parent_padding_origin,
1281 Size::new(
1282 AvailableSpace::Definite(final_content_w),
1283 AvailableSpace::Definite(final_content_h),
1284 ),
1285 measure_fn,
1286 depth + 1,
1287 )?;
1288 let child_node = self.node(child_id)?;
1289 let child_margin = crate::layout::box_sizing::resolve_margin(
1290 &child_node.style.margin,
1291 inner_avail,
1292 );
1293 let inset =
1294 crate::layout::box_sizing::resolve_inset(&child_node.style.inset, inner_avail);
1295 let abs_pos = crate::layout::box_sizing::resolve_absolute_position(
1296 parent_padding_origin,
1297 parent_padding_size,
1298 Size::new(child_rect.width, child_rect.height),
1299 &inset,
1300 &child_margin,
1301 );
1302 let final_abs_rect =
1303 LayoutRect::new(abs_pos.x, abs_pos.y, child_rect.width, child_rect.height);
1304 let c_slot = self.slots[child_id.index].node.as_mut().unwrap();
1305 c_slot.layout = final_abs_rect;
1306 c_slot.unrounded_layout = final_abs_rect;
1307 }
1308 }
1309
1310 let rect = LayoutRect::new(origin.x, origin.y, resolved_width, resolved_height);
1311
1312 let n = self.slots[node_id.index].node.as_mut().unwrap();
1313 n.layout = rect;
1314 n.unrounded_layout = rect;
1315 n.dirty = false;
1316
1317 Ok(rect)
1318 }
1319}
1320
1321#[cfg(test)]
1322mod tests {
1323 use super::*;
1324 use crate::layout::{AvailableSpace, Dimension, LengthPercentage, LengthPercentageAuto, Rect};
1325
1326 #[test]
1327 fn test_solve_node_depth_geometry_regression() {
1328 let mut tree = LayoutTree::new();
1329
1330 let root_style = Style {
1332 size: Size::new(Dimension::Length(300.0), Dimension::Length(200.0)),
1333 padding: Rect::all(LengthPercentage::Length(10.0)),
1334 ..Style::default()
1335 };
1336 let root = tree.create_node(root_style);
1337
1338 let c1_style = Style {
1340 size: Size::new(Dimension::Length(80.0), Dimension::Length(50.0)),
1341 ..Style::default()
1342 };
1343 let c1 = tree.create_node(c1_style);
1344 tree.attach_child(root, c1).unwrap();
1345
1346 let c2_style = Style {
1348 size: Size::new(Dimension::Length(100.0), Dimension::Length(60.0)),
1349 position: Position::Relative,
1350 inset: Rect {
1351 left: LengthPercentageAuto::Length(5.0),
1352 top: LengthPercentageAuto::Length(5.0),
1353 ..Rect::auto()
1354 },
1355 ..Style::default()
1356 };
1357 let c2 = tree.create_node(c2_style);
1358 tree.attach_child(root, c2).unwrap();
1359
1360 let space = Size::new(
1361 AvailableSpace::Definite(300.0),
1362 AvailableSpace::Definite(200.0),
1363 );
1364 let rect = tree
1365 .compute_layout(root, space)
1366 .expect("layout computation succeeded");
1367 assert_eq!(rect, LayoutRect::new(0.0, 0.0, 300.0, 200.0));
1368
1369 let l1 = tree.layout(c1).unwrap();
1370 assert_eq!(l1, LayoutRect::new(10.0, 10.0, 80.0, 50.0));
1371
1372 let l2 = tree.layout(c2).unwrap();
1373 assert_eq!(l2, LayoutRect::new(95.0, 15.0, 100.0, 60.0));
1375 }
1376
1377 #[test]
1378 fn test_cache_retention_only_roots_and_pruning() {
1379 let mut tree = LayoutTree::new();
1380
1381 let root = tree.create_node(Style::default());
1383 let c1 = tree.create_node(Style::default());
1384 let c2 = tree.create_node(Style::default());
1385 tree.attach_child(root, c1).unwrap();
1386 tree.attach_child(root, c2).unwrap();
1387
1388 let leaf1 = tree.create_node(Style::default());
1389 let leaf2 = tree.create_node(Style::default());
1390 tree.attach_child(c1, leaf1).unwrap();
1391 tree.attach_child(c2, leaf2).unwrap();
1392
1393 let space = Size::new(
1395 AvailableSpace::Definite(500.0),
1396 AvailableSpace::Definite(400.0),
1397 );
1398 let _ = tree.compute_layout(root, space).unwrap();
1399
1400 assert_eq!(
1402 tree.cache.len(),
1403 1,
1404 "cache should hold only the root container entry"
1405 );
1406 let cached_key = tree.cache.keys().next().unwrap();
1407 assert_eq!(cached_key.node_id, root);
1408
1409 tree.remove_node(c1).unwrap();
1411 assert_eq!(tree.cache.len(), 1);
1412
1413 tree.remove_node(root).unwrap();
1415 assert_eq!(tree.cache.len(), 0, "removing root must prune the cache");
1416 }
1417
1418 #[test]
1419 fn auto_container_with_min_size_distributes_grown_definite_space() {
1420 let mut tree = LayoutTree::new();
1421 let root = tree.create_node(Style {
1422 flex_direction: crate::layout::FlexDirection::Row,
1423 ..Style::default()
1424 });
1425 let sidebar = tree.create_node(Style {
1426 size: Size::new(Dimension::Length(220.0), Dimension::Auto),
1427 ..Style::default()
1428 });
1429 let split = tree.create_node(Style {
1432 flex_direction: crate::layout::FlexDirection::Row,
1433 flex_grow: 1.0,
1434 min_size: Size::new(Dimension::Length(640.0), Dimension::Length(0.0)),
1435 ..Style::default()
1436 });
1437 let left_pane = tree.create_node(Style {
1438 flex_grow: 0.72,
1439 min_size: Size::new(Dimension::Length(456.0), Dimension::Length(0.0)),
1440 ..Style::default()
1441 });
1442 let right_pane = tree.create_node(Style {
1443 flex_grow: 0.28,
1444 min_size: Size::new(Dimension::Length(260.0), Dimension::Length(0.0)),
1445 ..Style::default()
1446 });
1447 tree.attach_child(root, sidebar).unwrap();
1448 tree.attach_child(root, split).unwrap();
1449 tree.attach_child(split, left_pane).unwrap();
1450 tree.attach_child(split, right_pane).unwrap();
1451
1452 let rect = tree
1453 .compute_layout(
1454 root,
1455 Size::new(
1456 AvailableSpace::Definite(1080.0),
1457 AvailableSpace::Definite(700.0),
1458 ),
1459 )
1460 .expect("layout succeeds");
1461 assert_eq!(rect.width, 1080.0);
1462
1463 let split_rect = tree.layout(split).unwrap();
1464 let left_rect = tree.layout(left_pane).unwrap();
1465 let right_rect = tree.layout(right_pane).unwrap();
1466 assert_eq!(split_rect.width, 860.0);
1467 assert!(
1468 (left_rect.width + right_rect.width - 860.0).abs() < 0.5,
1469 "children must consume grown split width 860, got {} + {}",
1470 left_rect.width,
1471 right_rect.width
1472 );
1473 assert!(left_rect.width >= 456.0);
1474 assert!(right_rect.width >= 260.0);
1475 }
1476}