481 lines
22 KiB
Rust
481 lines
22 KiB
Rust
//! 从可变托管对象图提取不可变 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<UiNode>,
|
|
dependencies: Vec<Dependency>,
|
|
children: Vec<ObjectRef>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
|
/// 反向依赖键:区分整个对象内容和精确属性名称,减少无关字段变化引起的失效。
|
|
struct Dependency {
|
|
object: ObjectRef,
|
|
property: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Default)]
|
|
/// 视觉快照缓存与反向依赖图。对象身份是借用索引,原生 Arc 数据不拥有 VM 根。
|
|
pub struct RenderCache {
|
|
// 场景对象身份到原生不可变几何的缓存;相机改变时仍有机会复用同一场景数据。
|
|
scenes3d: HashMap<ObjectRef, Arc<crate::scene3d::Scene>>,
|
|
// 每个业务 Block 的视觉结果;这里只保存原生快照,不通过 ObjectRef 增加 VM 强引用。
|
|
entries: HashMap<ObjectRef, Cached>,
|
|
// 读取源 -> 读取它的 Block。属性变动从这里找到首批需要重建的快照。
|
|
dependents: HashMap<Dependency, HashSet<ObjectRef>>,
|
|
// 子 Block -> 所有父 Block。共享子组件改变后,所有引用该子项的父快照都需要更新。
|
|
parents: HashMap<ObjectRef, HashSet<ObjectRef>>,
|
|
// 已失效但尚未重建的 Block 集合,同时用于传播去重。
|
|
dirty: HashSet<ObjectRef>,
|
|
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 {
|
|
// 属性变更使用精确名称,Contents 使用整个对象键;与提取时登记的依赖粒度一致。
|
|
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<Item = ObjectRef>) {
|
|
let mut queue: VecDeque<_> = objects.into_iter().collect();
|
|
while let Some(block) = queue.pop_front() {
|
|
// 只有第一次加入 dirty 才继续向父链传播,避免共享祖先被反复展开。
|
|
if self.dirty.insert(block)
|
|
&& let Some(parents) = self.parents.get(&block)
|
|
{
|
|
queue.extend(parents);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 撤销旧缓存的反向读取边和父子边,为重新登记该节点做准备。
|
|
fn remove(&mut self, block: ObjectRef) -> Option<Cached> {
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
// 只撤销当前 Block 对孩子的父边;其他共享父节点仍保留。空集合及时删除以缩小索引。
|
|
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());
|
|
// 先收集死亡身份,再修改 entries 与反向索引,避免一边借用遍历一边删除。
|
|
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<Arc<UiNode>, VmError> {
|
|
self.visited = 0;
|
|
self.reused = 0;
|
|
// 使用进入/退出两阶段的显式 DFS,避免深层组成消耗 Rust 调用栈。
|
|
// values 是后序结果栈:每个退出节点消费刚完成的孩子快照,再压入自己。
|
|
let mut work = vec![(root, false)];
|
|
let mut path = HashSet::new();
|
|
let mut values = Vec::<Arc<UiNode>>::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;
|
|
}
|
|
// 计数的是本次实际展开次数;共享节点可复用缓存,脏图展开仍有 10000 次上限。
|
|
self.visited += 1;
|
|
if self.visited > 10_000 {
|
|
return Err(VmError::ExecutionLimit("expanded Block graph"));
|
|
}
|
|
}
|
|
// 提取前验证实例存储与类型契约;resolve_tracked 同时提供数据以及经过的代理/存储依赖。
|
|
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()),
|
|
});
|
|
}
|
|
}
|
|
// 3D 面板把托管内容映射为子 Block,同时保留尺寸与稳定 slot,供后续布局和出现身份使用。
|
|
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 pointer_connection = data.subscriptions.iter().any(|&o| {
|
|
store
|
|
.payload::<crate::event_dispatch::Connection>(o, "Subscription")
|
|
.is_ok_and(|s| s.handler.is_some() && s.kind.starts_with("pointer"))
|
|
});
|
|
// 协议键包含类型身份、实际方法身份及其内容版本,供布局/绘制缓存识别实现变化。
|
|
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::<endor_core::EndorTypeObject>(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);
|
|
}
|
|
// 订阅连接的取消会改变 handler;记录连接内容依赖,使交互资格能随取消及时更新。
|
|
let mut click_connection = false;
|
|
for connection in &data.subscriptions {
|
|
dependencies.push(Dependency {
|
|
object: *connection,
|
|
property: None,
|
|
});
|
|
let item = store
|
|
.payload::<crate::event_dispatch::Connection>(*connection, "Connection")?;
|
|
click_connection |= item.kind == "click" && item.handler.is_some();
|
|
}
|
|
// 逆序压入孩子确保后序结果与 data.children 原顺序一致;只取尾部的本节点孩子,保留兄弟结果。
|
|
let children = values.split_off(values.len() - data.children.len());
|
|
let kind = match &data.kind {
|
|
Kind::Text { value, size, color } => {
|
|
// 旧 textOf 路径按实际源字段提取字符串。属性路径中间对象用整对象依赖,末端用字段依赖。
|
|
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::<Result<Vec<_>, 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::<Result<Vec<_>, 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,
|
|
},
|
|
};
|
|
// 统一外层样式与交互标志。UiKind 只表示具体内容,UiNode 保存所有类别共享的视觉元信息。
|
|
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(),
|
|
pointer_events: pointer_connection,
|
|
interactive: pointer_connection
|
|
|| matches!(&data.kind, Kind::Button | Kind::Viewport3D { .. })
|
|
|| data.click.is_some()
|
|
|| click_connection
|
|
|| custom_event,
|
|
kind,
|
|
};
|
|
// 即使本次重算结果相同,也要重新登记依赖。shallow_eq 相同时复用旧 Arc,减少下游无效重建。
|
|
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"))
|
|
}
|
|
}
|