feat: retain managed visual objects and dispatch native input through Endor
Verify Tessera GUI / verify (push) Successful in 9m28s

This commit is contained in:
2026-10-21 01:49:35 +08:00
parent 757fa22d9b
commit 0d5e4b318d
21 changed files with 3295 additions and 892 deletions
+269 -107
View File
@@ -1,25 +1,50 @@
//! Layout consumes only owned native UI data, after the candidate VM is gone.
use anyhow::{Result, bail};
//! Iterative measure/arrange/paint over derived visual data. Every occurrence
//! has its own geometry; measurement caches never become semantic object state.
use crate::{
document::{Frame, RenderCommand},
document::{Frame, MountGeometry, RenderCommand},
text::{self, TextStyle},
ui_bridge::{MAX_DIMENSION, UiKind, UiNode},
};
use anyhow::{Context as _, Result, bail};
use std::collections::{HashMap, HashSet};
const MAX_LAYOUT_VISITS: usize = 10_000;
#[derive(Default, Clone, Copy)]
struct Size {
width: f32,
height: f32,
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct Size {
pub width: f32,
pub height: f32,
}
pub fn frame(root: &UiNode) -> Result<Frame> {
let mut frame = Frame::default();
let mut visits = 0;
layout(root, 0.0, 0.0, &mut frame.commands, &mut visits)?;
Ok(frame)
#[derive(Debug, Clone, PartialEq)]
enum Shape {
Text(String, u32),
Rect(f32, f32),
Container(bool, f32, f32, Vec<Size>),
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
struct Key {
parent: Option<u64>,
slot: u64,
block: String,
}
#[derive(Debug, Clone, Default)]
pub struct LayoutRuntime {
sizes: HashMap<String, (Shape, Size)>,
ids: HashMap<Key, u64>,
next_id: u64,
pub version: u64,
pub measured: usize,
pub arranged: usize,
}
struct Item<'a> {
node: &'a UiNode,
parent: Option<usize>,
children: Vec<usize>,
id: u64,
}
fn bounded(value: f32) -> Result<f32> {
@@ -29,99 +54,236 @@ fn bounded(value: f32) -> Result<f32> {
Ok(value)
}
fn layout(
node: &UiNode,
x: f32,
y: f32,
commands: &mut Vec<RenderCommand>,
visits: &mut usize,
) -> Result<Size> {
*visits += 1;
if *visits > MAX_LAYOUT_VISITS {
bail!("expanded UI layout exceeds 10000 nodes");
fn container(node: &UiNode) -> Option<(bool, f32, f32)> {
match &node.kind {
UiKind::Row { padding, gap, .. } => Some((true, *padding, *gap)),
UiKind::Column { padding, gap, .. } | UiKind::Button { padding, gap, .. } => {
Some((false, *padding, *gap))
}
_ => None,
}
bounded(x)?;
bounded(y)?;
let size = match &node.kind {
UiKind::Text { value, size, color } => {
commands.push(RenderCommand::Text {
x,
y,
value: value.clone(),
size: *size,
color: color.clone(),
});
let measured = text::measure(value, TextStyle::ui(*size));
Size {
width: measured.width,
height: measured.height,
}
}
UiKind::Rect {
width,
height,
radius,
color,
} => {
commands.push(RenderCommand::RoundedRect {
x,
y,
width: *width,
height: *height,
radius: *radius,
color: color.clone(),
});
Size {
width: *width,
height: *height,
}
}
UiKind::Spacer(size) => Size {
width: *size,
height: *size,
},
UiKind::Column {
padding,
gap,
children,
}
| UiKind::Row {
padding,
gap,
children,
} => {
let row = matches!(node.kind, UiKind::Row { .. });
let mut cursor = *padding;
let mut cross: f32 = 0.0;
for (index, child) in children.iter().enumerate() {
if index > 0 {
cursor = bounded(cursor + gap)?;
}
let (child_x, child_y) = if row {
(x + cursor, y + padding)
} else {
(x + padding, y + cursor)
};
let size = layout(child, child_x, child_y, commands, visits)?;
cursor = bounded(cursor + if row { size.width } else { size.height })?;
cross = cross.max(if row { size.height } else { size.width });
}
let along = bounded(cursor + padding)?;
let across = bounded(cross + padding * 2.0)?;
if row {
Size {
width: along,
height: across,
}
} else {
Size {
width: across,
height: along,
}
}
}
};
bounded(x + size.width)?;
bounded(y + size.height)?;
Ok(size)
}
impl LayoutRuntime {
pub fn clear_occurrences(&mut self) {
self.ids.clear();
}
pub fn frame(&mut self, root: &UiNode) -> Result<Frame> {
// Stage all cache/identity changes; a rejected frame leaves the last
// valid occurrence registry intact and never publishes partial geometry.
let mut next = self.clone();
let frame = next.build(root)?;
*self = next;
Ok(frame)
}
fn build(&mut self, root: &UiNode) -> Result<Frame> {
self.measured = 0;
self.arranged = 0;
let mut items = Vec::<Item<'_>>::new();
let mut work = vec![(root, None::<usize>, 0)];
let mut used = HashSet::new();
while let Some((node, parent, slot)) = work.pop() {
if items.len() >= MAX_LAYOUT_VISITS {
bail!("expanded UI layout exceeds 10000 nodes");
}
if node.slots.len() != node.children().len() {
bail!("invalid child slot table");
}
let key = Key {
parent: parent.map(|i| items[i].id),
slot,
block: node.block_id.clone(),
};
let id = if let Some(id) = self.ids.get(&key) {
*id
} else {
self.next_id = self
.next_id
.checked_add(1)
.context("Mount identity exhausted")?;
self.ids.insert(key.clone(), self.next_id);
self.next_id
};
if !used.insert(key) {
bail!("duplicate child slot in one presentation");
}
let index = items.len();
if let Some(parent) = parent {
items[parent].children.push(index);
}
items.push(Item {
node,
parent,
children: vec![],
id,
});
for (child, slot) in node.children().iter().zip(&node.slots).rev() {
work.push((child.as_ref(), Some(index), *slot));
}
}
let mut sizes = vec![Size::default(); items.len()];
for (index, item) in items.iter().enumerate().rev() {
let shape = match &item.node.kind {
UiKind::Text { value, size, .. } => Shape::Text(value.clone(), *size),
UiKind::Rect { width, height, .. } => Shape::Rect(*width, *height),
UiKind::Spacer(size) => Shape::Rect(*size, *size),
_ => {
let (row, padding, gap) =
container(item.node).context("unknown native visual protocol")?;
Shape::Container(
row,
padding,
gap,
item.children.iter().map(|i| sizes[*i]).collect(),
)
}
};
let size = if let Some((old_shape, size)) = self
.sizes
.get(&item.node.block_id)
.filter(|(old, _)| *old == shape)
{
let _ = old_shape;
*size
} else {
self.measured += 1;
let size = match &shape {
Shape::Text(value, size) => {
let result = text::measure(value, TextStyle::ui(*size));
Size {
width: result.width,
height: result.height,
}
}
Shape::Rect(width, height) => Size {
width: *width,
height: *height,
},
Shape::Container(row, padding, gap, children) => {
let along = children
.iter()
.map(|s| if *row { s.width } else { s.height })
.sum::<f32>()
+ padding * 2.0
+ gap * children.len().saturating_sub(1) as f32;
let cross = children
.iter()
.map(|s| if *row { s.height } else { s.width })
.fold(0.0_f32, f32::max)
+ padding * 2.0;
if *row {
Size {
width: along,
height: cross,
}
} else {
Size {
width: cross,
height: along,
}
}
}
};
bounded(size.width)?;
bounded(size.height)?;
self.sizes.insert(item.node.block_id.clone(), (shape, size));
size
};
sizes[index] = size;
}
let mut points = vec![(0.0_f32, 0.0_f32); items.len()];
let mut mounts = Vec::with_capacity(items.len());
let mut commands = Vec::new();
let mut siblings = vec![None; items.len()];
for item in &items {
for pair in item.children.windows(2) {
siblings[pair[0]] = Some(items[pair[1]].id);
}
}
for (index, item) in items.iter().enumerate() {
self.arranged += 1;
let (x, y) = points[index];
let size = sizes[index];
bounded(x)?;
bounded(y)?;
bounded(x + size.width)?;
bounded(y + size.height)?;
mounts.push(MountGeometry {
id: item.id,
block_id: item.node.block_id.clone(),
parent: item.parent.map(|i| items[i].id),
first_child: item.children.first().map(|i| items[*i].id),
next_sibling: siblings[index],
x,
y,
width: size.width,
height: size.height,
interactive: item.node.interactive,
});
match &item.node.kind {
UiKind::Text { value, size, color } => commands.push(RenderCommand::Text {
x,
y,
value: value.clone(),
size: *size,
color: color.clone(),
}),
UiKind::Rect { radius, color, .. } => commands.push(RenderCommand::RoundedRect {
x,
y,
width: size.width,
height: size.height,
radius: *radius,
color: color.clone(),
}),
UiKind::Button { .. } => commands.push(RenderCommand::RoundedRect {
x,
y,
width: size.width,
height: size.height,
radius: 7.0,
color: "#E3EAF7".into(),
}),
_ => {}
}
if let Some((row, padding, gap)) = container(item.node) {
let mut cursor = padding;
for child in &item.children {
points[*child] = if row {
(x + cursor, y + padding)
} else {
(x + padding, y + cursor)
};
cursor += if row {
sizes[*child].width
} else {
sizes[*child].height
};
cursor += gap;
}
}
}
self.ids.retain(|key, _| used.contains(key));
let blocks: HashSet<_> = items
.iter()
.map(|item| item.node.block_id.as_str())
.collect();
self.sizes
.retain(|block, _| blocks.contains(block.as_str()));
self.version = self
.version
.checked_add(1)
.context("layout version exhausted")?;
Ok(Frame {
commands,
mounts,
layout_version: self.version,
..Frame::default()
})
}
}
pub fn frame(root: &UiNode) -> Result<Frame> {
LayoutRuntime::default().frame(root)
}