use crate::error::{GuiError, GuiResult};
pub mod box_sizing;
pub mod flex;
pub mod grid;
pub mod tree;
pub use box_sizing::{
apply_relative_offset, compute_box_sizing, resolve_absolute_position, resolve_box_constraints,
resolve_dimension, resolve_inset, resolve_margin, resolve_padding, BoxConstraints,
BoxDimensions, Measurer, TextMeasurementCache, MAX_LAYOUT_DEPTH, STRICT_TOLERANCE_PX,
};
pub use flex::{compute_flex, compute_multi_line_flex, compute_single_line_flex, FlexItem};
pub use grid::compute_grid;
pub use tree::{
AvailableSpaceKey, CachedLayout, LayoutCacheKey, LayoutMetrics, LayoutNode, LayoutNodeId,
LayoutTree,
};
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AvailableSpace {
Definite(f32),
MinContent,
MaxContent,
}
impl AvailableSpace {
pub fn is_definite(&self) -> bool {
matches!(self, Self::Definite(_))
}
pub fn into_option(self) -> Option<f32> {
match self {
Self::Definite(val) => Some(val),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Size<T> {
pub width: T,
pub height: T,
}
impl<T> Size<T> {
pub const fn new(width: T, height: T) -> Self {
Self { width, height }
}
}
impl<T: Copy> Size<T> {
pub fn all(value: T) -> Self {
Self {
width: value,
height: value,
}
}
}
impl Size<Dimension> {
pub fn auto() -> Self {
Self {
width: Dimension::Auto,
height: Dimension::Auto,
}
}
pub fn from_lengths(width: f32, height: f32) -> Self {
Self {
width: Dimension::Length(width),
height: Dimension::Length(height),
}
}
}
impl Size<LengthPercentage> {
pub fn zero() -> Self {
Self {
width: LengthPercentage::Length(0.0),
height: LengthPercentage::Length(0.0),
}
}
}
impl Size<f32> {
pub const ZERO: Self = Self {
width: 0.0,
height: 0.0,
};
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Point<T> {
pub x: T,
pub y: T,
}
impl<T> Point<T> {
pub const fn new(x: T, y: T) -> Self {
Self { x, y }
}
}
impl Point<f32> {
pub const ZERO: Self = Self { x: 0.0, y: 0.0 };
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Rect<T> {
pub left: T,
pub right: T,
pub top: T,
pub bottom: T,
}
impl<T> Rect<T> {
pub const fn new(left: T, right: T, top: T, bottom: T) -> Self {
Self {
left,
right,
top,
bottom,
}
}
}
impl<T: Copy> Rect<T> {
pub fn all(value: T) -> Self {
Self {
left: value,
right: value,
top: value,
bottom: value,
}
}
pub fn symmetric(vertical: T, horizontal: T) -> Self {
Self {
left: horizontal,
right: horizontal,
top: vertical,
bottom: vertical,
}
}
}
impl Rect<LengthPercentage> {
pub fn zero() -> Self {
Self::all(LengthPercentage::Length(0.0))
}
}
impl Rect<LengthPercentageAuto> {
pub fn zero() -> Self {
Self::all(LengthPercentageAuto::Length(0.0))
}
pub fn auto() -> Self {
Self::all(LengthPercentageAuto::Auto)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct LayoutRect {
pub x: f32,
pub y: f32,
pub width: f32,
pub height: f32,
}
impl LayoutRect {
pub const fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
Self {
x,
y,
width,
height,
}
}
pub const ZERO: Self = Self {
x: 0.0,
y: 0.0,
width: 0.0,
height: 0.0,
};
pub fn location(&self) -> Point<f32> {
Point::new(self.x, self.y)
}
pub fn size(&self) -> Size<f32> {
Size::new(self.width, self.height)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Dimension {
#[default]
Auto,
Length(f32),
Percent(f32),
}
impl Dimension {
pub const fn auto() -> Self {
Self::Auto
}
pub const fn length(px: f32) -> Self {
Self::Length(px)
}
pub const fn percent(pct: f32) -> Self {
Self::Percent(pct)
}
pub fn is_auto(&self) -> bool {
matches!(self, Self::Auto)
}
pub fn is_length(&self) -> bool {
matches!(self, Self::Length(_))
}
pub fn is_percent(&self) -> bool {
matches!(self, Self::Percent(_))
}
pub fn validate(&self) -> GuiResult<()> {
match self {
Self::Auto => Ok(()),
Self::Length(v) | Self::Percent(v) => {
if !v.is_finite() {
Err(GuiError::InvalidNumericInput)
} else if *self == Self::Length(*v) && *v < 0.0 {
Err(GuiError::InvalidLayoutGeometry)
} else {
Ok(())
}
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum LengthPercentage {
Length(f32),
Percent(f32),
}
impl LengthPercentage {
pub const fn length(px: f32) -> Self {
Self::Length(px)
}
pub const fn percent(pct: f32) -> Self {
Self::Percent(pct)
}
pub fn is_length(&self) -> bool {
matches!(self, Self::Length(_))
}
pub fn is_percent(&self) -> bool {
matches!(self, Self::Percent(_))
}
pub fn to_i32_pixels(&self) -> i32 {
match self {
Self::Length(px) => px.max(0.0).round() as i32,
_ => 0,
}
}
pub fn validate(&self) -> GuiResult<()> {
match self {
Self::Length(v) | Self::Percent(v) => {
if !v.is_finite() {
Err(GuiError::InvalidNumericInput)
} else if *v < 0.0 {
Err(GuiError::InvalidLayoutGeometry)
} else {
Ok(())
}
}
}
}
}
impl Default for LengthPercentage {
fn default() -> Self {
Self::Length(0.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum LengthPercentageAuto {
#[default]
Auto,
Length(f32),
Percent(f32),
}
impl LengthPercentageAuto {
pub const fn auto() -> Self {
Self::Auto
}
pub const fn length(px: f32) -> Self {
Self::Length(px)
}
pub const fn percent(pct: f32) -> Self {
Self::Percent(pct)
}
pub fn is_auto(&self) -> bool {
matches!(self, Self::Auto)
}
pub fn is_length(&self) -> bool {
matches!(self, Self::Length(_))
}
pub fn is_percent(&self) -> bool {
matches!(self, Self::Percent(_))
}
pub fn to_i32_pixels(&self) -> i32 {
match self {
Self::Length(px) => px.max(0.0).round() as i32,
_ => 0,
}
}
pub fn validate(&self) -> GuiResult<()> {
match self {
Self::Auto => Ok(()),
Self::Length(v) | Self::Percent(v) => {
if !v.is_finite() {
Err(GuiError::InvalidNumericInput)
} else {
Ok(())
}
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Display {
#[default]
Flex,
Grid,
None,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Position {
#[default]
Relative,
Absolute,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum FlexDirection {
#[default]
Row,
Column,
RowReverse,
ColumnReverse,
}
impl FlexDirection {
pub const ROW: Self = Self::Row;
pub const COLUMN: Self = Self::Column;
pub const ROW_REVERSE: Self = Self::RowReverse;
pub const COLUMN_REVERSE: Self = Self::ColumnReverse;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum FlexWrap {
#[default]
NoWrap,
Wrap,
WrapReverse,
}
impl FlexWrap {
pub const NO_WRAP: Self = Self::NoWrap;
pub const WRAP: Self = Self::Wrap;
pub const WRAP_REVERSE: Self = Self::WrapReverse;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AlignItems {
Start,
End,
Center,
Baseline,
Stretch,
}
impl AlignItems {
pub const START: Self = Self::Start;
pub const END: Self = Self::End;
pub const CENTER: Self = Self::Center;
pub const BASELINE: Self = Self::Baseline;
pub const STRETCH: Self = Self::Stretch;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AlignSelf {
Start,
End,
Center,
Baseline,
Stretch,
}
impl AlignSelf {
pub const START: Self = Self::Start;
pub const END: Self = Self::End;
pub const CENTER: Self = Self::Center;
pub const BASELINE: Self = Self::Baseline;
pub const STRETCH: Self = Self::Stretch;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AlignContent {
Start,
End,
Center,
Stretch,
SpaceBetween,
SpaceAround,
SpaceEvenly,
}
impl AlignContent {
pub const START: Self = Self::Start;
pub const END: Self = Self::End;
pub const CENTER: Self = Self::Center;
pub const STRETCH: Self = Self::Stretch;
pub const SPACE_BETWEEN: Self = Self::SpaceBetween;
pub const SPACE_AROUND: Self = Self::SpaceAround;
pub const SPACE_EVENLY: Self = Self::SpaceEvenly;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum JustifyContent {
Start,
End,
Center,
Stretch,
SpaceBetween,
SpaceAround,
SpaceEvenly,
}
impl JustifyContent {
pub const START: Self = Self::Start;
pub const END: Self = Self::End;
pub const CENTER: Self = Self::Center;
pub const STRETCH: Self = Self::Stretch;
pub const SPACE_BETWEEN: Self = Self::SpaceBetween;
pub const SPACE_AROUND: Self = Self::SpaceAround;
pub const SPACE_EVENLY: Self = Self::SpaceEvenly;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum GridAutoFlow {
#[default]
Row,
Column,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TrackSizingFunction {
Fixed(f32),
Percent(f32),
Flex(f32),
Auto,
MinMax(Box<TrackSizingFunction>, Box<TrackSizingFunction>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GridPlacement {
pub start: i16,
pub span: u16,
}
impl GridPlacement {
pub const fn new(start: i16, span: u16) -> Self {
Self { start, span }
}
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Style {
pub display: Display,
pub position: Position,
pub size: Size<Dimension>,
pub min_size: Size<Dimension>,
pub max_size: Size<Dimension>,
pub aspect_ratio: Option<f32>,
pub padding: Rect<LengthPercentage>,
pub margin: Rect<LengthPercentageAuto>,
pub inset: Rect<LengthPercentageAuto>,
pub flex_direction: FlexDirection,
pub flex_wrap: FlexWrap,
pub flex_grow: f32,
pub flex_shrink: f32,
pub flex_basis: Dimension,
pub gap: Size<LengthPercentage>,
pub align_items: Option<AlignItems>,
pub align_self: Option<AlignSelf>,
pub justify_items: Option<AlignItems>,
pub justify_self: Option<AlignSelf>,
pub align_content: Option<AlignContent>,
pub justify_content: Option<JustifyContent>,
pub grid_template_rows: Vec<TrackSizingFunction>,
pub grid_template_columns: Vec<TrackSizingFunction>,
pub grid_auto_rows: Vec<TrackSizingFunction>,
pub grid_auto_columns: Vec<TrackSizingFunction>,
pub grid_auto_flow: GridAutoFlow,
pub grid_row: GridPlacement,
pub grid_column: GridPlacement,
}
impl Default for Style {
fn default() -> Self {
Self {
display: Display::Flex,
position: Position::Relative,
size: Size::auto(),
min_size: Size::auto(),
max_size: Size::auto(),
aspect_ratio: None,
padding: Rect::<LengthPercentage>::zero(),
margin: Rect::<LengthPercentageAuto>::zero(),
inset: Rect::auto(),
flex_direction: FlexDirection::Row,
flex_wrap: FlexWrap::NoWrap,
flex_grow: 0.0,
flex_shrink: 1.0,
flex_basis: Dimension::Auto,
gap: Size::zero(),
align_items: None,
align_self: None,
justify_items: None,
justify_self: None,
align_content: None,
justify_content: None,
grid_template_rows: Vec::new(),
grid_template_columns: Vec::new(),
grid_auto_rows: Vec::new(),
grid_auto_columns: Vec::new(),
grid_auto_flow: GridAutoFlow::Row,
grid_row: GridPlacement::default(),
grid_column: GridPlacement::default(),
}
}
}
impl Style {
pub fn validate(&self) -> GuiResult<()> {
if let Some(ratio) = self.aspect_ratio {
if !ratio.is_finite() || ratio <= 0.0 {
return Err(GuiError::InvalidNumericInput);
}
}
if !self.flex_grow.is_finite() || self.flex_grow < 0.0 {
return Err(GuiError::InvalidNumericInput);
}
if !self.flex_shrink.is_finite() || self.flex_shrink < 0.0 {
return Err(GuiError::InvalidNumericInput);
}
self.size.width.validate()?;
self.size.height.validate()?;
self.min_size.width.validate()?;
self.min_size.height.validate()?;
self.max_size.width.validate()?;
self.max_size.height.validate()?;
self.padding.left.validate()?;
self.padding.right.validate()?;
self.padding.top.validate()?;
self.padding.bottom.validate()?;
self.gap.width.validate()?;
self.gap.height.validate()?;
self.margin.left.validate()?;
self.margin.right.validate()?;
self.margin.top.validate()?;
self.margin.bottom.validate()?;
self.inset.left.validate()?;
self.inset.right.validate()?;
self.inset.top.validate()?;
self.inset.bottom.validate()?;
self.flex_basis.validate()?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_style_defaults_and_validation() {
let style = Style::default();
assert_eq!(style.display, Display::Flex);
assert_eq!(style.flex_grow, 0.0);
assert_eq!(style.flex_shrink, 1.0);
assert!(style.validate().is_ok());
}
#[test]
fn test_style_validation_rejects_nan_and_negative_dimensions() {
let mut style = Style {
flex_grow: -1.0,
..Style::default()
};
assert_eq!(style.validate(), Err(GuiError::InvalidNumericInput));
style.flex_grow = f32::NAN;
assert_eq!(style.validate(), Err(GuiError::InvalidNumericInput));
style = Style {
size: Size {
width: Dimension::Length(-10.0),
..Size::auto()
},
..Style::default()
};
assert_eq!(style.validate(), Err(GuiError::InvalidLayoutGeometry));
style = Style {
aspect_ratio: Some(-2.0),
..Style::default()
};
assert_eq!(style.validate(), Err(GuiError::InvalidNumericInput));
}
#[test]
fn test_layout_rect_helpers() {
let rect = LayoutRect::new(10.0, 20.0, 300.0, 200.0);
assert_eq!(rect.location(), Point::new(10.0, 20.0));
assert_eq!(rect.size(), Size::new(300.0, 200.0));
}
}