931 lines
40 KiB
Rust
931 lines
40 KiB
Rust
//! 每次展示的托管上下文:同一个 Block 出现在两个位置时,有两个独立 Mount。
|
|
//! Mount 保存父子关系、出现几何和布局期间的查询上下文;MountTable 用弱索引定位对象,不靠索引强行保活业务树。
|
|
//! 同步会安排 onMount/onUnmount。布局取消时使用 Checkpoint 恢复未发布状态,避免半完成的出现关系影响下一次刷新。
|
|
//!
|
|
//! Managed presentation contexts. The active desktop owns the mount dictionary;
|
|
//! reverse links and the host registry are weak, so shared content cannot retain a Page.
|
|
use crate::document::{Frame, MountGeometry};
|
|
use endor_core::{
|
|
ContextNativeFunction, NativeCallable, NativeContext, NativeResult, ObjectPayload, ObjectRef,
|
|
Value, Vm, VmError, WeakObjectRef,
|
|
};
|
|
use std::{
|
|
collections::HashMap,
|
|
sync::{Arc, Mutex},
|
|
};
|
|
|
|
#[derive(Debug, Clone)]
|
|
/// 一个组件在一个展示位置上的上下文。强持有 Block,反向页面/父子链接使用弱身份,避免共享组件把已关闭页面保活。
|
|
pub struct Mount {
|
|
// 组件是强引用;页面、父节点和兄弟链接是弱引用,防止反向链接形成保活环。
|
|
pub block: ObjectRef,
|
|
pub page: Option<WeakObjectRef>,
|
|
pub parent: Option<WeakObjectRef>,
|
|
pub first_child: Option<WeakObjectRef>,
|
|
pub next_sibling: Option<WeakObjectRef>,
|
|
// 已发布几何与每次出现的滚动位置分开保存,同一 Block 的多个位置互不覆盖。
|
|
pub geometry: MountGeometry,
|
|
pub scroll_offset: [f32; 2],
|
|
// 最后同步的布局版本,Bounds 查询会一并返回,便于调用方识别几何属于哪轮发布。
|
|
pub version: u64,
|
|
// false 后禁止依赖当前几何的操作;外部即使还持有 Mount 对象也不能把它当活动出现。
|
|
pub mounted: bool,
|
|
// Mount 可以拥有任务;退役后任务交付还要检查 owner 是否仍有效。
|
|
pub tasks: Option<ObjectRef>,
|
|
// Private derived scratch, installed before the read-only layout call and
|
|
// cleared by geometry commit. It contains no managed references or roots.
|
|
pub layout: Option<Arc<Mutex<crate::layout::Context>>>,
|
|
}
|
|
|
|
impl ObjectPayload for Mount {
|
|
/// 声明此 payload 的赋值遵循引用身份语义,避免把内部宿主状态当作可复制值。
|
|
fn reference_assignment_only(&self) -> bool {
|
|
true
|
|
}
|
|
/// 提供受检查的 Any 下转型入口,让宿主按具体 payload 类型读取数据。
|
|
fn as_any(&self) -> &dyn std::any::Any {
|
|
self
|
|
}
|
|
/// 返回运行时诊断/类型检查使用的稳定 payload 名称。
|
|
fn kind_name(&self) -> &'static str {
|
|
"tessera-mount"
|
|
}
|
|
/// 声明此 payload 是否允许使用托管属性存储,具体字段仍由类型与调用检查约束。
|
|
fn allows_attributes(&self) -> bool {
|
|
true
|
|
}
|
|
/// 枚举本对象真正拥有的托管强引用,供 Aster 引用追踪和循环回收使用。
|
|
// 仅 block 和 tasks 是 payload 的强拥有边;page/parent/child/sibling 是弱边,不参与 trace。
|
|
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
|
|
visit(self.block);
|
|
if let Some(tasks) = self.tasks {
|
|
visit(tasks);
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy)]
|
|
/// 该原生能力的查询/操作分类,方法包装用它选择具体实现。
|
|
enum Query {
|
|
Bounds,
|
|
ScrollTo,
|
|
ScrollBy,
|
|
ScrollPosition,
|
|
ScrollIntoView,
|
|
FitView,
|
|
Pick3D,
|
|
ToView,
|
|
ToLocal,
|
|
Parent,
|
|
FirstChild,
|
|
NextSibling,
|
|
Page,
|
|
Focus,
|
|
HitTest,
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
/// 保存 owner、签名或操作枚举的原生方法适配器,统一由 VM 调用。
|
|
struct Method {
|
|
signature: endor_core::CallSignature,
|
|
owner: ObjectRef,
|
|
// 方法对象拥有 Mount,但不能经桌面反向保活整个窗口;需要桌面能力时再 upgrade。
|
|
desktop: WeakObjectRef,
|
|
query: Query,
|
|
}
|
|
|
|
impl NativeCallable for Method {
|
|
/// 给出参数与返回值的托管类型契约;实际操作在 invoke 中执行。
|
|
fn signature(&self) -> Option<endor_core::CallSignature> {
|
|
Some(self.signature.clone())
|
|
}
|
|
/// 适配器已绑定 Mount;坐标测试/转换与scrollTo/By接受两个数,其余层次/几何/焦点查询零参。
|
|
fn arity(&self) -> Option<endor_core::CallArity> {
|
|
Some(endor_core::CallArity::exact(
|
|
if matches!(
|
|
self.query,
|
|
Query::HitTest
|
|
| Query::Pick3D
|
|
| Query::ToView
|
|
| Query::ToLocal
|
|
| Query::ScrollTo
|
|
| Query::ScrollBy
|
|
) {
|
|
2
|
|
} else {
|
|
0
|
|
},
|
|
))
|
|
}
|
|
|
|
/// 读取具体出现位置,先检查仍挂载与几何可用性,再执行层次、坐标、焦点、滚动或拾取操作,避免使用已退役上下文。
|
|
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
|
|
let mount = cx.store().payload::<Mount>(self.owner, "Mount")?.clone();
|
|
// 层次查询允许观察已经脱离的对象(通常得到 Nil);几何、焦点、滚动、拾取等必须仍挂接。
|
|
if !mount.mounted
|
|
&& matches!(
|
|
self.query,
|
|
Query::Bounds
|
|
| Query::Focus
|
|
| Query::HitTest
|
|
| Query::ScrollTo
|
|
| Query::ScrollBy
|
|
| Query::ScrollIntoView
|
|
| Query::FitView
|
|
| Query::Pick3D
|
|
| Query::ToView
|
|
| Query::ToLocal
|
|
| Query::ScrollPosition
|
|
)
|
|
{
|
|
return Err(VmError::InvalidArgument("Mount is no longer attached"));
|
|
}
|
|
// 除 VM 元数据检查外入口再核对实际参数数目;二维坐标/位移操作取两个 Number,其余零参。
|
|
let arity = if matches!(
|
|
self.query,
|
|
Query::HitTest
|
|
| Query::Pick3D
|
|
| Query::ToView
|
|
| Query::ToLocal
|
|
| Query::ScrollTo
|
|
| Query::ScrollBy
|
|
) {
|
|
2
|
|
} else {
|
|
0
|
|
};
|
|
if args.len() != arity {
|
|
return Err(VmError::InvalidArgument("incorrect Mount method arity"));
|
|
}
|
|
let value = match self.query {
|
|
Query::ToView | Query::ToLocal => {
|
|
// 布局期间几何尚未提交,坐标转换不能把临时 bounds 与上帧投影混用。
|
|
if mount.layout.is_some() {
|
|
return Err(VmError::InvalidArgument(
|
|
"coordinate conversion requires committed geometry",
|
|
));
|
|
}
|
|
let point = crate::geometry::Point::new(
|
|
crate::scroll::coordinate(&args[0])?,
|
|
crate::scroll::coordinate(&args[1])?,
|
|
);
|
|
let point =
|
|
if matches!(self.query, Query::ToView) {
|
|
// ToView 先将局部点加节点原点,再套二维 view;若在世界面板内,还继续向外投影到页面。
|
|
let point = mount.geometry.view.unwrap_or_default().point(
|
|
crate::geometry::Point::new(
|
|
point.x + mount.geometry.x,
|
|
point.y + mount.geometry.y,
|
|
),
|
|
);
|
|
mount
|
|
.geometry
|
|
.panel
|
|
.as_ref()
|
|
.map_or(Some(point), |panel| panel.project_point(point))
|
|
} else {
|
|
// ToLocal 先撤销面板和视图投影,再减节点几何原点;不可逆时返回 Nil,而非虚构坐标。
|
|
mount.geometry.logical_point(point).map(|point| {
|
|
crate::geometry::Point::new(
|
|
point.x - mount.geometry.x,
|
|
point.y - mount.geometry.y,
|
|
)
|
|
})
|
|
};
|
|
// 转换成功才分配名义 Point;失败返回 Nil,不把无效数值写进结果属性。
|
|
if let Some(point) = point {
|
|
let result = cx.new_object()?;
|
|
let desktop = cx.upgrade(self.desktop)?.ok_or(VmError::InvalidArgument(
|
|
"coordinate conversion desktop expired",
|
|
))?;
|
|
crate::ui_bridge::attach_desktop_type(cx, result, "Point", desktop)?;
|
|
cx.set_attr(result, "x", crate::native_visual::value(point.x))?;
|
|
cx.set_attr(result, "y", crate::native_visual::value(point.y))?;
|
|
Value::Object(result)
|
|
} else {
|
|
Value::Nil
|
|
}
|
|
}
|
|
// 同一滚动入口区分绝对位置和相对增量,钳制、挂接状态与写屏障交由 scroll::set 统一执行。
|
|
Query::ScrollTo | Query::ScrollBy => {
|
|
crate::scroll::set(
|
|
cx,
|
|
self.owner,
|
|
self.desktop,
|
|
[
|
|
crate::scroll::coordinate(&args[0])?,
|
|
crate::scroll::coordinate(&args[1])?,
|
|
],
|
|
matches!(self.query, Query::ScrollBy),
|
|
)?;
|
|
Value::Nil
|
|
}
|
|
Query::ScrollIntoView => {
|
|
crate::scroll::into_view(cx, self.owner, self.desktop)?;
|
|
Value::Nil
|
|
}
|
|
Query::FitView => {
|
|
crate::viewport::fit(cx, &mount)?;
|
|
Value::Nil
|
|
}
|
|
Query::Pick3D => {
|
|
let desktop = cx
|
|
.upgrade(self.desktop)?
|
|
.ok_or(VmError::InvalidArgument("viewport desktop expired"))?;
|
|
crate::scene3d_model::pick(
|
|
cx,
|
|
desktop,
|
|
&mount,
|
|
crate::geometry::Point::new(
|
|
crate::scroll::coordinate(&args[0])?,
|
|
crate::scroll::coordinate(&args[1])?,
|
|
),
|
|
)?
|
|
}
|
|
// 返回帧中已钳制的有效位置与最大偏移,不直接暴露可能尚未投影的 scroll_offset 原值。
|
|
Query::ScrollPosition => {
|
|
let p = mount
|
|
.geometry
|
|
.scroll
|
|
.ok_or(VmError::InvalidArgument("Mount is not scrollable"))?;
|
|
let result = cx.new_object()?;
|
|
for (name, value) in [("x", p[0]), ("y", p[1]), ("maxX", p[2]), ("maxY", p[3])] {
|
|
cx.set_attr(result, name, Value::Number((value as f64).into()))?;
|
|
}
|
|
Value::Object(result)
|
|
}
|
|
Query::Bounds => {
|
|
// 布局只读调用中可查询当前安排阶段的临时 bounds;测量时尚无 bounds,明确报错。
|
|
// 非布局期则读取最后提交的 MountGeometry。
|
|
let geometry = if let Some(layout) = &mount.layout {
|
|
layout
|
|
.lock()
|
|
.map_err(|_| VmError::InvalidArgument("layout context poisoned"))?
|
|
.bounds
|
|
.ok_or(VmError::InvalidArgument(
|
|
"Mount geometry is unavailable during measurement",
|
|
))?
|
|
} else {
|
|
[
|
|
mount.geometry.x,
|
|
mount.geometry.y,
|
|
mount.geometry.width,
|
|
mount.geometry.height,
|
|
]
|
|
};
|
|
let bounds = cx.new_object()?;
|
|
// 从本方法返回签名取得 Bounds 的名义类型,避免生成一个仅字段相似的普通对象。
|
|
let endor_core::CallType::Single(endor_core::AnnotationType::Nominal(definition)) =
|
|
&self.signature.returns
|
|
else {
|
|
return Err(VmError::InvalidArgument("invalid Mount bounds signature"));
|
|
};
|
|
cx.attach_type(bounds, *definition)?;
|
|
for (name, value) in [
|
|
("x", geometry[0]),
|
|
("y", geometry[1]),
|
|
("width", geometry[2]),
|
|
("height", geometry[3]),
|
|
] {
|
|
cx.set_attr(bounds, name, Value::Number((value as f64).into()))?;
|
|
}
|
|
cx.set_attr(
|
|
bounds,
|
|
"layoutVersion",
|
|
Value::Number((mount.version as i64).into()),
|
|
)?;
|
|
Value::Object(bounds)
|
|
}
|
|
// 请求焦点先让出现进入可见范围,再检查可聚焦资格并写入桌面请求;后续发布负责实际生效。
|
|
Query::Focus => {
|
|
crate::scroll::into_view(cx, self.owner, self.desktop)?;
|
|
if !mount.geometry.interactive {
|
|
return Err(VmError::InvalidArgument("Mount is not focusable"));
|
|
}
|
|
let desktop = cx
|
|
.upgrade(self.desktop)?
|
|
.ok_or(VmError::InvalidArgument("Mount window has expired"))?;
|
|
cx.set_attr(
|
|
desktop,
|
|
"focus",
|
|
Value::Number((mount.geometry.id as i64).into()),
|
|
)?;
|
|
cx.set_attr(desktop, "focusRequested", Value::Bool(true))?;
|
|
Value::Nil
|
|
}
|
|
// 这里是 Mount 已提交几何的 contains 查询;源 Block 的 hitTest 覆盖由 source_hit 驱动另行执行。
|
|
Query::HitTest => {
|
|
if mount.layout.is_some() {
|
|
return Err(VmError::InvalidArgument(
|
|
"Mount hitTest is unavailable during layout",
|
|
));
|
|
}
|
|
// 命中坐标只要求 Number 可转有限 f32;与 scroll::coordinate 不同,此处不限制绝对值至一百万。
|
|
let number = |value: &Value| -> Result<f32, VmError> {
|
|
let Value::Number(number) = value else {
|
|
return Err(VmError::InvalidArgument(
|
|
"point coordinates must be numbers",
|
|
));
|
|
};
|
|
let number = number
|
|
.to_string()
|
|
.parse::<f32>()
|
|
.map_err(|_| VmError::InvalidArgument("invalid point coordinate"))?;
|
|
if !number.is_finite() {
|
|
return Err(VmError::InvalidArgument("invalid point coordinate"));
|
|
}
|
|
Ok(number)
|
|
};
|
|
Value::Bool(mount.geometry.contains(crate::geometry::Point::new(
|
|
number(&args[0])?,
|
|
number(&args[1])?,
|
|
)))
|
|
}
|
|
query => {
|
|
let weak = match query {
|
|
Query::Parent => mount.parent,
|
|
Query::FirstChild => mount.first_child,
|
|
Query::NextSibling => mount.next_sibling,
|
|
Query::Page => mount.page,
|
|
_ => unreachable!(),
|
|
};
|
|
// 弱链接不存在或目标已回收都返回 Nil;升级本身失败才传播 VM 错误。
|
|
weak.map(|weak| cx.upgrade(weak))
|
|
.transpose()?
|
|
.flatten()
|
|
.map(Value::Object)
|
|
.unwrap_or(Value::Nil)
|
|
}
|
|
};
|
|
Ok(NativeResult::Return(value))
|
|
}
|
|
}
|
|
|
|
/// 声明 Mount 查询方法的源类型契约,区分几何、层次与坐标操作。
|
|
fn mount_signature(
|
|
store: &endor_core::ObjectStore,
|
|
desktop: ObjectRef,
|
|
query: Query,
|
|
) -> Result<endor_core::CallSignature, VmError> {
|
|
use endor_core::{AnnotationType as T, CallEffect, CallSignature, CallType};
|
|
let nominal = |name| crate::ui_bridge::desktop_type(store, name, desktop).map(T::Nominal);
|
|
// 层次、拾取和坐标转换可能没有结果,使用 nullable 名义类型;变更操作返回 Unit。
|
|
let returns = match query {
|
|
Query::Bounds => nominal("Bounds")?.into(),
|
|
Query::Parent | Query::FirstChild | Query::NextSibling => {
|
|
CallType::nullable(nominal("Mount")?)
|
|
}
|
|
Query::Page => CallType::nullable(nominal("Page")?),
|
|
Query::HitTest => T::Bool.into(),
|
|
Query::Pick3D => CallType::nullable(nominal("RayHit3D")?),
|
|
Query::ToView | Query::ToLocal => CallType::nullable(nominal("Point")?),
|
|
Query::ScrollPosition => T::Any.into(),
|
|
_ => T::Unit.into(),
|
|
};
|
|
// 滚动、相机拟合和焦点会写业务/桌面属性,声明 Mutating;其余查询允许在只读协议中调用。
|
|
let effect = if matches!(
|
|
query,
|
|
Query::ScrollTo | Query::ScrollBy | Query::ScrollIntoView | Query::FitView | Query::Focus
|
|
) {
|
|
CallEffect::Mutating
|
|
} else {
|
|
CallEffect::ReadOnly
|
|
};
|
|
let parameters = if matches!(
|
|
query,
|
|
Query::HitTest
|
|
| Query::Pick3D
|
|
| Query::ToView
|
|
| Query::ToLocal
|
|
| Query::ScrollTo
|
|
| Query::ScrollBy
|
|
) {
|
|
vec![T::Number, T::Number]
|
|
} else {
|
|
vec![]
|
|
};
|
|
let mut signature = CallSignature::exact(parameters, T::Any, effect);
|
|
signature.returns = returns;
|
|
Ok(signature)
|
|
}
|
|
|
|
#[derive(Debug, Default, Clone)]
|
|
/// 活动出现的弱索引。真实托管拥有关系在 desktop 的挂载字典中,索引不能充当隐藏 GC 根。
|
|
pub struct MountTable {
|
|
// Mount ID 到托管弱身份,真实强拥有者是 desktop.mounts 字典;order 单独保存原布局顺序。
|
|
pub active: HashMap<u64, WeakObjectRef>,
|
|
order: Vec<u64>,
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
/// 同步出现关系时的共享临时工作状态,保存本轮重用、建立和退役安排。
|
|
struct Sync {
|
|
desktop: ObjectRef,
|
|
page: Option<ObjectRef>,
|
|
nodes: Vec<WeakObjectRef>,
|
|
old: HashMap<u64, WeakObjectRef>,
|
|
old_order: Vec<u64>,
|
|
frame: Frame,
|
|
// true 为布局准备阶段,安装临时 Context 并保留已有滚动偏移;false 为几何提交,清 Context。
|
|
preparing: bool,
|
|
output: Arc<Mutex<HashMap<u64, WeakObjectRef>>>,
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
/// 将一个生命周期回调及参数接入同一 VM 调用序列。
|
|
struct LifecycleCall {
|
|
function: ObjectRef,
|
|
block: ObjectRef,
|
|
mount: ObjectRef,
|
|
unmount: bool,
|
|
}
|
|
impl NativeCallable for LifecycleCall {
|
|
/// Block、Mount 与用户钩子都已捕获,生命周期序列无参调用此适配器。
|
|
fn arity(&self) -> Option<endor_core::CallArity> {
|
|
Some(endor_core::CallArity::exact(0))
|
|
}
|
|
|
|
/// 卸载时先取消 Mount 所有任务,再以 Block/Mount 为实参请求 VM 执行用户 onMount/onUnmount,不在 Rust 中直接运行源体。
|
|
fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> {
|
|
// 用户 onUnmount 运行前先取消该出现拥有的任务,防止退役后继续交付旧工作。
|
|
if self.unmount {
|
|
crate::tasks::cancel_owner(cx, self.mount)?;
|
|
}
|
|
Ok(NativeResult::Invoke {
|
|
function: self.function,
|
|
arguments: vec![Value::Object(self.block), Value::Object(self.mount)],
|
|
})
|
|
}
|
|
}
|
|
|
|
/// 构造生命周期调用所需的托管函数与参数,使回调遵循同一 VM 的引用和执行约束。
|
|
fn lifecycle_call(
|
|
cx: &mut NativeContext<'_>,
|
|
mount: ObjectRef,
|
|
name: &'static str,
|
|
) -> Result<ObjectRef, VmError> {
|
|
let block = cx.store().payload::<Mount>(mount, "Mount")?.block;
|
|
let definition = cx
|
|
.store()
|
|
.type_of(block)?
|
|
.ok_or(VmError::InvalidArgument("untyped mounted Block"))?;
|
|
let function = cx
|
|
.store()
|
|
.lookup_method(definition, name)?
|
|
.ok_or(VmError::InvalidArgument("Block has no lifecycle method"))?;
|
|
// 生命周期包装显式捕获函数、Block、Mount,使序列执行到回调前这些对象不会被回收。
|
|
cx.allocate(ContextNativeFunction::new(
|
|
name,
|
|
LifecycleCall {
|
|
function,
|
|
block,
|
|
mount,
|
|
unmount: name == "onUnmount",
|
|
},
|
|
vec![function, block, mount],
|
|
))
|
|
}
|
|
|
|
impl NativeCallable for Sync {
|
|
/// 展示同步步骤从捕获的帧与弱节点表读取输入,无需外部实参。
|
|
fn arity(&self) -> Option<endor_core::CallArity> {
|
|
Some(endor_core::CallArity::exact(0))
|
|
}
|
|
|
|
/// 把弱业务身份升级为本轮对象映射,再同步帧中出现位置到托管 Mount,建立结构/几何与待通知生命周期。
|
|
fn invoke(&self, cx: &mut NativeContext<'_>, _args: &[Value]) -> Result<NativeResult, VmError> {
|
|
// 帧只含 Block 字符串身份,先将弱节点表升级为本次同步可用的实际对象映射。
|
|
let mut blocks = HashMap::new();
|
|
for weak in &self.nodes {
|
|
if let Some(block) = cx.upgrade(*weak)? {
|
|
blocks.insert(block.to_string(), block);
|
|
}
|
|
}
|
|
let page = self
|
|
.page
|
|
.map(|page| cx.store().downgrade(page))
|
|
.transpose()?;
|
|
let mut objects = HashMap::new();
|
|
let mut created = Vec::new();
|
|
for geometry in &self.frame.mounts {
|
|
let block = *blocks
|
|
.get(&geometry.block_id)
|
|
.ok_or(VmError::InvalidArgument(
|
|
"frame references an unavailable Block",
|
|
))?;
|
|
let old = self
|
|
.old
|
|
.get(&geometry.id)
|
|
.map(|weak| cx.upgrade(*weak))
|
|
.transpose()?
|
|
.flatten();
|
|
// Mount ID 相同仍不足以复用:必须仍挂接、页面相同、真实 Block 相同,防止身份误归属。
|
|
let reusable = if let Some(old) = old {
|
|
let mount = cx.store().payload::<Mount>(old, "Mount")?;
|
|
(mount.mounted && mount.page == page && mount.block == block).then_some(old)
|
|
} else {
|
|
None
|
|
};
|
|
let object = if let Some(old) = reusable {
|
|
old
|
|
} else {
|
|
let object = cx.allocate(Mount {
|
|
block,
|
|
page,
|
|
parent: None,
|
|
first_child: None,
|
|
next_sibling: None,
|
|
geometry: geometry.clone(),
|
|
scroll_offset: [0.0, 0.0],
|
|
version: self.frame.layout_version,
|
|
mounted: true,
|
|
tasks: None,
|
|
layout: None,
|
|
})?;
|
|
crate::ui_bridge::attach_desktop_type(cx, object, "Mount", self.desktop)?;
|
|
// 每个新 Mount 安装捕获自身的原生方法;captures 中只放 Mount,桌面仍保留弱身份。
|
|
for (name, query) in [
|
|
("bounds", Query::Bounds),
|
|
("scrollTo", Query::ScrollTo),
|
|
("scrollBy", Query::ScrollBy),
|
|
("scrollPosition", Query::ScrollPosition),
|
|
("scrollIntoView", Query::ScrollIntoView),
|
|
("fitView", Query::FitView),
|
|
("pick3D", Query::Pick3D),
|
|
("toView", Query::ToView),
|
|
("toLocal", Query::ToLocal),
|
|
("parent", Query::Parent),
|
|
("firstChild", Query::FirstChild),
|
|
("nextSibling", Query::NextSibling),
|
|
("page", Query::Page),
|
|
("requestFocus", Query::Focus),
|
|
("hitTest", Query::HitTest),
|
|
] {
|
|
let function = cx.allocate(ContextNativeFunction::new(
|
|
name,
|
|
Method {
|
|
signature: mount_signature(cx.store(), self.desktop, query)?,
|
|
owner: object,
|
|
desktop: cx.store().downgrade(self.desktop)?,
|
|
query,
|
|
},
|
|
vec![object],
|
|
))?;
|
|
cx.set_attr(object, name, Value::Object(function))?;
|
|
}
|
|
cx.set_attr(object, "id", Value::Number((geometry.id as i64).into()))?;
|
|
cx.set_attr(object, "block", Value::Object(block))?;
|
|
created.push(object);
|
|
object
|
|
};
|
|
objects.insert(geometry.id, object);
|
|
}
|
|
// 先建立全部 Mount,再第二遍补链接,保证 parent/child/sibling 无论先后都能找到目标身份。
|
|
let root = cx.new_dict()?;
|
|
for geometry in &self.frame.mounts {
|
|
let object = objects[&geometry.id];
|
|
let link = |id: Option<u64>| -> Result<Option<WeakObjectRef>, VmError> {
|
|
id.map(|id| cx.store().downgrade(objects[&id])).transpose()
|
|
};
|
|
let mount = Mount {
|
|
tasks: cx.store().payload::<Mount>(object, "Mount")?.tasks,
|
|
block: blocks[&geometry.block_id],
|
|
page,
|
|
parent: link(geometry.parent)?,
|
|
first_child: link(geometry.first_child)?,
|
|
next_sibling: link(geometry.next_sibling)?,
|
|
geometry: geometry.clone(),
|
|
// 准备阶段沿用用户滚动状态;提交阶段以帧中有效偏移为准,非滚动容器归零。
|
|
scroll_offset: if self.preparing {
|
|
cx.store().payload::<Mount>(object, "Mount")?.scroll_offset
|
|
} else {
|
|
geometry.scroll.map(|s| [s[0], s[1]]).unwrap_or([0.0, 0.0])
|
|
},
|
|
version: self.frame.layout_version,
|
|
mounted: true,
|
|
// 临时 Context 只有原生派生数据,无托管根;提交时置 None,表示几何可供外部查询。
|
|
layout: if self.preparing {
|
|
Some(Arc::new(Mutex::new(crate::layout::Context::default())))
|
|
} else {
|
|
None
|
|
},
|
|
};
|
|
let old = cx.store().payload::<Mount>(object, "Mount")?;
|
|
// 只在上下文、几何、版本、链接或公开挂接属性确实需更新时替换 payload,减少无关变更日志。
|
|
if self.preparing
|
|
|| old.layout.is_some()
|
|
|| !old.mounted
|
|
|| old.version != mount.version
|
|
|| old.geometry != mount.geometry
|
|
|| old.page != mount.page
|
|
|| old.parent != mount.parent
|
|
|| old.first_child != mount.first_child
|
|
|| old.next_sibling != mount.next_sibling
|
|
|| matches!(
|
|
cx.store().get_attr(object, "mounted"),
|
|
Err(VmError::AttributeNotFound(_))
|
|
)
|
|
{
|
|
cx.replace_payload(object, mount)?;
|
|
cx.set_attr(object, "mounted", Value::Bool(true))?;
|
|
cx.set_attr(
|
|
object,
|
|
"layoutVersion",
|
|
Value::Number((self.frame.layout_version as i64).into()),
|
|
)?;
|
|
}
|
|
// 新字典逐项拥有活动 Mount;弱链接本身不负责让整棵出现树存活。
|
|
cx.dict_set(
|
|
root,
|
|
Value::Text(geometry.id.to_string()),
|
|
Value::Object(object),
|
|
)?;
|
|
}
|
|
let mut hooks = Vec::new();
|
|
// Layout records are preorder; reversing guarantees children unmount
|
|
// before their parents. A Page change creates fresh Mount contexts.
|
|
// 旧帧按父先子后记录,逆序退役保证孩子 onUnmount 在父之前;复用对象不退役。
|
|
for id in self.old_order.iter().rev() {
|
|
let weak = self.old[id];
|
|
if let Some(object) = cx.upgrade(weak)?
|
|
&& objects.get(id) != Some(&object)
|
|
{
|
|
let mut mount = cx.store().payload::<Mount>(object, "Mount")?.clone();
|
|
// 先撤销挂接和全部关系,再安排回调;onUnmount 不能继续使用失效几何或沿旧链操作。
|
|
mount.mounted = false;
|
|
mount.layout = None;
|
|
mount.parent = None;
|
|
mount.first_child = None;
|
|
mount.next_sibling = None;
|
|
cx.replace_payload(object, mount)?;
|
|
cx.set_attr(object, "mounted", Value::Bool(false))?;
|
|
hooks.push(lifecycle_call(cx, object, "onUnmount")?);
|
|
}
|
|
}
|
|
// 新建顺序沿帧先序,onMount 默认父先子后;全部旧退役回调排在新挂载回调之前。
|
|
for object in created {
|
|
hooks.push(lifecycle_call(cx, object, "onMount")?);
|
|
}
|
|
// 同步只返回生命周期序列,不在此处立即执行用户回调;调用方决定在后续阶段何时运行。
|
|
let driver = if hooks.is_empty() {
|
|
None
|
|
} else {
|
|
Some(crate::vm_sequence::build(
|
|
cx,
|
|
hooks,
|
|
"<mount lifecycle>",
|
|
self.desktop,
|
|
)?)
|
|
};
|
|
let weak = objects
|
|
.into_iter()
|
|
.map(|(id, object)| Ok((id, cx.store().downgrade(object)?)))
|
|
.collect::<Result<HashMap<_, _>, VmError>>()?;
|
|
// 先让桌面拥有新字典,再公布原生弱索引;返回的驱动保持待退役对象直到回调结束。
|
|
cx.set_attr(self.desktop, "mounts", Value::Object(root))?;
|
|
*self
|
|
.output
|
|
.lock()
|
|
.map_err(|_| VmError::InvalidArgument("Mount registry poisoned"))? = weak;
|
|
Ok(NativeResult::Return(
|
|
driver.map(Value::Object).unwrap_or(Value::Nil),
|
|
))
|
|
}
|
|
}
|
|
|
|
/// Explicitly owned roots protect the old presentation while preparation
|
|
/// temporarily replaces its desktop dictionary and Mount payloads.
|
|
/// 布局准备前的挂载快照与临时保留,用于取消恢复;成功提交后必须释放其保留引用。
|
|
pub struct Checkpoint {
|
|
table: MountTable,
|
|
dictionary: Option<ObjectRef>,
|
|
// 保存 payload 与 mounted/layoutVersion 两项公开属性;None 表示原先没有属性,回滚要删除。
|
|
states: Vec<(ObjectRef, Mount, Option<Value>, Option<Value>)>,
|
|
roots: Vec<ObjectRef>,
|
|
}
|
|
|
|
impl Checkpoint {
|
|
/// 释放检查点为回滚临时保留的托管根,成功提交后不再需要这些引用。
|
|
pub fn release(self, vm: &mut Vm) -> Result<(), VmError> {
|
|
let mut result = Ok(());
|
|
// 逆序释放所有临时根,单项失败仍继续尝试余下根,最终返回最后一次释放错误。
|
|
for root in self.roots.into_iter().rev() {
|
|
if let Err(error) = vm.release(root) {
|
|
result = Err(error);
|
|
}
|
|
}
|
|
result
|
|
}
|
|
|
|
/// 恢复检查点中尚未发布的出现关系与布局上下文,并释放临时保留。
|
|
pub fn restore(
|
|
self,
|
|
vm: &mut Vm,
|
|
desktop: ObjectRef,
|
|
table: &mut MountTable,
|
|
) -> Result<(), VmError> {
|
|
let result = (|| {
|
|
// 回滚先识别本轮新增的出现并将其脱离,再恢复原有 Mount payload、公开属性和桌面拥有字典。
|
|
let old: std::collections::HashSet<_> =
|
|
self.states.iter().map(|state| state.0).collect();
|
|
for weak in table.ordered() {
|
|
if let Some(object) = vm.upgrade(weak)? {
|
|
let result = (|| {
|
|
if !old.contains(&object) {
|
|
let mut mount = vm.payload::<Mount>(object, "Mount")?.clone();
|
|
mount.mounted = false;
|
|
mount.layout = None;
|
|
mount.parent = None;
|
|
mount.first_child = None;
|
|
mount.next_sibling = None;
|
|
vm.replace_payload(object, mount)?;
|
|
vm.set_attr(object, "mounted", Value::Bool(false))?;
|
|
}
|
|
Ok::<_, VmError>(())
|
|
})();
|
|
// 保存处理结果后先释放 upgrade 根,再传播处理错误,避免失败路径遗留临时强引用。
|
|
vm.release(object)?;
|
|
result?;
|
|
}
|
|
}
|
|
for (object, mount, mounted, version) in &self.states {
|
|
vm.replace_payload(*object, mount.clone())?;
|
|
for (name, value) in [("mounted", mounted), ("layoutVersion", version)] {
|
|
// 原属性存在则恢复旧值,不存在则 del_attr;已缺失可忽略,其余删除错误仍要传播。
|
|
if let Some(value) = value {
|
|
vm.set_attr(*object, name, value.clone())?;
|
|
} else {
|
|
match vm.del_attr(*object, name) {
|
|
Ok(()) | Err(VmError::AttributeNotFound(_)) => {}
|
|
Err(error) => return Err(error),
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if let Some(dictionary) = self.dictionary {
|
|
vm.set_attr(desktop, "mounts", Value::Object(dictionary))?;
|
|
} else {
|
|
match vm.del_attr(desktop, "mounts") {
|
|
Ok(()) | Err(VmError::AttributeNotFound(_)) => {}
|
|
Err(error) => return Err(error),
|
|
}
|
|
}
|
|
*table = self.table.clone();
|
|
Ok(())
|
|
})();
|
|
// 恢复过程失败也要释放检查点根;先尝试两项操作,再按恢复错误优先的顺序返回。
|
|
let released = self.release(vm);
|
|
result?;
|
|
released
|
|
}
|
|
}
|
|
|
|
impl MountTable {
|
|
/// 保留布局准备前的 Mount 状态,供失败或取消路径恢复。
|
|
pub fn checkpoint(&self, vm: &mut Vm, desktop: ObjectRef) -> Result<Checkpoint, VmError> {
|
|
let dictionary = match vm.get_attr(desktop, "mounts") {
|
|
Ok(Value::Object(dictionary)) => Some(dictionary),
|
|
Err(VmError::AttributeNotFound(_)) => None,
|
|
Ok(_) => return Err(VmError::InvalidArgument("invalid mount dictionary")),
|
|
Err(error) => return Err(error),
|
|
};
|
|
let mut roots = Vec::new();
|
|
// 保留旧字典,避免准备阶段 desktop.mounts 换成新字典后旧出现提前回收,导致无法恢复。
|
|
if let Some(dictionary) = dictionary {
|
|
vm.retain(dictionary)?;
|
|
roots.push(dictionary);
|
|
}
|
|
let mut checkpoint = Checkpoint {
|
|
table: self.clone(),
|
|
dictionary,
|
|
states: Vec::new(),
|
|
roots,
|
|
};
|
|
let result = (|| {
|
|
for weak in self.ordered() {
|
|
if let Some(object) = vm.upgrade(weak)? {
|
|
// upgrade 已提供一个拥有根,直接记录待释放列表,不重复 retain;随后读取失败也会统一清理。
|
|
checkpoint.roots.push(object);
|
|
let mount = vm.payload::<Mount>(object, "Mount")?.clone();
|
|
let mut attributes = Vec::new();
|
|
for name in ["mounted", "layoutVersion"] {
|
|
let value = match vm.get_attr(object, name) {
|
|
Ok(value) => Some(value),
|
|
Err(VmError::AttributeNotFound(_)) => None,
|
|
Err(error) => return Err(error),
|
|
};
|
|
// 公开属性理论上可能持有对象,快照保存 Value 本身不会自动增加 VM 根,须额外 retain。
|
|
if let Some(Value::Object(object)) = &value {
|
|
vm.retain(*object)?;
|
|
checkpoint.roots.push(*object);
|
|
}
|
|
attributes.push(value);
|
|
}
|
|
checkpoint.states.push((
|
|
object,
|
|
mount,
|
|
attributes.remove(0),
|
|
attributes.remove(0),
|
|
));
|
|
}
|
|
}
|
|
Ok::<_, VmError>(())
|
|
})();
|
|
// 检查点创建到一半失败时释放已经取得的根,不返回一个不完整且可能泄漏的检查点。
|
|
if let Err(error) = result {
|
|
checkpoint.release(vm)?;
|
|
return Err(error);
|
|
}
|
|
Ok(checkpoint)
|
|
}
|
|
|
|
/// A faulted domain cannot run user onUnmount callbacks. Still detach every
|
|
/// context and release its owning dictionary through the normal heap barrier.
|
|
/// 退役当前出现表,撤销挂载关系并准备不再展示的生命周期状态。
|
|
pub fn retire(&mut self, vm: &mut Vm, desktop: ObjectRef) -> Result<(), VmError> {
|
|
for weak in self.ordered().into_iter().rev() {
|
|
if let Some(object) = vm.upgrade(weak)? {
|
|
let result = (|| {
|
|
let mut mount = vm.payload::<Mount>(object, "Mount")?.clone();
|
|
mount.mounted = false;
|
|
mount.layout = None;
|
|
mount.parent = None;
|
|
mount.first_child = None;
|
|
mount.next_sibling = None;
|
|
vm.replace_payload(object, mount)?;
|
|
vm.set_attr(object, "mounted", Value::Bool(false))
|
|
})();
|
|
vm.release(object)?;
|
|
result?;
|
|
}
|
|
}
|
|
// 故障退役不执行用户回调;将 desktop.mounts 换成空字典,再清除原生索引,撤销桌面拥有关系。
|
|
let dictionary = vm.new_dict()?;
|
|
let result = vm.set_attr(desktop, "mounts", Value::Object(dictionary));
|
|
vm.release(dictionary)?;
|
|
result?;
|
|
self.active.clear();
|
|
self.order.clear();
|
|
Ok(())
|
|
}
|
|
|
|
/// 按原始展示顺序返回弱 Mount 身份,供事件和协议驱动器保持稳定顺序。
|
|
pub fn ordered(&self) -> Vec<WeakObjectRef> {
|
|
self.order
|
|
.iter()
|
|
.filter_map(|id| self.active.get(id).copied())
|
|
.collect()
|
|
}
|
|
|
|
/// 根据新结构复用或建立每次出现的 Mount,连接父子关系并准备生命周期调用。
|
|
pub fn synchronize(
|
|
&mut self,
|
|
vm: &mut Vm,
|
|
desktop: ObjectRef,
|
|
page: Option<ObjectRef>,
|
|
nodes: Vec<WeakObjectRef>,
|
|
frame: &Frame,
|
|
preparing: bool,
|
|
) -> Result<Option<ObjectRef>, VmError> {
|
|
let output = Arc::new(Mutex::new(HashMap::new()));
|
|
// 同步入口显式保活桌面与可选页面;旧表和节点表本身仍是弱索引,不增加隐式根。
|
|
let mut captures = vec![desktop];
|
|
captures.extend(page);
|
|
let function = vm.allocate(ContextNativeFunction::new(
|
|
"mount-sync",
|
|
Sync {
|
|
desktop,
|
|
page,
|
|
nodes,
|
|
old: self.active.clone(),
|
|
old_order: self.order.clone(),
|
|
frame: frame.clone(),
|
|
preparing,
|
|
output: output.clone(),
|
|
},
|
|
captures,
|
|
))?;
|
|
// 先保存调用结果再释放同步入口,错误时同样清理;只有成功后才替换活动索引与顺序。
|
|
let result = vm.call(function, &[]);
|
|
vm.release(function)?;
|
|
let result = result?;
|
|
// 从共享输出移动弱表而不是克隆;生命周期驱动若存在则作为拥有结果交给调用方释放。
|
|
self.active = std::mem::take(
|
|
&mut *output
|
|
.lock()
|
|
.map_err(|_| VmError::InvalidArgument("Mount registry poisoned"))?,
|
|
);
|
|
self.order = frame.mounts.iter().map(|mount| mount.id).collect();
|
|
match result {
|
|
Value::Object(hooks) => Ok(Some(hooks)),
|
|
Value::Nil => Ok(None),
|
|
value => {
|
|
vm.release_value(value)?;
|
|
Err(VmError::InvalidArgument("invalid lifecycle batch"))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
pub use crate::object_list::collection;
|