Make alignment a widget property

This commit is contained in:
iris-ai committed 2026-09-15 23:12:16 -04:00
1 parent 8220a78d4a
commit d3b0ebf90c
21 files changed
+823 -300

No files matched your search

+113 -15
View File
@@ -13,7 +13,7 @@ use std::collections::HashMap;
use iris::harness::Harness;
use iris::prelude::*;
use iris::random::{Edits, Lens, Rng, SpanEdit, Tree, grow};
use iris::random::{Aligns, Edits, Lens, Rng, SpanEdit, Tree, grow};
/// How deep the generator branches. The generator widens two to four ways per
/// level, so depth is exponential in width and a deep narrow tree is not
@@ -179,12 +179,28 @@ fn describe(id: WidgetId, h: &Harness) -> String {
Some(len) => format!("{len}"),
None => "-".into(),
};
// A size rule is a property of whatever carries it, so it prints with
// that widget rather than as one of its own.
match (rules.x, rules.y) {
(SizeRule::Free, SizeRule::Free) => describe_widget(id, h),
(x, y) => format!("{}[x:{},y:{}]", describe_widget(id, h), rule(x), rule(y)),
let align = h.rsc.widgets().alignment(id);
let side = |a: AxisAlign| {
if a == AxisAlign::NEG {
"neg".into()
} else if a == AxisAlign::CENTER {
"mid".into()
} else if a == AxisAlign::POS {
"pos".into()
} else {
format!("{:.2}", a.rel())
}
};
// A rule and an alignment are properties of whatever carries them, so
// they print with that widget rather than as widgets of their own.
let mut out = describe_widget(id, h);
if (rules.x, rules.y) != (SizeRule::Free, SizeRule::Free) {
out += &format!("[x:{},y:{}]", rule(rules.x), rule(rules.y));
}
if align != RegionAlign::default() {
out += &format!("@{},{}", side(align.x), side(align.y));
}
out
}
fn describe_widget(id: WidgetId, h: &Harness) -> String {
@@ -210,15 +226,6 @@ fn describe_widget(id: WidgetId, h: &Harness) -> String {
p.left, p.right, p.top, p.bottom
);
}
if let Some(w) = any.downcast_ref::<Aligned>() {
let a = |v: Option<AxisAlign>| match v {
None => "-",
Some(AxisAlign::Neg) => "neg",
Some(AxisAlign::Center) => "mid",
Some(AxisAlign::Pos) => "pos",
};
return format!("Aligned{{x:{},y:{}}}", a(w.align.x), a(w.align.y));
}
if let Some(w) = any.downcast_ref::<Stack>() {
return format!("Stack{{n:{}}}", w.children.len());
}
@@ -290,6 +297,87 @@ fn changed_size(seed: u64) {
assert_same(seed, "a size change", (&warm, &grown), (&cold, &same));
}
/// Moves one widget to a different corner of the box it is given.
fn realign_one(h: &mut Harness, tree: &Tree, idx: usize, rng: &mut Rng) -> Aligns {
let mut side = || match rng.below(4) {
0 => None,
1 => Some(AxisAlign::NEG),
2 => Some(AxisAlign::CENTER),
_ => Some(AxisAlign::POS),
};
let aligns = [side(), side()];
for (axis, align) in [Axis::X, Axis::Y].into_iter().zip(aligns) {
h.rsc
.widgets_mut()
.set_alignment(tree.aligned[idx], axis, align.unwrap_or_default());
}
aligns
}
fn changed_alignment(seed: u64) {
let mut warm = Harness::new((900, 1200));
let grown = plant(&mut warm, seed, &Edits::default());
if grown.aligned.is_empty() {
return;
}
let mut rng = Rng::new(seed ^ 0xa11);
let aligns = (0..grown.aligned.len())
.step_by(3)
.map(|idx| (idx, realign_one(&mut warm, &grown, idx, &mut rng)))
.collect();
warm.frame();
let mut cold = Harness::new((900, 1200));
let same = plant(
&mut cold,
seed,
&Edits {
aligns,
..Default::default()
},
);
assert_same(seed, "an alignment change", (&warm, &grown), (&cold, &same));
}
/// Giving a widget a movable region of its own, or taking it away, is a
/// structural change: every primitive under it changes which chain resolves
/// it. A cold tree built that way is what says the rebuild was complete.
fn changed_region_node(seed: u64) {
let mut warm = Harness::new((900, 1200));
let grown = plant(&mut warm, seed, &Edits::default());
if grown.nodes.is_empty() {
return;
}
let nodes: HashMap<usize, bool> = (0..grown.nodes.len())
.step_by(2)
.map(|idx| {
let id = grown.nodes[idx];
let was = warm.rsc.widgets().is_region_node(id);
warm.rsc.widgets_mut().set_region_node(id, !was);
(idx, !was)
})
.collect();
warm.frame();
let mut cold = Harness::new((900, 1200));
let same = plant(
&mut cold,
seed,
&Edits {
nodes,
..Default::default()
},
);
assert_same(
seed,
"a region-node change",
(&warm, &grown),
(&cold, &same),
);
}
fn reshuffled(seed: u64, shuffle: Shuffle) {
let mut warm = Harness::new((900, 1200));
let mut grown = plant(&mut warm, seed, &Edits::default());
@@ -411,6 +499,16 @@ fn a_changed_size_lands_where_growing_it_that_way_would() {
SEEDS.into_iter().for_each(changed_size);
}
#[test]
fn a_changed_alignment_lands_where_growing_it_that_way_would() {
SEEDS.into_iter().for_each(changed_alignment);
}
#[test]
fn a_toggled_region_node_lands_where_growing_it_that_way_would() {
SEEDS.into_iter().for_each(changed_region_node);
}
#[test]
fn every_size_changing_at_once_lands_where_growing_it_that_way_would() {
SEEDS.into_iter().for_each(changed_every_size);
+29 -5
View File
@@ -74,17 +74,39 @@ fn an_empty_widget_takes_a_share_of_a_span() {
#[test]
fn a_child_drawn_twice_moves_once() {
let mut h = Harness::new((400, 200));
// `Aligned` draws its child twice; listing it twice would move it twice.
// The span measures a child and then places it; listing it twice would
// move it twice. The span's own fixed total is shorter than the window,
// so the span is centred in it and everything under it carries that.
let inner = rect(Color::BLUE).add(&mut h.rsc);
let centered = inner.center().width(200).add(&mut h.rsc);
let left = rect(Color::RED).width(100).add(&mut h.rsc);
h.set_root((left, centered).span(Dir::RIGHT));
assert_corners!(h, inner, (100, 0), (300, 200));
assert_corners!(h, inner, (150, 0), (350, 200));
h.set_len(left, Axis::X, 150);
h.frame();
assert_corners!(h, inner, (150, 0), (350, 200));
assert_corners!(h, inner, (175, 0), (375, 200));
}
#[test]
fn alignment_accepts_an_arbitrary_fraction_and_changes_at_runtime() {
let mut h = Harness::new((400, 200));
let fixed = rect(Color::BLUE).sized((100, 100)).add(&mut h.rsc);
h.rsc
.widgets_mut()
.set_alignment(fixed, Axis::X, AxisAlign::new(0.25));
h.rsc
.widgets_mut()
.set_alignment(fixed, Axis::Y, AxisAlign::NEG);
h.set_root(fixed);
assert_corners!(h, fixed, (75, 0), (175, 100));
h.rsc
.widgets_mut()
.set_alignment(fixed, Axis::X, AxisAlign::new(0.75));
h.frame();
assert_corners!(h, fixed, (225, 0), (325, 100));
}
#[test]
@@ -143,15 +165,17 @@ fn a_moved_subtree_takes_its_children_with_it() {
let first = rect(Color::RED).height(40).add(&mut h.rsc);
let inner = rect(Color::BLUE).add(&mut h.rsc);
let row = inner.pad(10).height(40).region_node().add(&mut h.rsc);
// 80 of fixed rows in a 400 window, so the span takes 80 and sits in the
// middle of what it was given.
h.set_root((first, row).span(Dir::DOWN));
assert_corners!(h, inner, (10, 50), (390, 70));
assert_corners!(h, inner, (10, 210), (390, 230));
h.set_len(first, Axis::Y, 80);
h.frame();
// The row opted into one movable region, so its descendants follow one
// entry rather than having their primitive regions rewritten.
assert_corners!(h, inner, (10, 90), (390, 110));
assert_corners!(h, inner, (10, 230), (390, 250));
}
#[test]
+15 -5
View File
@@ -159,10 +159,15 @@ fn a_span_child_that_declares_its_length_is_drawn_once() {
h.set_root((hinted, asked).span(Dir::RIGHT));
assert_eq!(told_draws.get(), 1);
// Reading its box makes its drawing hold for the measuring box alone,
// and it reports less than that box: so it is drawn again in the box its
// answer places it in, and once more in the final box the span chooses.
// A widget that says what it holds for, as text does, skips the middle
// one.
assert_eq!(
asked_draws.get(),
2,
"drawn to be measured, then again in its final box"
3,
"drawn to be measured, in its placed box, then in its final box"
);
}
@@ -256,6 +261,11 @@ impl Widget for ReadsBox {
/// Reads its box across one axis only, so its drawing holds for a taller
/// box on its own and only a wider one is worth a draw.
///
/// Both of these report a quarter of what they read, without saying that the
/// drawing holds there too, so each length they are asked at costs two draws:
/// one to answer, and one in the quarter-sized box that answer places them
/// in. The counts below are in those pairs.
struct ReadsWidth {
draws: Rc<Cell<usize>>,
}
@@ -336,7 +346,7 @@ fn a_resize_redraws_what_read_its_box() {
h.resize((800, 100));
h.frame();
assert_eq!(draws.get(), settled + 1);
assert_eq!(draws.get(), settled + 2);
}
#[test]
@@ -356,7 +366,7 @@ fn a_resize_only_redraws_read_axes() {
h.resize((800, 300));
h.frame();
assert_eq!(draws.get(), settled + 1, "width changes its answer");
assert_eq!(draws.get(), settled + 2, "width changes its answer");
}
#[test]
@@ -378,7 +388,7 @@ fn subpixel_resize_changes_accumulate_from_the_last_layout() {
h.resize((400.06, 200.0));
h.frame();
assert_eq!(draws.get(), settled + 1);
assert_eq!(draws.get(), settled + 2);
}
#[test]
+92 -21
View File
@@ -76,9 +76,9 @@ enum Node {
fn axis_align(v: u8) -> Option<AxisAlign> {
match v % 4 {
0 => None,
1 => Some(AxisAlign::Neg),
2 => Some(AxisAlign::Center),
_ => Some(AxisAlign::Pos),
1 => Some(AxisAlign::NEG),
2 => Some(AxisAlign::CENTER),
_ => Some(AxisAlign::POS),
}
}
@@ -94,6 +94,7 @@ impl Node {
h: &mut Harness,
out: &mut Vec<WidgetId>,
spans: &mut Vec<WeakWidget<Span>>,
sized: &mut Vec<WidgetId>,
) -> StrongWidget {
let id: StrongWidget = match self {
Node::Text(words, wrap) => {
@@ -106,7 +107,10 @@ impl Node {
Node::OneLine => wtext(ONE_LINE).size(16).wrap(false).add_strong(&mut h.rsc),
Node::Rect => rect(Color::RED).add_strong(&mut h.rsc),
Node::Span(down, gap, kids, order) => {
let mut built: Vec<_> = kids.iter().map(|k| Some(k.build(h, out, spans))).collect();
let mut built: Vec<_> = kids
.iter()
.map(|k| Some(k.build(h, out, spans, sized)))
.collect();
// `order` is a permutation, so each is taken exactly once.
let children = order
.iter()
@@ -126,7 +130,7 @@ impl Node {
handle.add_strong(&mut h.rsc)
}
Node::Stack(kids) => {
let children = kids.iter().map(|k| k.build(h, out, spans)).collect();
let children = kids.iter().map(|k| k.build(h, out, spans, sized)).collect();
Stack {
children,
size: StackSize::Child(0),
@@ -134,7 +138,7 @@ impl Node {
.add_strong(&mut h.rsc)
}
Node::Pad(p, kid) => {
let inner = kid.build(h, out, spans);
let inner = kid.build(h, out, spans, sized);
Pad {
padding: Padding {
left: *p,
@@ -147,30 +151,29 @@ impl Node {
.add_strong(&mut h.rsc)
}
Node::Aligned(x, y, kid) => {
let inner = kid.build(h, out, spans);
Aligned {
inner,
align: Align {
x: axis_align(*x),
y: axis_align(*y),
},
let inner = kid.build(h, out, spans, sized);
for (axis, align) in [(Axis::X, axis_align(*x)), (Axis::Y, axis_align(*y))] {
if let Some(align) = align {
h.rsc.widgets_mut().set_alignment(&inner, axis, align);
}
}
.add_strong(&mut h.rsc)
inner
}
Node::Sized(x, y, kid) => {
let inner = kid.build(h, out, spans);
let inner = kid.build(h, out, spans, sized);
h.rsc.widgets_mut().set_size_rules(&inner, *x, *y);
sized.push(inner.id());
inner
}
Node::Scroll(down, kid) => {
let inner = kid.build(h, out, spans);
let inner = kid.build(h, out, spans, sized);
let axis = if *down { Axis::Y } else { Axis::X };
Scroll::new(inner, axis).add_strong(&mut h.rsc)
}
Node::Branch(probe, a, b, at) => {
let probe = probe.build(h, out, spans);
let wide = a.build(h, out, spans);
let narrow = b.build(h, out, spans);
let probe = probe.build(h, out, spans, sized);
let wide = a.build(h, out, spans, sized);
let narrow = b.build(h, out, spans, sized);
Branch {
probe,
wide,
@@ -184,6 +187,27 @@ impl Node {
id
}
/// The lengths every `Sized` node would carry after `resized`, in the
/// order `build` pushes them.
fn sized_lens(&self, out: &mut Vec<(Option<Len>, Option<Len>)>) {
match self {
Node::Text(..) | Node::OneLine | Node::Rect => {}
Node::Span(_, _, kids, _) | Node::Stack(kids) => {
kids.iter().for_each(|k| k.sized_lens(out));
}
Node::Pad(_, k) | Node::Aligned(_, _, k) | Node::Scroll(_, k) => k.sized_lens(out),
Node::Sized(x, y, k) => {
k.sized_lens(out);
out.push((resized_len(*x), resized_len(*y)));
}
Node::Branch(p, a, b, _) => {
p.sized_lens(out);
a.sized_lens(out);
b.sized_lens(out);
}
}
}
fn size(&self) -> usize {
1 + match self {
Node::Text(..) | Node::OneLine | Node::Rect => 0,
@@ -377,6 +401,41 @@ enum Case {
Repaint,
ResizeRepaint,
Reorder,
SizeChange,
}
/// A different declared length, kept the same kind so the change is to the
/// value alone.
fn resized_len(len: Option<Len>) -> Option<Len> {
len.map(|len| Len {
px: len.px * 0.5 + 13.0,
rel: len.rel * 0.5,
leftover: len.leftover,
})
}
/// Every declared size changed, as a tree rather than as a change.
fn resized(node: &Node) -> Node {
match node {
Node::Span(down, gap, kids, order) => Node::Span(
*down,
*gap,
kids.iter().map(resized).collect(),
order.clone(),
),
Node::Stack(kids) => Node::Stack(kids.iter().map(resized).collect()),
Node::Pad(p, k) => Node::Pad(*p, Box::new(resized(k))),
Node::Aligned(x, y, k) => Node::Aligned(*x, *y, Box::new(resized(k))),
Node::Sized(x, y, k) => Node::Sized(resized_len(*x), resized_len(*y), Box::new(resized(k))),
Node::Scroll(d, k) => Node::Scroll(*d, Box::new(resized(k))),
Node::Branch(p, a, b, at) => Node::Branch(
Box::new(resized(p)),
Box::new(resized(a)),
Box::new(resized(b)),
*at,
),
leaf => leaf.clone(),
}
}
/// Every span's children rotated by one, as a tree rather than as a change:
@@ -413,7 +472,8 @@ fn diverges(node: &Node, case: Case) -> Option<String> {
let mut warm = Harness::new(start);
let mut warm_ids = Vec::new();
let mut warm_spans = Vec::new();
let root = node.build(&mut warm, &mut warm_ids, &mut warm_spans);
let mut warm_sized = Vec::new();
let root = node.build(&mut warm, &mut warm_ids, &mut warm_spans, &mut warm_sized);
warm.state.root = Some(root);
// The frame that makes it warm: without it there is nothing retained and
// the comparison is two cold starts agreeing with each other.
@@ -434,16 +494,26 @@ fn diverges(node: &Node, case: Case) -> Option<String> {
}
warm.frame();
}
if case == Case::SizeChange {
let mut lens = Vec::new();
node.sized_lens(&mut lens);
for (id, (x, y)) in warm_sized.iter().zip(lens) {
warm.rsc.widgets_mut().set_size_rules(*id, x, y);
}
warm.frame();
}
// What the warm tree was moved into, grown that way from the start.
let want = match case {
Case::Reorder => reordered(node),
Case::SizeChange => resized(node),
_ => node.clone(),
};
let mut cold = Harness::new(INNER);
let mut cold_ids = Vec::new();
let mut cold_spans = Vec::new();
let root = want.build(&mut cold, &mut cold_ids, &mut cold_spans);
let mut cold_sized = Vec::new();
let root = want.build(&mut cold, &mut cold_ids, &mut cold_spans, &mut cold_sized);
cold.state.root = Some(root);
cold.frame();
@@ -497,6 +567,7 @@ fn no_grown_tree_lays_out_differently_warm_than_cold() {
"repaint" => Case::Repaint,
"resize-repaint" => Case::ResizeRepaint,
"reorder" => Case::Reorder,
"size-change" => Case::SizeChange,
_ => Case::Resize,
};
+11 -16
View File
@@ -11,14 +11,13 @@ fn plant(h: &mut Harness) -> Vec<WidgetId> {
let plain = wtext("Wrapping").size(16).wrap(false).add(&mut h.rsc);
let wrapped = wtext("Wrapping shapes").size(16).wrap(true).add(&mut h.rsc);
let sized = wrapped.width(76).add(&mut h.rsc);
let aligned = Aligned {
inner: sized.add_strong(&mut h.rsc),
align: Align {
x: Some(AxisAlign::Pos),
y: Some(AxisAlign::Pos),
},
}
.add(&mut h.rsc);
let aligned = sized;
h.rsc
.widgets_mut()
.set_alignment(sized, Axis::X, AxisAlign::POS);
h.rsc
.widgets_mut()
.set_alignment(sized, Axis::Y, AxisAlign::POS);
let stack = Stack {
children: vec![plain.add_strong(&mut h.rsc), aligned.add_strong(&mut h.rsc)],
size: StackSize::Child(0),
@@ -94,14 +93,10 @@ fn what_box_the_text_is_drawn_in() {
fn plant_fixed(h: &mut Harness) -> Vec<WidgetId> {
let words = "Wrapping shapes one source into as many lines as the box leaves";
let text = wtext(words).size(16).wrap(true).add(&mut h.rsc);
let aligned = Aligned {
inner: text.add_strong(&mut h.rsc),
align: Align {
x: Some(AxisAlign::Neg),
y: None,
},
}
.add(&mut h.rsc);
let aligned = text;
h.rsc
.widgets_mut()
.set_alignment(text, Axis::X, AxisAlign::NEG);
let inner = (aligned,).span(Dir::RIGHT).add(&mut h.rsc);
let sized = inner.sized((189, 176)).add(&mut h.rsc);
let filler = rect(Color::RED).add(&mut h.rsc);
+19 -32
View File
@@ -16,14 +16,13 @@ fn plant(h: &mut Harness) -> Vec<WidgetId> {
let plain = wtext("Wrapping").size(16).wrap(false).add(&mut h.rsc);
let wrapped = wtext("Wrapping shapes").size(16).wrap(true).add(&mut h.rsc);
let sized = wrapped.width(76).add(&mut h.rsc);
let aligned = Aligned {
inner: sized.add_strong(&mut h.rsc),
align: Align {
x: Some(AxisAlign::Pos),
y: Some(AxisAlign::Pos),
},
}
.add(&mut h.rsc);
let aligned = sized;
h.rsc
.widgets_mut()
.set_alignment(sized, Axis::X, AxisAlign::POS);
h.rsc
.widgets_mut()
.set_alignment(sized, Axis::Y, AxisAlign::POS);
let stack = Stack {
children: vec![plain.add_strong(&mut h.rsc), aligned.add_strong(&mut h.rsc)],
size: StackSize::Child(0),
@@ -96,14 +95,10 @@ fn repainting_everything_moves_nothing() {
fn plant_fixed(h: &mut Harness) -> Vec<WidgetId> {
let words = "Wrapping shapes one source into as many lines as the box leaves";
let text = wtext(words).size(16).wrap(true).add(&mut h.rsc);
let aligned = Aligned {
inner: text.add_strong(&mut h.rsc),
align: Align {
x: Some(AxisAlign::Neg),
y: None,
},
}
.add(&mut h.rsc);
let aligned = text;
h.rsc
.widgets_mut()
.set_alignment(text, Axis::X, AxisAlign::NEG);
let inner = (aligned,).span(Dir::RIGHT).add(&mut h.rsc);
let sized = inner.sized((189, 176)).add(&mut h.rsc);
let filler = rect(Color::RED).add(&mut h.rsc);
@@ -167,14 +162,10 @@ fn plant_pair(h: &mut Harness, swapped: bool) -> (Vec<WidgetId>, WeakWidget<Span
}
.add(&mut h.rsc);
let span_handle = span;
let aligned = Aligned {
inner: span.add_strong(&mut h.rsc),
align: Align {
x: Some(AxisAlign::Center),
y: None,
},
}
.add(&mut h.rsc);
let aligned = span;
h.rsc
.widgets_mut()
.set_alignment(span, Axis::X, AxisAlign::CENTER);
h.state.root = Some(aligned.add_strong(&mut h.rsc));
(
vec![wrapped.id(), plain.id(), span.id(), aligned.id()],
@@ -300,14 +291,10 @@ impl Widget for Wider {
fn plant_wider(h: &mut Harness, extra: f32) -> (WeakWidget<Wider>, WidgetId) {
let content = Wider { extra }.add(&mut h.rsc);
let scroll = Scroll::new(content.add_strong(&mut h.rsc), Axis::X).add(&mut h.rsc);
let root = Aligned {
inner: scroll.add_strong(&mut h.rsc),
align: Align {
x: Some(AxisAlign::Neg),
y: None,
},
}
.add(&mut h.rsc);
let root = scroll;
h.rsc
.widgets_mut()
.set_alignment(scroll, Axis::X, AxisAlign::NEG);
h.set_root(root);
(content, scroll.id())
}