use crate::fasthash::{fast_map, fast_set, FastMap, FastSet};
use crate::color::Color;
use crate::event::{EventResult, UiEvent};
use crate::geometry::{Edges, Rect, Size};
use crate::widget::{
Align, Axis, Constraints, Dimension, EventCtx, FlexItem, Justify, RenderCtx, Role, Semantics,
TextMetrics, Widget,
};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LayoutStats {
pub measured: u32,
pub arranged: u32,
pub skipped: bool,
}
#[derive(Clone, Copy, Debug)]
struct Entry {
constraints: Constraints,
version: u64,
size: Size,
}
pub fn id_key(id: &str) -> u64 {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for b in id.as_bytes() {
hash ^= *b as u64;
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
hash
}
pub(crate) fn key_of(node: &dyn crate::widget::Widget) -> u64 {
let id_key = id_key(node.id());
match node.cache_key() {
Some(k) => {
debug_assert_eq!(
k,
id_key,
"Widget::cache_key() 必须等于 id_key(id())(id = {:?}):它只能当作 id 键的\
预算缓存,不能当作自定义键。自定义键会让按 id 的查询(rect_of/invalidate)\
与按节点的查询(measure/rebuild_indices)指向不同的桶。",
node.id()
);
k
}
None => id_key,
}
}
pub struct LayoutCache {
entries: FastMap<u64, Entry>,
dirty: FastSet<u64>,
parents: FastMap<u64, u64>,
stack: Vec<u64>,
stats: LayoutStats,
}
impl Default for LayoutCache {
fn default() -> Self {
Self::new()
}
}
impl LayoutCache {
pub fn new() -> Self {
Self {
entries: fast_map(),
dirty: fast_set(),
parents: fast_map(),
stack: Vec::new(),
stats: LayoutStats::default(),
}
}
pub fn stats(&self) -> LayoutStats {
self.stats
}
pub fn mark_dirty(&mut self, id: &str) {
let mut cursor = Some(id_key(id));
let mut guard = 0;
while let Some(current) = cursor {
if !self.dirty.insert(current) {
break; }
cursor = self.parents.get(¤t).copied();
guard += 1;
if guard > 4096 {
break; }
}
}
pub fn mark_all_dirty(&mut self) {
self.entries.clear();
self.dirty.clear();
}
pub fn clear(&mut self) {
self.entries.clear();
self.dirty.clear();
self.parents.clear();
}
pub fn forget(&mut self, key: u64) {
self.entries.remove(&key);
self.dirty.remove(&key);
self.parents.remove(&key);
}
pub fn last_size(&self, id: &str) -> Option<Size> {
self.entries.get(&id_key(id)).map(|e| e.size)
}
pub fn is_dirty(&self, id: &str) -> bool {
self.dirty.contains(&id_key(id))
}
fn is_fresh(&self, id: &str, constraints: Constraints, version: u64) -> bool {
self.is_fresh_by_key(id_key(id), constraints, version)
}
fn is_fresh_by_key(&self, key: u64, constraints: Constraints, version: u64) -> bool {
if self.dirty.contains(&key) {
return false;
}
match self.entries.get(&key) {
Some(entry) => entry.version == version && entry.constraints == constraints,
None => false,
}
}
pub fn measure(
&mut self,
widget: &mut dyn Widget,
metrics: &dyn TextMetrics,
constraints: Constraints,
) -> Size {
let key = key_of(widget);
let version = widget.layout_version();
if self.is_fresh_by_key(key, constraints, version) {
return self.entries.get(&key).map(|e| e.size).unwrap_or(Size::ZERO);
}
if let Some(parent) = self.stack.last().copied() {
self.parents.insert(key, parent);
}
self.stats.measured += 1;
self.stack.push(key);
let size = widget.measure(metrics, constraints, self);
self.stack.pop();
self.entries.insert(
key,
Entry {
constraints,
version,
size,
},
);
self.dirty.remove(&key);
size
}
pub fn size_for_arrange(
&mut self,
widget: &mut dyn Widget,
metrics: &dyn TextMetrics,
constraints: Constraints,
) -> Size {
if let Some(size) = self.last_size(widget.id()) {
return size;
}
self.measure(widget, metrics, constraints)
}
fn begin_layout(&mut self) {
self.stats = LayoutStats::default();
}
fn finish_layout(&mut self) {
self.dirty.clear();
}
}
pub fn flex_measure(
axis: Axis,
padding: Edges,
gap: f32,
children: &mut [Box<dyn Widget>],
metrics: &dyn TextMetrics,
constraints: Constraints,
cache: &mut LayoutCache,
) -> Size {
let mut measured = Vec::new();
flex_measure_into(
axis,
padding,
gap,
children,
metrics,
constraints,
cache,
&mut measured,
)
}
fn clamp_axis(v: f32, min: Dimension, max: Dimension, avail: f32) -> f32 {
let floor = min.resolve(avail, 0.0).max(0.0);
let ceil = match max {
Dimension::Auto => f32::INFINITY,
d => d.resolve(avail, v),
};
let mut out = v.max(floor).min(ceil);
if !out.is_finite() {
out = v;
}
if avail.is_finite() {
out = out.min(avail.max(0.0));
}
out
}
fn clamp_pair(
axis: Axis,
item: FlexItem,
main_avail: f32,
cross_avail: f32,
main: f32,
cross: f32,
) -> (f32, f32) {
let (mw, mh, cw, ch) = match axis {
Axis::Horizontal => (
item.min_width,
item.max_width,
item.min_height,
item.max_height,
),
Axis::Vertical => (
item.min_height,
item.max_height,
item.min_width,
item.max_width,
),
};
(
clamp_axis(main, mw, mh, main_avail),
clamp_axis(cross, cw, ch, cross_avail),
)
}
#[allow(clippy::too_many_arguments)] pub fn flex_measure_into(
axis: Axis,
padding: Edges,
gap: f32,
children: &mut [Box<dyn Widget>],
metrics: &dyn TextMetrics,
constraints: Constraints,
cache: &mut LayoutCache,
measured: &mut Vec<(Size, FlexItem)>,
) -> Size {
let scale = metrics.scale();
measured.clear();
let inner_max = Size::new(
if constraints.is_unbounded(Axis::Horizontal) {
f32::INFINITY
} else {
(constraints.max.w - padding.horizontal()).max(0.0)
},
if constraints.is_unbounded(Axis::Vertical) {
f32::INFINITY
} else {
(constraints.max.h - padding.vertical()).max(0.0)
},
);
let mut main_total = 0.0f32;
let mut cross_max = 0.0f32;
let mut visible = 0usize;
for child in children.iter_mut() {
let item = child.flex();
let size = cache.measure(child.as_mut(), metrics, Constraints::loose(inner_max));
let _ = &size;
let (main_dim, cross_dim) = match axis {
Axis::Horizontal => (item.width, item.height),
Axis::Vertical => (item.height, item.width),
};
let (main_content, cross_content) = match axis {
Axis::Horizontal => (size.w, size.h),
Axis::Vertical => (size.h, size.w),
};
let main = match main_dim {
Dimension::Px(v) => v * scale,
Dimension::Percent(p) => {
let base = match axis {
Axis::Horizontal => inner_max.w,
Axis::Vertical => inner_max.h,
};
if base.is_finite() {
base * (p / 100.0)
} else {
main_content }
}
Dimension::Flex(_) | Dimension::Auto => main_content,
};
let cross = match cross_dim {
Dimension::Px(v) => v * scale,
Dimension::Percent(p) => {
let base = match axis {
Axis::Horizontal => inner_max.h,
Axis::Vertical => inner_max.w,
};
if base.is_finite() {
base * (p / 100.0)
} else {
cross_content
}
}
_ => cross_content,
};
let (main, cross) = clamp_pair(
axis,
item,
match axis {
Axis::Horizontal => inner_max.w,
Axis::Vertical => inner_max.h,
},
match axis {
Axis::Horizontal => inner_max.h,
Axis::Vertical => inner_max.w,
},
main,
cross,
);
main_total += main;
cross_max = cross_max.max(cross);
visible += 1;
measured.push((
match axis {
Axis::Horizontal => Size::new(main, cross),
Axis::Vertical => Size::new(cross, main),
},
item,
));
}
if visible > 1 {
main_total += gap * (visible - 1) as f32;
}
let (w, h) = match axis {
Axis::Horizontal => (
main_total + padding.horizontal(),
cross_max + padding.vertical(),
),
Axis::Vertical => (
cross_max + padding.horizontal(),
main_total + padding.vertical(),
),
};
constraints.constrain(Size::new(w, h))
}
pub fn flex_arrange(
axis: Axis,
padding: Edges,
gap: f32,
children: &mut [Box<dyn Widget>],
rect: Rect,
metrics: &dyn TextMetrics,
cache: &mut LayoutCache,
) {
flex_arrange_with(
axis,
padding,
gap,
Align::Stretch,
Justify::Start,
children,
rect,
metrics,
cache,
&[],
);
}
#[allow(clippy::too_many_arguments)] pub fn flex_arrange_with(
axis: Axis,
padding: Edges,
gap: f32,
align: Align,
justify: Justify,
children: &mut [Box<dyn Widget>],
rect: Rect,
metrics: &dyn TextMetrics,
cache: &mut LayoutCache,
measured: &[(Size, FlexItem)],
) {
let _ = metrics;
if children.is_empty() {
return;
}
let inner = rect.inset(padding);
let (main_avail, cross_avail) = match axis {
Axis::Horizontal => (inner.w, inner.h),
Axis::Vertical => (inner.h, inner.w),
};
let mut fixed_total = 0.0f32;
let mut flex_total = 0.0f32;
let mut sizes: Vec<Size> = Vec::with_capacity(children.len());
let reuse = measured.len() == children.len();
for (idx, child) in children.iter_mut().enumerate() {
let (size, item) = if reuse {
measured[idx]
} else {
(
cache.size_for_arrange(child.as_mut(), metrics, Constraints::loose(inner.size())),
child.flex(),
)
};
let main_dim = match axis {
Axis::Horizontal => item.width,
Axis::Vertical => item.height,
};
sizes.push(size);
if let Some(factor) = main_dim.flex_factor() {
flex_total += factor;
} else {
fixed_total += match axis {
Axis::Horizontal => size.w,
Axis::Vertical => size.h,
};
}
}
let gaps = if children.len() > 1 {
gap * (children.len() - 1) as f32
} else {
0.0
};
let leftover = (main_avail - fixed_total - gaps).max(0.0);
let n = children.len() as f32;
let main_used = fixed_total + if flex_total > 0.0 { leftover } else { 0.0 } + gaps;
let free = (main_avail - main_used).max(0.0);
let free = if free.is_finite() { free } else { 0.0 };
let (mut cursor, gap_extra) = match justify {
Justify::Start => (0.0, 0.0),
Justify::Center => (free * 0.5, 0.0),
Justify::End => (free, 0.0),
Justify::SpaceBetween => (0.0, if n > 1.0 { free / (n - 1.0) } else { 0.0 }),
Justify::SpaceAround => (free / n * 0.5, free / n),
};
for (idx, child) in children.iter_mut().enumerate() {
let item = if reuse { measured[idx].1 } else { child.flex() };
let size = sizes[idx];
let (main_dim, cross_dim) = match axis {
Axis::Horizontal => (item.width, item.height),
Axis::Vertical => (item.height, item.width),
};
let main = match main_dim.flex_factor() {
Some(factor) if flex_total > 0.0 => leftover * factor / flex_total,
_ => match axis {
Axis::Horizontal => size.w,
Axis::Vertical => size.h,
},
};
let content_cross = match axis {
Axis::Horizontal => size.h,
Axis::Vertical => size.w,
};
let cross = match cross_dim {
Dimension::Px(_) | Dimension::Percent(_) => content_cross,
_ => match align {
Align::Stretch => cross_avail,
_ => content_cross,
},
};
let cross = if cross.is_finite() { cross } else { 0.0 };
let (main, cross) = clamp_pair(axis, item, main_avail, cross_avail, main, cross);
let cross = cross.min(cross_avail);
let cross_off = match align {
Align::Start | Align::Stretch => 0.0,
Align::Center => ((cross_avail - cross) * 0.5).max(0.0),
Align::End => (cross_avail - cross).max(0.0),
};
let child_rect = match axis {
Axis::Horizontal => Rect::new(inner.x + cursor, inner.y + cross_off, main, cross),
Axis::Vertical => Rect::new(inner.x + cross_off, inner.y + cursor, cross, main),
};
cache.stats.arranged += 1;
child.arrange(child_rect, metrics, cache);
cursor += main + gap + gap_extra;
}
}
pub fn content_rect(viewport: Rect, content: Size, offset: f32) -> Rect {
let height = if content.h.is_finite() {
content.h
} else {
viewport.h
};
let offset = if offset.is_finite() { offset } else { 0.0 };
Rect::new(viewport.x, viewport.y - offset, viewport.w, height)
}
pub struct Flex {
id: String,
axis: Axis,
padding: Edges,
scaled_padding: Option<Edges>,
fixed_padding: Option<Edges>,
gap: f32,
scaled_gap: Option<f32>,
fixed_gap: Option<f32>,
wrap: bool,
wrap_lines: Vec<Vec<usize>>,
wrap_line_heights: Vec<f32>,
align_items: Align,
justify_content: Justify,
background: Option<Color>,
radius: f32,
border: Option<(Color, f32)>,
children: Vec<Box<dyn Widget>>,
rect: Rect,
item: FlexItem,
key: u64,
measured: Vec<(Size, FlexItem)>,
}
impl Flex {
pub fn new(id: impl Into<String>, axis: Axis) -> Self {
let id = id.into();
let key = id_key(&id);
Self {
id,
key,
axis,
padding: Edges::ZERO,
scaled_padding: None,
fixed_padding: None,
gap: 0.0,
scaled_gap: None,
fixed_gap: None,
wrap: false,
wrap_lines: Vec::new(),
wrap_line_heights: Vec::new(),
align_items: Align::Stretch,
justify_content: Justify::Start,
background: None,
radius: 0.0,
border: None,
children: Vec::new(),
rect: Rect::ZERO,
item: FlexItem::default(),
measured: Vec::new(),
}
}
pub fn row(id: impl Into<String>) -> Self {
Self::new(id, Axis::Horizontal)
}
pub fn column(id: impl Into<String>) -> Self {
Self::new(id, Axis::Vertical)
}
pub fn padding(mut self, padding: Edges) -> Self {
self.padding = padding;
self.scaled_padding = None;
self.fixed_padding = None;
self
}
pub fn padding_fixed(mut self, padding: Edges) -> Self {
self.fixed_padding = Some(padding);
self.scaled_padding = None;
self.padding = Edges::ZERO;
self
}
pub fn gap(mut self, gap: f32) -> Self {
self.gap = gap;
self.scaled_gap = None;
self.fixed_gap = None;
self
}
pub fn gap_fixed(mut self, gap: f32) -> Self {
self.fixed_gap = Some(gap);
self.scaled_gap = None;
self.gap = 0.0;
self
}
pub fn gap_scaled(mut self, base: f32) -> Self {
self.scaled_gap = Some(base);
self.fixed_gap = None;
self
}
pub fn padding_scaled(mut self, base: Edges) -> Self {
self.scaled_padding = Some(base);
self.fixed_padding = None;
self
}
fn padding_for(&self, scale: f32) -> Edges {
if let Some(fixed) = self.fixed_padding {
return fixed;
}
let base = self.scaled_padding.unwrap_or(self.padding);
Edges {
left: base.left * scale,
top: base.top * scale,
right: base.right * scale,
bottom: base.bottom * scale,
}
}
pub fn wrap(mut self, enabled: bool) -> Self {
self.wrap = enabled;
self
}
fn gap_for(&self, scale: f32) -> f32 {
if let Some(fixed) = self.fixed_gap {
return fixed;
}
self.scaled_gap.unwrap_or(self.gap) * scale
}
fn wrap_lines_of(
axis: Axis,
measured: &[(Size, FlexItem)],
main_max: f32,
gap: f32,
) -> (Vec<Vec<usize>>, Vec<f32>, f32, f32) {
let mut lines: Vec<Vec<usize>> = Vec::new();
let mut heights: Vec<f32> = Vec::new();
let mut cur: Vec<usize> = Vec::new();
let mut cur_main = 0.0f32;
let mut cur_cross = 0.0f32;
let mut max_main = 0.0f32;
for (i, (size, _item)) in measured.iter().enumerate() {
let (m, c) = match axis {
Axis::Horizontal => (size.w, size.h),
Axis::Vertical => (size.h, size.w),
};
let extra = if cur.is_empty() { 0.0 } else { gap };
if !cur.is_empty() && cur_main + extra + m > main_max {
max_main = max_main.max(cur_main);
lines.push(std::mem::take(&mut cur));
heights.push(cur_cross);
cur_main = 0.0;
cur_cross = 0.0;
}
cur_main += if cur.is_empty() { m } else { gap + m };
cur_cross = cur_cross.max(c);
cur.push(i);
}
if !cur.is_empty() {
max_main = max_main.max(cur_main);
lines.push(cur);
heights.push(cur_cross);
}
let cross_total =
heights.iter().sum::<f32>() + gap * (heights.len().saturating_sub(1)) as f32;
(lines, heights, max_main, cross_total)
}
fn wrap_measure(
&mut self,
metrics: &dyn TextMetrics,
constraints: Constraints,
cache: &mut LayoutCache,
) -> Size {
let scale = metrics.scale();
let padding = self.padding_for(scale);
let gap = self.gap_for(scale);
let inner_max = Size::new(
if constraints.is_unbounded(Axis::Horizontal) {
f32::INFINITY
} else {
(constraints.max.w - padding.horizontal()).max(0.0)
},
if constraints.is_unbounded(Axis::Vertical) {
f32::INFINITY
} else {
(constraints.max.h - padding.vertical()).max(0.0)
},
);
let main_max = match self.axis {
Axis::Horizontal => inner_max.w,
Axis::Vertical => inner_max.h,
};
self.measured.clear();
for child in self.children.iter_mut() {
let item = child.flex();
let size = cache.measure(child.as_mut(), metrics, Constraints::loose(inner_max));
self.measured.push((size, item));
}
let (lines, heights, main_total, cross_total) =
Self::wrap_lines_of(self.axis, &self.measured, main_max, gap);
self.wrap_lines = lines;
self.wrap_line_heights = heights;
match self.axis {
Axis::Horizontal => constraints.constrain(Size::new(
main_total + padding.horizontal(),
cross_total + padding.vertical(),
)),
Axis::Vertical => constraints.constrain(Size::new(
cross_total + padding.horizontal(),
main_total + padding.vertical(),
)),
}
}
fn wrap_arrange(&mut self, rect: Rect, metrics: &dyn TextMetrics, cache: &mut LayoutCache) {
let scale = metrics.scale();
let padding = self.padding_for(scale);
let gap = self.gap_for(scale);
let inner = rect.inset(padding);
let main_max = match self.axis {
Axis::Horizontal => inner.w,
Axis::Vertical => inner.h,
};
let (lines, heights, _main_total, _cross_total) =
Self::wrap_lines_of(self.axis, &self.measured, main_max, gap);
let measured_lines = self.wrap_lines.len();
debug_assert!(
measured_lines == 0 || measured_lines == lines.len(),
"wrap: measure 分行数 {} 与 arrange 分行数 {} 不同(宽度变了)",
measured_lines,
lines.len()
);
let line_ranges: Vec<(usize, usize, f32)> = lines
.iter()
.zip(heights.iter())
.map(|(l, h)| {
let start = *l.first().unwrap_or(&0);
let end = *l.last().unwrap_or(&0) + 1;
(start, end, *h)
})
.collect();
self.wrap_lines = lines;
self.wrap_line_heights = heights;
let Self {
children,
measured,
align_items,
justify_content,
..
} = self;
let mut cursor = match self.axis {
Axis::Horizontal => inner.y,
Axis::Vertical => inner.x,
};
for (start, end, h) in line_ranges {
let sub = match self.axis {
Axis::Horizontal => Rect::new(inner.x, cursor, inner.w, h),
Axis::Vertical => Rect::new(cursor, inner.y, h, inner.h),
};
let line_measured: Vec<(Size, FlexItem)> = measured[start..end]
.iter()
.map(|(size, item)| {
let main_flex = match self.axis {
Axis::Horizontal => item.width.flex_factor(),
Axis::Vertical => item.height.flex_factor(),
};
let mut item = *item;
if main_flex.is_some() {
let px = match self.axis {
Axis::Horizontal => size.w,
Axis::Vertical => size.h,
};
match self.axis {
Axis::Horizontal => item.width = crate::Dimension::Px(px),
Axis::Vertical => item.height = crate::Dimension::Px(px),
}
}
(*size, item)
})
.collect();
flex_arrange_with(
self.axis,
Edges::ZERO,
gap,
*align_items,
*justify_content,
&mut children[start..end],
sub,
metrics,
cache,
&line_measured,
);
cursor += h + gap;
}
}
pub fn align(mut self, align: Align) -> Self {
self.align_items = align;
self
}
pub fn justify(mut self, justify: Justify) -> Self {
self.justify_content = justify;
self
}
pub fn background(mut self, color: Color) -> Self {
self.background = Some(color);
self
}
pub fn radius(mut self, radius: f32) -> Self {
self.radius = radius.max(0.0);
self
}
pub fn border(mut self, color: Color, width: f32) -> Self {
self.border = Some((color, width.max(0.0)));
self
}
pub fn flex_item(mut self, item: FlexItem) -> Self {
self.item = item;
self
}
pub fn push(mut self, child: Box<dyn Widget>) -> Self {
self.children.push(child);
self
}
pub fn push_boxed(&mut self, child: Box<dyn Widget>) {
self.children.push(child);
}
}
impl Widget for Flex {
fn id(&self) -> &str {
&self.id
}
fn cache_key(&self) -> Option<u64> {
Some(self.key)
}
fn role(&self) -> Role {
Role::PANEL
}
fn flex(&self) -> FlexItem {
self.item
}
fn children(&self) -> &[Box<dyn Widget>] {
&self.children
}
fn children_mut(&mut self) -> Option<&mut Vec<Box<dyn Widget>>> {
Some(&mut self.children)
}
fn measure(
&mut self,
metrics: &dyn TextMetrics,
constraints: Constraints,
cache: &mut LayoutCache,
) -> Size {
if self.wrap {
return self.wrap_measure(metrics, constraints, cache);
}
flex_measure_into(
self.axis,
self.padding_for(metrics.scale()),
self.gap_for(metrics.scale()),
&mut self.children,
metrics,
constraints,
cache,
&mut self.measured,
)
}
fn arrange(&mut self, rect: Rect, metrics: &dyn TextMetrics, cache: &mut LayoutCache) {
self.rect = rect;
if self.wrap {
self.wrap_arrange(rect, metrics, cache);
return;
}
flex_arrange_with(
self.axis,
self.padding_for(metrics.scale()),
self.gap_for(metrics.scale()),
self.align_items,
self.justify_content,
&mut self.children,
rect,
metrics,
cache,
&self.measured,
);
}
fn rect(&self) -> Rect {
self.rect
}
fn padding(&self) -> Edges {
self.padding
}
fn event(&mut self, _ctx: &mut EventCtx, _event: &UiEvent) -> EventResult {
EventResult::Ignored
}
fn render(&mut self, ctx: &mut dyn RenderCtx) {
let plain = self.radius <= 0.0 && self.border.is_none();
if let Some(bg) = self.background {
if plain {
ctx.fill_rect(self.rect, bg);
} else {
ctx.fill_round_rect(self.rect, bg, self.radius);
}
}
if let Some((color, width)) = self.border {
if width > 0.0 {
ctx.stroke_round_rect(self.rect, color, width, self.radius);
}
}
}
fn semantics(&self) -> Semantics {
Semantics::default().exposed(true)
}
}
pub fn layout_tree(
root: &mut dyn Widget,
viewport: Size,
metrics: &dyn TextMetrics,
cache: &mut LayoutCache,
) -> LayoutStats {
cache.begin_layout();
cache.stack.clear();
let tight = Constraints::tight(viewport);
if cache.is_fresh(root.id(), tight, root.layout_version()) {
cache.stats.skipped = true;
return cache.stats;
}
let _ = cache.measure(root, metrics, tight);
cache.stats.arranged += 1;
root.arrange(Rect::from_size(viewport), metrics, cache);
cache.finish_layout();
cache.stats
}
pub struct Stack {
id: String,
children: Vec<Box<dyn Widget>>,
rect: Rect,
item: FlexItem,
key: u64,
}
impl Stack {
pub fn new(id: impl Into<String>) -> Self {
let id: String = id.into();
let key = id_key(&id);
Self {
id,
key,
children: Vec::new(),
rect: Rect::ZERO,
item: FlexItem::default(),
}
}
pub fn push(mut self, child: Box<dyn Widget>) -> Self {
self.children.push(child);
self
}
pub fn flex_item(mut self, item: FlexItem) -> Self {
self.item = item;
self
}
}
impl Widget for Stack {
fn id(&self) -> &str {
&self.id
}
fn cache_key(&self) -> Option<u64> {
Some(self.key)
}
fn role(&self) -> Role {
Role::PANEL
}
fn flex(&self) -> FlexItem {
self.item
}
fn children(&self) -> &[Box<dyn Widget>] {
&self.children
}
fn children_mut(&mut self) -> Option<&mut Vec<Box<dyn Widget>>> {
Some(&mut self.children)
}
fn measure(&mut self, m: &dyn TextMetrics, c: Constraints, cache: &mut LayoutCache) -> Size {
let mut content_w = 0.0f32;
let mut content_h = 0.0f32;
for child in self.children.iter_mut() {
let s = cache.measure(child.as_mut(), m, c);
content_w = content_w.max(s.w);
content_h = content_h.max(s.h);
}
let w = if c.max.w.is_finite() {
c.max.w
} else {
content_w
};
let h = if c.max.h.is_finite() {
c.max.h
} else {
content_h
};
c.constrain(Size::new(w, h))
}
fn arrange(&mut self, rect: Rect, m: &dyn TextMetrics, cache: &mut LayoutCache) {
self.rect = rect;
for child in self.children.iter_mut() {
child.arrange(rect, m, cache);
}
}
fn rect(&self) -> Rect {
self.rect
}
fn event(&mut self, _ctx: &mut EventCtx, _event: &UiEvent) -> EventResult {
EventResult::Ignored
}
fn render(&mut self, _ctx: &mut dyn RenderCtx) {}
fn semantics(&self) -> Semantics {
Semantics::default().exposed(true)
}
}
#[cfg(test)]
mod align_justify_tests {
use super::*;
use crate::widget::{Constraints, Widget};
use crate::{Size, TextStyle};
struct Box1 {
id: &'static str,
size: Size,
rect: Rect,
item: FlexItem,
}
impl Box1 {
fn new(id: &'static str, w: f32, h: f32) -> Self {
Self {
id,
size: Size::new(w, h),
rect: Rect::ZERO,
item: FlexItem::default(),
}
}
fn with_item(mut self, item: FlexItem) -> Self {
self.item = item;
self
}
}
impl Widget for Box1 {
fn id(&self) -> &str {
self.id
}
fn measure(
&mut self,
_m: &dyn TextMetrics,
c: Constraints,
_cache: &mut LayoutCache,
) -> Size {
c.constrain(self.size)
}
fn arrange(&mut self, rect: Rect, _m: &dyn TextMetrics, _cache: &mut LayoutCache) {
self.rect = rect;
}
fn rect(&self) -> Rect {
self.rect
}
fn flex(&self) -> FlexItem {
self.item
}
fn event(&mut self, _c: &mut EventCtx, _e: &UiEvent) -> EventResult {
EventResult::Ignored
}
fn children(&self) -> &[Box<dyn Widget>] {
&[]
}
fn render(&mut self, _ctx: &mut dyn RenderCtx) {}
fn semantics(&self) -> Semantics {
Semantics::default()
}
}
struct Dummy;
impl TextMetrics for Dummy {
fn measure_text(&self, text: &str, _s: &TextStyle) -> Size {
Size::new(text.chars().count() as f32 * 8.0, 16.0)
}
fn line_height(&self, _s: &TextStyle) -> f32 {
16.0
}
fn scale(&self) -> f32 {
1.0
}
}
fn layout(flex: &mut Flex, w: f32, h: f32) -> Vec<Rect> {
let mut cache = LayoutCache::new();
let m = Dummy;
let _ = cache.measure(flex, &m, Constraints::tight(Size::new(w, h)));
flex.arrange(Rect::from_size(Size::new(w, h)), &m, &mut cache);
let mut out = Vec::new();
walk(flex, &mut out);
out
}
fn walk(node: &mut dyn Widget, out: &mut Vec<Rect>) {
for c in node.children_mut().unwrap_or(&mut Vec::new()).iter_mut() {
out.push(c.rect());
walk(c.as_mut(), out);
}
}
#[test]
fn align_center_offsets_each_child() {
let mut flex = Flex::row("row")
.align(Align::Center)
.push(Box::new(Box1::new("a", 10.0, 10.0)))
.push(Box::new(Box1::new("b", 10.0, 20.0)))
.push(Box::new(Box1::new("c", 10.0, 30.0)));
let rects = layout(&mut flex, 100.0, 100.0);
assert_eq!(rects[0].y, 45.0, "高 10 居中 → y=45");
assert_eq!(rects[1].y, 40.0, "高 20 居中 → y=40");
assert_eq!(rects[2].y, 35.0, "高 30 居中 → y=35");
assert_eq!(rects[0].h, 10.0);
assert_eq!(rects[2].h, 30.0);
}
#[test]
fn align_stretch_keeps_old_behaviour() {
let mut flex = Flex::row("row")
.push(Box::new(Box1::new("a", 10.0, 10.0)))
.push(Box::new(Box1::new("b", 10.0, 20.0)));
let rects = layout(&mut flex, 100.0, 100.0);
assert_eq!(rects[0].y, 0.0);
assert_eq!(rects[0].h, 100.0, "Stretch: 交叉轴拉满");
assert_eq!(rects[1].x, 10.0, "主轴从起点紧排");
}
#[test]
fn justify_space_between_spreads_free_space() {
let mut flex = Flex::row("row")
.justify(Justify::SpaceBetween)
.push(Box::new(Box1::new("a", 20.0, 10.0)))
.push(Box::new(Box1::new("b", 20.0, 10.0)))
.push(Box::new(Box1::new("c", 20.0, 10.0)));
let rects = layout(&mut flex, 100.0, 100.0);
assert_eq!(rects[0].x, 0.0);
assert_eq!(rects[1].x, 40.0, "20 + gap(0) + extra(20)");
assert_eq!(rects[2].x, 80.0);
}
#[test]
fn justify_space_around_puts_half_gap_at_ends() {
let mut flex = Flex::row("row")
.justify(Justify::SpaceAround)
.push(Box::new(Box1::new("a", 20.0, 10.0)))
.push(Box::new(Box1::new("b", 20.0, 10.0)));
let rects = layout(&mut flex, 100.0, 100.0);
assert_eq!(rects[0].x, 15.0, "首端留半份间距");
assert_eq!(rects[1].x, 65.0, "15 + 20 + 30");
}
#[test]
fn align_center_with_justify_center_centers_child() {
let mut flex = Flex::row("row")
.align(Align::Center)
.justify(Justify::Center)
.push(Box::new(Box1::new("only", 20.0, 20.0)));
let rects = layout(&mut flex, 100.0, 100.0);
assert_eq!(rects[0].x, 40.0);
assert_eq!(rects[0].y, 40.0);
}
#[test]
fn min_width_applies() {
let mut flex = Flex::row("row").push(Box::new(
Box1::new("a", 20.0, 10.0).with_item(FlexItem::width(20.0).min_width(100.0)),
));
let rects = layout(&mut flex, 300.0, 100.0);
assert_eq!(rects[0].w, 100.0, "min_width 应把 20 抬到 100");
}
#[test]
fn max_width_applies() {
let mut flex = Flex::row("row").push(Box::new(
Box1::new("a", 200.0, 10.0).with_item(FlexItem::width(200.0).max_width(80.0)),
));
let rects = layout(&mut flex, 300.0, 100.0);
assert_eq!(rects[0].w, 80.0, "max_width 应把 200 压到 80");
}
#[test]
fn min_larger_than_available_degrades_to_available() {
let mut flex = Flex::row("row").push(Box::new(
Box1::new("a", 20.0, 10.0).with_item(FlexItem::width(20.0).min_width(100.0)),
));
let rects = layout(&mut flex, 50.0, 100.0);
assert_eq!(
rects[0].w, 50.0,
"min > 可用空间时应 clamp 到可用空间(不溢出父容器)"
);
}
#[test]
fn default_min_max_does_not_change_layout() {
let mut flex = Flex::row("row")
.push(Box::new(Box1::new("a", 30.0, 10.0)))
.push(Box::new(Box1::new("b", 40.0, 10.0)));
let rects = layout(&mut flex, 200.0, 100.0);
assert_eq!(rects[0].w, 30.0);
assert_eq!(rects[1].w, 40.0);
assert_eq!(rects[1].x, 30.0);
}
}
#[cfg(test)]
mod gap_scaled_tests {
use super::*;
use crate::widget::Constraints;
use crate::{Size, TextStyle};
struct ScaledMetrics(f32);
impl TextMetrics for ScaledMetrics {
fn measure_text(&self, text: &str, _s: &TextStyle) -> Size {
Size::new(text.chars().count() as f32 * 8.0, 16.0)
}
fn line_height(&self, _s: &TextStyle) -> f32 {
16.0
}
fn scale(&self) -> f32 {
self.0
}
}
struct Box1 {
id: &'static str,
size: Size,
rect: Rect,
item: FlexItem,
}
impl Box1 {
fn new(id: &'static str, w: f32, h: f32) -> Self {
Self {
id,
size: Size::new(w, h),
rect: Rect::ZERO,
item: FlexItem::default(),
}
}
}
impl Widget for Box1 {
fn id(&self) -> &str {
self.id
}
fn measure(
&mut self,
_m: &dyn TextMetrics,
c: Constraints,
_cache: &mut LayoutCache,
) -> Size {
c.constrain(self.size)
}
fn arrange(&mut self, rect: Rect, _m: &dyn TextMetrics, _cache: &mut LayoutCache) {
self.rect = rect;
}
fn rect(&self) -> Rect {
self.rect
}
fn flex(&self) -> FlexItem {
self.item
}
fn event(&mut self, _c: &mut EventCtx, _e: &UiEvent) -> EventResult {
EventResult::Ignored
}
fn children(&self) -> &[Box<dyn Widget>] {
&[]
}
fn render(&mut self, _ctx: &mut dyn RenderCtx) {}
fn semantics(&self) -> Semantics {
Semantics::default()
}
}
fn layout_with(flex: &mut Flex, scale: f32) -> Vec<Rect> {
let mut cache = LayoutCache::new();
let m = ScaledMetrics(scale);
let _ = cache.measure(flex, &m, Constraints::tight(Size::new(200.0, 100.0)));
flex.arrange(Rect::from_size(Size::new(200.0, 100.0)), &m, &mut cache);
let mut out = Vec::new();
for c in flex.children_mut().unwrap_or(&mut Vec::new()).iter_mut() {
out.push(c.rect());
}
out
}
fn three_boxes(gap_fixed: Option<f32>, gap_scaled: Option<f32>) -> Flex {
let mut f = Flex::row("row");
if let Some(g) = gap_fixed {
f = f.gap(g);
}
if let Some(g) = gap_scaled {
f = f.gap_scaled(g);
}
f.push(Box::new(Box1::new("a", 20.0, 10.0)))
.push(Box::new(Box1::new("b", 20.0, 10.0)))
.push(Box::new(Box1::new("c", 20.0, 10.0)))
}
#[test]
fn gap_scaled_at_scale_one_equals_gap() {
let mut fixed = three_boxes(Some(8.0), None);
let mut scaled = three_boxes(None, Some(8.0));
let rf = layout_with(&mut fixed, 1.0);
let rs = layout_with(&mut scaled, 1.0);
assert_eq!(rf, rs, "scale=1.0 时 gap_scaled(8) 必须等价于 gap(8)");
}
#[test]
fn gap_scaled_follows_scale() {
let mut scaled = three_boxes(None, Some(8.0));
let rs = layout_with(&mut scaled, 1.25);
assert_eq!(rs[1].x, 30.0, "125% 下间距应为 8*1.25=10(而非 8)");
assert_eq!(rs[2].x, 60.0);
}
#[test]
fn padding_scaled_follows_scale() {
let mut f = Flex::column("col")
.padding_scaled(Edges::all(8.0))
.push(Box::new(Box1::new("a", 20.0, 10.0)));
let r = layout_with(&mut f, 1.25);
assert_eq!(r[0].x, 10.0, "左内边距应 8*1.25=10");
assert_eq!(r[0].y, 10.0, "上内边距应 8*1.25=10");
}
}
#[cfg(test)]
mod wrap_tests {
use super::*;
use crate::widget::{Constraints, Widget};
use crate::{Size, TextStyle};
struct Fixed;
impl TextMetrics for Fixed {
fn measure_text(&self, t: &str, _s: &TextStyle) -> Size {
Size::new(t.chars().count() as f32 * 8.0, 16.0)
}
fn line_height(&self, _s: &TextStyle) -> f32 {
16.0
}
fn scale(&self) -> f32 {
1.0
}
}
struct Box1 {
id: &'static str,
size: Size,
rect: Rect,
item: FlexItem,
}
impl Box1 {
fn new(id: &'static str, w: f32, h: f32) -> Self {
Self {
id,
size: Size::new(w, h),
rect: Rect::ZERO,
item: FlexItem::default(),
}
}
}
impl Widget for Box1 {
fn id(&self) -> &str {
self.id
}
fn measure(
&mut self,
_m: &dyn TextMetrics,
c: Constraints,
_cache: &mut LayoutCache,
) -> Size {
c.constrain(self.size)
}
fn arrange(&mut self, rect: Rect, _m: &dyn TextMetrics, _cache: &mut LayoutCache) {
self.rect = rect;
}
fn rect(&self) -> Rect {
self.rect
}
fn flex(&self) -> FlexItem {
self.item
}
fn event(&mut self, _c: &mut EventCtx, _e: &UiEvent) -> EventResult {
EventResult::Ignored
}
fn children(&self) -> &[Box<dyn Widget>] {
&[]
}
fn render(&mut self, _ctx: &mut dyn RenderCtx) {}
fn semantics(&self) -> Semantics {
Semantics::default()
}
}
fn layout(flex: &mut Flex, w: f32, h: f32) -> (Size, Vec<Rect>) {
let mut cache = LayoutCache::new();
let m = Fixed;
let size = cache.measure(flex, &m, Constraints::tight(Size::new(w, h)));
flex.arrange(Rect::from_size(Size::new(w, h)), &m, &mut cache);
let mut out = Vec::new();
for c in flex.children_mut().unwrap_or(&mut Vec::new()).iter_mut() {
out.push(c.rect());
}
(size, out)
}
#[test]
fn default_no_wrap_still_overflows() {
let mut f = Flex::row("r")
.push(Box::new(Box1::new("a", 20.0, 10.0)))
.push(Box::new(Box1::new("b", 20.0, 10.0)))
.push(Box::new(Box1::new("c", 20.0, 10.0)));
let (_size, rects) = layout(&mut f, 50.0, 100.0);
assert_eq!(rects[0].y, rects[1].y, "默认应单行");
assert_eq!(rects[1].y, rects[2].y, "默认应单行");
assert!(rects[2].right() > 50.0, "默认应允许溢出:{rects:?}");
}
#[test]
fn wrap_breaks_into_multiple_lines() {
let mut f = Flex::row("r")
.wrap(true)
.push(Box::new(Box1::new("a", 20.0, 10.0)))
.push(Box::new(Box1::new("b", 20.0, 10.0)))
.push(Box::new(Box1::new("c", 20.0, 10.0)));
let (_size, rects) = layout(&mut f, 50.0, 100.0);
assert_eq!(rects[0].y, rects[1].y, "第一行放 a,b");
assert!(rects[2].y > rects[1].y, "第二行放 c:{rects:?}");
assert_eq!(rects[2].x, 0.0, "新行从左侧重新开始");
}
#[test]
fn wrap_line_height_is_max_of_row() {
let mut f = Flex::row("r")
.wrap(true)
.push(Box::new(Box1::new("a", 15.0, 10.0)))
.push(Box::new(Box1::new("b", 15.0, 20.0)))
.push(Box::new(Box1::new("c", 15.0, 10.0)));
let (_size, rects) = layout(&mut f, 30.0, 100.0);
assert_eq!(rects[0].y, rects[1].y, "a、b 应在同一行:{rects:?}");
assert_eq!(rects[2].y, 20.0, "行高应取该行最大子项高 20:{rects:?}");
}
#[test]
fn wrap_empty_children_no_panic() {
let mut f = Flex::row("r").wrap(true);
let (size, rects) = layout(&mut f, 50.0, 100.0);
assert!(rects.is_empty(), "空子项集不应有 rect");
assert!(
size.w.is_finite() && size.h.is_finite(),
"尺寸必须有限:{size:?}"
);
assert!(f.wrap_lines.is_empty(), "空子项集不五有分行结果");
}
#[test]
fn wrap_with_flex_child_does_not_overflow() {
let mut flex_child = Box1::new("f", 20.0, 10.0);
flex_child.item.width = crate::Dimension::Flex(1.0);
let mut f = Flex::row("r")
.wrap(true)
.push(Box::new(Box1::new("a", 20.0, 10.0)))
.push(Box::new(flex_child))
.push(Box::new(Box1::new("c", 20.0, 10.0)));
let (_size, rects) = layout(&mut f, 50.0, 100.0);
for (i, r) in rects.iter().enumerate() {
assert!(
r.right() <= 50.0 + 0.01,
"子项 {i} 溢出容器:right={} rect={r:?}",
r.right()
);
}
}
#[test]
fn wrap_line_aligns_children_with_center() {
let mut f = Flex::row("r")
.wrap(true)
.align(Align::Center)
.push(Box::new(Box1::new("a", 15.0, 10.0)))
.push(Box::new(Box1::new("b", 15.0, 20.0)))
.push(Box::new(Box1::new("c", 15.0, 10.0)));
let (_size, rects) = layout(&mut f, 30.0, 100.0);
assert_eq!(rects[0].y, 5.0, "a 应在行内垂直居中:{rects:?}");
assert_eq!(rects[1].y, 0.0, "b 撑满行高:{rects:?}");
}
#[test]
fn stack_reports_content_on_unbounded_axis() {
use crate::Axis2;
let mut stack = Stack::new("s").push(Box::new(Box1::new("a", 10.0, 20.0)));
let mut cache = LayoutCache::new();
let m = Fixed;
let c = Constraints {
min: Size::ZERO,
max: Size::new(100.0, f32::INFINITY),
unbounded: Axis2::V,
};
let size = cache.measure(&mut stack, &m, c);
assert_eq!(
(size.w, size.h),
(100.0, 20.0),
"有界轴填满(100),无界轴回退内容(20)"
);
}
#[test]
fn stack_still_fills_bounded_constraints() {
let mut stack = Stack::new("s2").push(Box::new(Box1::new("a", 10.0, 20.0)));
let mut cache = LayoutCache::new();
let size = cache.measure(
&mut stack,
&Fixed,
Constraints::loose(Size::new(100.0, 80.0)),
);
assert_eq!((size.w, size.h), (100.0, 80.0), "有界时填满父级");
}
}