use crate::{
Align, BlockStyle, BlockTitle, Canvas, GridStyle, Key, Length, Overflow, Sides, StyledText,
TextStyle, VerticalAlign, View, Viewport,
};
use super::geometry::Constraint;
use super::grid;
use super::sizing::{
Claim, Kind, border_extent, degrade, distribute_constraints, horizontal, kind_of, vertical,
width_axis,
};
static WRAP: Overflow = Overflow::Wrap;
#[derive(Debug)]
pub(super) struct Metrics {
natural: usize,
floor: usize,
height_floor: usize,
fills: bool,
width_projection: bool,
height_projection: bool,
width_kind: Kind,
height_kind: Kind,
children: Vec<Metrics>,
}
fn metrics(view: &View) -> Metrics {
match view {
View::Text(text) => {
let lines = text.lines();
Metrics {
natural: lines
.iter()
.map(|line| line.iter().map(|grapheme| grapheme.width()).sum())
.max()
.unwrap_or(0),
floor: lines
.iter()
.flat_map(|line| line.iter().map(|grapheme| grapheme.width()))
.max()
.unwrap_or(0),
height_floor: 0,
fills: false,
width_projection: false,
height_projection: false,
width_kind: Kind::Auto,
height_kind: Kind::Auto,
children: Vec::new(),
}
}
View::Canvas(canvas) => {
let width = canvas.width_requirements();
let kind = if canvas.uses_viewport_sizing() {
Kind::fill(1)
} else {
Kind::Auto
};
Metrics {
natural: width.demand(),
floor: width.floor(),
height_floor: 0,
fills: canvas.uses_viewport_sizing(),
width_projection: false,
height_projection: false,
width_kind: kind,
height_kind: kind,
children: Vec::new(),
}
}
View::Block(style, title, child) | View::AnchorBlock(_, style, title, child) => {
let inner = metrics(child);
let frame = style.frame_size();
let margin = style.get_margin();
let intrinsic = inner
.natural
.max(title_width(style, title.as_ref()).saturating_sub(frame.width()));
let natural = width_axis(style, frame.width()).used(
Constraint::unbounded(),
intrinsic,
inner.floor,
) + horizontal(margin);
let floor = style
.get_min_width()
.map_or(0, usize::from)
.max(frame.width() + inner.floor)
+ horizontal(margin);
let height_floor = style
.get_min_height()
.map_or(0, usize::from)
.max(frame.height() + inner.height_floor)
+ vertical(margin);
let fills = match style.get_width() {
Some(Length::Fill(_)) => true,
Some(Length::Cells(_)) => false,
None => inner.fills,
};
let width_projection = match (style.get_width(), style.get_max_width()) {
(None, None) => inner.width_projection,
_ => false,
};
let height_projection = match (style.get_height(), style.get_max_height()) {
(None, None) => inner.height_projection,
_ => false,
};
Metrics {
natural,
floor,
height_floor,
fills,
width_projection,
height_projection,
width_kind: dependent_kind(style.get_width(), width_projection),
height_kind: dependent_kind(style.get_height(), height_projection),
children: vec![inner],
}
}
View::Row(_, children) => {
let children: Vec<Metrics> = children.iter().map(metrics).collect();
let fills = children.iter().any(|child| child.fills);
let width_projection = children.iter().any(|child| child.width_projection);
let height_projection = children.iter().any(|child| child.height_projection);
Metrics {
natural: children.iter().map(|child| child.natural).sum(),
floor: children.iter().map(|child| child.floor).sum(),
height_floor: children
.iter()
.map(|child| child.height_floor)
.max()
.unwrap_or(0),
fills,
width_projection,
height_projection,
width_kind: dependent_kind(None, width_projection),
height_kind: dependent_kind(None, height_projection),
children,
}
}
View::Column(_, children) => {
let children: Vec<Metrics> = children.iter().map(metrics).collect();
let fills = children.iter().any(|child| child.fills);
let width_projection = children.iter().any(|child| child.width_projection);
let height_projection = children.iter().any(|child| child.height_projection);
Metrics {
natural: children
.iter()
.map(|child| child.natural)
.max()
.unwrap_or(0),
floor: children.iter().map(|child| child.floor).max().unwrap_or(0),
height_floor: children.iter().map(|child| child.height_floor).sum(),
fills,
width_projection,
height_projection,
width_kind: dependent_kind(None, width_projection),
height_kind: dependent_kind(None, height_projection),
children,
}
}
View::Grid(style, rows) => {
let columns = grid::columns(rows);
let mut cells = Vec::with_capacity(rows.len() * columns);
for row in 0..rows.len() {
for column in 0..columns {
cells.push(metrics(grid::cell(rows, row, column)));
}
}
let claims = column_claims(style, rows, &cells, columns);
let fills = cells.iter().any(|cell| cell.fills)
|| (0..columns)
.any(|column| matches!(style.get_column(column), Some(Length::Fill(_))));
let width_projection = (0..columns).any(|column| {
style.get_column(column).is_none()
&& (0..rows.len()).any(|row| cells[row * columns + column].width_projection)
});
let height_projection = cells.iter().any(|cell| cell.height_projection);
Metrics {
natural: claims.iter().map(|claim| claim.demand).sum(),
floor: claims.iter().map(|claim| claim.floor).sum(),
height_floor: (0..rows.len())
.map(|row| row_floor(style, rows, &cells, columns, row))
.sum(),
fills,
width_projection,
height_projection,
width_kind: dependent_kind(None, width_projection),
height_kind: dependent_kind(None, height_projection),
children: cells,
}
}
View::Viewport(viewport, child) => {
let inner = metrics(child);
let horizontal = viewport.horizontal_projection().is_some();
let vertical = viewport.vertical_projection().is_some();
let fills = horizontal || inner.fills;
let width_projection = horizontal || inner.width_projection;
let height_projection = vertical || inner.height_projection;
Metrics {
natural: inner.natural,
floor: if horizontal { 0 } else { inner.floor },
height_floor: if vertical { 0 } else { inner.height_floor },
fills,
width_projection,
height_projection,
width_kind: dependent_kind(None, width_projection),
height_kind: dependent_kind(None, height_projection),
children: vec![inner],
}
}
}
}
fn dependent_kind(length: Option<Length>, depends_on_area: bool) -> Kind {
match length {
None if depends_on_area => Kind::fill(1),
_ => kind_of(length),
}
}
fn column_claims(
style: &GridStyle,
rows: &[Vec<View>],
cells: &[Metrics],
columns: usize,
) -> Vec<Claim> {
(0..columns)
.map(|column| {
let (mut demand, mut floor) = (0, 0);
for row in 0..rows.len() {
let padding = horizontal(grid::cell_padding(style, grid::cell(rows, row, column)));
let cell = &cells[row * columns + column];
demand = demand.max(cell.natural + padding);
floor = floor.max(cell.floor + padding);
}
let length = style.get_column(column);
let depends_on_area =
(0..rows.len()).any(|row| cells[row * columns + column].width_projection);
Claim {
kind: dependent_kind(length, depends_on_area),
demand: match length {
Some(Length::Cells(cells)) => usize::from(cells).max(floor),
_ => demand,
},
floor,
}
})
.collect()
}
fn row_floor(
style: &GridStyle,
rows: &[Vec<View>],
cells: &[Metrics],
columns: usize,
row: usize,
) -> usize {
(0..columns)
.map(|column| {
let padding = vertical(grid::cell_padding(style, grid::cell(rows, row, column)));
cells[row * columns + column].height_floor + padding
})
.max()
.unwrap_or(0)
}
#[derive(Debug)]
pub(super) struct Widths<'a> {
pub width: usize,
pub height_kind: Kind,
pub height_floor: usize,
pub height_projection: bool,
pub node: WidthNode<'a>,
}
#[derive(Debug)]
pub(super) enum WidthNode<'a> {
Text(TextBox<'a>),
Block(BlockBox<'a>),
Row(VerticalAlign, Vec<Widths<'a>>),
Column(Align, Vec<Widths<'a>>),
Grid(GridBox<'a>),
Canvas(&'a Canvas, bool, super::canvas::CanvasRequirements),
Viewport(&'a Viewport, bool, Box<Widths<'a>>),
}
#[derive(Debug)]
pub(super) struct GridBox<'a> {
pub columns: Vec<usize>,
pub rows: Vec<Vec<GridCell<'a>>>,
}
#[derive(Debug)]
pub(super) struct GridCell<'a> {
pub padding: Sides,
pub align: Align,
pub vertical_align: VerticalAlign,
pub child: Widths<'a>,
}
#[derive(Debug)]
pub(super) struct TextBox<'a> {
pub text: &'a StyledText,
pub area: Option<usize>,
pub overflow: &'a Overflow,
pub align: Align,
pub fill: TextStyle,
}
#[derive(Debug)]
pub(super) struct BlockBox<'a> {
pub style: &'a BlockStyle,
pub title: Option<&'a BlockTitle>,
pub anchor: Option<Key>,
pub padding: Sides,
pub margin: Sides,
pub content_width: usize,
pub child: Box<Widths<'a>>,
}
#[derive(Clone, Copy)]
struct TextFit<'a> {
align: Align,
fill: &'a TextStyle,
overflow: &'a Overflow,
}
pub(super) fn widths(view: &View, area: Option<usize>) -> Widths<'_> {
place(
view,
&metrics(view),
Constraint::available(area),
area.is_some(),
None,
)
}
fn place<'a>(
view: &'a View,
metrics: &Metrics,
constraint: Constraint,
bounded: bool,
fit: Option<TextFit<'a>>,
) -> Widths<'a> {
match view {
View::Text(text) => {
let (align, fill, overflow) = fit.map_or_else(
|| {
(
Align::Left,
text.uniform_style().cloned().unwrap_or_else(TextStyle::new),
&WRAP,
)
},
|fit| (fit.align, fit.fill.clone(), fit.overflow),
);
Widths {
width: text_width(constraint.cap, overflow, metrics),
height_kind: metrics.height_kind,
height_floor: metrics.height_floor,
height_projection: metrics.height_projection,
node: WidthNode::Text(TextBox {
text,
area: constraint.cap,
overflow,
align,
fill,
}),
}
}
View::Canvas(canvas) => {
let width = constraint
.reference
.map(|area| area.max(metrics.floor))
.unwrap_or(metrics.natural);
let height = canvas.height_requirements(width);
Widths {
width,
height_kind: metrics.height_kind,
height_floor: height.floor(),
height_projection: metrics.height_projection,
node: WidthNode::Canvas(canvas, bounded, height),
}
}
View::Block(style, title, child) | View::AnchorBlock(_, style, title, child) => {
let inner = &metrics.children[0];
let border = border_extent(style);
let mut padding = style.get_padding();
let mut margin = style.get_margin();
let across = degrade(
constraint.cap,
horizontal(margin),
border.width(),
horizontal(padding),
inner.floor,
);
if across.margin {
margin.left = 0;
margin.right = 0;
}
if across.padding {
padding.left = 0;
padding.right = 0;
}
let axis = width_axis(
style,
border.width() + usize::from(padding.left) + usize::from(padding.right),
);
let box_constraint = Constraint {
reference: constraint
.reference
.map(|area| area.saturating_sub(horizontal(margin))),
cap: constraint
.cap
.map(|area| area.saturating_sub(horizontal(margin))),
};
let title_intrinsic = title_width(style, title.as_ref()).saturating_sub(axis.frame);
let intrinsic = if inner.fills
&& let Some(area) = box_constraint.reference
{
area.saturating_sub(axis.frame)
} else {
inner.natural.max(title_intrinsic)
};
let used = axis.used(box_constraint, intrinsic, inner.floor);
let content_width = used - axis.frame;
let child_constraint = Constraint::established(content_width);
let local_bound = matches!(axis.length, Some(Length::Cells(_))) || axis.max.is_some();
let child = place(
child,
inner,
child_constraint,
bounded || local_bound,
Some(TextFit {
align: style.get_align(),
fill: style.text_style(),
overflow: style.get_overflow(),
}),
);
debug_assert!(
child.width <= content_width,
"a child never resolves wider than the box that assigned it: \
{} > {content_width}",
child.width
);
let height_floor = style
.get_min_height()
.map_or(0, usize::from)
.max(border.height() + vertical(padding) + child.height_floor)
+ vertical(margin);
Widths {
width: used + horizontal(margin),
height_kind: metrics.height_kind,
height_floor,
height_projection: metrics.height_projection,
node: WidthNode::Block(BlockBox {
style,
title: title.as_ref(),
anchor: match view {
View::AnchorBlock(key, _, _, _) => Some(*key),
_ => None,
},
padding,
margin,
content_width,
child: Box::new(child),
}),
}
}
View::Row(align, children) => {
let claims: Vec<Claim> = metrics
.children
.iter()
.map(|child| Claim {
kind: child.width_kind,
demand: child.natural,
floor: child.floor,
})
.collect();
let shares = distribute_constraints(constraint.reference, constraint.cap, &claims);
let children: Vec<Widths<'a>> = children
.iter()
.zip(&metrics.children)
.enumerate()
.map(|(index, (child, inner))| {
place(
child,
inner,
if constraint.reference.is_some() {
Constraint::established(shares[index])
} else {
Constraint::unbounded()
},
bounded,
None,
)
})
.collect();
Widths {
width: children.iter().map(|child| child.width).sum(),
height_kind: metrics.height_kind,
height_floor: children
.iter()
.map(|child| child.height_floor)
.max()
.unwrap_or(0),
height_projection: metrics.height_projection,
node: WidthNode::Row(*align, children),
}
}
View::Column(align, children) => {
let children: Vec<Widths<'a>> = children
.iter()
.zip(&metrics.children)
.map(|(child, inner)| place(child, inner, constraint, bounded, None))
.collect();
Widths {
width: children.iter().map(|child| child.width).max().unwrap_or(0),
height_kind: metrics.height_kind,
height_floor: children.iter().map(|child| child.height_floor).sum(),
height_projection: metrics.height_projection,
node: WidthNode::Column(*align, children),
}
}
View::Grid(style, rows) => {
let columns = grid::columns(rows);
let claims = column_claims(style, rows, &metrics.children, columns);
let mut widths = distribute_constraints(constraint.reference, constraint.cap, &claims);
let mut placed = Vec::with_capacity(rows.len());
for row in 0..rows.len() {
let mut cells = Vec::with_capacity(columns);
for (column, width) in widths.iter_mut().enumerate() {
let view = grid::cell(rows, row, column);
let inner = &metrics.children[row * columns + column];
let share = *width;
let mut padding = grid::cell_padding(style, view);
let across = degrade(Some(share), 0, 0, horizontal(padding), inner.floor);
if across.padding {
padding.left = 0;
padding.right = 0;
}
let child = place(
view,
inner,
Constraint::established(share.saturating_sub(horizontal(padding))),
bounded || matches!(claims[column].kind, Kind::Cells),
None,
);
*width = (*width).max(child.width + horizontal(padding));
let (align, vertical_align) = grid::cell_alignment(view);
cells.push(GridCell {
padding,
align,
vertical_align,
child,
});
}
placed.push(cells);
}
let height_floor = placed
.iter()
.map(|row| {
row.iter()
.map(|cell| cell.child.height_floor + vertical(cell.padding))
.max()
.unwrap_or(0)
})
.sum();
Widths {
width: widths.iter().sum(),
height_kind: metrics.height_kind,
height_floor,
height_projection: metrics.height_projection,
node: WidthNode::Grid(GridBox {
columns: widths,
rows: placed,
}),
}
}
View::Viewport(viewport, child) => {
let horizontal = viewport.horizontal_projection().is_some();
let extent = constraint.reference;
let child_constraint = if horizontal {
Constraint {
reference: extent,
cap: None,
}
} else {
constraint
};
let child = place(child, &metrics.children[0], child_constraint, bounded, None);
Widths {
width: if horizontal {
extent.unwrap_or(child.width)
} else {
child.width
},
height_kind: metrics.height_kind,
height_floor: metrics.height_floor,
height_projection: metrics.height_projection,
node: WidthNode::Viewport(viewport, bounded, Box::new(child)),
}
}
}
}
fn title_width(style: &BlockStyle, title: Option<&BlockTitle>) -> usize {
let Some(title) = title else {
return 0;
};
debug_assert!(
style.get_border().is_some() && style.get_border_top(),
"a titled block requires an enabled top border"
);
if style.get_border().is_none() || !style.get_border_top() {
return 0;
}
if title.text().as_str().is_empty() {
return 0;
}
let text = title
.text()
.lines()
.first()
.map(|line| line.iter().map(|grapheme| grapheme.width()).sum())
.unwrap_or(0);
let border = border_extent(style).width();
border
.saturating_add(text)
.saturating_add(usize::from(title.horizontal_padding()).saturating_mul(2))
}
fn text_width(area: Option<usize>, overflow: &Overflow, metrics: &Metrics) -> usize {
match (area, overflow) {
(None, _) => metrics.natural,
(Some(area), Overflow::Wrap) => area.min(metrics.natural).max(metrics.floor),
(Some(area), Overflow::Clip(_)) => area.min(metrics.natural),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Border, TextStyle};
fn text(content: &str) -> View {
View::text(content, TextStyle::new())
}
fn natural(view: &View) -> usize {
metrics(view).natural
}
fn floor(view: &View) -> usize {
metrics(view).floor
}
fn fills(view: &View) -> bool {
metrics(view).fills
}
#[test]
fn text_is_measured_by_its_widest_line_and_its_widest_grapheme() {
assert_eq!(natural(&text("ab\nabcd\nabc")), 4);
assert_eq!(floor(&text("ab\nabcd\nabc")), 1);
assert_eq!(natural(&text("日本語")), 6);
assert_eq!(
floor(&text("日本語")),
2,
"a wide character cannot be split"
);
assert_eq!(floor(&text("a👩💻")), 2, "nor can a cluster");
assert_eq!(natural(&text("")), 0);
assert_eq!(floor(&text("")), 0);
}
#[test]
fn a_block_measures_its_frame_bounds_and_margin() {
let bordered = View::block(
BlockStyle::new().border(Border::NORMAL).padding((0, 1)),
text("abc"),
);
assert_eq!(natural(&bordered), 7, "3 content + 2 padding + 2 border");
assert_eq!(floor(&bordered), 5, "one grapheme plus the frame");
let bounded = View::block(BlockStyle::new().max_width(2), text("abcd"));
assert_eq!(natural(&bounded), 2, "the maximum caps the measure");
let floored = View::block(BlockStyle::new().min_width(9), text("abcd"));
assert_eq!(natural(&floored), 9);
assert_eq!(floor(&floored), 9, "the minimum is a floor too");
let spaced = View::block(BlockStyle::new().margin((0, 2)), text("ab"));
assert_eq!(natural(&spaced), 6, "margin lies outside the box");
assert_eq!(floor(&spaced), 5);
}
#[test]
fn a_row_sums_its_children_and_a_column_takes_the_widest() {
let children = [text("abcd"), text("日本")];
let row = View::row(VerticalAlign::Top, children.clone());
let column = View::column(Align::Left, children);
assert_eq!(natural(&row), 8);
assert_eq!(floor(&row), 3, "one grapheme from each child");
assert_eq!(natural(&column), 4);
assert_eq!(floor(&column), 2);
}
#[test]
fn a_height_floor_is_the_frame_and_a_width_floor_is_the_content() {
let bordered = View::block(BlockStyle::new().border(Border::NORMAL), text("abc"));
assert_eq!(metrics(&text("abc")).height_floor, 0, "a row can be absent");
assert_eq!(metrics(&bordered).height_floor, 2, "the frame cannot");
assert_eq!(floor(&bordered), 3, "one grapheme plus it");
let floored = View::block(BlockStyle::new().min_height(5), text("a"));
assert_eq!(metrics(&floored).height_floor, 5);
let spaced = View::block(BlockStyle::new().margin((1, 0)), text("a"));
assert_eq!(metrics(&spaced).height_floor, 2, "margin lies outside");
}
#[test]
fn a_view_fills_its_area_when_anything_inside_it_does() {
let filling = View::block(BlockStyle::new().width(Length::fill(1)), text("a"));
assert!(!fills(&text("a")));
assert!(fills(&filling));
assert!(
fills(&View::block(BlockStyle::new(), filling.clone())),
"an automatic box inherits its content's appetite"
);
assert!(
!fills(&View::block(BlockStyle::new().width(4), filling.clone())),
"a stated size settles the box, whatever it contains"
);
assert!(fills(&View::row(VerticalAlign::Top, [text("a"), filling])));
}
#[test]
fn a_text_leaf_is_capped_by_its_area_and_never_widened_by_it() {
let wide = metrics(&text("日本"));
assert_eq!(text_width(None, &Overflow::Wrap, &wide), 4, "its own lines");
assert_eq!(text_width(Some(3), &Overflow::Wrap, &wide), 3);
assert_eq!(
text_width(Some(10), &Overflow::Wrap, &wide),
4,
"an area wider than the text is a cap, not a size to take"
);
assert_eq!(
text_width(Some(10), &Overflow::clip(), &wide),
4,
"nor is there anything for a clip to cut"
);
assert_eq!(
text_width(Some(1), &Overflow::Wrap, &wide),
2,
"one unsplittable grapheme is wider than the area"
);
assert_eq!(
text_width(Some(1), &Overflow::clip(), &wide),
1,
"a clip cuts to the area instead of widening"
);
}
#[test]
fn a_block_hands_its_content_width_down_and_keeps_its_own() {
let view = View::block(
BlockStyle::new().border(Border::NORMAL).padding((0, 1)),
text("abcdefgh"),
);
let placed = widths(&view, Some(6));
assert_eq!(placed.width, 6);
let WidthNode::Block(block) = &placed.node else {
panic!("a block");
};
assert_eq!(block.content_width, 2, "6 less two borders and two pads");
assert_eq!(block.child.width, 2);
}
}