feat: retain managed visual objects and dispatch native input through Endor
Verify Tessera GUI / verify (push) Successful in 9m28s

This commit is contained in:
2026-10-21 01:49:35 +08:00
parent 757fa22d9b
commit 0d5e4b318d
21 changed files with 3295 additions and 892 deletions
+390
View File
@@ -0,0 +1,390 @@
//! 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)]
pub struct Mount {
pub block: ObjectRef,
pub page: Option<WeakObjectRef>,
pub parent: Option<WeakObjectRef>,
pub first_child: Option<WeakObjectRef>,
pub next_sibling: Option<WeakObjectRef>,
pub geometry: MountGeometry,
pub version: u64,
pub mounted: bool,
}
impl ObjectPayload for Mount {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn kind_name(&self) -> &'static str {
"tessera-mount"
}
fn allows_attributes(&self) -> bool {
true
}
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
visit(self.block);
}
}
#[derive(Debug, Clone, Copy)]
enum Query {
Bounds,
Parent,
FirstChild,
NextSibling,
Page,
Focus,
HitTest,
}
#[derive(Debug)]
struct Method {
owner: ObjectRef,
desktop: ObjectRef,
query: Query,
}
impl NativeCallable for Method {
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
let mount = cx.store().payload::<Mount>(self.owner, "Mount")?.clone();
if !mount.mounted {
return Err(VmError::InvalidArgument("Mount is no longer attached"));
}
let arity = if matches!(self.query, Query::HitTest) {
2
} else {
0
};
if args.len() != arity {
return Err(VmError::InvalidArgument("incorrect Mount method arity"));
}
let value = match self.query {
Query::Bounds => {
let bounds = cx.new_object()?;
for (name, value) in [
("x", mount.geometry.x),
("y", mount.geometry.y),
("width", mount.geometry.width),
("height", mount.geometry.height),
] {
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 => {
if !mount.geometry.interactive {
return Err(VmError::InvalidArgument("Mount is not focusable"));
}
cx.set_attr(
self.desktop,
"focus",
Value::Number((mount.geometry.id as i64).into()),
)?;
cx.set_attr(self.desktop, "focusRequested", Value::Bool(true))?;
Value::Nil
}
Query::HitTest => {
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(
crate::geometry::Rect::new(
mount.geometry.x,
mount.geometry.y,
mount.geometry.width,
mount.geometry.height,
)
.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!(),
};
weak.map(|weak| cx.upgrade(weak))
.transpose()?
.flatten()
.map(Value::Object)
.unwrap_or(Value::Nil)
}
};
Ok(NativeResult::Return(value))
}
}
#[derive(Debug, Default, Clone)]
pub struct MountTable {
pub active: HashMap<u64, WeakObjectRef>,
}
#[derive(Debug)]
struct Sync {
desktop: ObjectRef,
page: Option<ObjectRef>,
nodes: Vec<WeakObjectRef>,
old: HashMap<u64, WeakObjectRef>,
frame: Frame,
output: Arc<Mutex<HashMap<u64, WeakObjectRef>>>,
}
impl NativeCallable for Sync {
fn invoke(&self, cx: &mut NativeContext<'_>, _args: &[Value]) -> Result<NativeResult, VmError> {
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();
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();
let object = if let Some(old) = old {
old
} else {
let object = cx.allocate(Mount {
block,
page,
parent: None,
first_child: None,
next_sibling: None,
geometry: geometry.clone(),
version: self.frame.layout_version,
mounted: true,
})?;
crate::ui_bridge::attach_desktop_type(cx, object, "Mount", self.desktop)?;
for (name, query) in [
("bounds", Query::Bounds),
("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 {
owner: object,
desktop: self.desktop,
query,
},
vec![object, self.desktop],
))?;
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))?;
object
};
objects.insert(geometry.id, object);
}
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 {
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(),
version: self.frame.layout_version,
mounted: true,
};
let old = cx.store().payload::<Mount>(object, "Mount")?;
if !old.mounted
|| 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()),
)?;
}
cx.dict_set(
root,
Value::Text(geometry.id.to_string()),
Value::Object(object),
)?;
}
for (id, weak) in &self.old {
if !objects.contains_key(id)
&& let Some(object) = cx.upgrade(*weak)?
{
let mut mount = cx.store().payload::<Mount>(object, "Mount")?.clone();
mount.mounted = false;
mount.parent = None;
mount.first_child = None;
mount.next_sibling = None;
cx.replace_payload(object, mount)?;
cx.set_attr(object, "mounted", Value::Bool(false))?;
}
}
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(Value::Nil))
}
}
impl MountTable {
pub fn synchronize(
&mut self,
vm: &mut Vm,
desktop: ObjectRef,
page: Option<ObjectRef>,
nodes: Vec<WeakObjectRef>,
frame: &Frame,
) -> Result<(), 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(),
frame: frame.clone(),
output: output.clone(),
},
captures,
))?;
let result = vm.call(function, &[]);
vm.release(function)?;
vm.release_value(result?)?;
self.active = std::mem::take(
&mut *output
.lock()
.map_err(|_| VmError::InvalidArgument("Mount registry poisoned"))?,
);
Ok(())
}
}
#[derive(Debug)]
struct MountSet(Vec<ObjectRef>);
impl ObjectPayload for MountSet {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn kind_name(&self) -> &'static str {
"tessera-mount-set"
}
fn allows_attributes(&self) -> bool {
true
}
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
for mount in &self.0 {
visit(*mount);
}
}
}
#[derive(Debug)]
struct At(ObjectRef);
impl NativeCallable for At {
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
let [Value::Number(index)] = args else {
return Err(VmError::InvalidArgument("mount set at expects an index"));
};
let index = index
.as_i64()
.and_then(|v| usize::try_from(v).ok())
.ok_or(VmError::InvalidArgument("invalid mount index"))?;
let mount = *cx
.store()
.payload::<MountSet>(self.0, "Mount set")?
.0
.get(index)
.ok_or(VmError::InvalidArgument("mount index out of range"))?;
Ok(NativeResult::Return(Value::Object(mount)))
}
}
pub fn collection(
cx: &mut NativeContext<'_>,
mounts: Vec<ObjectRef>,
) -> Result<ObjectRef, VmError> {
let first = mounts
.first()
.copied()
.map(Value::Object)
.unwrap_or(Value::Nil);
let count = mounts.len();
let set = cx.allocate(MountSet(mounts))?;
cx.set_attr(set, "first", first)?;
cx.set_attr(set, "count", Value::Number((count as i64).into()))?;
let at = cx.allocate(ContextNativeFunction::new("at", At(set), vec![set]))?;
cx.set_attr(set, "at", Value::Object(at))?;
Ok(set)
}