use std::collections::HashMap;
use std::fmt;
use crate::error::{GuiError, GuiResult};
use crate::layout::{AvailableSpace, Display, LayoutRect, Point, Position, Size, Style};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct LayoutNodeId {
pub index: usize,
pub generation: u32,
}
impl LayoutNodeId {
pub const fn new(index: usize, generation: u32) -> Self {
Self { index, generation }
}
pub fn index(&self) -> usize {
self.index
}
pub fn generation(&self) -> u32 {
self.generation
}
}
impl fmt::Display for LayoutNodeId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "LayoutNodeId({}:{})", self.index, self.generation)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct LayoutMetrics {
pub node_creations: usize,
pub attachments: usize,
pub removals: usize,
pub style_updates: usize,
pub dirty_markings: usize,
pub cache_hits: usize,
pub cache_misses: usize,
pub solves: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AvailableSpaceKey {
Definite(u32),
MinContent,
MaxContent,
}
impl From<AvailableSpace> for AvailableSpaceKey {
fn from(space: AvailableSpace) -> Self {
match space {
AvailableSpace::Definite(px) => {
let norm = if px == 0.0 { 0.0 } else { px };
AvailableSpaceKey::Definite(norm.to_bits())
}
AvailableSpace::MinContent => AvailableSpaceKey::MinContent,
AvailableSpace::MaxContent => AvailableSpaceKey::MaxContent,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct LayoutCacheKey {
pub node_id: LayoutNodeId,
pub available_width: AvailableSpaceKey,
pub available_height: AvailableSpaceKey,
pub measurement_revision: u64,
pub style_revision: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CachedLayout {
pub layout: LayoutRect,
pub unrounded: LayoutRect,
pub content_size: Size<f32>,
}
#[derive(Debug, Clone)]
pub struct LayoutNode {
id: LayoutNodeId,
style: Style,
parent: Option<LayoutNodeId>,
children: Vec<LayoutNodeId>,
revision: u64,
style_revision: u64,
measurement_revision: u64,
dirty: bool,
layout: LayoutRect,
unrounded_layout: LayoutRect,
}
impl LayoutNode {
pub fn id(&self) -> LayoutNodeId {
self.id
}
pub fn style(&self) -> &Style {
&self.style
}
pub fn parent(&self) -> Option<LayoutNodeId> {
self.parent
}
pub fn children(&self) -> &[LayoutNodeId] {
&self.children
}
pub fn revision(&self) -> u64 {
self.revision
}
pub fn style_revision(&self) -> u64 {
self.style_revision
}
pub fn measurement_revision(&self) -> u64 {
self.measurement_revision
}
pub fn is_dirty(&self) -> bool {
self.dirty
}
pub fn layout(&self) -> LayoutRect {
self.layout
}
pub fn unrounded_layout(&self) -> LayoutRect {
self.unrounded_layout
}
}
#[derive(Debug, Clone)]
struct Slot {
generation: u32,
node: Option<LayoutNode>,
}
#[derive(Debug, Clone, Default)]
pub struct LayoutTree {
slots: Vec<Slot>,
free_indices: Vec<usize>,
roots: Vec<LayoutNodeId>,
cache: HashMap<LayoutCacheKey, CachedLayout>,
metrics: LayoutMetrics,
}
impl LayoutTree {
pub fn new() -> Self {
Self::default()
}
pub fn validate_node_id(&self, id: LayoutNodeId) -> GuiResult<()> {
let slot = self.slots.get(id.index).ok_or_else(|| {
GuiError::Backend(format!("stale or invalid layout node id: {:?}", id))
})?;
if slot.generation != id.generation || slot.node.is_none() {
return Err(GuiError::Backend(format!(
"stale or invalid layout node id: {:?}",
id
)));
}
Ok(())
}
pub fn node(&self, id: LayoutNodeId) -> GuiResult<&LayoutNode> {
self.validate_node_id(id)?;
Ok(self.slots[id.index].node.as_ref().unwrap())
}
pub fn node_mut(&mut self, id: LayoutNodeId) -> GuiResult<&mut LayoutNode> {
self.validate_node_id(id)?;
Ok(self.slots[id.index].node.as_mut().unwrap())
}
pub fn create_node(&mut self, style: Style) -> LayoutNodeId {
let index = if let Some(free_idx) = self.free_indices.pop() {
free_idx
} else {
let idx = self.slots.len();
self.slots.push(Slot {
generation: 1,
node: None,
});
idx
};
let generation = self.slots[index].generation;
let id = LayoutNodeId::new(index, generation);
let node = LayoutNode {
id,
style,
parent: None,
children: Vec::new(),
revision: 1,
style_revision: 1,
measurement_revision: 1,
dirty: true,
layout: LayoutRect::ZERO,
unrounded_layout: LayoutRect::ZERO,
};
self.slots[index].node = Some(node);
self.roots.push(id);
self.metrics.node_creations += 1;
self.metrics.dirty_markings += 1;
id
}
pub fn attach_child(&mut self, parent: LayoutNodeId, child: LayoutNodeId) -> GuiResult<()> {
self.validate_node_id(parent)?;
self.validate_node_id(child)?;
self.check_cycle(parent, child)?;
let old_parent = self.node(child)?.parent;
if old_parent == Some(parent) {
return Ok(());
}
if let Some(old_p_id) = old_parent {
let old_p = self.slots[old_p_id.index].node.as_mut().unwrap();
old_p.children.retain(|&c| c != child);
old_p.revision += 1;
self.propagate_dirty(old_p_id);
} else {
self.roots.retain(|&r| r != child);
self.cache.retain(|k, _| k.node_id != child);
}
let p_node = self.slots[parent.index].node.as_mut().unwrap();
if !p_node.children.contains(&child) {
p_node.children.push(child);
}
p_node.revision += 1;
let c_node = self.slots[child.index].node.as_mut().unwrap();
c_node.parent = Some(parent);
c_node.revision += 1;
self.propagate_dirty(parent);
self.propagate_dirty(child);
self.metrics.attachments += 1;
Ok(())
}
pub fn reparent_child(
&mut self,
new_parent: LayoutNodeId,
child: LayoutNodeId,
) -> GuiResult<()> {
self.attach_child(new_parent, child)
}
pub fn detach_child(&mut self, child: LayoutNodeId) -> GuiResult<()> {
self.validate_node_id(child)?;
let old_parent = self.node(child)?.parent;
if let Some(old_p_id) = old_parent {
let old_p = self.slots[old_p_id.index].node.as_mut().unwrap();
if let Some(pos) = old_p.children.iter().position(|&c| c == child) {
old_p.children.remove(pos);
}
old_p.revision += 1;
self.propagate_dirty(old_p_id);
let c_node = self.slots[child.index].node.as_mut().unwrap();
c_node.parent = None;
c_node.revision += 1;
self.propagate_dirty(child);
if !self.roots.contains(&child) {
self.roots.push(child);
}
}
Ok(())
}
pub fn detach_all_children(&mut self, parent: LayoutNodeId) -> GuiResult<Vec<LayoutNodeId>> {
self.validate_node_id(parent)?;
let p = self.slots[parent.index].node.as_mut().unwrap();
let children = std::mem::take(&mut p.children);
p.revision += 1;
self.propagate_dirty(parent);
for &child in &children {
if let Some(c_node) = self.slots[child.index].node.as_mut() {
c_node.parent = None;
c_node.revision += 1;
}
}
Ok(children)
}
pub fn remove_node(&mut self, node: LayoutNodeId) -> GuiResult<()> {
self.validate_node_id(node)?;
let subtree = self.collect_subtree(node)?;
let parent = self.node(node)?.parent;
if let Some(p_id) = parent {
let p_node = self.slots[p_id.index].node.as_mut().unwrap();
if let Some(pos) = p_node.children.iter().position(|&c| c == node) {
p_node.children.remove(pos);
}
p_node.revision += 1;
self.propagate_dirty(p_id);
} else {
if let Some(pos) = self.roots.iter().position(|&r| r == node) {
self.roots.swap_remove(pos);
}
self.cache.retain(|k, _| k.node_id != node);
}
for id in subtree {
let slot = &mut self.slots[id.index];
slot.generation = slot.generation.wrapping_add(1);
slot.node = None;
self.free_indices.push(id.index);
if let Some(pos) = self.roots.iter().position(|&r| r == id) {
self.roots.swap_remove(pos);
}
self.metrics.removals += 1;
}
Ok(())
}
pub fn set_style(&mut self, node: LayoutNodeId, style: Style) -> GuiResult<()> {
self.validate_node_id(node)?;
style.validate()?;
let n = self.slots[node.index].node.as_mut().unwrap();
n.style = style;
n.style_revision += 1;
n.revision += 1;
self.propagate_dirty(node);
self.metrics.style_updates += 1;
Ok(())
}
pub fn style(&self, node: LayoutNodeId) -> GuiResult<&Style> {
Ok(&self.node(node)?.style)
}
pub fn children(&self, node: LayoutNodeId) -> GuiResult<&[LayoutNodeId]> {
Ok(&self.node(node)?.children)
}
pub fn parent(&self, node: LayoutNodeId) -> GuiResult<Option<LayoutNodeId>> {
Ok(self.node(node)?.parent)
}
pub fn is_dirty(&self, node: LayoutNodeId) -> GuiResult<bool> {
Ok(self.node(node)?.dirty)
}
pub fn mark_dirty(&mut self, node: LayoutNodeId) -> GuiResult<()> {
self.validate_node_id(node)?;
self.propagate_dirty(node);
Ok(())
}
pub fn set_measurement_revision(&mut self, node: LayoutNodeId, revision: u64) -> GuiResult<()> {
self.validate_node_id(node)?;
let n = self.slots[node.index].node.as_mut().unwrap();
if n.measurement_revision != revision {
n.measurement_revision = revision;
n.revision += 1;
self.propagate_dirty(node);
}
Ok(())
}
pub fn layout(&self, node: LayoutNodeId) -> GuiResult<LayoutRect> {
Ok(self.node(node)?.layout)
}
pub fn unrounded_layout(&self, node: LayoutNodeId) -> GuiResult<LayoutRect> {
Ok(self.node(node)?.unrounded_layout)
}
pub fn node_count(&self) -> usize {
self.slots.iter().filter(|s| s.node.is_some()).count()
}
pub fn contains(&self, node: LayoutNodeId) -> bool {
self.validate_node_id(node).is_ok()
}
pub fn roots(&self) -> &[LayoutNodeId] {
&self.roots
}
pub fn is_root(&self, node: LayoutNodeId) -> GuiResult<bool> {
self.validate_node_id(node)?;
Ok(self.node(node)?.parent.is_none())
}
pub fn root_for(&self, node: LayoutNodeId) -> GuiResult<LayoutNodeId> {
self.validate_node_id(node)?;
let mut current = node;
while let Some(p) = self.node(current)?.parent {
current = p;
}
Ok(current)
}
pub fn metrics(&self) -> &LayoutMetrics {
&self.metrics
}
pub fn reset_metrics(&mut self) {
self.metrics = LayoutMetrics::default();
}
pub fn clear_cache(&mut self) {
self.cache.clear();
}
pub fn cache_len(&self) -> usize {
self.cache.len()
}
pub fn compute_layout(
&mut self,
root: LayoutNodeId,
available_space: Size<AvailableSpace>,
) -> GuiResult<LayoutRect> {
self.compute_layout_with_measure(root, available_space, |_, _, _| None)
}
pub fn compute_layout_with_measure<F>(
&mut self,
root: LayoutNodeId,
available_space: Size<AvailableSpace>,
mut measure_fn: F,
) -> GuiResult<LayoutRect>
where
F: FnMut(LayoutNodeId, Size<Option<f32>>, Size<AvailableSpace>) -> Option<Size<f32>>,
{
self.validate_node_id(root)?;
let root_node = self.node(root)?;
let is_root = root_node.parent.is_none();
let is_dirty = root_node.dirty;
let meas_rev = root_node.measurement_revision;
let style_rev = root_node.style_revision;
let key = LayoutCacheKey {
node_id: root,
available_width: available_space.width.into(),
available_height: available_space.height.into(),
measurement_revision: meas_rev,
style_revision: style_rev,
};
if is_root && !is_dirty {
if let Some(cached) = self.cache.get(&key) {
self.metrics.cache_hits += 1;
self.metrics.solves += 1;
return Ok(cached.layout);
}
}
self.metrics.cache_misses += 1;
self.metrics.solves += 1;
let rect = self.solve_node(root, Point::ZERO, available_space, &mut measure_fn)?;
if is_root {
self.cache.retain(|k, _| k.node_id != root);
self.cache.insert(
key,
CachedLayout {
layout: rect,
unrounded: rect,
content_size: Size::new(rect.width, rect.height),
},
);
}
Ok(rect)
}
fn check_cycle(&self, parent: LayoutNodeId, child: LayoutNodeId) -> GuiResult<()> {
if parent == child {
return Err(GuiError::Backend(format!(
"cannot create a widget parent cycle: node {:?} attached to itself",
parent
)));
}
let mut current = Some(parent);
while let Some(curr_id) = current {
if curr_id == child {
return Err(GuiError::Backend(format!(
"cannot create a widget parent cycle: child {:?} is an ancestor of parent {:?}",
child, parent
)));
}
let node = self.node(curr_id)?;
current = node.parent;
}
Ok(())
}
fn propagate_dirty(&mut self, node_id: LayoutNodeId) {
let mut current = Some(node_id);
while let Some(curr_id) = current {
if let Some(slot) = self.slots.get_mut(curr_id.index) {
if let Some(node) = slot.node.as_mut() {
if !node.dirty {
node.dirty = true;
self.metrics.dirty_markings += 1;
}
current = node.parent;
} else {
break;
}
} else {
break;
}
}
}
fn collect_subtree(&self, root: LayoutNodeId) -> GuiResult<Vec<LayoutNodeId>> {
let mut result = Vec::new();
let mut stack = vec![root];
while let Some(current) = stack.pop() {
result.push(current);
let node = self.node(current)?;
for &child in node.children.iter().rev() {
stack.push(child);
}
}
Ok(result)
}
fn solve_node<F>(
&mut self,
node_id: LayoutNodeId,
origin: Point<f32>,
available_space: Size<AvailableSpace>,
measure_fn: &mut F,
) -> GuiResult<LayoutRect>
where
F: FnMut(LayoutNodeId, Size<Option<f32>>, Size<AvailableSpace>) -> Option<Size<f32>>,
{
self.solve_node_depth(node_id, origin, available_space, measure_fn, 0)
}
fn intrinsic_extent<F>(
&self,
node_id: LayoutNodeId,
along_width: bool,
available_main: Option<f32>,
measure_fn: &mut F,
depth: usize,
) -> GuiResult<f32>
where
F: FnMut(LayoutNodeId, Size<Option<f32>>, Size<AvailableSpace>) -> Option<Size<f32>>,
{
use crate::layout::{
Dimension, FlexDirection, FlexWrap, LengthPercentage, LengthPercentageAuto,
};
if depth >= crate::layout::box_sizing::MAX_LAYOUT_DEPTH {
return Ok(0.0);
}
let node = self.node(node_id)?;
let style = &node.style;
if style.display == Display::None {
return Ok(0.0);
}
let pick = |size: &Size<Dimension>| if along_width { size.width } else { size.height };
let length = |dim: Dimension| match dim {
Dimension::Length(px) => Some(px.max(0.0)),
_ => None,
};
let min = length(pick(&style.min_size)).unwrap_or(0.0);
let max = length(pick(&style.max_size)).unwrap_or(f32::INFINITY);
let clamp = |value: f32| {
if min > max {
min
} else {
value.clamp(min, max)
}
};
if let Some(px) = length(pick(&style.size)) {
return Ok(clamp(px));
}
let content = if node.children.is_empty() {
let measured = measure_fn(
node_id,
Size::new(None, None),
Size::new(AvailableSpace::MaxContent, AvailableSpace::MaxContent),
);
measured.map_or(
0.0,
|size| if along_width { size.width } else { size.height },
)
} else if style.display == Display::Grid {
0.0
} else {
let is_row = matches!(
style.flex_direction,
FlexDirection::Row | FlexDirection::RowReverse
);
let along_main = is_row == along_width;
let lp = |value: LengthPercentageAuto| match value {
LengthPercentageAuto::Length(px) => px.max(0.0),
_ => 0.0,
};
let mut total = 0.0f32;
let mut largest = 0.0f32;
let mut count = 0usize;
let is_wrapping = !along_main && style.flex_wrap != FlexWrap::NoWrap;
let mut child_extents = Vec::new();
for &child in &node.children {
let child_node = self.node(child)?;
if child_node.style.position == Position::Absolute
|| child_node.style.display == Display::None
{
continue;
}
let margins = if along_width {
lp(child_node.style.margin.left) + lp(child_node.style.margin.right)
} else {
lp(child_node.style.margin.top) + lp(child_node.style.margin.bottom)
};
let extent =
self.intrinsic_extent(child, along_width, None, measure_fn, depth + 1)?
+ margins;
total += extent;
largest = largest.max(extent);
count += 1;
if is_wrapping {
let main_margins = if is_row {
lp(child_node.style.margin.left) + lp(child_node.style.margin.right)
} else {
lp(child_node.style.margin.top) + lp(child_node.style.margin.bottom)
};
let child_main =
self.intrinsic_extent(child, is_row, None, measure_fn, depth + 1)?
+ main_margins;
child_extents.push((child_main, extent));
}
}
if along_main {
let gap = match if along_width {
style.gap.width
} else {
style.gap.height
} {
LengthPercentage::Length(px) => px.max(0.0),
LengthPercentage::Percent(_) => 0.0,
};
total + gap * count.saturating_sub(1) as f32
} else if is_wrapping {
let padding_func = |value: LengthPercentage| match value {
LengthPercentage::Length(px) => px.max(0.0),
LengthPercentage::Percent(_) => 0.0,
};
let pad_main = if is_row {
padding_func(style.padding.left) + padding_func(style.padding.right)
} else {
padding_func(style.padding.top) + padding_func(style.padding.bottom)
};
let main_dim = if is_row {
style.size.width
} else {
style.size.height
};
let mut main_limit = length(main_dim);
if main_limit.is_none() {
main_limit = available_main;
}
let max_main_dim = if is_row {
style.max_size.width
} else {
style.max_size.height
};
if let Some(max_px) = length(max_main_dim) {
main_limit = Some(main_limit.map_or(max_px, |v| v.min(max_px)));
}
let min_main_dim = if is_row {
style.min_size.width
} else {
style.min_size.height
};
if let Some(min_px) = length(min_main_dim) {
main_limit = Some(main_limit.map_or(min_px, |v| v.max(min_px)));
}
if let Some(limit) = main_limit {
let inner_main = (limit - pad_main).max(0.0);
let gap_main = match if is_row {
style.gap.width
} else {
style.gap.height
} {
LengthPercentage::Length(px) => px.max(0.0),
LengthPercentage::Percent(_) => 0.0,
};
let gap_cross = match if is_row {
style.gap.height
} else {
style.gap.width
} {
LengthPercentage::Length(px) => px.max(0.0),
LengthPercentage::Percent(_) => 0.0,
};
let mut lines_cross: Vec<f32> = Vec::new();
let mut cur_main = 0.0f32;
let mut cur_cross = 0.0f32;
let mut line_has_items = false;
for (c_main, c_cross) in child_extents {
if !line_has_items {
cur_main = c_main;
cur_cross = c_cross;
line_has_items = true;
} else {
let needed = gap_main + c_main;
if cur_main + needed <= inner_main + 1e-4 {
cur_main += needed;
cur_cross = cur_cross.max(c_cross);
} else {
lines_cross.push(cur_cross);
cur_main = c_main;
cur_cross = c_cross;
}
}
}
if line_has_items {
lines_cross.push(cur_cross);
}
lines_cross.iter().sum::<f32>()
+ gap_cross * lines_cross.len().saturating_sub(1) as f32
} else {
largest
}
} else {
largest
}
};
let padding = |value: LengthPercentage| match value {
LengthPercentage::Length(px) => px.max(0.0),
LengthPercentage::Percent(_) => 0.0,
};
let pad = if along_width {
padding(style.padding.left) + padding(style.padding.right)
} else {
padding(style.padding.top) + padding(style.padding.bottom)
};
Ok(clamp(content + pad))
}
fn solve_node_depth<F>(
&mut self,
node_id: LayoutNodeId,
origin: Point<f32>,
available_space: Size<AvailableSpace>,
measure_fn: &mut F,
depth: usize,
) -> GuiResult<LayoutRect>
where
F: FnMut(LayoutNodeId, Size<Option<f32>>, Size<AvailableSpace>) -> Option<Size<f32>>,
{
if depth >= crate::layout::box_sizing::MAX_LAYOUT_DEPTH {
return Err(GuiError::Backend(
"maximum layout recursion depth exceeded".to_string(),
));
}
let (is_leaf, style) = {
let n = self.node(node_id)?;
(n.children.is_empty(), n.style.clone())
};
let display = style.display;
let auto_w = style.size.width.is_auto();
let auto_h = style.size.height.is_auto();
if display == Display::None {
let rect = LayoutRect::new(origin.x, origin.y, 0.0, 0.0);
let n = self.slots[node_id.index].node.as_mut().unwrap();
n.layout = rect;
n.unrounded_layout = rect;
n.dirty = false;
return Ok(rect);
}
let mut intrinsic_size = None;
if is_leaf && (auto_w || auto_h) {
let known = {
let n = self.node(node_id)?;
Size::new(
crate::layout::box_sizing::resolve_dimension(
n.style.size.width,
available_space.width,
),
crate::layout::box_sizing::resolve_dimension(
n.style.size.height,
available_space.height,
),
)
};
if let Some(measured) = measure_fn(node_id, known, available_space) {
intrinsic_size = Some(measured);
}
}
let box_dims = {
let n = self.node(node_id)?;
crate::layout::box_sizing::compute_box_sizing(
&n.style,
available_space,
intrinsic_size,
)?
};
let mut resolved_width = box_dims.border_box().width;
let mut resolved_height = box_dims.border_box().height;
if !is_leaf {
let inner_avail_w = if resolved_width > 0.0 && !auto_w {
AvailableSpace::Definite(box_dims.content.width)
} else {
available_space.width
};
let inner_avail_h = if resolved_height > 0.0 && !auto_h {
AvailableSpace::Definite(box_dims.content.height)
} else {
available_space.height
};
let inner_avail = Size::new(inner_avail_w, inner_avail_h);
let mut in_flow_children = Vec::new();
let mut out_of_flow_children = Vec::new();
for &child_id in &self.slots[node_id.index].node.as_ref().unwrap().children {
let child_node = self.node(child_id)?;
if child_node.style.position == Position::Absolute {
out_of_flow_children.push(child_id);
} else {
in_flow_children.push(child_id);
}
}
let mut child_info = Vec::with_capacity(in_flow_children.len());
for &child_id in &in_flow_children {
let (child_style, child_is_leaf) = {
let child_node = self.node(child_id)?;
(child_node.style.clone(), child_node.children.is_empty())
};
let mut measured_size = None;
if !child_is_leaf
&& style.display != Display::Grid
&& child_style.aspect_ratio.is_none()
&& child_style.flex_basis.is_auto()
{
let parent_is_row = matches!(
style.flex_direction,
crate::layout::FlexDirection::Row
| crate::layout::FlexDirection::RowReverse
);
let main_is_auto = if parent_is_row {
child_style.size.width.is_auto()
} else {
child_style.size.height.is_auto()
};
if main_is_auto {
let lp_margin = |value: crate::layout::LengthPercentageAuto| match value {
crate::layout::LengthPercentageAuto::Length(px) => px.max(0.0),
_ => 0.0,
};
let child_is_row = matches!(
child_style.flex_direction,
crate::layout::FlexDirection::Row
| crate::layout::FlexDirection::RowReverse
);
let available_main = if parent_is_row {
if !child_is_row {
let mut avail = match child_style.size.height {
crate::layout::Dimension::Length(h) => Some(h.max(0.0)),
crate::layout::Dimension::Percent(pct) => match inner_avail
.height
{
AvailableSpace::Definite(ph) => Some((ph * pct).max(0.0)),
_ => None,
},
crate::layout::Dimension::Auto => match inner_avail.height {
AvailableSpace::Definite(ph) => {
let margin_h = lp_margin(child_style.margin.top)
+ lp_margin(child_style.margin.bottom);
Some((ph - margin_h).max(0.0))
}
_ => None,
},
};
if let crate::layout::Dimension::Length(max_h) =
child_style.max_size.height
{
avail = Some(
avail.map_or(max_h.max(0.0), |v| v.min(max_h.max(0.0))),
);
}
if let crate::layout::Dimension::Length(min_h) =
child_style.min_size.height
{
avail = Some(
avail.map_or(min_h.max(0.0), |v| v.max(min_h.max(0.0))),
);
}
avail
} else {
match child_style.size.width {
crate::layout::Dimension::Length(w) => Some(w.max(0.0)),
_ => None,
}
}
} else if child_is_row {
let mut avail = match child_style.size.width {
crate::layout::Dimension::Length(w) => Some(w.max(0.0)),
crate::layout::Dimension::Percent(pct) => match inner_avail.width {
AvailableSpace::Definite(pw) => Some((pw * pct).max(0.0)),
_ => None,
},
crate::layout::Dimension::Auto => match inner_avail.width {
AvailableSpace::Definite(pw) => {
let margin_w = lp_margin(child_style.margin.left)
+ lp_margin(child_style.margin.right);
Some((pw - margin_w).max(0.0))
}
_ => None,
},
};
if let crate::layout::Dimension::Length(max_w) =
child_style.max_size.width
{
avail =
Some(avail.map_or(max_w.max(0.0), |v| v.min(max_w.max(0.0))));
}
if let crate::layout::Dimension::Length(min_w) =
child_style.min_size.width
{
avail =
Some(avail.map_or(min_w.max(0.0), |v| v.max(min_w.max(0.0))));
}
avail
} else {
match child_style.size.height {
crate::layout::Dimension::Length(h) => Some(h.max(0.0)),
_ => None,
}
};
let extent = self.intrinsic_extent(
child_id,
parent_is_row,
available_main,
measure_fn,
depth + 1,
)?;
if extent > 0.0 {
measured_size = Some(if parent_is_row {
Size::new(extent, 0.0)
} else {
Size::new(0.0, extent)
});
}
}
}
if child_is_leaf
&& (child_style.size.width.is_auto() || child_style.size.height.is_auto())
{
let known = Size::new(
crate::layout::box_sizing::resolve_dimension(
child_style.size.width,
inner_avail.width,
),
crate::layout::box_sizing::resolve_dimension(
child_style.size.height,
inner_avail.height,
),
);
if let Some(measured) = measure_fn(child_id, known, inner_avail) {
measured_size = Some(measured);
}
}
let child_box = crate::layout::box_sizing::compute_box_sizing(
&child_style,
inner_avail,
measured_size,
)?;
let hypo_w = child_box.border_box().width;
let hypo_h = child_box.border_box().height;
child_info.push((child_id, child_style, Size::new(hypo_w, hypo_h)));
}
let content_origin = Point::new(
origin.x + box_dims.padding.left,
origin.y + box_dims.padding.top,
);
let constraints =
crate::layout::box_sizing::resolve_box_constraints(&style, available_space);
let keep_box_w = !auto_w
|| (style.aspect_ratio.is_some() && !auto_h && box_dims.content.width > 0.0);
let inner_content_w = if keep_box_w {
box_dims.content.width
} else {
match available_space.width {
AvailableSpace::Definite(w) => {
let clamped = crate::layout::box_sizing::BoxConstraints::clamp_dimension(
w,
constraints.min_size.width,
constraints.max_size.width,
);
(clamped - box_dims.padding.left - box_dims.padding.right).max(0.0)
}
_ => box_dims.content.width,
}
};
let keep_box_h = !auto_h
|| (style.aspect_ratio.is_some() && !auto_w && box_dims.content.height > 0.0);
let inner_content_h = if keep_box_h {
box_dims.content.height
} else {
match available_space.height {
AvailableSpace::Definite(h) => {
let clamped = crate::layout::box_sizing::BoxConstraints::clamp_dimension(
h,
constraints.min_size.height,
constraints.max_size.height,
);
(clamped - box_dims.padding.top - box_dims.padding.bottom).max(0.0)
}
_ => box_dims.content.height,
}
};
let inner_content_size = Size::new(inner_content_w, inner_content_h);
let flex_placements = {
let n = self.node(node_id)?;
if display == Display::Grid {
crate::layout::grid::compute_grid(
&n.style,
inner_content_size,
inner_avail,
&child_info,
content_origin,
)?
} else {
crate::layout::flex::compute_flex(
&n.style,
inner_content_size,
inner_avail,
&child_info,
content_origin,
)?
}
};
let mut max_x = content_origin.x;
let mut max_y = content_origin.y;
for (child_id, placed_rect) in flex_placements {
let (child_position, child_inset, child_display, is_child_leaf) = {
let child_node = self.node(child_id)?;
(
child_node.style.position,
child_node.style.inset,
child_node.style.display,
child_node.children.is_empty(),
)
};
let mut solved_rect = if is_child_leaf {
placed_rect
} else {
let child_avail = Size::new(
AvailableSpace::Definite(placed_rect.width),
AvailableSpace::Definite(placed_rect.height),
);
let mut r = self.solve_node_depth(
child_id,
Point::new(placed_rect.x, placed_rect.y),
child_avail,
measure_fn,
depth + 1,
)?;
r.width = placed_rect.width;
r.height = placed_rect.height;
r
};
if child_position == Position::Relative {
let inset = crate::layout::box_sizing::resolve_inset(&child_inset, inner_avail);
let new_loc = crate::layout::box_sizing::apply_relative_offset(
Point::new(solved_rect.x, solved_rect.y),
&inset,
);
solved_rect.x = new_loc.x;
solved_rect.y = new_loc.y;
}
if child_display != Display::None {
max_x = max_x.max(solved_rect.x + solved_rect.width);
max_y = max_y.max(solved_rect.y + solved_rect.height);
}
let c_slot = self.slots[child_id.index].node.as_mut().unwrap();
c_slot.layout = solved_rect;
c_slot.unrounded_layout = solved_rect;
c_slot.dirty = false;
}
if auto_w {
let content_extent =
(max_x - origin.x + box_dims.padding.right).max(resolved_width);
resolved_width = match available_space.width {
AvailableSpace::Definite(w)
if in_flow_children.iter().any(|&c| {
self.node(c)
.map(|n| n.style.flex_grow > 0.0)
.unwrap_or(false)
}) =>
{
w
}
_ => content_extent,
};
}
if auto_h {
let content_extent =
(max_y - origin.y + box_dims.padding.bottom).max(resolved_height);
resolved_height = match available_space.height {
AvailableSpace::Definite(h) => h,
_ => content_extent,
};
}
let constraints = {
let n = self.node(node_id)?;
crate::layout::box_sizing::resolve_box_constraints(&n.style, available_space)
};
resolved_width = crate::layout::box_sizing::BoxConstraints::clamp_dimension(
resolved_width,
constraints.min_size.width,
constraints.max_size.width,
);
resolved_height = crate::layout::box_sizing::BoxConstraints::clamp_dimension(
resolved_height,
constraints.min_size.height,
constraints.max_size.height,
);
let final_content_w =
(resolved_width - box_dims.padding.left - box_dims.padding.right).max(0.0);
let final_content_h =
(resolved_height - box_dims.padding.top - box_dims.padding.bottom).max(0.0);
let parent_padding_origin = Point::new(
origin.x + box_dims.padding.left,
origin.y + box_dims.padding.top,
);
let parent_padding_size = Size::new(final_content_w, final_content_h);
for child_id in out_of_flow_children {
let child_rect = self.solve_node_depth(
child_id,
parent_padding_origin,
Size::new(
AvailableSpace::Definite(final_content_w),
AvailableSpace::Definite(final_content_h),
),
measure_fn,
depth + 1,
)?;
let child_node = self.node(child_id)?;
let child_margin = crate::layout::box_sizing::resolve_margin(
&child_node.style.margin,
inner_avail,
);
let inset =
crate::layout::box_sizing::resolve_inset(&child_node.style.inset, inner_avail);
let abs_pos = crate::layout::box_sizing::resolve_absolute_position(
parent_padding_origin,
parent_padding_size,
Size::new(child_rect.width, child_rect.height),
&inset,
&child_margin,
);
let final_abs_rect =
LayoutRect::new(abs_pos.x, abs_pos.y, child_rect.width, child_rect.height);
let c_slot = self.slots[child_id.index].node.as_mut().unwrap();
c_slot.layout = final_abs_rect;
c_slot.unrounded_layout = final_abs_rect;
}
}
let rect = LayoutRect::new(origin.x, origin.y, resolved_width, resolved_height);
let n = self.slots[node_id.index].node.as_mut().unwrap();
n.layout = rect;
n.unrounded_layout = rect;
n.dirty = false;
Ok(rect)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::layout::{AvailableSpace, Dimension, LengthPercentage, LengthPercentageAuto, Rect};
#[test]
fn test_solve_node_depth_geometry_regression() {
let mut tree = LayoutTree::new();
let root_style = Style {
size: Size::new(Dimension::Length(300.0), Dimension::Length(200.0)),
padding: Rect::all(LengthPercentage::Length(10.0)),
..Style::default()
};
let root = tree.create_node(root_style);
let c1_style = Style {
size: Size::new(Dimension::Length(80.0), Dimension::Length(50.0)),
..Style::default()
};
let c1 = tree.create_node(c1_style);
tree.attach_child(root, c1).unwrap();
let c2_style = Style {
size: Size::new(Dimension::Length(100.0), Dimension::Length(60.0)),
position: Position::Relative,
inset: Rect {
left: LengthPercentageAuto::Length(5.0),
top: LengthPercentageAuto::Length(5.0),
..Rect::auto()
},
..Style::default()
};
let c2 = tree.create_node(c2_style);
tree.attach_child(root, c2).unwrap();
let space = Size::new(
AvailableSpace::Definite(300.0),
AvailableSpace::Definite(200.0),
);
let rect = tree
.compute_layout(root, space)
.expect("layout computation succeeded");
assert_eq!(rect, LayoutRect::new(0.0, 0.0, 300.0, 200.0));
let l1 = tree.layout(c1).unwrap();
assert_eq!(l1, LayoutRect::new(10.0, 10.0, 80.0, 50.0));
let l2 = tree.layout(c2).unwrap();
assert_eq!(l2, LayoutRect::new(95.0, 15.0, 100.0, 60.0));
}
#[test]
fn test_cache_retention_only_roots_and_pruning() {
let mut tree = LayoutTree::new();
let root = tree.create_node(Style::default());
let c1 = tree.create_node(Style::default());
let c2 = tree.create_node(Style::default());
tree.attach_child(root, c1).unwrap();
tree.attach_child(root, c2).unwrap();
let leaf1 = tree.create_node(Style::default());
let leaf2 = tree.create_node(Style::default());
tree.attach_child(c1, leaf1).unwrap();
tree.attach_child(c2, leaf2).unwrap();
let space = Size::new(
AvailableSpace::Definite(500.0),
AvailableSpace::Definite(400.0),
);
let _ = tree.compute_layout(root, space).unwrap();
assert_eq!(
tree.cache.len(),
1,
"cache should hold only the root container entry"
);
let cached_key = tree.cache.keys().next().unwrap();
assert_eq!(cached_key.node_id, root);
tree.remove_node(c1).unwrap();
assert_eq!(tree.cache.len(), 1);
tree.remove_node(root).unwrap();
assert_eq!(tree.cache.len(), 0, "removing root must prune the cache");
}
#[test]
fn auto_container_with_min_size_distributes_grown_definite_space() {
let mut tree = LayoutTree::new();
let root = tree.create_node(Style {
flex_direction: crate::layout::FlexDirection::Row,
..Style::default()
});
let sidebar = tree.create_node(Style {
size: Size::new(Dimension::Length(220.0), Dimension::Auto),
..Style::default()
});
let split = tree.create_node(Style {
flex_direction: crate::layout::FlexDirection::Row,
flex_grow: 1.0,
min_size: Size::new(Dimension::Length(640.0), Dimension::Length(0.0)),
..Style::default()
});
let left_pane = tree.create_node(Style {
flex_grow: 0.72,
min_size: Size::new(Dimension::Length(456.0), Dimension::Length(0.0)),
..Style::default()
});
let right_pane = tree.create_node(Style {
flex_grow: 0.28,
min_size: Size::new(Dimension::Length(260.0), Dimension::Length(0.0)),
..Style::default()
});
tree.attach_child(root, sidebar).unwrap();
tree.attach_child(root, split).unwrap();
tree.attach_child(split, left_pane).unwrap();
tree.attach_child(split, right_pane).unwrap();
let rect = tree
.compute_layout(
root,
Size::new(
AvailableSpace::Definite(1080.0),
AvailableSpace::Definite(700.0),
),
)
.expect("layout succeeds");
assert_eq!(rect.width, 1080.0);
let split_rect = tree.layout(split).unwrap();
let left_rect = tree.layout(left_pane).unwrap();
let right_rect = tree.layout(right_pane).unwrap();
assert_eq!(split_rect.width, 860.0);
assert!(
(left_rect.width + right_rect.width - 860.0).abs() < 0.5,
"children must consume grown split width 860, got {} + {}",
left_rect.width,
right_rect.width
);
assert!(left_rect.width >= 456.0);
assert!(right_rect.width >= 260.0);
}
}