use crate::error::{GuiError, GuiResult};
use crate::layout::box_sizing::{resolve_dimension, BoxConstraints};
use crate::layout::{
AlignItems, AlignSelf, AvailableSpace, Dimension, GridAutoFlow, LayoutNodeId, LayoutRect,
Point, Size, Style, TrackSizingFunction,
};
#[derive(Debug, Clone, Copy, PartialEq)]
enum Track {
Fixed(f32),
Flex {
floor: f32,
weight: f32,
},
}
#[derive(Debug, Clone, Copy)]
struct ActiveChild {
idx: usize,
hypo: Size<f32>,
}
#[derive(Debug, Clone, Copy)]
struct PlacedItem {
active_idx: usize,
row_start: usize,
row_span: usize,
col_start: usize,
col_span: usize,
}
pub fn compute_grid(
container_style: &Style,
container_inner: Size<f32>,
available_space: Size<AvailableSpace>,
children: &[(LayoutNodeId, Style, Size<f32>)],
content_origin: Point<f32>,
) -> GuiResult<Vec<(LayoutNodeId, LayoutRect)>> {
if children.is_empty() {
return Ok(Vec::new());
}
let mut hidden: Vec<usize> = Vec::new();
let mut active: Vec<ActiveChild> = Vec::with_capacity(children.len());
for (idx, (_id, style, hypo)) in children.iter().enumerate() {
if style.display == crate::layout::Display::None {
hidden.push(idx);
} else {
active.push(ActiveChild { idx, hypo: *hypo });
}
}
let gap_col = resolve_gap(container_style, true, available_space.width)?;
let gap_row = resolve_gap(container_style, false, available_space.height)?;
let mut placements: Vec<PlacedItem> = Vec::with_capacity(active.len());
let (total_rows, total_cols) = place_items(&active, children, container_style, &mut placements);
let col_sizes = size_axis_tracks(
total_cols,
&container_style.grid_template_columns,
&container_style.grid_auto_columns,
&placements,
&active,
true,
container_inner.width,
gap_col,
)?;
let row_sizes = size_axis_tracks(
total_rows,
&container_style.grid_template_rows,
&container_style.grid_auto_rows,
&placements,
&active,
false,
container_inner.height,
gap_row,
)?;
let col_pos = line_positions(&col_sizes, gap_col);
let row_pos = line_positions(&row_sizes, gap_row);
let mut hidden_set = std::collections::HashSet::new();
for &idx in &hidden {
hidden_set.insert(idx);
}
let mut active_by_child_idx: std::collections::HashMap<usize, usize> =
std::collections::HashMap::new();
for (active_idx, ac) in active.iter().enumerate() {
active_by_child_idx.insert(ac.idx, active_idx);
}
let mut out: Vec<(LayoutNodeId, LayoutRect)> = Vec::with_capacity(children.len());
for (idx, (id, _, _)) in children.iter().enumerate() {
if hidden_set.contains(&idx) {
out.push((
*id,
LayoutRect::new(content_origin.x, content_origin.y, 0.0, 0.0),
));
continue;
}
let active_idx = active_by_child_idx[&idx];
let p = placements[active_idx];
let ac = active[active_idx];
let style = &children[idx].1;
let area_w = area_size(&col_sizes, p.col_start, p.col_span, gap_col);
let area_h = area_size(&row_sizes, p.row_start, p.row_span, gap_row);
let area_x = col_pos[p.col_start];
let area_y = row_pos[p.row_start];
let item_w = resolve_item_size(
&style.size.width,
&style.min_size.width,
&style.max_size.width,
area_w,
ac.hypo.width,
);
let item_h = resolve_item_size(
&style.size.height,
&style.min_size.height,
&style.max_size.height,
area_h,
ac.hypo.height,
);
let justify = effective_align(style.justify_self, container_style.justify_items);
let align = effective_align(style.align_self, container_style.align_items);
let x = content_origin.x + area_x + align_offset(item_w, area_w, justify);
let y = content_origin.y + area_y + align_offset(item_h, area_h, align);
out.push((*id, LayoutRect::new(x, y, item_w, item_h)));
}
Ok(out)
}
fn resolve_gap(
container_style: &Style,
horizontal: bool,
available: AvailableSpace,
) -> GuiResult<f32> {
let gap = if horizontal {
container_style.gap.width
} else {
container_style.gap.height
};
match gap {
crate::layout::LengthPercentage::Length(px) => {
if !px.is_finite() {
return Err(GuiError::InvalidNumericInput);
}
Ok(px.max(0.0))
}
crate::layout::LengthPercentage::Percent(p) => {
if !p.is_finite() {
return Err(GuiError::InvalidNumericInput);
}
match available {
AvailableSpace::Definite(base) => Ok((base * p).max(0.0)),
_ => Ok(0.0),
}
}
}
}
fn place_items(
active: &[ActiveChild],
children: &[(LayoutNodeId, Style, Size<f32>)],
container_style: &Style,
placements: &mut Vec<PlacedItem>,
) -> (usize, usize) {
let row_capacity = container_style.grid_template_rows.len();
let col_capacity = container_style.grid_template_columns.len();
let mut next_row = 0usize;
let mut next_col = 0usize;
let flow = container_style.grid_auto_flow;
for (active_idx, ac) in active.iter().enumerate() {
let style = &children[ac.idx].1;
let row_span = (style.grid_row.span.max(1) as usize).max(1);
let col_span = (style.grid_column.span.max(1) as usize).max(1);
let explicit_row = if style.grid_row.start > 0 {
Some((style.grid_row.start as usize) - 1)
} else {
None
};
let explicit_col = if style.grid_column.start > 0 {
Some((style.grid_column.start as usize) - 1)
} else {
None
};
let (row_start, col_start) = match (explicit_row, explicit_col) {
(Some(r), Some(c)) => (r, c),
(Some(r), None) => (r, next_col),
(None, Some(c)) => (next_row, c),
(None, None) => {
if flow == GridAutoFlow::Column {
let r = next_row;
let c = next_col;
next_row += row_span;
if row_capacity > 0 && next_row >= row_capacity {
next_row = 0;
next_col += col_span;
}
(r, c)
} else {
let r = next_row;
let c = next_col;
next_col += col_span;
if col_capacity > 0 && next_col >= col_capacity {
next_col = 0;
next_row += row_span;
}
(r, c)
}
}
};
placements.push(PlacedItem {
active_idx,
row_start,
row_span,
col_start,
col_span,
});
}
let mut total_rows = row_capacity.max(1);
let mut total_cols = col_capacity.max(1);
for p in placements {
total_rows = total_rows.max(p.row_start + p.row_span);
total_cols = total_cols.max(p.col_start + p.col_span);
}
(total_rows, total_cols)
}
fn resolve_definite(func: &TrackSizingFunction, base: f32, content: f32) -> GuiResult<f32> {
match func {
TrackSizingFunction::Fixed(px) => {
if !px.is_finite() {
return Err(GuiError::InvalidNumericInput);
}
Ok(px.max(0.0))
}
TrackSizingFunction::Percent(p) => {
if !p.is_finite() {
return Err(GuiError::InvalidNumericInput);
}
Ok((base * p).max(0.0))
}
TrackSizingFunction::Auto => Ok(content.max(0.0)),
TrackSizingFunction::Flex(_fr) => Ok(0.0),
TrackSizingFunction::MinMax(min, max) => {
let min_res = resolve_definite(min, base, content)?;
let max_res = resolve_definite(max, base, content)?;
Ok(min_res.max(max_res))
}
}
}
fn classify_track(func: &TrackSizingFunction, base: f32, content: f32) -> GuiResult<Track> {
match func {
TrackSizingFunction::Fixed(px) => {
if !px.is_finite() {
return Err(GuiError::InvalidNumericInput);
}
Ok(Track::Fixed(px.max(0.0)))
}
TrackSizingFunction::Percent(p) => {
if !p.is_finite() {
return Err(GuiError::InvalidNumericInput);
}
Ok(Track::Fixed((base * p).max(0.0)))
}
TrackSizingFunction::Auto => Ok(Track::Fixed(content.max(0.0))),
TrackSizingFunction::Flex(fr) => {
let fr = *fr;
if !fr.is_finite() || fr < 0.0 {
return Err(GuiError::InvalidNumericInput);
}
Ok(Track::Flex {
floor: 0.0,
weight: fr,
})
}
TrackSizingFunction::MinMax(min, max) => {
let min_res = resolve_definite(min, base, content)?;
if let TrackSizingFunction::Flex(fr) = **max {
if !fr.is_finite() || fr < 0.0 {
return Err(GuiError::InvalidNumericInput);
}
Ok(Track::Flex {
floor: min_res.max(content.max(0.0)),
weight: fr,
})
} else {
let max_res = resolve_definite(max, base, content)?;
Ok(Track::Fixed(min_res.max(max_res)))
}
}
}
}
#[allow(clippy::too_many_arguments)]
fn size_axis_tracks(
total: usize,
template: &[TrackSizingFunction],
auto: &[TrackSizingFunction],
placements: &[PlacedItem],
active: &[ActiveChild],
horizontal: bool,
base: f32,
gap: f32,
) -> GuiResult<Vec<f32>> {
if total == 0 {
return Ok(Vec::new());
}
let mut content = vec![0.0f32; total];
for p in placements {
let hypo = active[p.active_idx].hypo;
let (start, span, len) = if horizontal {
(p.col_start, p.col_span, hypo.width)
} else {
(p.row_start, p.row_span, hypo.height)
};
let end = (start + span).min(total);
if start < total {
for c in &mut content[start..end] {
*c = c.max(len);
}
}
}
let mut tracks = Vec::with_capacity(total);
for t in 0..total {
let func: &TrackSizingFunction = if t < template.len() {
&template[t]
} else {
auto.first().unwrap_or(&TrackSizingFunction::Auto)
};
tracks.push(classify_track(func, base, content[t])?);
}
let fixed_sum: f32 = tracks
.iter()
.map(|t| match t {
Track::Fixed(x) => *x,
Track::Flex { floor, .. } => *floor,
})
.sum();
let gap_sum = (total.saturating_sub(1) as f32) * gap;
let free = base - fixed_sum - gap_sum;
let floor_sum: f32 = tracks
.iter()
.map(|t| match t {
Track::Flex { floor, .. } => *floor,
Track::Fixed(_) => 0.0,
})
.sum();
let distributable = (free - floor_sum).max(0.0);
let total_weight: f32 = tracks
.iter()
.map(|t| match t {
Track::Flex { weight, .. } => *weight,
Track::Fixed(_) => 0.0,
})
.sum();
let mut sizes = Vec::with_capacity(total);
for t in tracks {
match t {
Track::Fixed(x) => sizes.push(x),
Track::Flex { floor, weight } => {
let share = if total_weight > 0.0 {
distributable * (weight / total_weight)
} else {
0.0
};
sizes.push((floor + share).max(0.0));
}
}
}
Ok(sizes)
}
fn line_positions(sizes: &[f32], gap: f32) -> Vec<f32> {
let mut pos = Vec::with_capacity(sizes.len());
let mut cursor = 0.0f32;
for (i, &s) in sizes.iter().enumerate() {
if i > 0 {
cursor += gap;
}
pos.push(cursor);
cursor += s;
}
pos
}
fn area_size(sizes: &[f32], start: usize, span: usize, gap: f32) -> f32 {
let end = (start + span).min(sizes.len());
if end <= start {
return 0.0;
}
let total: f32 = sizes[start..end].iter().sum();
total + (span.saturating_sub(1) as f32) * gap
}
fn resolve_item_size(
dim: &Dimension,
min_dim: &Dimension,
max_dim: &Dimension,
area_base: f32,
hypo: f32,
) -> f32 {
let base_space = AvailableSpace::Definite(area_base.max(0.0));
let requested = resolve_dimension(*dim, base_space).unwrap_or(hypo.max(0.0));
let min_val = resolve_dimension(*min_dim, base_space);
let max_val = resolve_dimension(*max_dim, base_space);
BoxConstraints::clamp_dimension(requested.max(0.0), min_val, max_val)
}
fn effective_align(
item_align: Option<AlignSelf>,
container_align: Option<AlignItems>,
) -> AlignItems {
if let Some(a) = item_align {
return to_align_items(a);
}
container_align.unwrap_or(AlignItems::Start)
}
fn to_align_items(align: AlignSelf) -> AlignItems {
match align {
AlignSelf::Start => AlignItems::Start,
AlignSelf::End => AlignItems::End,
AlignSelf::Center => AlignItems::Center,
AlignSelf::Baseline | AlignSelf::Stretch => AlignItems::Start,
}
}
fn align_offset(item_size: f32, area_size: f32, align: AlignItems) -> f32 {
match align {
AlignItems::Start => 0.0,
AlignItems::End => (area_size - item_size).max(0.0),
AlignItems::Center => ((area_size - item_size) * 0.5).max(0.0),
AlignItems::Baseline | AlignItems::Stretch => 0.0,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn leaf(size: Size<f32>, style: Option<Style>) -> (LayoutNodeId, Style, Size<f32>) {
let style = style.unwrap_or_else(|| Style {
size: Size::new(
Dimension::Length(size.width),
Dimension::Length(size.height),
),
..Default::default()
});
(LayoutNodeId::new(0, 0), style, size)
}
fn grid_style(cols: Vec<TrackSizingFunction>, rows: Vec<TrackSizingFunction>) -> Style {
Style {
display: crate::layout::Display::Grid,
grid_template_columns: cols,
grid_template_rows: rows,
..Default::default()
}
}
fn run(
style: &Style,
inner: Size<f32>,
children: &[(LayoutNodeId, Style, Size<f32>)],
) -> Vec<LayoutRect> {
compute_grid(
style,
inner,
Size::new(
AvailableSpace::Definite(inner.width),
AvailableSpace::Definite(inner.height),
),
children,
Point::new(0.0, 0.0),
)
.unwrap()
.into_iter()
.map(|(_, r)| r)
.collect()
}
fn approx(a: f32, b: f32) -> bool {
(a - b).abs() <= crate::layout::STRICT_TOLERANCE_PX
}
#[test]
fn grd_001_fixed_tracks() {
let style = grid_style(
vec![
TrackSizingFunction::Fixed(100.0),
TrackSizingFunction::Fixed(150.0),
TrackSizingFunction::Fixed(50.0),
],
vec![],
);
let children = vec![
leaf(Size::new(100.0, 40.0), None),
leaf(Size::new(150.0, 40.0), None),
leaf(Size::new(50.0, 40.0), None),
];
let rects = run(&style, Size::new(300.0, 100.0), &children);
assert!(
approx(rects[0].x, 0.0)
&& approx(rects[0].width, 100.0)
&& approx(rects[0].height, 40.0)
);
assert!(approx(rects[1].x, 100.0) && approx(rects[1].width, 150.0));
assert!(approx(rects[2].x, 250.0) && approx(rects[2].width, 50.0));
}
#[test]
fn grd_002_fractional_tracks() {
let style = grid_style(
vec![
TrackSizingFunction::Flex(1.0),
TrackSizingFunction::Flex(2.0),
],
vec![],
);
let children = vec![
leaf(Size::new(100.0, 40.0), None),
leaf(Size::new(100.0, 40.0), None),
];
let rects = run(&style, Size::new(300.0, 100.0), &children);
assert!(approx(rects[0].x, 0.0) && approx(rects[0].width, 100.0));
assert!(approx(rects[1].x, 100.0) && approx(rects[1].width, 100.0));
}
#[test]
fn grd_003_auto_track_content() {
let style = grid_style(vec![TrackSizingFunction::Auto], vec![]);
let children = vec![leaf(Size::new(140.0, 40.0), None)];
let rects = run(&style, Size::new(300.0, 100.0), &children);
assert!(approx(rects[0].x, 0.0) && approx(rects[0].width, 140.0));
}
#[test]
fn grd_004_minmax_track() {
let style = grid_style(
vec![TrackSizingFunction::MinMax(
Box::new(TrackSizingFunction::Fixed(50.0)),
Box::new(TrackSizingFunction::Flex(1.0)),
)],
vec![],
);
let children = vec![leaf(Size::new(20.0, 20.0), None)];
let rects = run(&style, Size::new(100.0, 50.0), &children);
assert!(rects[0].width >= 20.0);
}
#[test]
fn grd_005_multi_column_span() {
let style = grid_style(
vec![
TrackSizingFunction::Fixed(100.0),
TrackSizingFunction::Fixed(100.0),
],
vec![],
);
let item = Style {
grid_column: crate::layout::GridPlacement::new(0, 2),
size: Size::new(Dimension::Percent(1.0), Dimension::Length(40.0)),
..Default::default()
};
let children = vec![(LayoutNodeId::new(0, 0), item, Size::new(200.0, 40.0))];
let rects = run(&style, Size::new(200.0, 100.0), &children);
assert!(
approx(rects[0].x, 0.0)
&& approx(rects[0].width, 200.0)
&& approx(rects[0].height, 40.0)
);
}
#[test]
fn grd_006_explicit_cell_placement() {
let style = grid_style(
vec![
TrackSizingFunction::Fixed(100.0),
TrackSizingFunction::Fixed(100.0),
TrackSizingFunction::Fixed(100.0),
],
vec![
TrackSizingFunction::Fixed(50.0),
TrackSizingFunction::Fixed(50.0),
],
);
let item = Style {
grid_row: crate::layout::GridPlacement::new(2, 1),
grid_column: crate::layout::GridPlacement::new(3, 1),
size: Size::new(Dimension::Length(100.0), Dimension::Length(50.0)),
..Default::default()
};
let children = vec![(LayoutNodeId::new(0, 0), item, Size::new(100.0, 50.0))];
let rects = run(&style, Size::new(300.0, 100.0), &children);
assert!(
approx(rects[0].x, 200.0) && approx(rects[0].y, 50.0) && approx(rects[0].width, 100.0)
);
}
#[test]
fn grd_007_grid_gaps() {
let style = grid_style(
vec![
TrackSizingFunction::Fixed(100.0),
TrackSizingFunction::Fixed(100.0),
],
vec![],
);
let style = Style {
gap: Size::new(
crate::layout::LengthPercentage::Length(10.0),
crate::layout::LengthPercentage::Length(10.0),
),
..style
};
let children = vec![
leaf(Size::new(100.0, 50.0), None),
leaf(Size::new(100.0, 50.0), None),
];
let rects = run(&style, Size::new(300.0, 100.0), &children);
assert!(approx(rects[0].x, 0.0) && approx(rects[0].width, 100.0));
assert!(approx(rects[1].x, 110.0) && approx(rects[1].width, 100.0));
}
#[test]
fn grd_008_nested_container_in_cell() {
let style = grid_style(vec![TrackSizingFunction::Fixed(150.0)], vec![]);
let child = Style {
size: Size::new(Dimension::Length(100.0), Dimension::Length(50.0)),
..Default::default()
};
let children = vec![(LayoutNodeId::new(0, 0), child, Size::new(100.0, 50.0))];
let rects = run(&style, Size::new(200.0, 100.0), &children);
assert!(
approx(rects[0].x, 0.0)
&& approx(rects[0].width, 100.0)
&& approx(rects[0].height, 50.0)
);
}
#[test]
fn grid_hidden_child_collapses() {
let style = grid_style(
vec![
TrackSizingFunction::Fixed(100.0),
TrackSizingFunction::Fixed(100.0),
],
vec![],
);
let hidden = Style {
display: crate::layout::Display::None,
size: Size::new(Dimension::Length(80.0), Dimension::Length(80.0)),
..Default::default()
};
let children = vec![
leaf(Size::new(100.0, 40.0), None),
(LayoutNodeId::new(1, 0), hidden, Size::new(80.0, 80.0)),
leaf(Size::new(100.0, 40.0), None),
];
let rects = run(&style, Size::new(200.0, 100.0), &children);
assert!(approx(rects[1].width, 0.0) && approx(rects[1].height, 0.0));
assert!(approx(rects[0].x, 0.0) && approx(rects[0].width, 100.0));
}
#[test]
fn grid_column_flow_placement() {
let mut style = grid_style(
vec![TrackSizingFunction::Fixed(100.0)],
vec![
TrackSizingFunction::Fixed(50.0),
TrackSizingFunction::Fixed(50.0),
],
);
style.grid_auto_flow = GridAutoFlow::Column;
let children = vec![
leaf(Size::new(100.0, 50.0), None),
leaf(Size::new(100.0, 50.0), None),
leaf(Size::new(100.0, 50.0), None),
];
let rects = run(&style, Size::new(100.0, 100.0), &children);
assert!(approx(rects[0].x, 0.0) && approx(rects[0].y, 0.0));
assert!(approx(rects[1].x, 0.0) && approx(rects[1].y, 50.0));
assert!(approx(rects[2].x, 100.0) && approx(rects[2].y, 0.0));
}
#[test]
fn grid_percent_item_size_uses_area() {
let style = grid_style(
vec![
TrackSizingFunction::Fixed(60.0),
TrackSizingFunction::Fixed(40.0),
],
vec![TrackSizingFunction::Fixed(100.0)],
);
let item = Style {
grid_column: crate::layout::GridPlacement::new(0, 2),
size: Size::new(Dimension::Percent(0.5), Dimension::Length(100.0)),
..Default::default()
};
let children = vec![(LayoutNodeId::new(0, 0), item, Size::new(100.0, 100.0))];
let rects = run(&style, Size::new(100.0, 100.0), &children);
assert!(approx(rects[0].width, 50.0) && approx(rects[0].height, 100.0));
}
}