docs: explain Tessera modules and execution flows in Chinese

This commit is contained in:
2026-11-11 23:36:03 +08:00
parent 4c3fc8b5dd
commit 1fedd21d3c
77 changed files with 1418 additions and 0 deletions
+85
View File
@@ -1,3 +1,7 @@
//! Endor 与 Tessera 的展示事务协调层:维护每个窗口的 Page、Mount、布局缓存和发布版本。
//! Session 保存托管对象的展示上下文;跨线程发布的是不可变 UiNode/Frame,而不是可以在窗口线程执行的 VM。
//! 刷新按 prepare → layout → paint → commit 推进。挂起工作必须恢复或显式取消;失败不能把未完成的几何和生命周期状态留作已发布结果。
//!
//! Tessera's native visual protocols over Aster's managed object graph.
mod bootstrap;
mod calls;
@@ -90,6 +94,7 @@ pub const QUERY_NAMES: &[&str] = &[
pub use tree::{UiKind, UiNode};
#[derive(Debug)]
/// 整个 VM 的桥接会话。节点索引跨窗口共享,presentations 按窗口隔离派生状态;current 决定方法当前访问哪份展示上下文。
struct Session {
// Weak visual-object registry belongs to the VM, not a particular window.
nodes: Vec<WeakObjectRef>,
@@ -109,6 +114,7 @@ struct Session {
}
impl Session {
/// 收集所有窗口的私有 desktop 身份,用于排除宿主记账读取造成的无关布局失效。
fn host_desktops(&self) -> std::collections::HashSet<ObjectRef> {
self.presentations
.values()
@@ -119,6 +125,7 @@ impl Session {
impl std::ops::Deref for Session {
type Target = crate::presentation::Presentation;
/// 将包装类型的只读访问转交给内部当前上下文。
fn deref(&self) -> &Self::Target {
self.presentations
.get(&self.current)
@@ -126,6 +133,7 @@ impl std::ops::Deref for Session {
}
}
impl std::ops::DerefMut for Session {
/// 将包装类型的可变访问转交给内部当前上下文。
fn deref_mut(&mut self) -> &mut Self::Target {
self.presentations
.get_mut(&self.current)
@@ -135,6 +143,7 @@ impl std::ops::DerefMut for Session {
type Shared = Arc<Mutex<Session>>;
#[derive(Debug, Clone, Copy)]
/// ui/组件宿主入口的操作枚举;统一由调用适配器分派,不直接代表已经发生的业务变更。
enum Operation {
IsInstance,
Implement,
@@ -202,6 +211,7 @@ enum Operation {
}
impl Operation {
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
fn arity(self) -> endor_core::CallArity {
use Operation::*;
let (minimum, maximum) = match self {
@@ -238,6 +248,7 @@ impl Operation {
}
#[derive(Debug)]
/// 将一个宿主 Operation 及会话环境封装成 VM 可调用对象。
struct Function {
signature: Option<CallSignature>,
operation: Operation,
@@ -249,6 +260,7 @@ struct Function {
/// One shared implementation on the nominal type. The VM binds receivers;
/// individual Blocks no longer allocate owner-capturing method closures.
#[derive(Debug)]
/// 类型查询/能力方法的原生包装,保存调用所需的声明与会话。
struct TypeMethod {
signature: CallSignature,
operation: Operation,
@@ -256,6 +268,7 @@ struct TypeMethod {
session: Shared,
}
/// 判断方法是否仍为宿主提供的原生事件实现,区分它与用户源覆盖。
pub(crate) fn is_intrinsic_event(
store: &endor_core::ObjectStore,
function: ObjectRef,
@@ -274,9 +287,11 @@ pub(crate) fn is_intrinsic_event(
}
impl NativeCallable for TypeMethod {
/// 给出参数与返回值的托管类型契约;实际操作在 invoke 中执行。
fn signature(&self) -> Option<CallSignature> {
Some(self.signature.clone())
}
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
fn arity(&self) -> Option<endor_core::CallArity> {
let arity = self.operation.arity();
Some(endor_core::CallArity::range(
@@ -285,6 +300,7 @@ impl NativeCallable for TypeMethod {
))
}
/// VM 调入本宿主能力的入口;按所属操作解码参数并返回托管值或后续调用。
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
let owner = object(args.first())?;
if !cx.store().is_instance(owner, self.expected)? {
@@ -304,6 +320,7 @@ impl NativeCallable for TypeMethod {
/// The Type dispatcher passes the requested subclass explicitly. Native
/// constructor options precede the subclass's inherited/own field arguments.
#[derive(Debug)]
/// 为源代码调用原生类型构造器提供受检查的分配入口。
struct NativeFactory {
signature: Option<CallSignature>,
options: Option<CallSignature>,
@@ -312,9 +329,11 @@ struct NativeFactory {
}
impl NativeCallable for NativeFactory {
/// 给出参数与返回值的托管类型契约;实际操作在 invoke 中执行。
fn signature(&self) -> Option<CallSignature> {
self.signature.clone()
}
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
fn arity(&self) -> Option<endor_core::CallArity> {
Some(endor_core::CallArity::range(
self.operation.arity().required + 1,
@@ -322,6 +341,7 @@ impl NativeCallable for NativeFactory {
))
}
/// VM 调入本宿主能力的入口;按所属操作解码参数并返回托管值或后续调用。
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
let requested = object(args.first())?;
let fields = cx
@@ -367,21 +387,25 @@ impl NativeCallable for NativeFactory {
}
}
/// 统一构造本模块的参数错误,让调用方停止处理无效输入。
fn invalid(message: &'static str) -> VmError {
VmError::InvalidArgument(message)
}
/// 从源值中提取并检查托管对象身份,错误类型沿 VM 错误返回。
fn object(value: Option<&Value>) -> Result<ObjectRef, VmError> {
match value {
Some(Value::Object(value)) => Ok(*value),
_ => Err(invalid("expected an object")),
}
}
/// 把当前源值或文本选择解码成此调用需要的文本表示。
fn text(value: Option<&Value>) -> Result<String, VmError> {
match value {
Some(Value::Text(value)) => Ok(value.clone()),
_ => Err(invalid("expected text")),
}
}
/// 读取整数参数,拒绝非整数或无法在目标范围表示的值。
fn integer(value: Option<&Value>) -> Result<u64, VmError> {
match value {
Some(Value::Number(value)) => value
@@ -391,6 +415,7 @@ fn integer(value: Option<&Value>) -> Result<u64, VmError> {
_ => Err(invalid("expected a nonnegative integer")),
}
}
/// 解析颜色值并检查其满足当前原生绘制约定。
fn color(value: Option<&Value>, default: &str) -> Result<String, VmError> {
let value = value
.map(|v| text(Some(v)))
@@ -399,6 +424,7 @@ fn color(value: Option<&Value>, default: &str) -> Result<String, VmError> {
parse_color(&value).map_err(|_| invalid("color must use #RRGGBB or #RRGGBBAA"))?;
Ok(value)
}
/// 读取布局尺寸参数,检查非负、有限和最大尺寸限制。
fn dimension(value: Option<&Value>) -> Result<f32, VmError> {
let Some(Value::Number(number)) = value else {
return Err(invalid("expected a finite nonnegative dimension"));
@@ -414,6 +440,7 @@ fn dimension(value: Option<&Value>) -> Result<f32, VmError> {
Ok(value as f32)
}
/// 为一个托管对象安装绑定到当前会话的原生方法,声明调用名与具体 Operation。
fn bind(
cx: &mut NativeContext<'_>,
owner: ObjectRef,
@@ -440,6 +467,7 @@ fn bind(
cx.set_attr(owner, name, Value::Object(function))
}
/// 使用默认原生类型创建 Block;需要源子类身份的构造走 new_typed_block。
fn new_block(
cx: &mut NativeContext<'_>,
data: Data,
@@ -448,6 +476,7 @@ fn new_block(
new_typed_block(cx, data, session, None)
}
/// 分配有名义类型和默认位置/缩放的独立相机,供新视口拥有自己的导航状态。
fn new_camera2d(
cx: &mut NativeContext<'_>,
session: &Shared,
@@ -473,6 +502,7 @@ fn new_camera2d(
Ok(camera)
}
/// 创建原生 Block 并附加请求的 Endor 类型;先验证继承关系,再登记到会话节点索引。
fn new_typed_block(
cx: &mut NativeContext<'_>,
data: Data,
@@ -528,6 +558,7 @@ fn new_typed_block(
Ok(block)
}
/// 在当前 VM 中建立窗口、desktop 和独立 Presentation,实际 OS 窗口等命令发布后再创建。
fn create_window(
cx: &mut NativeContext<'_>,
state: &mut Session,
@@ -557,6 +588,7 @@ fn create_window(
Ok(window)
}
/// 从页面登记信息取得所属窗口,保持 Page 的归属与原生资源身份一致。
fn page_window(
store: &endor_core::ObjectStore,
state: &Session,
@@ -570,6 +602,7 @@ fn page_window(
}
Ok(None)
}
/// 撤销页面在展示会话中的登记,配合模型层处理活动页面与生命周期。
fn remove_page(
cx: &mut NativeContext<'_>,
view: &mut crate::presentation::Presentation,
@@ -588,6 +621,7 @@ fn remove_page(
}
Ok(())
}
/// 在指定窗口安排页面展示,并维护目标 Presentation 的活动/待发布状态。
fn show_in(
cx: &mut NativeContext<'_>,
page: ObjectRef,
@@ -638,20 +672,24 @@ fn show_in(
view.pending = Some(Some(page));
Ok(())
}
/// 在当前窗口安排页面展示,实际几何和画面由后续刷新提交。
fn show(cx: &mut NativeContext<'_>, page: ObjectRef, session: &Shared) -> Result<(), VmError> {
show_in(cx, page, session, None)
}
#[derive(Debug)]
/// 接收源 present 结果并将其转换成宿主可展示内容的原生续接步骤。
struct PresentResult {
open: bool,
session: Shared,
}
impl NativeCallable for PresentResult {
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
fn arity(&self) -> Option<endor_core::CallArity> {
Some(endor_core::CallArity::exact(1))
}
/// VM 调入本宿主能力的入口;按所属操作解码参数并返回托管值或后续调用。
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
let [Value::Object(root)] = args else {
return Err(invalid("Presentable.present must return a Block"));
@@ -676,6 +714,7 @@ impl NativeCallable for PresentResult {
}
}
/// 根据 Presentable 能力把任意源值转换成可展示内容,避免只允许某个原生 Block 类型。
fn present_value(
cx: &mut NativeContext<'_>,
value: &Value,
@@ -718,11 +757,13 @@ fn present_value(
}
#[must_use = "pending layout must be resumed on its owning VM"]
/// 桥接布局的挂起/完成结果;PendingLayout 必须与其窗口上下文一起继续处理。
pub enum LayoutProgress {
Pending(Box<PendingLayout>),
Complete(Box<crate::document::Frame>),
}
/// 一次未提交布局的上下文:目标窗口、根、布局/缓存、延后钩子以及用于失败恢复的检查点。
struct LayoutContext {
surface: crate::page::Surface,
root: Arc<UiNode>,
@@ -734,17 +775,20 @@ struct LayoutContext {
checkpoint: crate::mount::Checkpoint,
}
/// 挂起布局的拥有者。续体与上下文必须一起保留并最终恢复或取消。
pub struct PendingLayout {
work: crate::source_layout::Work,
context: LayoutContext,
}
/// 运行时持有的桥接能力句柄,通过共享 Session 协调托管对象与每窗口展示。
pub struct UiBridge {
pub ui: ObjectRef,
session: Shared,
tasks: crate::tasks::Scheduler,
}
/// 解析对象的方法并在同一 VM 中调用,使源覆盖与原生成员共用方法查找规则。
fn invoke_member(
vm: &mut Vm,
owner: ObjectRef,
@@ -770,6 +814,7 @@ fn invoke_member(
result
}
/// 将托管页面注册表投影成稳定标签 ID、标题与活动状态,不把托管引用交给原生侧栏。
fn project_tabs(
vm: &Vm,
state: &mut crate::presentation::Presentation,
@@ -816,6 +861,7 @@ fn project_tabs(
impl UiBridge {
/// Detach all occurrences without running layout/paint. All windows are
/// already closed before source unmount hooks run, so they cannot remount.
/// 按窗口和展示生命周期执行有界退出清理,允许调用方根据故障状态决定是否执行回调。
pub fn shutdown(&self, vm: &mut Vm, callbacks: bool) -> Result<(usize, usize, usize)> {
let tasks = self.tasks.quiesce(vm)?;
let mut drivers = Vec::new();
@@ -885,16 +931,20 @@ impl UiBridge {
result
}
/// 查询任务系统是否仍有可推进的协作工作,供 worker 选择等待策略。
pub fn has_cooperative_tasks(&self) -> bool {
self.tasks.has_cooperative_work()
}
/// 把当前 VM 交给任务调度器推进,限制一轮交付数量。
pub fn poll_tasks(&self, vm: &mut Vm, limit: usize) -> Result<usize> {
self.tasks.poll(vm, limit)
}
/// 取消当前域中的任务,撤销关闭/失败后不应再发生的交付。
pub fn cancel_tasks(&self, vm: &mut Vm) -> Result<usize> {
self.tasks.cancel_all(vm)
}
/// 返回当前仍有效的展示窗口身份,用于稳定遍历一次全窗口刷新。
pub fn window_ids(&self) -> Result<Vec<u64>> {
let state = self
.session
@@ -917,6 +967,7 @@ impl UiBridge {
});
Ok(ids)
}
/// 判断窗口是否仍登记且没有进入关闭状态。
pub fn accepts_window(&self, id: u64) -> bool {
self.session.lock().is_ok_and(|state| {
state
@@ -926,6 +977,7 @@ impl UiBridge {
})
}
/// 切换当前 Presentation 上下文;不会创建新窗口或复制 VM。
pub fn select_window(&self, id: u64) -> Result<()> {
let mut state = self
.session
@@ -937,6 +989,7 @@ impl UiBridge {
state.current = id;
Ok(())
}
/// 从托管展示域撤销窗口,退役 Mount 并清理该窗口的私有对象关系。
pub fn retire_window(&self, vm: &mut Vm, id: u64) -> Result<()> {
if id == crate::window::MAIN_WINDOW {
bail!("the primary shell is closed by the OS window control");
@@ -964,6 +1017,7 @@ impl UiBridge {
Ok(())
}
/// 收尾已经关闭的展示资源,避免它们参与下一次窗口遍历。
pub fn finish_closed(&self, vm: &mut Vm) -> Result<()> {
let mut state = self
.session
@@ -988,6 +1042,7 @@ impl UiBridge {
state.current = crate::window::MAIN_WINDOW;
Ok(())
}
/// 从各托管窗口收集待发布命令;原生执行时还需校验 session。
pub fn take_window_commands(&self, vm: &Vm) -> Result<Vec<crate::window::Command>> {
let mut state = self
.session
@@ -1002,6 +1057,7 @@ impl UiBridge {
Ok(commands)
}
/// 校验并更新所属窗口的逻辑尺寸输入;尺寸不变时不制造新布局,改变时标记需要刷新。
pub fn set_viewport(&self, vm: &mut Vm, viewport: Option<crate::layout::Size>) -> Result<bool> {
if let Some(size) = viewport
&& (!size.width.is_finite()
@@ -1037,6 +1093,7 @@ impl UiBridge {
Ok(true)
}
/// 将 ui 入口与兼容名称安装到本次程序的全局字典,保持所有调用处在同一个 VM 域。
pub fn install_globals(&self, vm: &mut Vm, globals: ObjectRef) -> Result<()> {
vm.dict_set(globals, Value::Text("ui".into()), Value::Object(self.ui))?;
// Compatibility spelling used by the original module examples.
@@ -1051,6 +1108,7 @@ impl UiBridge {
}
Ok(())
}
/// 检查当前会话是否已经安排或拥有可展示页面。
pub fn has_page(&self) -> Result<bool> {
Ok(self
.session
@@ -1060,6 +1118,7 @@ impl UiBridge {
.values()
.any(|view| view.pending.flatten().is_some() || view.active.is_some()))
}
/// 验证标签拖放仍指向有效页面和窗口关系,避免旧拖动操作跨域生效。
pub fn accepts_tab_drop(&self, vm: &Vm, input: &crate::events::Input) -> bool {
let Some(target) = &input.tab_drop else {
return true;
@@ -1097,12 +1156,14 @@ impl UiBridge {
}
true
}
/// 通过展示协议打开源值,必要时创建或选择承载它的页面。
pub fn open_value(&self, vm: &mut Vm, value: &Value) -> Result<()> {
let function = object(Some(&vm.get_attr(self.ui, "open")?))?;
let page = vm.call(function, std::slice::from_ref(value))?;
vm.release_value(page)?;
Ok(())
}
/// 处理页面激活、关闭、移动和拆分等标签操作,保持窗口所有权与展示状态一致。
fn dispatch_tab(&self, vm: &mut Vm, input: &crate::events::Input) -> Result<()> {
let page = {
let state = self
@@ -1214,6 +1275,7 @@ impl UiBridge {
Ok(())
}
/// 在所属窗口的展示上下文中处理输入,区分页面管理、滚动、焦点、相机与普通事件。
pub fn dispatch(&self, vm: &mut Vm, input: &crate::events::Input) -> Result<()> {
input
.validate()
@@ -1419,6 +1481,7 @@ impl UiBridge {
vm.release(mount)?;
result
}
/// 整理不再有效的弱索引与展示根,并配合 VM 回收,避免派生缓存延长业务对象生命周期。
pub fn reclaim(&self, vm: &mut Vm, _roots: &mut Vec<ObjectRef>) -> Result<()> {
vm.collect_cycles();
let mut state = self
@@ -1438,6 +1501,7 @@ impl UiBridge {
}
Ok(())
}
/// 丢弃未成功发布的展示请求,恢复后续输入可以使用的会话状态。
pub fn discard_pending(&self, vm: &mut Vm) -> Result<()> {
let mut state = self
.session
@@ -1488,6 +1552,7 @@ impl UiBridge {
}
Ok(())
}
/// 重新评估已失效的属性绑定,并把结果计入会话统计。
pub fn refresh_bindings(&self, vm: &mut Vm) -> Result<()> {
let (nodes, desktops) = {
let state = self
@@ -1504,6 +1569,7 @@ impl UiBridge {
state.binding_evaluations = state.binding_evaluations.saturating_add(evaluated);
Ok(())
}
/// 排空一次 VM 变化记录并通知各窗口,提取活动页面快照,判断本次是否需要布局与发布。
pub fn prepare_frame(&self, vm: &mut Vm) -> Result<Option<Option<Arc<UiNode>>>> {
let changes = vm.take_changes();
let mut state = self
@@ -1548,6 +1614,7 @@ impl UiBridge {
}
Ok(changed.then_some(root))
}
/// 提交已经完成的出现几何与快照,并处理展示生命周期;不把挂起或失败的布局当成已发布帧。
pub fn commit_frame(
&self,
vm: &mut Vm,
@@ -1603,6 +1670,7 @@ impl UiBridge {
result
}
/// 在已完成的几何上启动绘制协议,保留绘制任务所需的宿主上下文。
pub fn begin_paint_frame(
&self,
vm: &mut Vm,
@@ -1633,6 +1701,7 @@ impl UiBridge {
self.accept_paint_progress(progress)
}
/// 恢复同一次源绘制调用,把完成的 Draft 交回发布流程。
pub fn resume_paint_frame(
&self,
vm: &mut Vm,
@@ -1642,6 +1711,7 @@ impl UiBridge {
self.accept_paint_progress(progress)
}
/// 区分挂起与完成的绘制进度;完成时保存真实读取依赖并接回发布流程。
fn accept_paint_progress(
&self,
progress: crate::source_paint::Progress,
@@ -1666,6 +1736,7 @@ impl UiBridge {
Ok(progress)
}
/// 取消尚未完成的源绘制,释放其续体和未发布上下文。
pub fn cancel_paint_frame(
&self,
vm: &mut Vm,
@@ -1684,6 +1755,7 @@ impl UiBridge {
invalidated
}
/// 为目标快照建立 Mount、检查点和布局上下文,再启动可挂起的只读布局求解。
pub fn begin_layout_frame(
&self,
vm: &mut Vm,
@@ -1806,6 +1878,7 @@ impl UiBridge {
self.accept_layout_progress(vm, context, progress)
}
/// 记录本次刷新主动让出 worker 的次数,用于诊断分片执行。
pub fn note_refresh_yield(&self) -> Result<()> {
let mut state = self
.session
@@ -1815,6 +1888,7 @@ impl UiBridge {
Ok(())
}
/// 记录视口目标替换导致的刷新重启,便于区分正常挂起与取消重试。
pub fn note_refresh_restart(
&self,
cancelled_layout: bool,
@@ -1834,6 +1908,7 @@ impl UiBridge {
Ok(())
}
/// 撤销未完成布局所保留的窗口、挂载与生命周期上下文。
fn discard_layout_context(&self, vm: &mut Vm, context: LayoutContext) -> Result<()> {
let LayoutContext {
surface: _,
@@ -1866,6 +1941,7 @@ impl UiBridge {
Ok(())
}
/// 取消源布局续体并清理对应上下文,保持已发布帧可用。
pub fn cancel_layout_frame(&self, vm: &mut Vm, pending: PendingLayout) -> Result<()> {
let PendingLayout { work, context } = pending;
let cancelled = work.cancel(vm);
@@ -1874,10 +1950,12 @@ impl UiBridge {
restored
}
/// 关闭失败布局的挂起工作并恢复检查点;供错误或候选撤销路径使用。
pub fn abort_layout_frame(&self, vm: &mut Vm, pending: PendingLayout) -> Result<()> {
self.cancel_layout_frame(vm, pending)
}
/// 继续同一次尚未发布的布局任务;完成时沿原上下文收尾,不能新建一轮来重放副作用。
pub fn resume_layout_frame(
&self,
vm: &mut Vm,
@@ -1895,6 +1973,7 @@ impl UiBridge {
self.accept_layout_progress(vm, context, progress)
}
/// 接收布局的 Pending/Complete 结果;保留上下文或执行最终投影和提交。
fn accept_layout_progress(
&self,
vm: &mut Vm,
@@ -1918,6 +1997,7 @@ impl UiBridge {
}
}
/// 依次投影滚动/视口、补页面元数据、保存读取版本、提交 Mount,并处理延后的生命周期调用。
fn finish_layout_frame(
&self,
vm: &mut Vm,
@@ -2018,6 +2098,7 @@ impl UiBridge {
Ok(frame)
}
/// 读取当前源程序已经选择的展示内容,为编译入口生成最终文档提供根。
pub fn rendered(&self, vm: &Vm) -> Result<Option<Arc<UiNode>>> {
let state = self
.session
@@ -2032,6 +2113,7 @@ impl UiBridge {
}
}
/// 从会话的类型注册表取得指定类型,再给原生分配的对象附加托管类型身份。
fn attach_named_type(
cx: &mut NativeContext<'_>,
object: ObjectRef,
@@ -2045,6 +2127,7 @@ fn attach_named_type(
attach_desktop_type(cx, object, name, desktop)
}
/// 按给定 desktop 查找类型并附加,支持不同窗口使用自己的展示上下文。
pub fn attach_desktop_type(
cx: &mut NativeContext<'_>,
instance: ObjectRef,
@@ -2055,6 +2138,7 @@ pub fn attach_desktop_type(
cx.attach_type(instance, definition)
}
/// 读取 desktop 的托管类型注册表;缺失或类型错误时返回 VM 错误。
pub(crate) fn desktop_type(
store: &endor_core::ObjectStore,
name: &str,
@@ -2064,6 +2148,7 @@ pub(crate) fn desktop_type(
object(store.dict_get(types, &Value::Text(name.into()))?.as_ref())
}
/// 将当前托管或可变状态提取为后续阶段使用的派生表示。
pub fn snapshot(vm: &Vm, value: &Value) -> Result<Arc<UiNode>> {
let Value::Object(root) = value else {
bail!("main must return a Block");