//! 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::{BTreeMap, BTreeSet, HashMap, HashSet}, sync::{Arc, Mutex}, }; fn invalid(message: &'static str) -> VmError { VmError::InvalidArgument(message) } fn desktop_type_registry(cx: &NativeContext<'_>, desktop: ObjectRef) -> Result { match cx.store().get_attr(desktop, "types")? { Value::Object(object) => Ok(object), _ => Err(invalid("missing type registry")), } } #[derive(Debug, Clone)] struct Measurement { owner: ObjectRef, method: ObjectRef, children: Vec, constraints: [f32; 4], size: Size, reads: BTreeMap, } /// Borrowed identities and versions only: this cache adds no managed roots. #[derive(Debug, Default, Clone)] pub struct Cache { entries: HashMap, pub hits: usize, pub misses: usize, } impl Cache { pub fn invalidate(&mut self, owners: &HashSet) { self.entries .retain(|_, entry| !owners.contains(&entry.owner)); } pub fn clear(&mut self) { self.entries.clear(); self.hits = 0; self.misses = 0; } } #[derive(Debug)] struct Pending { token: usize, owner: ObjectRef, method: ObjectRef, children: Vec, constraints: [f32; 4], key: WeakObjectRef, } #[derive(Debug)] struct Plan { nodes: Vec>, children: Vec>, sizes: Vec, preferred: Vec>, bounds: Vec>, runtime: LayoutRuntime, custom: bool, cache: Cache, pending: Vec>, constraints: Vec<[f32; 4]>, // Source-arranged dimensions remain exact for this solve, not business state. allocations: Vec<[Option; 2]>, custom_arrange: Vec, native_arrange: Vec, custom_measure: Vec, measured_limits: Vec<[Option; 2]>, previous: Option>, seen: BTreeSet>, } type Shared = Arc>; #[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 arity(&self) -> Option { Some(endor_core::CallArity::exact(0)) } fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result { let mount = cx.store().payload::(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 intrinsic = crate::native_visual::is_intrinsic( cx.store(), method, self.phase.method(), self.desktop, )?; let (node, children, preferred, 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::>(); let preferred = plan.children[self.index] .iter() .map(|child| plan.preferred[*child].unwrap_or(plan.sizes[*child])) .collect::>(); let bounds = if matches!(self.phase, Phase::Arrange) { plan.bounds[self.index] } else { None }; if matches!(self.phase, Phase::Measure) { plan.custom_measure[self.index] = !intrinsic; } let native_size = if matches!(self.phase, Phase::Measure) && intrinsic { let constraints = plan.constraints[self.index]; Some( plan.runtime .measure_node(&node, children.clone(), constraints) .map_err(|_| invalid("native measurement exceeds layout limits"))?, ) } else { if !intrinsic { plan.custom = true; } if matches!(self.phase, Phase::Measure) { let key = cx.store().downgrade(self.mount)?; let constraints = plan.constraints[self.index]; let cached = plan .cache .entries .get(&key) .filter(|entry| { entry.owner == mount.block && entry.method == method && entry.children == children && entry.constraints == constraints && entry.reads.iter().all(|(object, version)| { cx.store().change_version(*object).ok() == Some(*version) }) }) .map(|entry| entry.size); if let Some(size) = cached { plan.cache.hits += 1; Some(size) } else { plan.cache.misses += 1; plan.runtime.measured += 1; plan.pending[self.index] = Some(Pending { token: 0, owner: mount.block, method, children: children.clone(), constraints, key, }); None } } else { None } }; if matches!(self.phase, Phase::Arrange) { plan.runtime.arranged += 1; plan.native_arrange[self.index] = intrinsic; plan.custom_arrange[self.index] = !intrinsic || node.children().iter().any(|child| child.has_flex()); } (node, children, preferred, 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.preferred = preferred; 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 => { let constraints = self .plan .lock() .map_err(|_| invalid("layout plan poisoned"))? .constraints[self.index]; record( cx, self.desktop, "Constraints", vec![ ("minWidth", value(constraints[0])), ("minHeight", value(constraints[1])), ("maxWidth", value(constraints[2])), ("maxHeight", value(constraints[3])), ], )? } 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)), ], )? } }; if matches!(self.phase, Phase::Measure) { let token = cx.store().begin_read_tracking()?; self.plan .lock() .map_err(|_| invalid("layout plan poisoned"))? .pending[self.index] .as_mut() .ok_or(invalid("missing measurement tracking state"))? .token = token; } 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 arity(&self) -> Option { Some(endor_core::CallArity::exact(1)) } fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result { let pending = if matches!(self.phase, Phase::Measure) { self.plan .lock() .map_err(|_| invalid("layout plan poisoned"))? .pending[self.index] .take() } else { None }; 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 = layout::constrained( Size { width: number(cx, *result, "width", false)?, height: number(cx, *result, "height", false)?, }, plan.constraints[self.index], ); // Native shrink-to-content containers keep their existing input // policy. Only a source measurement that differs from the native // result supplies an additional content constraint. if plan.custom_measure[self.index] && !plan.children[self.index].is_empty() { let children = plan.children[self.index] .iter() .map(|child| plan.sizes[*child]) .collect(); let native = layout::measure_native( &plan.nodes[self.index], children, plan.constraints[self.index], ) .ok() .map(|native| layout::constrained(native, plan.constraints[self.index])); // Equality after remeasurement does not retract a source // limit selected earlier in this solve. New renders start fresh. if !native.is_some_and(|native| native.width == size.width) { plan.measured_limits[self.index][0] = Some(size.width); } if !native.is_some_and(|native| native.height == size.height) { plan.measured_limits[self.index][1] = Some(size.height); } } // Decoding is part of the subcall dependency region: a source // method may return an existing result whose fields can change. let tracked = pending .map(|pending| { cx.store() .end_read_tracking_details(pending.token) .map(|reads| (pending, reads)) }) .transpose()?; if let Some((pending, reads)) = tracked { let mut versions = BTreeMap::new(); let mut volatile = false; let registry = desktop_type_registry(cx, self.desktop)?; for read in reads { let object = read.object; if object == self.desktop || object == registry { continue; } // A Mount's layoutVersion/geometry may be observed by // source. Object-granular tracking cannot prove those // accesses stable, so conservatively bypass its cache. if cx.store().object(object)?.payload().as_any().is::() { volatile |= read.content_read; continue; } versions.insert(object, cx.store().change_version(object)?); } if volatile { plan.cache.entries.remove(&pending.key); } else { plan.cache.entries.insert( pending.key, Measurement { owner: pending.owner, method: pending.method, children: pending.children, constraints: pending.constraints, size, reads: versions, }, ); } } plan.preferred[self.index].get_or_insert(size); 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")); } let child = children[position]; if plan.custom_arrange[self.index] { if plan.native_arrange[self.index] && let Some(main) = layout::main_axis(&plan.nodes[self.index]) { // Keep an allocation explicit even if this pass's // natural size happens to match it. It must survive // the next parent-constraint propagation pass. plan.allocations[child][main] = Some(bounds[main + 2]); } if bounds[2] != plan.sizes[child].width { plan.allocations[child][0] = Some(bounds[2]); } if bounds[3] != plan.sizes[child].height { plan.allocations[child][1] = Some(bounds[3]); } } plan.bounds[child] = Some(bounds); } } } Ok(NativeResult::Return(Value::Nil)) } } #[derive(Debug)] struct Settle { plan: Shared, mounts: Vec, } impl NativeCallable for Settle { fn arity(&self) -> Option { Some(endor_core::CallArity::exact(0)) } fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result { let repeat = { let mut plan = self .plan .lock() .map_err(|_| invalid("layout plan poisoned"))?; plan.runtime.settle_passes += 1; let mut next = plan.constraints.clone(); for index in 0..plan.nodes.len() { let children = plan.children[index].clone(); let [_, _, width, height] = plan.bounds[index].ok_or(invalid("unarranged occurrence"))?; let mut available = next[index]; if let Some(width) = plan.measured_limits[index][0] { available[2] = width; } if let Some(height) = plan.measured_limits[index][1] { available[3] = height; } if width != plan.sizes[index].width { available[2] = width; } if height != plan.sizes[index].height { available[3] = height; } let base = layout::arranged_child_constraints( &plan.nodes[index], available, Size { width, height }, ); for child in children { let mut constraints = base; if let Some(width) = plan.allocations[child][0] { constraints[0] = width; constraints[2] = width; } if let Some(height) = plan.allocations[child][1] { constraints[1] = height; constraints[3] = height; } if let Some(main) = layout::main_axis(&plan.nodes[index]) { let cross = 1 - main; if constraints[cross] != plan.constraints[child][cross] || constraints[cross + 2] != plan.constraints[child][cross + 2] { // Wrapping or other cross-dependent measurement // invalidates this occurrence's natural main size. plan.preferred[child] = None; if plan.native_arrange[index] { // Derived flex sizes must not constrain their // own replacement measurement. Source arrange // allocations remain authoritative. plan.allocations[child][main] = None; constraints[main] = base[main]; constraints[main + 2] = base[main + 2]; } } } next[child] = constraints; } } let mut state = Vec::with_capacity(plan.nodes.len() * 14); let bits = |value: f32| if value == 0.0 { 0 } else { value.to_bits() }; for (index, constraints) in next.iter().enumerate() { state.extend(constraints.iter().copied().map(bits)); state.extend([ bits(plan.sizes[index].width), bits(plan.sizes[index].height), ]); state.extend( plan.bounds[index] .ok_or(invalid("unarranged occurrence"))? .into_iter() .map(bits), ); for dimension in plan.allocations[index] { state.push(u32::from(dimension.is_some())); state.push(dimension.map_or(0, bits)); } state.push(u32::from(plan.preferred[index].is_some())); if let Some(size) = plan.preferred[index] { state.extend([bits(size.width), bits(size.height)]); } else { state.extend([0, 0]); } } if plan.previous.as_ref() == Some(&state) && plan.constraints == next { false } else { if !plan.seen.insert(state.clone()) { return Err(invalid("layout constraints did not converge (cycle)")); } plan.previous = Some(state); plan.constraints = next; plan.bounds.fill(None); true } }; if repeat { // No stale geometry from a prior pass is observable during measurement. for weak in &self.mounts { let mount = cx.upgrade(*weak)?.ok_or(invalid("layout Mount expired"))?; if let Some(context) = &cx.store().payload::(mount, "Mount")?.layout { context .lock() .map_err(|_| invalid("layout context poisoned"))? .bounds = None; } } } Ok(NativeResult::Return(Value::Bool(repeat))) } } #[derive(Debug)] struct Prepare { plan: Shared, mounts: Vec, desktop: ObjectRef, } impl NativeCallable for Prepare { fn arity(&self) -> Option { Some(endor_core::CallArity::exact(0)) } fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result { 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 settle = cx.allocate(ContextNativeFunction::new( "settle source layout", Settle { plan: self.plan.clone(), mounts: self.mounts.clone(), }, vec![], ))?; let check = constants.len() as u32; constants.push(Value::Object(settle)); instructions.extend([ Instruction::new(Opcode::LoadConst, check), Instruction::simple(Opcode::PushNull), Instruction::new(Opcode::Call, 0), ]); crate::vm_sequence::repeat_while(&mut instructions)?; 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("", "", 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, root: Arc, frame: &mut Frame, runtime: &mut LayoutRuntime, cache: &mut Cache, ) -> Result> { cache.hits = 0; cache.misses = 0; let live: HashSet<_> = mounts.iter().copied().collect(); cache.entries.retain(|mount, _| live.contains(mount)); // Preserve the existing native measurement cache and avoid VM/result // allocation for trees without custom layout methods. Contexts already exist. 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")?.block; let definition = vm .object_store() .type_of(block)? .ok_or(invalid("untyped layout target"))?; for name in ["measure", "arrange"] { let Some(method) = vm.object_store().lookup_method(definition, name)? else { return Ok::<_, VmError>(true); }; if !crate::native_visual::is_intrinsic(vm.object_store(), method, name, desktop)? { return Ok(true); } } Ok(false) })(); vm.release(mount)?; custom |= result?; } let mut nodes = Vec::new(); let mut work = vec![root.clone()]; while let Some(node) = work.pop() { custom |= node.has_flex(); work.extend(node.children().iter().rev().cloned()); nodes.push(node); } // Flex allocation can change text wrapping and ancestor measurements even // when every protocol method is native. Use the same settling driver. if !custom { cache.clear(); 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()); } 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 mut constraints = vec![layout::root_constraints(runtime.viewport); nodes.len()]; for index in 0..nodes.len() { let next = layout::child_constraints(&nodes[index], constraints[index]); for child in &children[index] { constraints[*child] = next; } } let count = nodes.len(); let plan = Arc::new(Mutex::new(Plan { sizes: vec![Size::default(); nodes.len()], preferred: vec![None; nodes.len()], bounds: vec![None; nodes.len()], nodes, children, runtime: runtime.clone(), custom: false, cache: cache.clone(), pending: (0..count).map(|_| None).collect(), constraints, allocations: vec![[None, None]; count], custom_arrange: vec![false; count], native_arrange: vec![false; count], custom_measure: vec![false; count], measured_limits: vec![[None, None]; count], previous: None, seen: BTreeSet::new(), })); let prepare = vm.allocate(ContextNativeFunction::new( "prepare source layout", Prepare { plan: plan.clone(), mounts, desktop, }, vec![desktop], ))?; let mut slices = 1; let result = (|| { let mut progress = vm.start_read_only_call( prepare, &[], endor_core::ExecutionLimits { max_frames: 128, max_instructions: 1_000_000, }, 256, )?; loop { match progress { endor_core::ExecutionProgress::Complete { value, reads, .. } => { return Ok((value, reads)); } endor_core::ExecutionProgress::Pending { .. } => { // The VM owns the continuation and keeps its read-only // dependency scope intact. Worker-level parking follows. std::thread::yield_now(); slices += 1; progress = vm.resume_read_only_call(256)?; } } } })(); vm.release(prepare)?; let (value, reads) = result.map_err(|error| crate::endor_host::runtime_error(vm, error))?; vm.release_value(value)?; let mut plan = plan .lock() .map_err(|_| anyhow::anyhow!("layout plan poisoned"))?; plan.runtime.slices = slices; 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(); *cache = plan.cache.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::()) }) .collect()) }