use std::collections::HashMap;
use crate::error::{GuiError, GuiResult};
use crate::layout::{
AvailableSpace, Dimension, LayoutNodeId, LengthPercentage, LengthPercentageAuto, Point, Rect,
Size, Style,
};
pub const MAX_LAYOUT_DEPTH: usize = 128;
pub const STRICT_TOLERANCE_PX: f32 = 0.01;
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct BoxDimensions {
pub content: Size<f32>,
pub padding: Rect<f32>,
pub border: Rect<f32>,
pub margin: Rect<f32>,
}
impl BoxDimensions {
pub const ZERO: Self = Self {
content: Size::ZERO,
padding: Rect {
left: 0.0,
right: 0.0,
top: 0.0,
bottom: 0.0,
},
border: Rect {
left: 0.0,
right: 0.0,
top: 0.0,
bottom: 0.0,
},
margin: Rect {
left: 0.0,
right: 0.0,
top: 0.0,
bottom: 0.0,
},
};
pub fn content_box(&self) -> Size<f32> {
self.content
}
pub fn padding_box(&self) -> Size<f32> {
Size::new(
(self.content.width + self.padding.left + self.padding.right).max(0.0),
(self.content.height + self.padding.top + self.padding.bottom).max(0.0),
)
}
pub fn border_box(&self) -> Size<f32> {
let p_box = self.padding_box();
Size::new(
(p_box.width + self.border.left + self.border.right).max(0.0),
(p_box.height + self.border.top + self.border.bottom).max(0.0),
)
}
pub fn margin_box(&self) -> Size<f32> {
let b_box = self.border_box();
Size::new(
(b_box.width + self.margin.left + self.margin.right).max(0.0),
(b_box.height + self.margin.top + self.margin.bottom).max(0.0),
)
}
pub fn validate(&self) -> GuiResult<()> {
if !self.content.width.is_finite()
|| !self.content.height.is_finite()
|| self.content.width < 0.0
|| self.content.height < 0.0
{
return Err(GuiError::InvalidLayoutGeometry);
}
if !self.padding.left.is_finite()
|| !self.padding.right.is_finite()
|| !self.padding.top.is_finite()
|| !self.padding.bottom.is_finite()
|| self.padding.left < 0.0
|| self.padding.right < 0.0
|| self.padding.top < 0.0
|| self.padding.bottom < 0.0
{
return Err(GuiError::InvalidLayoutGeometry);
}
if !self.border.left.is_finite()
|| !self.border.right.is_finite()
|| !self.border.top.is_finite()
|| !self.border.bottom.is_finite()
|| self.border.left < 0.0
|| self.border.right < 0.0
|| self.border.top < 0.0
|| self.border.bottom < 0.0
{
return Err(GuiError::InvalidLayoutGeometry);
}
if !self.margin.left.is_finite()
|| !self.margin.right.is_finite()
|| !self.margin.top.is_finite()
|| !self.margin.bottom.is_finite()
{
return Err(GuiError::InvalidNumericInput);
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct BoxConstraints {
pub min_size: Size<Option<f32>>,
pub max_size: Size<Option<f32>>,
pub aspect_ratio: Option<f32>,
}
impl BoxConstraints {
pub fn clamp_dimension(val: f32, min: Option<f32>, max: Option<f32>) -> f32 {
let mut result = val;
if let Some(max_val) = max {
result = result.min(max_val);
}
if let Some(min_val) = min {
result = result.max(min_val);
}
result.max(0.0)
}
pub fn clamp_size(&self, size: Size<f32>) -> Size<f32> {
Size::new(
Self::clamp_dimension(size.width, self.min_size.width, self.max_size.width),
Self::clamp_dimension(size.height, self.min_size.height, self.max_size.height),
)
}
pub fn apply_aspect_ratio(&self, size: Size<Option<f32>>) -> Size<Option<f32>> {
let Some(ratio) = self.aspect_ratio else {
return size;
};
if ratio <= 0.0 || !ratio.is_finite() {
return size;
}
match (size.width, size.height) {
(Some(w), None) => Size::new(Some(w), Some((w / ratio).max(0.0))),
(None, Some(h)) => Size::new(Some((h * ratio).max(0.0)), Some(h)),
_ => size,
}
}
}
pub fn resolve_dimension(dim: Dimension, space: AvailableSpace) -> Option<f32> {
match dim {
Dimension::Length(px) => Some(px.max(0.0)),
Dimension::Percent(pct) => match space {
AvailableSpace::Definite(parent_size) => Some((parent_size * pct).max(0.0)),
_ => None,
},
Dimension::Auto => None,
}
}
pub fn resolve_padding(
padding: &Rect<LengthPercentage>,
available_space: Size<AvailableSpace>,
) -> Rect<f32> {
let left = match padding.left {
LengthPercentage::Length(px) => px.max(0.0),
LengthPercentage::Percent(p) => match available_space.width {
AvailableSpace::Definite(w) => (w * p).max(0.0),
_ => 0.0,
},
};
let right = match padding.right {
LengthPercentage::Length(px) => px.max(0.0),
LengthPercentage::Percent(p) => match available_space.width {
AvailableSpace::Definite(w) => (w * p).max(0.0),
_ => 0.0,
},
};
let top = match padding.top {
LengthPercentage::Length(px) => px.max(0.0),
LengthPercentage::Percent(p) => match available_space.height {
AvailableSpace::Definite(h) => (h * p).max(0.0),
_ => 0.0,
},
};
let bottom = match padding.bottom {
LengthPercentage::Length(px) => px.max(0.0),
LengthPercentage::Percent(p) => match available_space.height {
AvailableSpace::Definite(h) => (h * p).max(0.0),
_ => 0.0,
},
};
Rect::new(left, right, top, bottom)
}
pub fn resolve_margin(
margin: &Rect<LengthPercentageAuto>,
available_space: Size<AvailableSpace>,
) -> Rect<f32> {
let left = match margin.left {
LengthPercentageAuto::Length(px) => px,
LengthPercentageAuto::Percent(p) => match available_space.width {
AvailableSpace::Definite(w) => w * p,
_ => 0.0,
},
LengthPercentageAuto::Auto => 0.0,
};
let right = match margin.right {
LengthPercentageAuto::Length(px) => px,
LengthPercentageAuto::Percent(p) => match available_space.width {
AvailableSpace::Definite(w) => w * p,
_ => 0.0,
},
LengthPercentageAuto::Auto => 0.0,
};
let top = match margin.top {
LengthPercentageAuto::Length(px) => px,
LengthPercentageAuto::Percent(p) => match available_space.height {
AvailableSpace::Definite(h) => h * p,
_ => 0.0,
},
LengthPercentageAuto::Auto => 0.0,
};
let bottom = match margin.bottom {
LengthPercentageAuto::Length(px) => px,
LengthPercentageAuto::Percent(p) => match available_space.height {
AvailableSpace::Definite(h) => h * p,
_ => 0.0,
},
LengthPercentageAuto::Auto => 0.0,
};
Rect::new(left, right, top, bottom)
}
pub fn resolve_inset(
inset: &Rect<LengthPercentageAuto>,
available_space: Size<AvailableSpace>,
) -> Rect<Option<f32>> {
let resolve_axis = |val: LengthPercentageAuto, space: AvailableSpace| match val {
LengthPercentageAuto::Length(px) => Some(px),
LengthPercentageAuto::Percent(p) => match space {
AvailableSpace::Definite(s) => Some(s * p),
_ => None,
},
LengthPercentageAuto::Auto => None,
};
Rect::new(
resolve_axis(inset.left, available_space.width),
resolve_axis(inset.right, available_space.width),
resolve_axis(inset.top, available_space.height),
resolve_axis(inset.bottom, available_space.height),
)
}
pub fn resolve_box_constraints(
style: &Style,
available_space: Size<AvailableSpace>,
) -> BoxConstraints {
BoxConstraints {
min_size: Size::new(
resolve_dimension(style.min_size.width, available_space.width),
resolve_dimension(style.min_size.height, available_space.height),
),
max_size: Size::new(
resolve_dimension(style.max_size.width, available_space.width),
resolve_dimension(style.max_size.height, available_space.height),
),
aspect_ratio: style.aspect_ratio,
}
}
pub fn compute_box_sizing(
style: &Style,
available_space: Size<AvailableSpace>,
intrinsic_size: Option<Size<f32>>,
) -> GuiResult<BoxDimensions> {
style.validate()?;
let padding = resolve_padding(&style.padding, available_space);
let border = Rect::<f32>::new(0.0, 0.0, 0.0, 0.0);
let margin = resolve_margin(&style.margin, available_space);
let constraints = resolve_box_constraints(style, available_space);
let mut raw_width = resolve_dimension(style.size.width, available_space.width);
let mut raw_height = resolve_dimension(style.size.height, available_space.height);
if raw_width.is_none() {
if let Some(intr) = intrinsic_size {
raw_width = Some(intr.width);
}
}
if raw_height.is_none() {
if let Some(intr) = intrinsic_size {
raw_height = Some(intr.height);
}
}
let sized = constraints.apply_aspect_ratio(Size::new(raw_width, raw_height));
let mut resolved_w = sized.width.unwrap_or(0.0);
let mut resolved_h = sized.height.unwrap_or(0.0);
resolved_w = BoxConstraints::clamp_dimension(
resolved_w,
constraints.min_size.width,
constraints.max_size.width,
);
resolved_h = BoxConstraints::clamp_dimension(
resolved_h,
constraints.min_size.height,
constraints.max_size.height,
);
if raw_height.is_none() && style.aspect_ratio.is_some() {
if let Some(ratio) = style.aspect_ratio {
if ratio > 0.0 && ratio.is_finite() {
resolved_h = (resolved_w / ratio).max(0.0);
resolved_h = BoxConstraints::clamp_dimension(
resolved_h,
constraints.min_size.height,
constraints.max_size.height,
);
}
}
} else if raw_width.is_none() && style.aspect_ratio.is_some() {
if let Some(ratio) = style.aspect_ratio {
if ratio > 0.0 && ratio.is_finite() {
resolved_w = (resolved_h * ratio).max(0.0);
resolved_w = BoxConstraints::clamp_dimension(
resolved_w,
constraints.min_size.width,
constraints.max_size.width,
);
}
}
}
let b_box = Size::new(resolved_w, resolved_h);
let content_w =
(b_box.width - padding.left - padding.right - border.left - border.right).max(0.0);
let content_h =
(b_box.height - padding.top - padding.bottom - border.top - border.bottom).max(0.0);
let dims = BoxDimensions {
content: Size::new(content_w, content_h),
padding,
border,
margin,
};
dims.validate()?;
Ok(dims)
}
pub fn apply_relative_offset(flow_position: Point<f32>, inset: &Rect<Option<f32>>) -> Point<f32> {
let mut x = flow_position.x;
let mut y = flow_position.y;
if let Some(left) = inset.left {
x += left;
} else if let Some(right) = inset.right {
x -= right;
}
if let Some(top) = inset.top {
y += top;
} else if let Some(bottom) = inset.bottom {
y -= bottom;
}
Point::new(x, y)
}
pub fn resolve_absolute_position(
parent_padding_origin: Point<f32>,
parent_padding_size: Size<f32>,
child_size: Size<f32>,
inset: &Rect<Option<f32>>,
margin: &Rect<f32>,
) -> Point<f32> {
let x = if let Some(left) = inset.left {
parent_padding_origin.x + left + margin.left
} else if let Some(right) = inset.right {
parent_padding_origin.x + parent_padding_size.width
- child_size.width
- right
- margin.right
} else {
parent_padding_origin.x + margin.left
};
let y = if let Some(top) = inset.top {
parent_padding_origin.y + top + margin.top
} else if let Some(bottom) = inset.bottom {
parent_padding_origin.y + parent_padding_size.height
- child_size.height
- bottom
- margin.bottom
} else {
parent_padding_origin.y + margin.top
};
Point::new(x, y)
}
pub trait Measurer {
fn measure(
&mut self,
node: LayoutNodeId,
known_dimensions: Size<Option<f32>>,
available_space: Size<AvailableSpace>,
) -> Option<Size<f32>>;
}
impl<F> Measurer for F
where
F: FnMut(LayoutNodeId, Size<Option<f32>>, Size<AvailableSpace>) -> Option<Size<f32>>,
{
fn measure(
&mut self,
node: LayoutNodeId,
known_dimensions: Size<Option<f32>>,
available_space: Size<AvailableSpace>,
) -> Option<Size<f32>> {
self(node, known_dimensions, available_space)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct TextMeasureKey {
text: String,
known_hundredths: Option<i64>,
avail_tag: u8,
avail_hundredths: i64,
font_tenths: i64,
}
impl TextMeasureKey {
fn from_inputs(
text: &str,
font_size: f32,
known_dimensions: Size<Option<f32>>,
available_space: Size<AvailableSpace>,
) -> Self {
let (avail_tag, avail_hundredths) = match available_space.width {
AvailableSpace::Definite(w) => (0, (w * 100.0).round() as i64),
AvailableSpace::MinContent => (1, 0),
AvailableSpace::MaxContent => (2, 0),
};
Self {
text: text.to_owned(),
known_hundredths: known_dimensions.width.map(|w| (w * 100.0).round() as i64),
avail_tag,
avail_hundredths,
font_tenths: (font_size * 10.0).round() as i64,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct TextMeasurementCache {
measure_calls: usize,
cache_hits: usize,
cache: HashMap<TextMeasureKey, Size<f32>>,
}
impl TextMeasurementCache {
pub fn new() -> Self {
Self::default()
}
pub fn call_count(&self) -> usize {
self.measure_calls
}
pub fn cache_hits(&self) -> usize {
self.cache_hits
}
pub fn reset_counts(&mut self) {
self.measure_calls = 0;
self.cache_hits = 0;
}
pub fn clear(&mut self) {
self.cache.clear();
self.reset_counts();
}
pub fn measure_text(
&mut self,
text: &str,
font_size: f32,
line_height: f32,
known_dimensions: Size<Option<f32>>,
available_space: Size<AvailableSpace>,
) -> Size<f32> {
let key = TextMeasureKey::from_inputs(text, font_size, known_dimensions, available_space);
if let Some(&cached) = self.cache.get(&key) {
self.cache_hits += 1;
return cached;
}
self.measure_calls += 1;
if text.is_empty() {
let res = Size::new(0.0, line_height);
self.cache.insert(key, res);
return res;
}
let char_width = font_size * 0.6;
let natural_width = text.len() as f32 * char_width;
let max_w = known_dimensions
.width
.or_else(|| available_space.width.into_option());
let res = match max_w {
Some(w) if w < natural_width && w > 0.0 => {
let chars_per_line = ((w / char_width).floor() as usize).max(1);
let lines = text.len().div_ceil(chars_per_line);
Size::new(w, lines as f32 * line_height)
}
_ => Size::new(natural_width, line_height),
};
self.cache.insert(key, res);
res
}
}