use core::hash::Hasher;
use crcbl_core::input::CursorIcon;
use taffy::{
AlignContent, AlignItems, BoxGenerationMode, CoreStyle, Dimension, FlexboxContainerStyle,
FlexboxItemStyle, LengthPercentage, LengthPercentageAuto, Point, Rect, Size,
};
use super::focus::Direction;
use crate::draw_list::CornerRadii;
use crate::font::face::{FontStyle, FontWeight};
use crate::font::layout::TextAlign;
use crate::font::{FamilyName, Font, FontFamily};
use crate::widget::NATURAL_FONT_SIZE;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Length {
Px(f32),
Percent(f32),
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LengthAuto {
Px(f32),
Percent(f32),
Auto,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Edges<T> {
pub top: T,
pub right: T,
pub bottom: T,
pub left: T,
}
impl<T: Copy> Edges<T> {
#[must_use]
pub const fn all(value: T) -> Self {
Self {
top: value,
right: value,
bottom: value,
left: value,
}
}
const fn sides(self) -> [T; 4] {
[self.top, self.right, self.bottom, self.left]
}
fn to_rect<U>(self, map: impl Fn(T) -> U) -> Rect<U> {
Rect {
left: map(self.left),
right: map(self.right),
top: map(self.top),
bottom: map(self.bottom),
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Display {
#[default]
Flex,
None,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum FlexDirection {
#[default]
Row,
Column,
RowReverse,
ColumnReverse,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum FlexWrap {
#[default]
NoWrap,
Wrap,
WrapReverse,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Align {
Start,
End,
FlexStart,
FlexEnd,
Center,
Stretch,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Justify {
Start,
End,
FlexStart,
FlexEnd,
Center,
SpaceBetween,
SpaceAround,
SpaceEvenly,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Position {
#[default]
Relative,
Absolute,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Overflow {
#[default]
Visible,
Hidden,
Scroll,
}
impl Overflow {
#[must_use]
pub const fn clips(self) -> bool {
matches!(self, Self::Hidden | Self::Scroll)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum WhiteSpace {
#[default]
Normal,
NoWrap,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TextOverflow {
#[default]
Clip,
Ellipsis,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TextDecoration {
#[default]
None,
Underline,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum LineHeight {
#[default]
Normal,
Multiple(f32),
Px(f32),
}
impl LineHeight {
#[must_use]
pub fn resolve(self, font_size: f32, normal: f32) -> f32 {
match self {
Self::Normal => normal,
Self::Multiple(factor) => factor * font_size,
Self::Px(px) => px,
}
}
pub(crate) fn bits(self) -> (u8, u32) {
match self {
Self::Normal => (0, 0),
Self::Multiple(factor) => (1, factor.to_bits()),
Self::Px(px) => (2, px.to_bits()),
}
}
pub(crate) fn from_bits((tag, bits): (u8, u32)) -> Self {
match tag {
1 => Self::Multiple(f32::from_bits(bits)),
2 => Self::Px(f32::from_bits(bits)),
_ => Self::Normal,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct NavId(pub(crate) u64);
impl NavId {
#[must_use]
pub fn new(name: &str) -> Self {
let mut hasher = std::hash::DefaultHasher::new();
std::hash::Hash::hash(name, &mut hasher);
Self(hasher.finish())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ImageName(pub(crate) u64);
impl ImageName {
#[must_use]
pub fn new(name: &str) -> Self {
let mut hasher = std::hash::DefaultHasher::new();
std::hash::Hash::hash(name, &mut hasher);
Self(hasher.finish())
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum BorderImageWidth {
Px(f32),
Multiple(f32),
}
impl BorderImageWidth {
#[must_use]
pub fn resolve(self, border: f32) -> f32 {
match self {
Self::Px(px) => px,
Self::Multiple(factor) => factor * border,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BorderImage {
pub source: Option<ImageName>,
pub slice: Edges<f32>,
pub fill: bool,
pub width: Edges<BorderImageWidth>,
}
impl BorderImage {
pub const NONE: Self = Self {
source: None,
slice: Edges::all(0.0),
fill: false,
width: Edges::all(BorderImageWidth::Multiple(1.0)),
};
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum NavTarget {
#[default]
Auto,
None,
Id(NavId),
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum NavWrap {
#[default]
None,
Horizontal,
Vertical,
Both,
}
impl NavWrap {
#[must_use]
pub const fn wraps(self, horizontal: bool) -> bool {
match self {
Self::None => false,
Self::Horizontal => horizontal,
Self::Vertical => !horizontal,
Self::Both => true,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct NodeStyle {
pub display: Display,
pub position: Position,
pub inset: Edges<LengthAuto>,
pub width: LengthAuto,
pub height: LengthAuto,
pub min_width: LengthAuto,
pub min_height: LengthAuto,
pub max_width: LengthAuto,
pub max_height: LengthAuto,
pub margin: Edges<LengthAuto>,
pub padding: Edges<Length>,
pub border: Edges<f32>,
pub overflow: Overflow,
pub flex_direction: FlexDirection,
pub flex_wrap: FlexWrap,
pub justify_content: Option<Justify>,
pub align_items: Option<Align>,
pub align_self: Option<Align>,
pub flex_grow: f32,
pub flex_shrink: f32,
pub flex_basis: LengthAuto,
pub column_gap: Length,
pub row_gap: Length,
pub background: [f32; 4],
pub border_color: [f32; 4],
pub radii: CornerRadii,
pub color: [f32; 4],
pub font_size: f32,
pub font_family: FontFamily,
pub family_name: Option<FamilyName>,
pub font_weight: FontWeight,
pub font_style: FontStyle,
pub line_height: LineHeight,
pub text_align: TextAlign,
pub white_space: WhiteSpace,
pub cursor: Option<CursorIcon>,
pub text_overflow: TextOverflow,
pub text_decoration: TextDecoration,
pub outline_width: f32,
pub outline_color: [f32; 4],
pub outline_offset: f32,
pub background_image: Option<ImageName>,
pub border_image: BorderImage,
pub nav_up: NavTarget,
pub nav_right: NavTarget,
pub nav_down: NavTarget,
pub nav_left: NavTarget,
pub nav_wrap: NavWrap,
}
impl NodeStyle {
pub const DEFAULT: Self = Self {
display: Display::Flex,
position: Position::Relative,
inset: Edges::all(LengthAuto::Auto),
width: LengthAuto::Auto,
height: LengthAuto::Auto,
min_width: LengthAuto::Auto,
min_height: LengthAuto::Auto,
max_width: LengthAuto::Auto,
max_height: LengthAuto::Auto,
margin: Edges::all(LengthAuto::Px(0.0)),
padding: Edges::all(Length::Px(0.0)),
border: Edges::all(0.0),
overflow: Overflow::Visible,
flex_direction: FlexDirection::Row,
flex_wrap: FlexWrap::NoWrap,
justify_content: None,
align_items: None,
align_self: None,
flex_grow: 0.0,
flex_shrink: 1.0,
flex_basis: LengthAuto::Auto,
column_gap: Length::Px(0.0),
row_gap: Length::Px(0.0),
background: [0.0; 4],
border_color: [0.0; 4],
radii: CornerRadii::uniform(0.0),
color: [1.0; 4],
font_size: NATURAL_FONT_SIZE,
font_family: FontFamily::Bitmap,
family_name: None,
font_weight: FontWeight::NORMAL,
font_style: FontStyle::Normal,
line_height: LineHeight::Normal,
text_align: TextAlign::Left,
white_space: WhiteSpace::Normal,
cursor: Some(CursorIcon::Default),
text_overflow: TextOverflow::Clip,
text_decoration: TextDecoration::None,
outline_width: 0.0,
outline_color: [0.0; 4],
outline_offset: 0.0,
background_image: None,
border_image: BorderImage::NONE,
nav_up: NavTarget::Auto,
nav_right: NavTarget::Auto,
nav_down: NavTarget::Auto,
nav_left: NavTarget::Auto,
nav_wrap: NavWrap::None,
};
pub fn layout_hash(&self, state: &mut impl Hasher) {
fn length(state: &mut impl Hasher, value: Length) {
match value {
Length::Px(px) => {
state.write_u8(0);
state.write_u32(px.to_bits());
}
Length::Percent(fraction) => {
state.write_u8(1);
state.write_u32(fraction.to_bits());
}
}
}
fn length_auto(state: &mut impl Hasher, value: LengthAuto) {
match value {
LengthAuto::Px(px) => {
state.write_u8(0);
state.write_u32(px.to_bits());
}
LengthAuto::Percent(fraction) => {
state.write_u8(1);
state.write_u32(fraction.to_bits());
}
LengthAuto::Auto => state.write_u8(2),
}
}
state.write_u8(self.display as u8);
state.write_u8(self.position as u8);
for side in self.inset.sides() {
length_auto(state, side);
}
for size in [
self.width,
self.height,
self.min_width,
self.min_height,
self.max_width,
self.max_height,
self.flex_basis,
] {
length_auto(state, size);
}
for side in self.margin.sides() {
length_auto(state, side);
}
for side in self.padding.sides() {
length(state, side);
}
for side in self.border.sides() {
state.write_u32(side.to_bits());
}
state.write_u8(self.overflow as u8);
state.write_u8(self.flex_direction as u8);
state.write_u8(self.flex_wrap as u8);
state.write_u8(
self.justify_content
.map_or(u8::MAX, |justify| justify as u8),
);
state.write_u8(self.align_items.map_or(u8::MAX, |align| align as u8));
state.write_u8(self.align_self.map_or(u8::MAX, |align| align as u8));
state.write_u32(self.flex_grow.to_bits());
state.write_u32(self.flex_shrink.to_bits());
length(state, self.column_gap);
length(state, self.row_gap);
}
}
impl NodeStyle {
#[must_use]
pub const fn nav(&self, direction: Direction) -> NavTarget {
match direction {
Direction::Up => self.nav_up,
Direction::Right => self.nav_right,
Direction::Down => self.nav_down,
Direction::Left => self.nav_left,
}
}
pub const fn nav_mut(&mut self, direction: Direction) -> &mut NavTarget {
match direction {
Direction::Up => &mut self.nav_up,
Direction::Right => &mut self.nav_right,
Direction::Down => &mut self.nav_down,
Direction::Left => &mut self.nav_left,
}
}
#[must_use]
pub fn text_line_height(&self, font: &Font) -> f32 {
self.line_height.resolve(
self.font_size,
font.metrics().normal_line_height(self.font_size),
)
}
}
impl Default for NodeStyle {
fn default() -> Self {
Self::DEFAULT
}
}
const fn length_percentage(value: Length) -> LengthPercentage {
match value {
Length::Px(px) => LengthPercentage::length(px),
Length::Percent(fraction) => LengthPercentage::percent(fraction),
}
}
const fn length_percentage_auto(value: LengthAuto) -> LengthPercentageAuto {
match value {
LengthAuto::Px(px) => LengthPercentageAuto::length(px),
LengthAuto::Percent(fraction) => LengthPercentageAuto::percent(fraction),
LengthAuto::Auto => LengthPercentageAuto::auto(),
}
}
const fn dimension(value: LengthAuto) -> Dimension {
match value {
LengthAuto::Px(px) => Dimension::length(px),
LengthAuto::Percent(fraction) => Dimension::percent(fraction),
LengthAuto::Auto => Dimension::auto(),
}
}
const fn align_items(value: Align) -> AlignItems {
match value {
Align::Start => AlignItems::START,
Align::End => AlignItems::END,
Align::FlexStart => AlignItems::FLEX_START,
Align::FlexEnd => AlignItems::FLEX_END,
Align::Center => AlignItems::CENTER,
Align::Stretch => AlignItems::STRETCH,
}
}
const fn justify_content(value: Justify) -> AlignContent {
match value {
Justify::Start => AlignContent::START,
Justify::End => AlignContent::END,
Justify::FlexStart => AlignContent::FLEX_START,
Justify::FlexEnd => AlignContent::FLEX_END,
Justify::Center => AlignContent::CENTER,
Justify::SpaceBetween => AlignContent::SPACE_BETWEEN,
Justify::SpaceAround => AlignContent::SPACE_AROUND,
Justify::SpaceEvenly => AlignContent::SPACE_EVENLY,
}
}
impl CoreStyle for NodeStyle {
type CustomIdent = String;
fn box_generation_mode(&self) -> BoxGenerationMode {
match self.display {
Display::Flex => BoxGenerationMode::Normal,
Display::None => BoxGenerationMode::None,
}
}
fn overflow(&self) -> Point<taffy::Overflow> {
let overflow = match self.overflow {
Overflow::Visible => taffy::Overflow::Visible,
Overflow::Hidden => taffy::Overflow::Hidden,
Overflow::Scroll => taffy::Overflow::Scroll,
};
Point {
x: overflow,
y: overflow,
}
}
fn position(&self) -> taffy::Position {
match self.position {
Position::Relative => taffy::Position::Relative,
Position::Absolute => taffy::Position::Absolute,
}
}
fn inset(&self) -> Rect<LengthPercentageAuto> {
self.inset.to_rect(length_percentage_auto)
}
fn size(&self) -> Size<Dimension> {
Size {
width: dimension(self.width),
height: dimension(self.height),
}
}
fn min_size(&self) -> Size<LengthPercentageAuto> {
Size {
width: length_percentage_auto(self.min_width),
height: length_percentage_auto(self.min_height),
}
}
fn max_size(&self) -> Size<LengthPercentageAuto> {
Size {
width: length_percentage_auto(self.max_width),
height: length_percentage_auto(self.max_height),
}
}
fn margin(&self) -> Rect<LengthPercentageAuto> {
self.margin.to_rect(length_percentage_auto)
}
fn padding(&self) -> Rect<LengthPercentage> {
self.padding.to_rect(length_percentage)
}
fn border(&self) -> Rect<LengthPercentage> {
self.border.to_rect(LengthPercentage::length)
}
}
impl FlexboxContainerStyle for NodeStyle {
fn flex_direction(&self) -> taffy::FlexDirection {
match self.flex_direction {
FlexDirection::Row => taffy::FlexDirection::Row,
FlexDirection::Column => taffy::FlexDirection::Column,
FlexDirection::RowReverse => taffy::FlexDirection::RowReverse,
FlexDirection::ColumnReverse => taffy::FlexDirection::ColumnReverse,
}
}
fn flex_wrap(&self) -> taffy::FlexWrap {
match self.flex_wrap {
FlexWrap::NoWrap => taffy::FlexWrap::NoWrap,
FlexWrap::Wrap => taffy::FlexWrap::Wrap,
FlexWrap::WrapReverse => taffy::FlexWrap::WrapReverse,
}
}
fn gap(&self) -> Size<LengthPercentage> {
Size {
width: length_percentage(self.column_gap),
height: length_percentage(self.row_gap),
}
}
fn align_items(&self) -> Option<AlignItems> {
self.align_items.map(align_items)
}
fn justify_content(&self) -> Option<AlignContent> {
self.justify_content.map(justify_content)
}
}
impl FlexboxItemStyle for NodeStyle {
fn flex_basis(&self) -> Dimension {
dimension(self.flex_basis)
}
fn flex_grow(&self) -> f32 {
self.flex_grow
}
fn flex_shrink(&self) -> f32 {
self.flex_shrink
}
fn align_self(&self) -> Option<AlignItems> {
self.align_self.map(align_items)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::hash::DefaultHasher;
fn layout_hash(style: &NodeStyle) -> u64 {
let mut hasher = DefaultHasher::new();
style.layout_hash(&mut hasher);
hasher.finish()
}
#[test]
fn the_layout_hash_sees_layout_fields_and_ignores_paint_fields() {
let base = NodeStyle::DEFAULT;
let painted = NodeStyle {
background: [1.0, 0.0, 0.0, 1.0],
border_color: [0.0, 1.0, 0.0, 1.0],
radii: CornerRadii::uniform(4.0),
color: [0.5; 4],
outline_width: 2.0,
outline_color: [1.0; 4],
outline_offset: 1.0,
background_image: Some(ImageName::new("x")),
border_image: BorderImage {
source: Some(ImageName::new("y")),
slice: Edges::all(4.0),
fill: true,
width: Edges::all(BorderImageWidth::Px(3.0)),
},
nav_up: NavTarget::None,
nav_left: NavTarget::Id(NavId::new("x")),
nav_wrap: NavWrap::Both,
text_overflow: TextOverflow::Ellipsis,
..base
};
assert_eq!(layout_hash(&base), layout_hash(&painted));
let moved: [NodeStyle; 8] = [
NodeStyle {
width: LengthAuto::Px(10.0),
..base
},
NodeStyle {
padding: Edges {
left: Length::Px(1.0),
..base.padding
},
..base
},
NodeStyle {
inset: Edges {
bottom: LengthAuto::Percent(0.5),
..base.inset
},
..base
},
NodeStyle {
border: Edges {
right: 2.0,
..base.border
},
..base
},
NodeStyle {
display: Display::None,
..base
},
NodeStyle {
align_self: Some(Align::Center),
..base
},
NodeStyle {
row_gap: Length::Percent(0.1),
..base
},
NodeStyle {
flex_shrink: 0.0,
..base
},
];
for style in moved {
assert_ne!(layout_hash(&base), layout_hash(&style), "{style:?}");
}
}
#[test]
fn edges_map_onto_the_sides_of_the_same_name() {
let style = NodeStyle {
border: Edges {
top: 1.0,
right: 2.0,
bottom: 3.0,
left: 4.0,
},
..NodeStyle::DEFAULT
};
let rect = CoreStyle::border(&style);
assert_eq!(
[rect.top, rect.right, rect.bottom, rect.left],
[1.0, 2.0, 3.0, 4.0].map(LengthPercentage::length)
);
}
}