Run source measurement and arrangement in the frame pipeline
Verify Tessera GUI / verify (push) Failing after 7m30s
Verify Tessera GUI / verify (push) Failing after 7m30s
This commit is contained in:
@@ -0,0 +1,449 @@
|
||||
//! Bottom-up measurement and top-down arrangement share one read-only VM call.
|
||||
//! The host scratch plan contains derived data only, never a second business heap.
|
||||
use crate::{
|
||||
document::Frame,
|
||||
layout::{self, LayoutRuntime, Size},
|
||||
mount::Mount,
|
||||
native_visual::{number, record, value},
|
||||
object_list,
|
||||
ui_bridge::{MAX_DIMENSION, UiNode, desktop_type},
|
||||
};
|
||||
use anyhow::Result;
|
||||
use endor_core::{
|
||||
CodeLayout, ContextNativeFunction, EndorCode, EndorCodeObject, Instruction, NativeCallable,
|
||||
NativeContext, NativeResult, ObjectRef, Opcode, Value, Vm, VmError, WeakObjectRef,
|
||||
};
|
||||
use std::{
|
||||
collections::{BTreeSet, HashMap},
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
fn invalid(message: &'static str) -> VmError {
|
||||
VmError::InvalidArgument(message)
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct Plan {
|
||||
nodes: Vec<Arc<UiNode>>,
|
||||
children: Vec<Vec<usize>>,
|
||||
sizes: Vec<Size>,
|
||||
bounds: Vec<Option<[f32; 4]>>,
|
||||
runtime: LayoutRuntime,
|
||||
custom: bool,
|
||||
}
|
||||
type Shared = Arc<Mutex<Plan>>;
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum Phase {
|
||||
Measure,
|
||||
Arrange,
|
||||
}
|
||||
impl Phase {
|
||||
fn method(self) -> &'static str {
|
||||
match self {
|
||||
Self::Measure => "measure",
|
||||
Self::Arrange => "arrange",
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct Step {
|
||||
plan: Shared,
|
||||
index: usize,
|
||||
phase: Phase,
|
||||
mount: ObjectRef,
|
||||
desktop: ObjectRef,
|
||||
}
|
||||
impl NativeCallable for Step {
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let mount = cx.store().payload::<Mount>(self.mount, "Mount")?.clone();
|
||||
let definition = cx
|
||||
.store()
|
||||
.type_of(mount.block)?
|
||||
.ok_or(invalid("untyped layout target"))?;
|
||||
let method = cx
|
||||
.store()
|
||||
.lookup_method(definition, self.phase.method())?
|
||||
.ok_or(invalid("missing layout method"))?;
|
||||
let native = cx
|
||||
.store()
|
||||
.lookup_method(
|
||||
desktop_type(cx.store(), "Block", self.desktop)?,
|
||||
self.phase.method(),
|
||||
)?
|
||||
.ok_or(invalid("missing native layout method"))?;
|
||||
let (node, children, bounds, native_size) = {
|
||||
let mut plan = self
|
||||
.plan
|
||||
.lock()
|
||||
.map_err(|_| invalid("layout plan poisoned"))?;
|
||||
let node = plan.nodes[self.index].clone();
|
||||
let children = plan.children[self.index]
|
||||
.iter()
|
||||
.map(|child| plan.sizes[*child])
|
||||
.collect::<Vec<_>>();
|
||||
let bounds = plan.bounds[self.index];
|
||||
let native_size = if matches!(self.phase, Phase::Measure) && method == native {
|
||||
Some(
|
||||
plan.runtime
|
||||
.measure_node(&node, children.clone())
|
||||
.map_err(|_| invalid("native measurement exceeds layout limits"))?,
|
||||
)
|
||||
} else {
|
||||
if method != native {
|
||||
plan.custom = true;
|
||||
}
|
||||
if matches!(self.phase, Phase::Measure) {
|
||||
plan.runtime.measured += 1;
|
||||
}
|
||||
None
|
||||
};
|
||||
if matches!(self.phase, Phase::Arrange) {
|
||||
plan.runtime.arranged += 1;
|
||||
}
|
||||
(node, children, bounds, native_size)
|
||||
};
|
||||
let context = mount.layout.ok_or(invalid("missing pre-layout context"))?;
|
||||
{
|
||||
let mut context = context
|
||||
.lock()
|
||||
.map_err(|_| invalid("layout context poisoned"))?;
|
||||
context.node = Some(node);
|
||||
context.children = children;
|
||||
context.bounds = bounds;
|
||||
}
|
||||
if let Some(size) = native_size {
|
||||
return Ok(NativeResult::Return(Value::Object(record(
|
||||
cx,
|
||||
self.desktop,
|
||||
"MeasureResult",
|
||||
vec![("width", value(size.width)), ("height", value(size.height))],
|
||||
)?)));
|
||||
}
|
||||
let input = match self.phase {
|
||||
Phase::Measure => record(
|
||||
cx,
|
||||
self.desktop,
|
||||
"Constraints",
|
||||
vec![
|
||||
("minWidth", value(0.0)),
|
||||
("minHeight", value(0.0)),
|
||||
("maxWidth", value(MAX_DIMENSION as f32)),
|
||||
("maxHeight", value(MAX_DIMENSION as f32)),
|
||||
],
|
||||
)?,
|
||||
Phase::Arrange => {
|
||||
let [x, y, width, height] =
|
||||
bounds.ok_or(invalid("arrangement has no allocated bounds"))?;
|
||||
record(
|
||||
cx,
|
||||
self.desktop,
|
||||
"Bounds",
|
||||
vec![
|
||||
("x", value(x)),
|
||||
("y", value(y)),
|
||||
("width", value(width)),
|
||||
("height", value(height)),
|
||||
],
|
||||
)?
|
||||
}
|
||||
};
|
||||
Ok(NativeResult::Invoke {
|
||||
function: method,
|
||||
arguments: vec![
|
||||
Value::Object(mount.block),
|
||||
Value::Object(self.mount),
|
||||
Value::Object(input),
|
||||
],
|
||||
})
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct Collect {
|
||||
plan: Shared,
|
||||
index: usize,
|
||||
phase: Phase,
|
||||
desktop: ObjectRef,
|
||||
}
|
||||
impl NativeCallable for Collect {
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let [Value::Object(result)] = args else {
|
||||
return Err(invalid("layout must return a managed result"));
|
||||
};
|
||||
let expected = match self.phase {
|
||||
Phase::Measure => "MeasureResult",
|
||||
Phase::Arrange => "Arrangement",
|
||||
};
|
||||
if !cx
|
||||
.store()
|
||||
.is_instance(*result, desktop_type(cx.store(), expected, self.desktop)?)?
|
||||
{
|
||||
return Err(invalid("layout returned the wrong result type"));
|
||||
}
|
||||
let mut plan = self
|
||||
.plan
|
||||
.lock()
|
||||
.map_err(|_| invalid("layout plan poisoned"))?;
|
||||
match self.phase {
|
||||
Phase::Measure => {
|
||||
let size = Size {
|
||||
width: number(cx, *result, "width", false)?,
|
||||
height: number(cx, *result, "height", false)?,
|
||||
};
|
||||
plan.sizes[self.index] = size;
|
||||
if self.index == 0 {
|
||||
plan.bounds[0] = Some([0.0, 0.0, size.width, size.height]);
|
||||
}
|
||||
}
|
||||
Phase::Arrange => {
|
||||
let Value::Object(list) = cx.store().get_attr(*result, "children")? else {
|
||||
return Err(invalid("Arrangement.children must be an ObjectList"));
|
||||
};
|
||||
let items = object_list::items(cx.store(), list)?;
|
||||
let children = plan.children[self.index].clone();
|
||||
if items.len() != children.len() {
|
||||
return Err(invalid(
|
||||
"Arrangement must assign every child slot exactly once",
|
||||
));
|
||||
}
|
||||
let slots: HashMap<_, _> = plan.nodes[self.index]
|
||||
.slots
|
||||
.iter()
|
||||
.copied()
|
||||
.enumerate()
|
||||
.map(|(index, slot)| (slot, index))
|
||||
.collect();
|
||||
let mut assigned = BTreeSet::new();
|
||||
let expected = desktop_type(cx.store(), "Bounds", self.desktop)?;
|
||||
for item in items {
|
||||
if !cx.store().is_instance(*item, expected)? {
|
||||
return Err(invalid("Arrangement child must be Bounds"));
|
||||
}
|
||||
let Value::Number(slot) = cx.store().get_attr(*item, "slot")? else {
|
||||
return Err(invalid("Arrangement child requires a slot"));
|
||||
};
|
||||
let slot = slot
|
||||
.as_i64()
|
||||
.and_then(|value| u64::try_from(value).ok())
|
||||
.ok_or(invalid("invalid arrangement slot"))?;
|
||||
let position = slots
|
||||
.get(&slot)
|
||||
.copied()
|
||||
.ok_or(invalid("Arrangement references a foreign child slot"))?;
|
||||
if !assigned.insert(slot) {
|
||||
return Err(invalid("duplicate arrangement slot"));
|
||||
}
|
||||
let bounds = [
|
||||
number(cx, *item, "x", false)?,
|
||||
number(cx, *item, "y", false)?,
|
||||
number(cx, *item, "width", false)?,
|
||||
number(cx, *item, "height", false)?,
|
||||
];
|
||||
if bounds[0] + bounds[2] > MAX_DIMENSION as f32
|
||||
|| bounds[1] + bounds[3] > MAX_DIMENSION as f32
|
||||
{
|
||||
return Err(invalid("arrangement bounds exceed limits"));
|
||||
}
|
||||
plan.bounds[children[position]] = Some(bounds);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(NativeResult::Return(Value::Nil))
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct Prepare {
|
||||
plan: Shared,
|
||||
mounts: Vec<WeakObjectRef>,
|
||||
desktop: ObjectRef,
|
||||
}
|
||||
impl NativeCallable for Prepare {
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let mut instructions = Vec::new();
|
||||
let mut constants = Vec::new();
|
||||
for phase in [Phase::Measure, Phase::Arrange] {
|
||||
let indices: Vec<_> = match phase {
|
||||
Phase::Measure => (0..self.mounts.len()).rev().collect(),
|
||||
Phase::Arrange => (0..self.mounts.len()).collect(),
|
||||
};
|
||||
for index in indices {
|
||||
let mount = cx
|
||||
.upgrade(self.mounts[index])?
|
||||
.ok_or(invalid("layout Mount expired"))?;
|
||||
let step = cx.allocate(ContextNativeFunction::new(
|
||||
"layout step",
|
||||
Step {
|
||||
plan: self.plan.clone(),
|
||||
index,
|
||||
phase,
|
||||
mount,
|
||||
desktop: self.desktop,
|
||||
},
|
||||
vec![mount, self.desktop],
|
||||
))?;
|
||||
let collector = cx.allocate(ContextNativeFunction::new(
|
||||
"collect layout",
|
||||
Collect {
|
||||
plan: self.plan.clone(),
|
||||
index,
|
||||
phase,
|
||||
desktop: self.desktop,
|
||||
},
|
||||
vec![self.desktop],
|
||||
))?;
|
||||
let start = constants.len() as u32;
|
||||
constants.extend([Value::Object(collector), Value::Object(step)]);
|
||||
instructions.extend([
|
||||
Instruction::new(Opcode::LoadConst, start),
|
||||
Instruction::simple(Opcode::PushNull),
|
||||
Instruction::new(Opcode::LoadConst, start + 1),
|
||||
Instruction::simple(Opcode::PushNull),
|
||||
Instruction::new(Opcode::Call, 0),
|
||||
Instruction::new(Opcode::Call, 1),
|
||||
Instruction::simple(Opcode::PopTop),
|
||||
]);
|
||||
}
|
||||
}
|
||||
let end = constants.len() as u32;
|
||||
constants.push(Value::Nil);
|
||||
instructions.extend([
|
||||
Instruction::new(Opcode::LoadConst, end),
|
||||
Instruction::simple(Opcode::ReturnValue),
|
||||
]);
|
||||
let code = EndorCode::from_instructions(&instructions, constants, CodeLayout::default())?
|
||||
.with_location("<source layout>", "<tessera>", 1);
|
||||
let code = cx.allocate(EndorCodeObject::new(code))?;
|
||||
let globals = cx.new_dict()?;
|
||||
let function = cx.new_function("source layout", code, globals)?;
|
||||
Ok(NativeResult::Invoke {
|
||||
function,
|
||||
arguments: vec![],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render(
|
||||
vm: &mut Vm,
|
||||
desktop: ObjectRef,
|
||||
mounts: Vec<WeakObjectRef>,
|
||||
root: Arc<UiNode>,
|
||||
frame: &mut Frame,
|
||||
runtime: &mut LayoutRuntime,
|
||||
) -> Result<BTreeSet<ObjectRef>> {
|
||||
// Preserve the existing native measurement cache and avoid VM/result
|
||||
// allocation for trees without custom layout methods. Contexts already exist.
|
||||
let block_type = desktop_type(vm.object_store(), "Block", desktop)?;
|
||||
let native_measure = vm.object_store().lookup_method(block_type, "measure")?;
|
||||
let native_arrange = vm.object_store().lookup_method(block_type, "arrange")?;
|
||||
let mut custom = false;
|
||||
for weak in &mounts {
|
||||
let mount = vm
|
||||
.upgrade(*weak)?
|
||||
.ok_or_else(|| anyhow::anyhow!("layout Mount expired"))?;
|
||||
let result = (|| {
|
||||
let block = vm.payload::<Mount>(mount, "Mount")?.block;
|
||||
let definition = vm
|
||||
.object_store()
|
||||
.type_of(block)?
|
||||
.ok_or(invalid("untyped layout target"))?;
|
||||
Ok::<_, VmError>(
|
||||
vm.object_store().lookup_method(definition, "measure")? != native_measure
|
||||
|| vm.object_store().lookup_method(definition, "arrange")? != native_arrange,
|
||||
)
|
||||
})();
|
||||
vm.release(mount)?;
|
||||
custom |= result?;
|
||||
}
|
||||
if !custom {
|
||||
let mut native = runtime.frame(&root)?;
|
||||
// Only the structural pass consumes a published version.
|
||||
native.layout_version = frame.layout_version;
|
||||
runtime.version = frame.layout_version;
|
||||
*frame = native;
|
||||
return Ok(BTreeSet::new());
|
||||
}
|
||||
let mut nodes = Vec::new();
|
||||
let mut work = vec![root];
|
||||
while let Some(node) = work.pop() {
|
||||
work.extend(node.children().iter().rev().cloned());
|
||||
nodes.push(node);
|
||||
}
|
||||
anyhow::ensure!(
|
||||
nodes.len() == mounts.len() && nodes.len() == frame.mounts.len(),
|
||||
"layout structure does not match Mount contexts"
|
||||
);
|
||||
let indices: HashMap<_, _> = frame
|
||||
.mounts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, mount)| (mount.id, index))
|
||||
.collect();
|
||||
let mut children = vec![Vec::new(); nodes.len()];
|
||||
for (index, mount) in frame.mounts.iter().enumerate() {
|
||||
if let Some(parent) = mount.parent {
|
||||
children[indices[&parent]].push(index);
|
||||
}
|
||||
}
|
||||
let plan = Arc::new(Mutex::new(Plan {
|
||||
sizes: vec![Size::default(); nodes.len()],
|
||||
bounds: vec![None; nodes.len()],
|
||||
nodes,
|
||||
children,
|
||||
runtime: runtime.clone(),
|
||||
custom: false,
|
||||
}));
|
||||
let prepare = vm.allocate(ContextNativeFunction::new(
|
||||
"prepare source layout",
|
||||
Prepare {
|
||||
plan: plan.clone(),
|
||||
mounts,
|
||||
desktop,
|
||||
},
|
||||
vec![desktop],
|
||||
))?;
|
||||
let result = vm.call_read_only_with_limits(
|
||||
prepare,
|
||||
&[],
|
||||
endor_core::ExecutionLimits {
|
||||
max_frames: 128,
|
||||
max_instructions: 1_000_000,
|
||||
},
|
||||
);
|
||||
vm.release(prepare)?;
|
||||
let (value, reads) = result.map_err(|error| crate::endor_host::runtime_error(vm, error))?;
|
||||
vm.release_value(value)?;
|
||||
let plan = plan
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("layout plan poisoned"))?;
|
||||
frame.commands.clear();
|
||||
for (index, mount) in frame.mounts.iter_mut().enumerate() {
|
||||
let [x, y, width, height] =
|
||||
plan.bounds[index].ok_or_else(|| anyhow::anyhow!("unarranged occurrence"))?;
|
||||
mount.x = x;
|
||||
mount.y = y;
|
||||
mount.width = width;
|
||||
mount.height = height;
|
||||
if let Some(command) =
|
||||
layout::paint_native(&plan.nodes[index], x, y, Size { width, height })
|
||||
{
|
||||
command.validate()?;
|
||||
frame.commands.push(command);
|
||||
}
|
||||
}
|
||||
*runtime = plan.runtime.clone();
|
||||
if !plan.custom {
|
||||
return Ok(BTreeSet::new());
|
||||
}
|
||||
let registry = match vm.get_attr(desktop, "types")? {
|
||||
Value::Object(object) => object,
|
||||
_ => anyhow::bail!("missing type registry"),
|
||||
};
|
||||
Ok(reads
|
||||
.into_iter()
|
||||
.filter(|object| {
|
||||
*object != desktop
|
||||
&& *object != registry
|
||||
&& vm
|
||||
.object(*object)
|
||||
.is_ok_and(|object| !object.payload().as_any().is::<Mount>())
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
Reference in New Issue
Block a user