use std::any::Any;
use std::collections::HashMap;
use std::hash::{DefaultHasher, Hash, Hasher};
use web_time::Instant;
use taffy::util::ResolveOrZero;
use taffy::{
AvailableSpace, Dimension, LengthPercentage, LengthPercentageAuto, NodeId, Position, Size,
TaffyTree, compute_leaf_layout,
};
use crate::render::Rect;
use crate::runtime::task::Tasks;
use crate::text::Text;
use crate::widget::{BuildCx, Element, Layer, Placement, Scope, State, Widget};
pub(crate) struct Node<'a> {
pub w: &'a dyn Widget,
pub id: u64,
pub parent: Option<usize>,
pub end: usize,
}
#[derive(Clone, Copy, Default, PartialEq, Debug)]
pub(crate) struct Measured {
pub rect: Rect,
pub content: Size<f32>,
}
#[derive(Clone, Copy, Default)]
pub(crate) struct Placed {
pub rect: Rect,
pub clip: Rect,
pub content: Size<f32>,
pub inert: bool,
}
pub(crate) fn flatten<'a>(
root: &'a Element,
states: &mut HashMap<u64, State>,
tasks: &mut Tasks,
) -> Vec<Node<'a>> {
struct Cx<'s, 'a> {
states: &'s mut HashMap<u64, State>,
tasks: &'s mut Tasks,
provided: Vec<&'a dyn Any>,
out: Vec<Node<'a>>,
}
fn go<'a>(e: &'a Element, parent: Option<usize>, slot: u64, cx: &mut Cx<'_, 'a>) {
let mut h = DefaultHasher::new();
parent.map(|p| cx.out[p].id).hash(&mut h);
e.key.is_some().hash(&mut h);
e.key.unwrap_or(slot).hash(&mut h);
let id = h.finish();
e.widget.expand(&mut BuildCx {
id,
state: cx.states.entry(id).or_default(),
scope: Scope(&cx.provided),
tasks: cx.tasks,
});
let i = cx.out.len();
cx.out.push(Node {
w: e.widget.as_ref(),
id,
parent,
end: 0,
});
let provides = e.widget.provide().map(|v| cx.provided.push(v)).is_some();
for (n, c) in e.widget.children().iter().enumerate() {
go(c, Some(i), n as u64, cx);
}
if provides {
cx.provided.pop();
}
cx.out[i].end = cx.out.len();
}
let mut cx = Cx {
states,
tasks,
provided: Vec::new(),
out: Vec::new(),
};
go(root, None, 0, &mut cx);
cx.out
}
pub(crate) fn walk<'a>(root: &'a Element, ids: &[u64]) -> Vec<Node<'a>> {
fn go<'a>(e: &'a Element, parent: Option<usize>, ids: &[u64], out: &mut Vec<Node<'a>>) {
let i = out.len();
out.push(Node {
w: e.widget.as_ref(),
id: ids[i],
parent,
end: 0,
});
for c in e.widget.children() {
go(c, Some(i), ids, out);
}
out[i].end = out.len();
}
let mut out = Vec::with_capacity(ids.len());
go(root, None, ids, &mut out);
debug_assert_eq!(out.len(), ids.len(), "tree changed without re-flattening");
out
}
pub(crate) fn walk_to<'a>(root: &'a Element, ends: &[usize], at: &[usize]) -> Vec<&'a dyn Widget> {
fn go<'a>(
e: &'a Element,
i: usize,
ends: &[usize],
at: &[usize],
out: &mut Vec<&'a dyn Widget>,
) {
if at.binary_search(&i).is_ok() {
out.push(e.widget.as_ref());
}
let mut j = i + 1;
for c in e.widget.children() {
let end = ends[j];
if at
.get(at.partition_point(|&t| t < j))
.is_some_and(|&t| t < end)
{
go(c, j, ends, at, out);
}
j = end;
}
}
let mut out = Vec::with_capacity(at.len());
if !at.is_empty() {
go(root, 0, ends, at, &mut out);
}
out
}
pub(crate) fn order(nodes: &[Node<'_>]) -> Vec<usize> {
let mut z = vec![0u32; nodes.len()];
for i in 1..nodes.len() {
z[i] = z[nodes[i].parent.unwrap()] + nodes[i].w.layer().is_some() as u32;
}
let mut o: Vec<usize> = (0..nodes.len()).collect();
o.sort_by_key(|&i| z[i]);
o
}
pub(crate) fn children(nodes: &[Node<'_>], i: usize) -> impl Iterator<Item = usize> {
let end = nodes[i].end;
let mut j = i + 1;
std::iter::from_fn(move || {
(j < end).then(|| {
let c = j;
j = nodes[c].end;
c
})
})
}
pub(crate) type Insets = [f32; 4];
struct Entry {
node: NodeId,
measure_key: u64,
seen: u32,
}
pub(crate) struct Layout {
tree: TaffyTree<u64>,
entries: HashMap<u64, Entry>,
spares: Vec<NodeId>,
generation: u32,
}
impl Default for Layout {
fn default() -> Self {
Layout {
tree: TaffyTree::new(),
entries: HashMap::new(),
spares: Vec::new(),
generation: 0,
}
}
}
impl Layout {
pub(crate) fn measure(
&mut self,
nodes: &[Node<'_>],
text: &Text,
viewport: (f32, f32),
insets: Insets,
) -> Vec<Measured> {
self.generation = self.generation.wrapping_add(1);
let generation = self.generation;
let tree = &mut self.tree;
for n in self.spares.drain(..) {
tree.remove(n).unwrap();
}
let mut ids = vec![NodeId::from(0u64); nodes.len()];
let mut index = HashMap::with_capacity(nodes.len());
for i in (0..nodes.len()).rev() {
let mut style = nodes[i].w.style();
if i == 0 {
style.size = Size {
width: Dimension::length(viewport.0),
height: Dimension::length(viewport.1),
};
let add = |p: LengthPercentage, inset: f32| {
LengthPercentage::length(
p.resolve_or_zero(Some(viewport.0), |_, _| 0.0) + inset,
)
};
let p = style.padding;
style.padding = taffy::Rect {
top: add(p.top, insets[0]),
right: add(p.right, insets[1]),
bottom: add(p.bottom, insets[2]),
left: add(p.left, insets[3]),
};
}
if let (Some(l), true) = (nodes[i].w.layer(), i > 0) {
let at = match l {
Layer::Parent | Layer::Screen => [0.0; 4],
Layer::Window => insets,
};
style.position = match l {
Layer::Parent => Position::Absolute,
Layer::Window | Layer::Screen => Position::Fixed,
};
style.inset = taffy::Rect {
top: LengthPercentageAuto::length(at[0]),
right: LengthPercentageAuto::length(at[1]),
bottom: LengthPercentageAuto::length(at[2]),
left: LengthPercentageAuto::length(at[3]),
};
}
if style.position == Position::Static
&& children(nodes, i).any(|c| nodes[c].w.layer() == Some(Layer::Parent))
{
style.position = Position::Relative;
}
let kids: Vec<NodeId> = children(nodes, i).map(|c| ids[c]).collect();
let (id, key) = (nodes[i].id, nodes[i].w.measure_key());
ids[i] = match self.entries.get_mut(&id) {
Some(e)
if e.seen != generation
&& kids.is_empty()
&& !tree.children(e.node).unwrap().is_empty() =>
{
e.seen = generation;
e.measure_key = key;
tree.remove(e.node).unwrap();
e.node = tree.new_leaf_with_context(style, id).unwrap();
e.node
}
Some(e) if e.seen != generation => {
e.seen = generation;
if *tree.style(e.node).unwrap() != style {
tree.set_style(e.node, style).unwrap();
}
if tree.children(e.node).unwrap() != kids {
tree.set_children(e.node, &kids).unwrap();
}
if e.measure_key != key {
e.measure_key = key;
tree.mark_dirty(e.node).unwrap();
}
e.node
}
seen => {
let node = tree.new_leaf_with_context(style, id).unwrap();
tree.set_children(node, &kids).unwrap();
if seen.is_some() {
self.spares.push(node);
} else {
self.entries.insert(
id,
Entry {
node,
measure_key: key,
seen: generation,
},
);
}
node
}
};
index.insert(id, i);
}
self.entries.retain(|_, e| {
let live = e.seen == generation;
if !live {
tree.remove(e.node).unwrap();
}
live
});
let avail = Size {
width: AvailableSpace::Definite(viewport.0),
height: AvailableSpace::Definite(viewport.1),
};
tree.compute_layout_with_measure(ids[0], avail, |input, _, ctx, style| {
compute_leaf_layout(
input,
style,
|_, _| 0.0,
|known, available| match ctx {
Some(id) => nodes[index[&*id]].w.measure(known, available, text),
None => Size::ZERO,
},
)
})
.unwrap();
(0..nodes.len())
.map(|i| {
let l = tree.layout(ids[i]).unwrap();
Measured {
rect: Rect::new(l.location.x, l.location.y, l.size.width, l.size.height),
content: children(nodes, i)
.filter(|&c| nodes[c].w.layer().is_none())
.fold(Size::ZERO, |s, c| {
let cl = tree.layout(ids[c]).unwrap();
Size {
width: s.width.max(cl.location.x + cl.size.width),
height: s.height.max(cl.location.y + cl.size.height),
}
}),
}
})
.collect()
}
}
pub(crate) fn place(
nodes: &[Node<'_>],
measured: &[Measured],
states: &mut HashMap<u64, State>,
now: Instant,
) -> Vec<Placed> {
let full = Rect::new(
f32::MIN / 4.0,
f32::MIN / 4.0,
f32::MAX / 2.0,
f32::MAX / 2.0,
);
let n = nodes.len();
let mut placed = vec![Placed::default(); n];
let mut offsets = vec![None; n];
let mut shifts = vec![(0.0, 0.0); n];
let mut rests = vec![None; n];
for i in 0..n {
let m = measured[i];
let (origin, clip) = match (nodes[i].parent, nodes[i].w.layer()) {
(None, _) => ((0.0, 0.0), full),
(Some(p), Some(Layer::Parent)) => {
let anchor = placed[p].rect;
let clip = match anchor.intersect(&placed[p].clip) {
v if v.w > 0.0 && v.h > 0.0 => placed[0].rect,
v => v,
};
((anchor.x, anchor.y), clip)
}
(Some(_), Some(Layer::Window | Layer::Screen)) => {
let w = placed[0].rect;
((w.x, w.y), w)
}
(Some(p), None) => {
let pr = placed[p].rect;
let (dx, dy) = offsets[p].unwrap_or((0.0, 0.0));
let (sx, sy) = shifts[p];
let clip = if offsets[p].is_some() && nodes[p].w.clips() {
placed[p].clip.intersect(&rests[p].unwrap_or(pr))
} else {
placed[p].clip
};
((pr.x - dx + sx, pr.y - dy + sy), clip)
}
};
placed[i] = Placed {
rect: Rect::new(origin.0 + m.rect.x, origin.1 + m.rect.y, m.rect.w, m.rect.h),
clip,
content: m.content,
inert: nodes[i].w.inert() || nodes[i].parent.is_some_and(|p| placed[p].inert),
};
let r = placed[i].rect;
let mut at = Placement {
clip: r,
rest: r,
anchor: r,
content: m.content,
};
let rest = nodes[i].w.layer().and_then(|layer| {
let rest = children(nodes, i)
.map(|c| measured[c].rect)
.map(|c| Rect::new(r.x + c.x, r.y + c.y, c.w, c.h))
.reduce(|a, b| a.union(&b))?;
Some((layer, rest))
});
match (rest, nodes[i].parent) {
(Some((Layer::Parent, rest)), Some(p)) => {
let (sx, sy) = fit(placed[0].rect, r, rest);
let rest = Rect::new(rest.x + sx, rest.y + sy, rest.w, rest.h);
at = Placement {
clip: rest,
rest,
anchor: placed[p].rect,
content: m.content,
};
(shifts[i], rests[i]) = ((sx, sy), Some(rest));
}
(Some((_, rest)), _) => {
at.rest = rest;
at.anchor = placed[0].rect;
}
(None, _) => {}
}
offsets[i] = nodes[i]
.w
.scroll(states.entry(nodes[i].id).or_default(), at, now);
}
placed
}
fn fit(window: Rect, anchor: Rect, content: Rect) -> (f32, f32) {
let out = |y: f32| y < window.y || y + content.h > window.y + window.h;
let mirrored = 2.0 * anchor.y + anchor.h - content.y - content.h;
let dy = if out(content.y) && !out(mirrored) {
mirrored - content.y
} else {
0.0
};
let right = window.x + window.w;
let dx = if content.x + content.w > right {
(right - content.x - content.w).max(window.x - content.x)
} else {
(window.x - content.x).max(0.0)
};
(dx, dy)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fit_flips_and_shifts_into_the_window() {
let window = Rect::new(0.0, 0.0, 100.0, 100.0);
let anchor = Rect::new(10.0, 80.0, 20.0, 10.0);
let below = Rect::new(10.0, 94.0, 40.0, 30.0);
assert_eq!(fit(window, anchor, below), (0.0, -48.0), "flips above");
let above = Rect::new(10.0, 46.0, 40.0, 30.0);
assert_eq!(fit(window, anchor, above), (0.0, 0.0), "already fits");
let wide = Rect::new(80.0, 10.0, 40.0, 10.0);
assert_eq!(fit(window, anchor, wide), (-20.0, 0.0), "shifts left");
let huge = Rect::new(10.0, 94.0, 40.0, 300.0);
assert_eq!(fit(window, anchor, huge).1, 0.0, "fits on neither side");
}
use crate::widgets::{Styled, column, row, spacer, stateful, text};
#[test]
fn column_padding_gap_grow() {
let root: Element = column([
row([]).height(20.0).into(),
spacer().grow(1.0).into(),
row([]).height(30.0).into(),
])
.padding(10.0)
.gap(5.0)
.into();
let mut states = HashMap::new();
let nodes = flatten(&root, &mut states, &mut Default::default());
let m = Layout::default().measure(&nodes, &Text::default(), (100.0, 200.0), [0.0; 4]);
let p = place(&nodes, &m, &mut states, Instant::now());
assert_eq!(p[0].rect, Rect::new(0.0, 0.0, 100.0, 200.0));
assert_eq!(p[1].rect, Rect::new(10.0, 10.0, 80.0, 20.0));
assert_eq!(p[2].rect, Rect::new(10.0, 35.0, 80.0, 120.0));
assert_eq!(p[3].rect, Rect::new(10.0, 160.0, 80.0, 30.0));
}
fn nested_scroll(fill: bool) -> Rect {
use crate::widgets::scroll;
let rows = (0..10).map(|_| column([]).height(50.0).into());
let list = scroll(column(rows));
let list = if fill { list.fill() } else { list.grow(1.0) };
let page = column([row([]).height(20.0).into(), list.into()]);
let page = if fill { page.fill() } else { page.grow(1.0) };
let root: Element = column([page.into()]).into();
let mut states = HashMap::new();
let nodes = flatten(&root, &mut states, &mut Default::default());
let m = Layout::default().measure(&nodes, &Text::default(), (100.0, 200.0), [0.0; 4]);
place(&nodes, &m, &mut states, Instant::now())[3].rect
}
#[test]
fn fill_bounds_a_nested_scroll() {
assert_eq!(nested_scroll(true), Rect::new(0.0, 20.0, 100.0, 180.0));
assert_eq!(nested_scroll(false).h, 500.0);
}
fn list(items: &[(u64, &str)]) -> Element {
let rows = items.iter().map(|&(k, s)| {
let r: Element = row([text(s).into(), spacer().grow(1.0).into()]).into();
r.key(k)
});
column([column(rows).gap(4.0).into(), text("footer").into()])
.padding(8.0)
.into()
}
#[test]
fn walk_matches_flatten() {
let root: Element = column([
list(&[(1, "a"), (2, "b")]),
stateful(|_: &u8, _| row([text("x").into(), spacer().into()])).into(),
])
.into();
let mut states = HashMap::new();
let flat = flatten(&root, &mut states, &mut Default::default());
let ids: Vec<u64> = flat.iter().map(|n| n.id).collect();
let walked = walk(&root, &ids);
let shape = |ns: &[Node]| {
ns.iter()
.map(|n| (n.id, n.parent, n.end))
.collect::<Vec<_>>()
};
assert_eq!(shape(&walked), shape(&flat));
}
#[test]
fn container_left_empty_by_a_removed_layer_lays_out() {
use crate::widgets::popup;
let t = Text::default();
let mut kept = Layout::default();
for kids in [vec![popup(text("menu")).into()], vec![]] {
let root: Element = column([row(kids).into()]).into();
let mut states = HashMap::new();
let nodes = flatten(&root, &mut states, &mut Default::default());
kept.measure(&nodes, &t, (300.0, 400.0), [0.0; 4]);
}
}
#[test]
fn kept_tree_matches_fresh_layout() {
let steps: [&[(u64, &str)]; 6] = [
&[(1, "a"), (2, "bb"), (3, "ccc")],
&[(1, "a"), (2, "a much longer label"), (3, "ccc")],
&[(3, "ccc"), (1, "a")],
&[(3, "ccc"), (4, "new"), (1, "a"), (5, "x")],
&[(4, "dup"), (4, "dup"), (1, "a")],
&[],
];
let text = Text::default();
let mut kept = Layout::default();
for (n, items) in steps.iter().enumerate() {
let root = list(items);
let mut states = HashMap::new();
let nodes = flatten(&root, &mut states, &mut Default::default());
let got = kept.measure(&nodes, &text, (300.0, 400.0), [0.0; 4]);
let want = Layout::default().measure(&nodes, &text, (300.0, 400.0), [0.0; 4]);
assert_eq!(got, want, "step {n}");
}
assert_eq!(
kept.tree.total_node_count(),
kept.entries.len() + kept.spares.len()
);
}
}