//! 从可变托管对象图提取不可变 UiNode,并维护反向依赖与父子失效传播。 //! 缓存只借用可检查的对象身份,不增加托管根。对象释放后必须清理缓存索引;快照仍可持有独立的原生数值数据。 //! 干净子树直接复用 Arc;脏节点重新检查属性、方法、绑定和子项,循环与展开数量在发布前拒绝。 //! //! Object-to-visual dependencies. Cached results never own VM references. use crate::{ block::{self, Kind}, ui_bridge::{UiKind, UiNode}, }; use endor_core::{ChangeBatch, ChangeKey, ObjectRef, ObjectStore, Value, VmError}; use std::{ collections::{HashMap, HashSet, VecDeque}, sync::Arc, }; #[derive(Debug)] /// 某个业务组件的视觉快照,以及使它失效的读取依赖和子项身份。 struct Cached { node: Arc, dependencies: Vec, children: Vec, } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] /// 反向依赖键:区分整个对象内容和精确属性名称,减少无关字段变化引起的失效。 struct Dependency { object: ObjectRef, property: Option, } #[derive(Debug, Default)] /// 视觉快照缓存与反向依赖图。对象身份是借用索引,原生 Arc 数据不拥有 VM 根。 pub struct RenderCache { scenes3d: HashMap>, entries: HashMap, dependents: HashMap>, parents: HashMap>, dirty: HashSet, pub last_invalidation: String, pub visited: usize, pub reused: usize, } impl RenderCache { /// 把 VM 变化映射到读取过这些属性/对象的视觉节点,再沿父链向上传播脏标记。 pub fn invalidate(&mut self, batch: ChangeBatch) { let mut queue = VecDeque::new(); if batch.rescan_required { self.last_invalidation = "change journal overflow".into(); queue.extend(self.entries.keys().copied()); } else { for change in batch.changes { let key = Dependency { object: change.object, property: match change.key { ChangeKey::Attribute(name) => Some(name), ChangeKey::Contents => None, }, }; if let Some(owners) = self.dependents.get(&key) { self.last_invalidation = format!("{} {:?}", key.object, key.property); queue.extend(owners); } } } self.invalidate_objects(queue); } /// 迭代传播显式失效,使用集合避免共享父链重复遍历或循环入队。 pub fn invalidate_objects(&mut self, objects: impl IntoIterator) { let mut queue: VecDeque<_> = objects.into_iter().collect(); while let Some(block) = queue.pop_front() { if self.dirty.insert(block) && let Some(parents) = self.parents.get(&block) { queue.extend(parents); } } } /// 撤销旧缓存的反向读取边和父子边,为重新登记该节点做准备。 fn remove(&mut self, block: ObjectRef) -> Option { let old = self.entries.remove(&block)?; for source in &old.dependencies { if let Some(owners) = self.dependents.get_mut(source) { owners.remove(&block); if owners.is_empty() { self.dependents.remove(source); } } } for child in &old.children { if let Some(parents) = self.parents.get_mut(child) { parents.remove(&block); if parents.is_empty() { self.parents.remove(child); } } } Some(old) } /// 删除托管堆中已不存在的身份,缓存本身不负责保持业务对象存活。 pub fn prune(&mut self, store: &ObjectStore) { self.scenes3d .retain(|object, _| store.object(*object).is_ok()); let dead: Vec<_> = self .entries .keys() .filter(|v| store.object(**v).is_err()) .copied() .collect(); for block in dead { self.remove(block); self.dirty.remove(&block); } } /// 按显式栈遍历托管组成;复用干净子树,重建脏节点,并在完成前检查循环和资源上限。 pub fn snapshot( &mut self, store: &ObjectStore, root: ObjectRef, ) -> Result, VmError> { self.visited = 0; self.reused = 0; let mut work = vec![(root, false)]; let mut path = HashSet::new(); let mut values = Vec::>::new(); while let Some((block, finish)) = work.pop() { // 入栈时先尝试复用;退出标记表示孩子已形成快照,可以组装父节点。 if !finish { if !self.dirty.contains(&block) && let Some(cached) = self.entries.get(&block) { self.reused += 1; values.push(cached.node.clone()); continue; } self.visited += 1; if self.visited > 10_000 { return Err(VmError::ExecutionLimit("expanded Block graph")); } } store.check_typed_instance_storage(block)?; let (data_ref, raw_data, raw_dependencies) = block::resolve_tracked(store, block)?; let mut data = block::visual_data(store, raw_data)?; let mut dependencies: Vec<_> = raw_dependencies .into_iter() .map(|object| Dependency { object, property: None, }) .collect(); let storage = *store .attribute_path(block)? .last() .expect("nonempty attribute path"); for name in store.typed_method_names(block)? { dependencies.push(Dependency { object: storage, property: Some(name), }); } if let Some(properties) = data.properties { for (name, _) in block::native_properties(&data) { dependencies.push(Dependency { object: properties, property: Some(name.into()), }); } } if matches!(data.kind, Kind::CanvasViewport { .. }) && let Some(camera) = data.camera { for name in ["x", "y", "zoom"] { dependencies.push(Dependency { object: camera, property: Some(name.into()), }); } } let mut panel_sizes = Vec::new(); let view3d = if matches!(data.kind, Kind::Viewport3D { .. }) { let scene = data .scene3d .ok_or(VmError::InvalidArgument("missing Scene3D"))?; let (view, reads, panels) = crate::scene3d_model::snapshot_reusing( store, scene, data.camera .ok_or(VmError::InvalidArgument("missing 3D camera"))?, self.scenes3d.get(&scene).cloned(), )?; self.scenes3d.insert(scene, view.scene.clone()); dependencies.extend(reads.into_iter().map(|(object, name)| Dependency { object, property: Some(name), })); data.children = panels .into_iter() .map(|panel| { panel_sizes.push(panel.size); crate::block::Child { slot: panel.key, block: panel.content, } }) .collect(); Some(view) } else { None }; // path 只追踪当前祖先链,因此允许同一业务组件在不同分支多次出现。 if !finish { if !path.insert(data_ref) { return Err(VmError::InvalidArgument("cyclic Block composition")); } work.push((block, true)); for child in data.children.iter().rev() { work.push((child.block, false)); } continue; } path.remove(&data_ref); let mut protocol_key = String::new(); let mut custom_event = false; if let Some(definition) = store.type_of(block)? { protocol_key.push_str(&definition.to_string()); for name in ["measure", "arrange", "paint", "hitTest", "onEvent"] { if let Some(method) = store.lookup_method(definition, name)? { let version = store.change_version(method)?; protocol_key.push_str(&format!("/{method}:{version}")); dependencies.push(Dependency { object: method, property: None, }); } } let event = store.lookup_method(definition, "onEvent")?; let mut current = Some(definition); while let Some(definition) = current { dependencies.push(Dependency { object: definition, property: None, }); let item = store.payload::(definition, "Type")?; current = item.base(); } custom_event = event .map(|function| { crate::ui_bridge::is_intrinsic_event(store, function).map(|native| !native) }) .transpose()? .unwrap_or(false); } let mut click_connection = false; for connection in &data.subscriptions { dependencies.push(Dependency { object: *connection, property: None, }); let item = store .payload::(*connection, "Connection")?; click_connection |= item.kind == "click" && item.handler.is_some(); } let children = values.split_off(values.len() - data.children.len()); let kind = match &data.kind { Kind::Text { value, size, color } => { let value = if let Some((source, field)) = &data.text_binding { let storage = store.attribute_path(*source)?; for (index, object) in storage.iter().enumerate() { dependencies.push(Dependency { object: *object, property: (index + 1 == storage.len()).then(|| field.clone()), }); } match store.get_attr(*source, field)? { Value::Nil => "nil".into(), Value::Bool(v) => v.to_string(), Value::Number(v) => v.to_string(), Value::Text(v) => v, Value::Object(v) => { dependencies.push(Dependency { object: v, property: None, }); store.str(v)? } } } else { value.clone() }; UiKind::Text { value, size: *size, color: color.clone(), } } Kind::Rect { width, height, radius, color, } => UiKind::Rect { width: *width, height: *height, radius: *radius, color: color.clone(), }, Kind::Scroll { width, height } => UiKind::Scroll { axis: data.scroll_axis, width: *width, height: *height, padding: data.padding, gap: data.gap, children, }, Kind::Spacer(size) => UiKind::Spacer(*size), Kind::Viewport3D { width, height } => UiKind::Viewport3D { width: *width, height: *height, view: view3d.ok_or(VmError::InvalidArgument("missing 3D view"))?, controls: data.controller.is_some(), panels: panel_sizes, children, }, Kind::CanvasViewport { width, height } => UiKind::CanvasViewport { width: *width, height: *height, camera: crate::viewport::camera( store, data.camera .ok_or(VmError::InvalidArgument("missing camera"))?, )?, children, }, Kind::Scene2D => UiKind::Scene2D { positions: data .children .iter() .map(|child| { let (_, child) = block::resolve(store, child.block)?; Ok(block::visual_data(store, child)?.position) }) .collect::, VmError>>()?, children, }, Kind::Overlay => UiKind::Overlay { padding: data.padding, children, }, Kind::Row => UiKind::Row { padding: data.padding, gap: data.gap, children, }, Kind::Page if data.surface.mode == crate::page::Mode::Canvas => UiKind::Canvas { positions: data .children .iter() .map(|child| { let (_, data) = block::resolve(store, child.block)?; Ok(block::visual_data(store, data)?.position) }) .collect::, VmError>>()?, children, }, Kind::Page if data.surface.mode == crate::page::Mode::Horizontal => UiKind::Row { padding: data.padding, gap: data.gap, children, }, Kind::Column | Kind::Page => UiKind::Column { padding: data.padding, gap: data.gap, children, }, Kind::Button => UiKind::Button { padding: data.padding, gap: data.gap, children, }, }; let next = UiNode { surface: matches!(data.kind, Kind::Page).then(|| { let mut surface = data.surface.clone(); surface.page = block.to_string(); surface }), flex: data.flex, flex_policy: data.flex_policy, main_align: data.main_align, cross_align: data.cross_align, align_self: data.align_self, margin: data.margin, sizing: data.sizing, padding_edges: data.padding_edges, border: data.border, border_color: data.border_color.clone(), clip_children: data.clip_children, block_id: block.to_string(), protocol_key, slots: data.children.iter().map(|c| c.slot).collect(), interactive: matches!(&data.kind, Kind::Button | Kind::Viewport3D { .. }) || data.click.is_some() || click_connection || custom_event, kind, }; let old = self.remove(block); let node = if let Some(old) = old.as_ref().filter(|old| old.node.shallow_eq(&next)) { old.node.clone() } else { Arc::new(next) }; dependencies.sort_unstable(); dependencies.dedup(); let child_refs: Vec<_> = data.children.iter().map(|child| child.block).collect(); for source in &dependencies { self.dependents .entry(source.clone()) .or_default() .insert(block); } for child in &child_refs { self.parents.entry(*child).or_default().insert(block); } self.entries.insert( block, Cached { node: node.clone(), dependencies, children: child_refs, }, ); self.dirty.remove(&block); values.push(node); } values .pop() .ok_or(VmError::InvalidArgument("empty Block snapshot")) } }