refactor: organize host modules and document architecture with UML
Verify Tessera GUI / verify (push) Failing after 2m2s
Verify Tessera GUI / verify (push) Failing after 2m2s
This commit is contained in:
@@ -0,0 +1,205 @@
|
||||
//! Target-owned managed bindings. Dependency versions are borrowed identities;
|
||||
//! the host's weak Block registry never roots an otherwise unreachable graph.
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use endor_core::{NativeContext, ObjectPayload, ObjectRef, Value, Vm, VmError, WeakObjectRef};
|
||||
|
||||
use crate::{block, event_dispatch::Subscription, ui_bridge::attach_desktop_type};
|
||||
|
||||
/// The output value is borrowed for equality only, including object handles.
|
||||
/// It never owns a reference or dereferences a possibly reclaimed cached object.
|
||||
#[derive(Debug, Clone)]
|
||||
struct Cached {
|
||||
reads: Vec<endor_core::ReadDependency>,
|
||||
output: Value,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Binding {
|
||||
field: String,
|
||||
pub compute: Option<ObjectRef>,
|
||||
reads: Arc<Mutex<Option<Cached>>>,
|
||||
}
|
||||
impl ObjectPayload for Binding {
|
||||
fn reference_assignment_only(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
fn kind_name(&self) -> &'static str {
|
||||
"tessera-binding"
|
||||
}
|
||||
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
|
||||
if let Some(compute) = self.compute {
|
||||
visit(compute);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn connect(
|
||||
cx: &mut NativeContext<'_>,
|
||||
target: ObjectRef,
|
||||
field: &str,
|
||||
compute: ObjectRef,
|
||||
desktop: ObjectRef,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
if field.is_empty() || field.len() > 128 || field == "type" {
|
||||
return Err(VmError::InvalidArgument("invalid binding property"));
|
||||
}
|
||||
let (reference, data) = block::resolve(cx.store(), target)?;
|
||||
let mut data = data.clone();
|
||||
// Only actual fields can be bound; method names are not writable targets.
|
||||
let properties = data
|
||||
.properties
|
||||
.ok_or(VmError::InvalidArgument("missing property storage"))?;
|
||||
cx.store().get_attr(properties, field)?;
|
||||
if !cx.store().object(compute)?.payload().is_function() {
|
||||
return Err(VmError::InvalidArgument(
|
||||
"binding compute must be a Function",
|
||||
));
|
||||
}
|
||||
if !cx
|
||||
.store()
|
||||
.call_arity(compute)?
|
||||
.ok_or(VmError::InvalidArgument(
|
||||
"binding compute requires positional metadata",
|
||||
))?
|
||||
.accepts(0)
|
||||
{
|
||||
return Err(VmError::InvalidArgument(
|
||||
"binding compute requires zero unbound parameters",
|
||||
));
|
||||
}
|
||||
let mut retained = vec![];
|
||||
for connection in &data.bindings {
|
||||
let mut binding = cx
|
||||
.store()
|
||||
.payload::<Binding>(*connection, "Binding")?
|
||||
.clone();
|
||||
if binding.compute.is_some() && binding.field != field {
|
||||
retained.push(*connection);
|
||||
} else if binding.compute.is_some() {
|
||||
binding.compute = None;
|
||||
*binding
|
||||
.reads
|
||||
.lock()
|
||||
.map_err(|_| VmError::InvalidArgument("binding cache poisoned"))? = None;
|
||||
cx.replace_payload(*connection, binding)?;
|
||||
}
|
||||
}
|
||||
if retained.len() >= 128 {
|
||||
return Err(VmError::ExecutionLimit("128 bindings per Block"));
|
||||
}
|
||||
let connection = cx.allocate(Binding {
|
||||
field: field.into(),
|
||||
compute: Some(compute),
|
||||
reads: Arc::new(Mutex::new(None)),
|
||||
})?;
|
||||
retained.push(connection);
|
||||
data.bindings = retained;
|
||||
// Generic text bindings replace the legacy textOf derivation.
|
||||
if field == "text" {
|
||||
data.text_binding = None;
|
||||
}
|
||||
cx.replace_payload(reference, data)?;
|
||||
let token = cx.allocate(Subscription {
|
||||
connection: cx.store().downgrade(connection)?,
|
||||
})?;
|
||||
attach_desktop_type(cx, token, "Subscription", desktop)?;
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
pub fn refresh(
|
||||
vm: &mut Vm,
|
||||
nodes: &[WeakObjectRef],
|
||||
host_desktops: &HashSet<ObjectRef>,
|
||||
) -> Result<usize> {
|
||||
let mut work = 0;
|
||||
loop {
|
||||
let mut evaluated = false;
|
||||
let mut seen = HashSet::new();
|
||||
for weak in nodes {
|
||||
let Some(target) = vm.upgrade(*weak)? else {
|
||||
continue;
|
||||
};
|
||||
let result: Result<()> = (|| {
|
||||
let (reference, data) = block::resolve(vm.object_store(), target)?;
|
||||
if !seen.insert(reference) {
|
||||
return Ok(());
|
||||
}
|
||||
let connections = data.bindings.clone();
|
||||
for connection in connections {
|
||||
let binding = vm.payload::<Binding>(connection, "Binding")?.clone();
|
||||
let Some(compute) = binding.compute else {
|
||||
continue;
|
||||
};
|
||||
let cached = binding
|
||||
.reads
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("binding cache poisoned"))?
|
||||
.clone();
|
||||
if cached.as_ref().is_some_and(|cached| {
|
||||
cached
|
||||
.reads
|
||||
.iter()
|
||||
.all(|read| vm.object_store().read_dependency_valid(read))
|
||||
&& vm
|
||||
.get_attr(target, &binding.field)
|
||||
.is_ok_and(|value| value == cached.output)
|
||||
}) {
|
||||
continue;
|
||||
}
|
||||
work += 1;
|
||||
if work > 10_000 {
|
||||
bail!("property bindings did not stabilize within the execution budget");
|
||||
}
|
||||
evaluated = true;
|
||||
let (value, reads) = vm
|
||||
.call_read_only_precise_with_limits(
|
||||
compute,
|
||||
&[],
|
||||
endor_core::ExecutionLimits {
|
||||
max_frames: 128,
|
||||
max_instructions: 100_000,
|
||||
},
|
||||
)
|
||||
.map_err(|error| crate::endor_host::runtime_error(vm, error))?;
|
||||
let applied: Result<()> = (|| {
|
||||
let reads = reads
|
||||
.dependencies
|
||||
.into_iter()
|
||||
.filter(|read| !host_desktops.contains(&read.object()))
|
||||
.collect();
|
||||
let (_, data) = block::resolve(vm.object_store(), target)?;
|
||||
block::apply_visual_property(&mut data.clone(), &binding.field, &value)?;
|
||||
if vm.get_attr(target, &binding.field)? != value {
|
||||
vm.set_attr(target, &binding.field, value.clone())?;
|
||||
}
|
||||
*binding
|
||||
.reads
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("binding cache poisoned"))? =
|
||||
Some(Cached {
|
||||
reads,
|
||||
output: value.clone(),
|
||||
});
|
||||
Ok(())
|
||||
})();
|
||||
vm.release_value(value)?;
|
||||
applied?;
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
vm.release(target)?;
|
||||
result?;
|
||||
}
|
||||
if !evaluated {
|
||||
return Ok(work);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,474 @@
|
||||
//! Live visual objects. All semantic references are owned by Aster's heap;
|
||||
//! native Arcs are reserved for immutable rendering snapshots.
|
||||
use std::sync::Arc;
|
||||
|
||||
use endor_core::{NativeContext, ObjectPayload, ObjectRef, ObjectStore, Value, VmError};
|
||||
|
||||
use crate::ui_bridge::UiNode;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Child {
|
||||
pub slot: u64,
|
||||
pub block: ObjectRef,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Kind {
|
||||
Text {
|
||||
value: String,
|
||||
size: u32,
|
||||
color: String,
|
||||
},
|
||||
Rect {
|
||||
width: f32,
|
||||
height: f32,
|
||||
radius: f32,
|
||||
color: String,
|
||||
},
|
||||
Spacer(f32),
|
||||
Scroll {
|
||||
width: f32,
|
||||
height: f32,
|
||||
},
|
||||
Row,
|
||||
Column,
|
||||
Button,
|
||||
Page,
|
||||
}
|
||||
|
||||
/// The VM owns the Block -> Cell -> Data relationship. Shared assignment
|
||||
/// changes the Cell to point at another Block, retaining the original identity.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Block {
|
||||
pub state: ObjectRef,
|
||||
pub page: bool,
|
||||
pub tasks: Option<ObjectRef>,
|
||||
}
|
||||
|
||||
impl ObjectPayload for Block {
|
||||
fn reference_assignment_only(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn attribute_target(&self, store: &ObjectStore) -> Result<Option<ObjectRef>, VmError> {
|
||||
let Value::Object(value) = store.cell_get(self.state)? else {
|
||||
return Err(VmError::InvalidArgument("Block state is not an object"));
|
||||
};
|
||||
if store.object(value)?.payload().as_any().is::<Block>() {
|
||||
Ok(Some(value))
|
||||
} else {
|
||||
store
|
||||
.payload::<Data>(value, "Block data")?
|
||||
.properties
|
||||
.map(Some)
|
||||
.ok_or(VmError::InvalidArgument(
|
||||
"Block has no managed property storage",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn type_target(&self, store: &ObjectStore) -> Result<Option<ObjectRef>, VmError> {
|
||||
let Value::Object(value) = store.cell_get(self.state)? else {
|
||||
return Err(VmError::InvalidArgument("Block state is not an object"));
|
||||
};
|
||||
if store.object(value)?.payload().as_any().is::<Block>() {
|
||||
Ok(Some(value))
|
||||
} else {
|
||||
store.payload::<Data>(value, "Block data")?;
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
fn kind_name(&self) -> &'static str {
|
||||
"tessera-block"
|
||||
}
|
||||
fn allows_attributes(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
|
||||
visit(self.state);
|
||||
if let Some(tasks) = self.tasks {
|
||||
visit(tasks);
|
||||
}
|
||||
}
|
||||
fn assignment_cell(
|
||||
&self,
|
||||
source: ObjectRef,
|
||||
store: &ObjectStore,
|
||||
) -> Result<Option<ObjectRef>, VmError> {
|
||||
if !store.object(source)?.payload().as_any().is::<Self>() {
|
||||
return Ok(None);
|
||||
}
|
||||
if store.payload::<Self>(source, "Block")?.page != self.page {
|
||||
return Err(VmError::InvalidArgument(
|
||||
"Page assignment requires another Page",
|
||||
));
|
||||
}
|
||||
validate(store, source, Some(self.state))?;
|
||||
Ok(Some(self.state))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Data {
|
||||
pub kind: Kind,
|
||||
pub children: Vec<Child>,
|
||||
pub padding: f32,
|
||||
pub gap: f32,
|
||||
pub flex: f32,
|
||||
pub flex_policy: crate::layout::FlexPolicy,
|
||||
pub main_align: crate::layout::MainAlign,
|
||||
pub scroll_axis: crate::scroll::Axis,
|
||||
pub next_slot: u64,
|
||||
pub history: Vec<ObjectRef>,
|
||||
pub history_index: usize,
|
||||
pub bindings: Vec<ObjectRef>,
|
||||
pub text_binding: Option<(ObjectRef, String)>,
|
||||
pub click: Option<ObjectRef>,
|
||||
pub subscriptions: Vec<ObjectRef>,
|
||||
pub properties: Option<ObjectRef>,
|
||||
}
|
||||
|
||||
impl Data {
|
||||
pub fn new(kind: Kind, children: Vec<ObjectRef>, padding: f32, gap: f32) -> Self {
|
||||
let next_slot = children.len() as u64;
|
||||
Self {
|
||||
kind,
|
||||
children: children
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(slot, block)| Child {
|
||||
slot: slot as u64,
|
||||
block,
|
||||
})
|
||||
.collect(),
|
||||
padding,
|
||||
gap,
|
||||
flex: 0.0,
|
||||
flex_policy: crate::layout::FlexPolicy::default(),
|
||||
main_align: crate::layout::MainAlign::Start,
|
||||
scroll_axis: crate::scroll::Axis::Both,
|
||||
next_slot,
|
||||
history: vec![],
|
||||
history_index: 0,
|
||||
bindings: vec![],
|
||||
text_binding: None,
|
||||
click: None,
|
||||
subscriptions: vec![],
|
||||
properties: None,
|
||||
}
|
||||
}
|
||||
pub fn is_container(&self) -> bool {
|
||||
matches!(
|
||||
self.kind,
|
||||
Kind::Row | Kind::Column | Kind::Button | Kind::Page | Kind::Scroll { .. }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl ObjectPayload for Data {
|
||||
fn reference_assignment_only(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
fn kind_name(&self) -> &'static str {
|
||||
"tessera-block-data"
|
||||
}
|
||||
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
|
||||
if let Some(properties) = self.properties {
|
||||
visit(properties);
|
||||
}
|
||||
for child in &self.children {
|
||||
visit(child.block);
|
||||
}
|
||||
for item in &self.history {
|
||||
visit(*item);
|
||||
}
|
||||
if let Some((source, _)) = &self.text_binding {
|
||||
visit(*source);
|
||||
}
|
||||
for binding in &self.bindings {
|
||||
visit(*binding);
|
||||
}
|
||||
for token in &self.subscriptions {
|
||||
visit(*token);
|
||||
}
|
||||
if let Some(handler) = self.click {
|
||||
visit(handler);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn allocate(cx: &mut NativeContext<'_>, mut data: Data) -> Result<ObjectRef, VmError> {
|
||||
let page = matches!(data.kind, Kind::Page);
|
||||
for child in &data.children {
|
||||
validate(cx.store(), child.block, None)?;
|
||||
}
|
||||
let properties = cx.new_object()?;
|
||||
for (name, value) in native_properties(&data) {
|
||||
cx.set_attr(properties, name, value)?;
|
||||
}
|
||||
data.properties = Some(properties);
|
||||
let data = cx.allocate(data)?;
|
||||
let state = cx.new_cell(Some(Value::Object(data)))?;
|
||||
cx.allocate(Block {
|
||||
state,
|
||||
page,
|
||||
tasks: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Borrowed final data; forwarding is part of the managed graph, never an Arc
|
||||
/// ownership graph hidden from the VM's cycle collector.
|
||||
pub fn resolve(store: &ObjectStore, block: ObjectRef) -> Result<(ObjectRef, &Data), VmError> {
|
||||
let (reference, data, _) = resolve_tracked(store, block)?;
|
||||
Ok((reference, data))
|
||||
}
|
||||
|
||||
pub fn resolve_tracked(
|
||||
store: &ObjectStore,
|
||||
block: ObjectRef,
|
||||
) -> Result<(ObjectRef, &Data, Vec<ObjectRef>), VmError> {
|
||||
let mut current = block;
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut dependencies = Vec::new();
|
||||
loop {
|
||||
if !seen.insert(current) {
|
||||
return Err(VmError::InvalidArgument("cyclic Block reference"));
|
||||
}
|
||||
let state = store.payload::<Block>(current, "Block")?.state;
|
||||
dependencies.extend([current, state]);
|
||||
let Value::Object(value) = store.cell_get(state)? else {
|
||||
return Err(VmError::InvalidArgument("Block state is not an object"));
|
||||
};
|
||||
if store.object(value)?.payload().as_any().is::<Data>() {
|
||||
dependencies.push(value);
|
||||
return Ok((
|
||||
value,
|
||||
store.payload::<Data>(value, "Block data")?,
|
||||
dependencies,
|
||||
));
|
||||
}
|
||||
current = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate the entire finite expansion before establishing a new composition
|
||||
/// edge. The node count is an explicit rejected resource quota, not truncated UI.
|
||||
pub fn validate(
|
||||
store: &ObjectStore,
|
||||
root: ObjectRef,
|
||||
forbidden_state: Option<ObjectRef>,
|
||||
) -> Result<(), VmError> {
|
||||
enum Step {
|
||||
Enter(ObjectRef),
|
||||
Exit(ObjectRef),
|
||||
}
|
||||
let mut work = vec![Step::Enter(root)];
|
||||
let mut path = std::collections::HashSet::new();
|
||||
let mut visits = 0;
|
||||
while let Some(step) = work.pop() {
|
||||
match step {
|
||||
Step::Exit(state) => {
|
||||
path.remove(&state);
|
||||
}
|
||||
Step::Enter(block) => {
|
||||
visits += 1;
|
||||
if visits > 10_000 {
|
||||
return Err(VmError::ExecutionLimit("expanded Block graph"));
|
||||
}
|
||||
let state = store.payload::<Block>(block, "Block")?.state;
|
||||
if forbidden_state == Some(state) || !path.insert(state) {
|
||||
return Err(VmError::InvalidArgument(
|
||||
"Block composition would create a cycle",
|
||||
));
|
||||
}
|
||||
work.push(Step::Exit(state));
|
||||
let Value::Object(value) = store.cell_get(state)? else {
|
||||
return Err(VmError::InvalidArgument("invalid Block state"));
|
||||
};
|
||||
if forbidden_state == Some(value) {
|
||||
return Err(VmError::InvalidArgument(
|
||||
"Block composition would create a cycle",
|
||||
));
|
||||
}
|
||||
if let Ok(data) = store.payload::<Data>(value, "Block data") {
|
||||
for child in data.children.iter().rev() {
|
||||
work.push(Step::Enter(child.block));
|
||||
}
|
||||
} else {
|
||||
work.push(Step::Enter(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn snapshot(store: &ObjectStore, root: ObjectRef) -> Result<Arc<UiNode>, VmError> {
|
||||
crate::snapshot::RenderCache::default().snapshot(store, root)
|
||||
}
|
||||
|
||||
/// Native visual parameters are ordinary managed attributes too. Composition,
|
||||
/// histories and connections remain structural payload edges.
|
||||
pub fn native_properties(data: &Data) -> Vec<(&'static str, Value)> {
|
||||
fn number(value: f32) -> Value {
|
||||
Value::Number((value as f64).into())
|
||||
}
|
||||
let mut fields = vec![
|
||||
("flex", number(data.flex)),
|
||||
(
|
||||
"flexBasis",
|
||||
data.flex_policy
|
||||
.basis
|
||||
.map_or_else(|| Value::Text("auto".into()), number),
|
||||
),
|
||||
("flexMin", number(data.flex_policy.min)),
|
||||
("flexMax", number(data.flex_policy.max)),
|
||||
("flexShrink", number(data.flex_policy.shrink)),
|
||||
];
|
||||
match &data.kind {
|
||||
Kind::Text { value, size, color } => fields.extend([
|
||||
("text", Value::Text(value.clone())),
|
||||
("size", Value::Number((*size as i64).into())),
|
||||
("color", Value::Text(color.clone())),
|
||||
]),
|
||||
Kind::Rect {
|
||||
width,
|
||||
height,
|
||||
radius,
|
||||
color,
|
||||
} => fields.extend([
|
||||
("width", number(*width)),
|
||||
("height", number(*height)),
|
||||
("radius", number(*radius)),
|
||||
("color", Value::Text(color.clone())),
|
||||
]),
|
||||
Kind::Scroll { width, height } => fields.extend([
|
||||
("width", number(*width)),
|
||||
("height", number(*height)),
|
||||
("axis", Value::Text(data.scroll_axis.name().into())),
|
||||
]),
|
||||
Kind::Spacer(size) => fields.push(("size", number(*size))),
|
||||
_ => {}
|
||||
}
|
||||
if data.is_container() {
|
||||
fields.extend([
|
||||
("padding", number(data.padding)),
|
||||
("gap", number(data.gap)),
|
||||
("mainAlign", Value::Text(data.main_align.name().into())),
|
||||
]);
|
||||
}
|
||||
fields
|
||||
}
|
||||
|
||||
pub fn visual_data(store: &ObjectStore, data: &Data) -> Result<Data, VmError> {
|
||||
let mut data = data.clone();
|
||||
let properties = data
|
||||
.properties
|
||||
.ok_or(VmError::InvalidArgument("missing Block properties"))?;
|
||||
for (name, _) in native_properties(&data) {
|
||||
let value = store.get_attr(properties, name)?;
|
||||
apply_visual_property(&mut data, name, &value)?;
|
||||
}
|
||||
if data.flex_policy.min > data.flex_policy.max {
|
||||
return Err(VmError::InvalidArgument("flexMin exceeds flexMax"));
|
||||
}
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Result<(), VmError> {
|
||||
let bad = || VmError::InvalidArgument("invalid native visual property");
|
||||
let number = || -> Result<f32, VmError> {
|
||||
let Value::Number(value) = value else {
|
||||
return Err(bad());
|
||||
};
|
||||
let n = value.to_string().parse::<f32>().map_err(|_| bad())?;
|
||||
if !n.is_finite() || !(0.0..=crate::ui_bridge::MAX_DIMENSION as f32).contains(&n) {
|
||||
return Err(bad());
|
||||
}
|
||||
Ok(n)
|
||||
};
|
||||
match name {
|
||||
"flexBasis" => {
|
||||
data.flex_policy.basis = if matches!(value, Value::Nil)
|
||||
|| matches!(value, Value::Text(text) if text == "auto")
|
||||
{
|
||||
None
|
||||
} else {
|
||||
Some(number()?)
|
||||
};
|
||||
return Ok(());
|
||||
}
|
||||
"flexMin" => {
|
||||
data.flex_policy.min = number()?;
|
||||
return Ok(());
|
||||
}
|
||||
"flexMax" => {
|
||||
data.flex_policy.max = number()?;
|
||||
return Ok(());
|
||||
}
|
||||
"flexShrink" => {
|
||||
data.flex_policy.shrink = number()?;
|
||||
return Ok(());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if name == "flex" {
|
||||
data.flex = number()?;
|
||||
return Ok(());
|
||||
}
|
||||
let container = data.is_container();
|
||||
if container && name == "mainAlign" {
|
||||
let Value::Text(value) = value else {
|
||||
return Err(bad());
|
||||
};
|
||||
data.main_align = crate::layout::MainAlign::parse(value)?;
|
||||
return Ok(());
|
||||
}
|
||||
match (&mut data.kind, name) {
|
||||
(Kind::Text { value: text, .. }, "text") => {
|
||||
let Value::Text(value) = value else {
|
||||
return Err(bad());
|
||||
};
|
||||
if value.len() > 16_384 {
|
||||
return Err(bad());
|
||||
}
|
||||
text.clone_from(value);
|
||||
}
|
||||
(Kind::Text { size, .. }, "size") => {
|
||||
let n = number()?;
|
||||
if !(1.0..=8.0).contains(&n) || n.fract() != 0.0 {
|
||||
return Err(bad());
|
||||
}
|
||||
*size = n as u32;
|
||||
}
|
||||
(Kind::Text { color, .. } | Kind::Rect { color, .. }, "color") => {
|
||||
let Value::Text(value) = value else {
|
||||
return Err(bad());
|
||||
};
|
||||
crate::document::parse_color(value).map_err(|_| bad())?;
|
||||
color.clone_from(value);
|
||||
}
|
||||
(Kind::Scroll { .. }, "axis") => {
|
||||
let Value::Text(name) = value else {
|
||||
return Err(bad());
|
||||
};
|
||||
data.scroll_axis = crate::scroll::Axis::parse(name)?;
|
||||
}
|
||||
(Kind::Scroll { width, .. }, "width") => *width = number()?,
|
||||
(Kind::Scroll { height, .. }, "height") => *height = number()?,
|
||||
(Kind::Rect { width, .. }, "width") => *width = number()?,
|
||||
(Kind::Rect { height, .. }, "height") => *height = number()?,
|
||||
(Kind::Rect { radius, .. }, "radius") => *radius = number()?,
|
||||
(Kind::Spacer(size), "size") => *size = number()?,
|
||||
(_, "padding") if container => data.padding = number()?,
|
||||
(_, "gap") if container => data.gap = number()?,
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,676 @@
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{Context as _, Result, bail};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{
|
||||
display_list::{Color, DisplayList, DrawCommand},
|
||||
geometry::{Point, Rect},
|
||||
ui_bridge::UiNode,
|
||||
};
|
||||
|
||||
pub const DEFAULT_NAMESPACE: &str = "app.main";
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct NamespaceState {
|
||||
pub name: String,
|
||||
pub revision: u64,
|
||||
pub submission: u64,
|
||||
pub document: RenderDocument,
|
||||
pub viewport: Option<crate::layout::Size>,
|
||||
pub window_viewports: std::collections::BTreeMap<u64, crate::layout::Size>,
|
||||
pub runtime_session: u64,
|
||||
pub window_commands: Vec<crate::window::Envelope>,
|
||||
}
|
||||
|
||||
impl Default for NamespaceState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
name: DEFAULT_NAMESPACE.to_owned(),
|
||||
revision: 0,
|
||||
submission: 0,
|
||||
document: RenderDocument::default(),
|
||||
viewport: None,
|
||||
window_viewports: std::collections::BTreeMap::new(),
|
||||
runtime_session: 0,
|
||||
window_commands: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NamespaceState {
|
||||
pub fn publish_window_commands(&mut self, session: u64, commands: Vec<crate::window::Command>) {
|
||||
if self.runtime_session != session {
|
||||
self.window_commands.clear();
|
||||
// The primary shell survives VM replacement. Secondary native
|
||||
// resources belong to their originating runtime generation.
|
||||
self.window_viewports
|
||||
.retain(|id, _| *id == crate::window::MAIN_WINDOW);
|
||||
}
|
||||
self.runtime_session = session;
|
||||
if session == 0 {
|
||||
self.window_commands.clear();
|
||||
return;
|
||||
}
|
||||
for command in commands {
|
||||
self.window_commands
|
||||
.retain(|old| !old.command.same_kind(&command));
|
||||
self.window_commands
|
||||
.push(crate::window::Envelope { session, command });
|
||||
}
|
||||
self.window_commands
|
||||
.sort_by_key(|command| command.command.sequence);
|
||||
}
|
||||
|
||||
pub fn next_submission(&self) -> Result<u64> {
|
||||
self.submission
|
||||
.checked_add(1)
|
||||
.context("submission counter exhausted")
|
||||
}
|
||||
|
||||
pub fn commit(&mut self, submission: u64, document: RenderDocument) -> Result<Option<u64>> {
|
||||
if submission != self.submission {
|
||||
return Ok(None);
|
||||
}
|
||||
let revision = self
|
||||
.revision
|
||||
.checked_add(1)
|
||||
.context("revision counter exhausted")?;
|
||||
self.document = document;
|
||||
self.revision = revision;
|
||||
Ok(Some(revision))
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) -> Result<u64> {
|
||||
let submission = self.next_submission()?;
|
||||
let revision = self
|
||||
.revision
|
||||
.checked_add(1)
|
||||
.context("revision counter exhausted")?;
|
||||
self.submission = submission;
|
||||
self.document = RenderDocument::default();
|
||||
self.runtime_session = 0;
|
||||
self.window_commands.clear();
|
||||
self.revision = revision;
|
||||
Ok(revision)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
pub struct RenderDocument {
|
||||
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
|
||||
pub windows: std::collections::BTreeMap<u64, RenderDocument>,
|
||||
#[serde(skip)]
|
||||
pub ui_root: Option<Arc<UiNode>>,
|
||||
#[serde(default)]
|
||||
pub source: String,
|
||||
#[serde(default)]
|
||||
pub root: Option<CodeNode>,
|
||||
#[serde(default)]
|
||||
pub frame: Frame,
|
||||
}
|
||||
|
||||
impl RenderDocument {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
if self.windows.len() > 15 {
|
||||
bail!("too many window projections");
|
||||
}
|
||||
for (id, document) in &self.windows {
|
||||
if *id == crate::window::MAIN_WINDOW
|
||||
|| *id != document.frame.window
|
||||
|| !document.windows.is_empty()
|
||||
{
|
||||
bail!("invalid secondary window projection");
|
||||
}
|
||||
document.validate()?;
|
||||
}
|
||||
if self.source.len() > 1_048_576 {
|
||||
bail!("source exceeds the 1 MiB limit");
|
||||
}
|
||||
if self.frame.commands.len() > 10_000 {
|
||||
bail!("frame exceeds the 10,000 command limit");
|
||||
}
|
||||
|
||||
if self.frame.window == 0 {
|
||||
bail!("invalid window identity");
|
||||
}
|
||||
parse_color(&self.frame.background)?;
|
||||
if !self.frame.command_clips.is_empty()
|
||||
&& self.frame.command_clips.len() != self.frame.commands.len()
|
||||
{
|
||||
bail!("invalid command clip table");
|
||||
}
|
||||
for clip in self.frame.command_clips.iter().flatten() {
|
||||
validate_rect(clip[0], clip[1], clip[2], clip[3], 0.0)?;
|
||||
}
|
||||
for command in &self.frame.commands {
|
||||
command.validate()?;
|
||||
}
|
||||
if self.frame.mounts.len() > 10_000 {
|
||||
bail!("frame exceeds the 10000 mount limit");
|
||||
}
|
||||
let mut tab_ids = HashSet::new();
|
||||
if self.frame.tabs.len() > crate::ui_bridge::MAX_PAGES
|
||||
|| self.frame.tabs.iter().filter(|tab| tab.active).count() > 1
|
||||
|| self
|
||||
.frame
|
||||
.tabs
|
||||
.iter()
|
||||
.any(|tab| tab.id == 0 || !tab_ids.insert(tab.id) || tab.title.len() > 1024)
|
||||
{
|
||||
bail!("invalid tab projection");
|
||||
}
|
||||
let mut mount_ids = HashSet::new();
|
||||
for mount in &self.frame.mounts {
|
||||
if mount.id == 0 || mount.block_id.is_empty() || !mount_ids.insert(mount.id) {
|
||||
bail!("invalid or duplicate mount identity");
|
||||
}
|
||||
validate_rect(mount.x, mount.y, mount.width, mount.height, 0.0)?;
|
||||
if let Some(clip) = mount.clip {
|
||||
validate_rect(clip[0], clip[1], clip[2], clip[3], 0.0)?;
|
||||
}
|
||||
if let Some(scroll) = mount.scroll
|
||||
&& (!scroll.iter().all(|n| {
|
||||
n.is_finite() && (0.0..=crate::ui_bridge::MAX_DIMENSION as f32).contains(n)
|
||||
}) || scroll[0] > scroll[2]
|
||||
|| scroll[1] > scroll[3])
|
||||
{
|
||||
bail!("invalid scroll projection");
|
||||
}
|
||||
}
|
||||
for mount in &self.frame.mounts {
|
||||
for linked in [mount.parent, mount.first_child, mount.next_sibling]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
if !mount_ids.contains(&linked) {
|
||||
bail!("mount links outside this frame");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(root) = &self.ui_root
|
||||
&& self
|
||||
.frame
|
||||
.mounts
|
||||
.first()
|
||||
.is_none_or(|mount| mount.block_id != root.block_id)
|
||||
{
|
||||
bail!("frame root does not match its visual projection");
|
||||
}
|
||||
let mut ids = HashSet::new();
|
||||
if let Some(root) = &self.root {
|
||||
root.validate(0, &mut ids)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn display_list(&self, scale: f32) -> Result<DisplayList> {
|
||||
let frame = &self.frame;
|
||||
let mut list = DisplayList::default();
|
||||
list.push(DrawCommand::Clear(parse_color(&frame.background)?));
|
||||
for (index, command) in frame.commands.iter().enumerate() {
|
||||
let clip = frame.command_clips.get(index).copied().flatten();
|
||||
if let Some(clip) = clip {
|
||||
list.push(DrawCommand::PushClip(scaled_rect(
|
||||
clip[0], clip[1], clip[2], clip[3], scale,
|
||||
)));
|
||||
}
|
||||
list.push(command.to_draw_command(scale)?);
|
||||
if clip.is_some() {
|
||||
list.push(DrawCommand::PopClip);
|
||||
}
|
||||
}
|
||||
if let Some(focus) = frame
|
||||
.focus
|
||||
.and_then(|id| frame.mounts.iter().find(|m| m.id == id))
|
||||
{
|
||||
if let Some(c) = focus.clip {
|
||||
list.push(DrawCommand::PushClip(scaled_rect(
|
||||
c[0], c[1], c[2], c[3], scale,
|
||||
)));
|
||||
}
|
||||
list.push(
|
||||
RenderCommand::StrokeRoundedRect {
|
||||
x: focus.x,
|
||||
y: focus.y,
|
||||
width: focus.width,
|
||||
height: focus.height,
|
||||
radius: 7.0,
|
||||
stroke_width: 2.0,
|
||||
color: "#4F6FDB".into(),
|
||||
}
|
||||
.to_draw_command(scale)?,
|
||||
);
|
||||
if focus.clip.is_some() {
|
||||
list.push(DrawCommand::PopClip);
|
||||
}
|
||||
}
|
||||
if let Some(error) = &frame.fault {
|
||||
list.push(
|
||||
RenderCommand::RoundedRect {
|
||||
x: 0.0,
|
||||
y: 0.0,
|
||||
width: 10000.0,
|
||||
height: 36.0,
|
||||
radius: 0.0,
|
||||
color: "#FFF1EF".into(),
|
||||
}
|
||||
.to_draw_command(scale)?,
|
||||
);
|
||||
list.push(
|
||||
RenderCommand::Text {
|
||||
x: 12.0,
|
||||
y: 8.0,
|
||||
value: format!("运行已停止:{}", error.lines().next().unwrap_or_default()),
|
||||
size: 1,
|
||||
color: "#A32D25".into(),
|
||||
wrap_bounds: None,
|
||||
}
|
||||
.to_draw_command(scale)?,
|
||||
);
|
||||
}
|
||||
Ok(list)
|
||||
}
|
||||
|
||||
pub fn node(&self, id: &str) -> Option<&CodeNode> {
|
||||
self.root.as_ref()?.find(id)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct CodeNode {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub kind: String,
|
||||
#[serde(default)]
|
||||
pub start_line: usize,
|
||||
#[serde(default)]
|
||||
pub end_line: usize,
|
||||
#[serde(default)]
|
||||
pub children: Vec<CodeNode>,
|
||||
}
|
||||
|
||||
impl CodeNode {
|
||||
fn validate<'a>(&'a self, depth: usize, ids: &mut HashSet<&'a str>) -> Result<()> {
|
||||
if depth > 64 {
|
||||
bail!("architecture tree exceeds 64 levels");
|
||||
}
|
||||
if self.id.is_empty() {
|
||||
bail!("architecture node id cannot be empty");
|
||||
}
|
||||
if !ids.insert(&self.id) {
|
||||
bail!("duplicate architecture node id: {}", self.id);
|
||||
}
|
||||
if self.start_line > 0 && self.end_line > 0 && self.start_line > self.end_line {
|
||||
bail!("invalid source range for node {}", self.id);
|
||||
}
|
||||
for child in &self.children {
|
||||
child.validate(depth + 1, ids)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn find(&self, id: &str) -> Option<&CodeNode> {
|
||||
if self.id == id {
|
||||
return Some(self);
|
||||
}
|
||||
self.children.iter().find_map(|child| child.find(id))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Frame {
|
||||
#[serde(default = "default_window")]
|
||||
pub window: u64,
|
||||
#[serde(default = "default_background")]
|
||||
pub background: String,
|
||||
#[serde(default)]
|
||||
pub commands: Vec<RenderCommand>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub command_clips: Vec<Option<[f32; 4]>>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub mounts: Vec<MountGeometry>,
|
||||
#[serde(default)]
|
||||
pub layout_version: u64,
|
||||
#[serde(default)]
|
||||
pub session: u64,
|
||||
#[serde(default)]
|
||||
pub focus: Option<u64>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub tabs: Vec<crate::tabs::Tab>,
|
||||
#[serde(default)]
|
||||
pub fault: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for Frame {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
window: crate::window::MAIN_WINDOW,
|
||||
background: default_background(),
|
||||
commands: Vec::new(),
|
||||
command_clips: Vec::new(),
|
||||
mounts: Vec::new(),
|
||||
layout_version: 0,
|
||||
session: 0,
|
||||
focus: None,
|
||||
tabs: Vec::new(),
|
||||
fault: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A position in a published frame. Identifiers are opaque data, never VM handles.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct MountGeometry {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub clip: Option<[f32; 4]>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub scroll: Option<[f32; 4]>,
|
||||
pub id: u64,
|
||||
pub block_id: String,
|
||||
pub parent: Option<u64>,
|
||||
pub first_child: Option<u64>,
|
||||
pub next_sibling: Option<u64>,
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
pub interactive: bool,
|
||||
}
|
||||
|
||||
impl MountGeometry {
|
||||
pub fn contains(&self, point: Point) -> bool {
|
||||
Rect::new(self.x, self.y, self.width, self.height).contains(point)
|
||||
&& self.clip.is_none_or(|c| {
|
||||
c[2] > 0.0 && c[3] > 0.0 && Rect::new(c[0], c[1], c[2], c[3]).contains(point)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Frame {
|
||||
pub fn hit_test(&self, point: Point) -> Option<&MountGeometry> {
|
||||
if self.fault.is_some() {
|
||||
return None;
|
||||
}
|
||||
self.mounts
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|mount| mount.interactive && mount.contains(point))
|
||||
}
|
||||
}
|
||||
|
||||
fn default_window() -> u64 {
|
||||
crate::window::MAIN_WINDOW
|
||||
}
|
||||
|
||||
fn default_background() -> String {
|
||||
"#F7F7F5".to_owned()
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum RenderCommand {
|
||||
RoundedRect {
|
||||
x: f32,
|
||||
y: f32,
|
||||
width: f32,
|
||||
height: f32,
|
||||
#[serde(default)]
|
||||
radius: f32,
|
||||
color: String,
|
||||
},
|
||||
StrokeRoundedRect {
|
||||
x: f32,
|
||||
y: f32,
|
||||
width: f32,
|
||||
height: f32,
|
||||
#[serde(default)]
|
||||
radius: f32,
|
||||
#[serde(default = "default_stroke_width")]
|
||||
stroke_width: f32,
|
||||
color: String,
|
||||
},
|
||||
Text {
|
||||
x: f32,
|
||||
y: f32,
|
||||
value: String,
|
||||
#[serde(default = "default_text_size")]
|
||||
size: u32,
|
||||
color: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
wrap_bounds: Option<[f32; 2]>,
|
||||
},
|
||||
}
|
||||
|
||||
impl RenderCommand {
|
||||
pub(crate) fn validate(&self) -> Result<()> {
|
||||
match self {
|
||||
Self::RoundedRect {
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
radius,
|
||||
color,
|
||||
} => {
|
||||
validate_rect(*x, *y, *width, *height, *radius)?;
|
||||
parse_color(color)?;
|
||||
}
|
||||
Self::StrokeRoundedRect {
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
radius,
|
||||
stroke_width,
|
||||
color,
|
||||
} => {
|
||||
validate_rect(*x, *y, *width, *height, *radius)?;
|
||||
if !stroke_width.is_finite() || *stroke_width <= 0.0 {
|
||||
bail!("stroke_width must be a positive finite number");
|
||||
}
|
||||
parse_color(color)?;
|
||||
}
|
||||
Self::Text {
|
||||
x,
|
||||
y,
|
||||
value,
|
||||
size,
|
||||
color,
|
||||
wrap_bounds,
|
||||
} => {
|
||||
if !x.is_finite() || !y.is_finite() {
|
||||
bail!("text coordinates must be finite");
|
||||
}
|
||||
if let Some([width, height]) = wrap_bounds {
|
||||
validate_rect(*x, *y, *width, *height, 0.0)?;
|
||||
if [*x, *y, *width, *height, *x + *width, *y + *height]
|
||||
.iter()
|
||||
.any(|value| value.abs() > crate::ui_bridge::MAX_DIMENSION as f32)
|
||||
{
|
||||
bail!("text wrap bounds exceed limits");
|
||||
}
|
||||
}
|
||||
if value.len() > 16_384 {
|
||||
bail!("text command exceeds 16 KiB");
|
||||
}
|
||||
if !(1..=8).contains(size) {
|
||||
bail!("text size must be between 1 and 8");
|
||||
}
|
||||
parse_color(color)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn to_draw_command(&self, scale: f32) -> Result<DrawCommand> {
|
||||
Ok(match self {
|
||||
Self::RoundedRect {
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
radius,
|
||||
color,
|
||||
} => DrawCommand::FillRoundedRect {
|
||||
rect: scaled_rect(*x, *y, *width, *height, scale),
|
||||
radius: radius * scale,
|
||||
color: parse_color(color)?,
|
||||
},
|
||||
Self::StrokeRoundedRect {
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
radius,
|
||||
stroke_width,
|
||||
color,
|
||||
} => DrawCommand::StrokeRoundedRect {
|
||||
rect: scaled_rect(*x, *y, *width, *height, scale),
|
||||
radius: radius * scale,
|
||||
width: stroke_width * scale,
|
||||
color: parse_color(color)?,
|
||||
},
|
||||
Self::Text {
|
||||
x,
|
||||
y,
|
||||
value,
|
||||
size,
|
||||
color,
|
||||
wrap_bounds,
|
||||
} => match wrap_bounds {
|
||||
Some([width, height]) => DrawCommand::WrappedText {
|
||||
rect: scaled_rect(*x, *y, *width, *height, scale),
|
||||
value: value.clone(),
|
||||
style: crate::text::TextStyle::ui(*size).scaled(scale),
|
||||
color: parse_color(color)?,
|
||||
},
|
||||
None => DrawCommand::Text {
|
||||
origin: Point::new(x * scale, y * scale),
|
||||
value: value.clone(),
|
||||
style: crate::text::TextStyle::ui(*size).scaled(scale),
|
||||
color: parse_color(color)?,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn default_stroke_width() -> f32 {
|
||||
1.0
|
||||
}
|
||||
|
||||
fn default_text_size() -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
fn validate_rect(x: f32, y: f32, width: f32, height: f32, radius: f32) -> Result<()> {
|
||||
if !x.is_finite() || !y.is_finite() || !width.is_finite() || !height.is_finite() {
|
||||
bail!("rectangle values must be finite");
|
||||
}
|
||||
if width < 0.0 || height < 0.0 || !radius.is_finite() || radius < 0.0 {
|
||||
bail!("rectangle dimensions and radius cannot be negative");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn scaled_rect(x: f32, y: f32, width: f32, height: f32, scale: f32) -> Rect {
|
||||
Rect::new(x * scale, y * scale, width * scale, height * scale)
|
||||
}
|
||||
|
||||
pub fn parse_color(value: &str) -> Result<Color> {
|
||||
let hex = value
|
||||
.strip_prefix('#')
|
||||
.ok_or_else(|| anyhow::anyhow!("color must begin with #"))?;
|
||||
if !hex.is_ascii() || (hex.len() != 6 && hex.len() != 8) {
|
||||
bail!("color must use #RRGGBB or #RRGGBBAA");
|
||||
}
|
||||
let parse = |range| u8::from_str_radix(&hex[range], 16);
|
||||
Ok(Color::rgba(
|
||||
parse(0..2)?,
|
||||
parse(2..4)?,
|
||||
parse(4..6)?,
|
||||
if hex.len() == 8 { parse(6..8)? } else { 255 },
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn text_wrap_bounds_validate_and_legacy_text_remains_unwrapped() {
|
||||
let mut command: RenderCommand = serde_json::from_str(
|
||||
r##"{"type":"text","x":0,"y":0,"value":"text","size":1,"color":"#000000"}"##,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
command.to_draw_command(1.0).unwrap(),
|
||||
DrawCommand::Text { .. }
|
||||
));
|
||||
if let RenderCommand::Text { wrap_bounds, .. } = &mut command {
|
||||
*wrap_bounds = Some([40.0, 20.0]);
|
||||
}
|
||||
command.validate().unwrap();
|
||||
assert!(
|
||||
matches!(command.to_draw_command(1.25).unwrap(),DrawCommand::WrappedText{rect,..}if rect.width==50.0 && rect.height==25.0)
|
||||
);
|
||||
if let RenderCommand::Text { wrap_bounds, .. } = &mut command {
|
||||
*wrap_bounds = Some([-1.0, 20.0]);
|
||||
}
|
||||
assert!(command.validate().is_err());
|
||||
}
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn empty_document_is_valid_and_blank() {
|
||||
let document = RenderDocument::default();
|
||||
document.validate().unwrap();
|
||||
assert!(document.root.is_none());
|
||||
assert!(document.frame.commands.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_rgb_and_rgba_colors() {
|
||||
assert_eq!(
|
||||
parse_color("#102030").unwrap(),
|
||||
Color::rgba(16, 32, 48, 255)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_color("#10203080").unwrap(),
|
||||
Color::rgba(16, 32, 48, 128)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod window_projection_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn replacement_and_reset_discard_old_window_projections() {
|
||||
let mut state = NamespaceState::default();
|
||||
let command = crate::window::Command {
|
||||
window: 1,
|
||||
sequence: 1,
|
||||
action: crate::window::Action::Focus,
|
||||
};
|
||||
state.publish_window_commands(1, vec![command.clone()]);
|
||||
let resize = crate::window::Command {
|
||||
window: 1,
|
||||
sequence: 2,
|
||||
action: crate::window::Action::Resize {
|
||||
width: 900.0,
|
||||
height: 600.0,
|
||||
},
|
||||
};
|
||||
state.publish_window_commands(1, vec![resize.clone()]);
|
||||
assert_eq!(state.window_commands.len(), 2);
|
||||
state.publish_window_commands(2, vec![resize]);
|
||||
assert_eq!(state.window_commands.len(), 1);
|
||||
assert_eq!(state.window_commands[0].session, 2);
|
||||
state.clear().unwrap();
|
||||
assert_eq!(state.runtime_session, 0);
|
||||
assert!(state.window_commands.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// Module ownership follows the directory; crate-root aliases keep internal call sites stable.
|
||||
pub(crate) mod binding;
|
||||
pub(crate) mod block;
|
||||
pub(crate) mod document;
|
||||
pub(crate) mod mount;
|
||||
pub(crate) mod object_list;
|
||||
pub(crate) mod presentation;
|
||||
pub(crate) mod protocols;
|
||||
pub(crate) mod snapshot;
|
||||
pub(crate) mod window;
|
||||
@@ -0,0 +1,750 @@
|
||||
//! 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 scroll_offset: [f32; 2],
|
||||
pub version: u64,
|
||||
pub mounted: bool,
|
||||
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 {
|
||||
fn reference_assignment_only(&self) -> bool {
|
||||
true
|
||||
}
|
||||
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);
|
||||
if let Some(tasks) = self.tasks {
|
||||
visit(tasks);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum Query {
|
||||
Bounds,
|
||||
ScrollTo,
|
||||
ScrollBy,
|
||||
ScrollPosition,
|
||||
ScrollIntoView,
|
||||
Parent,
|
||||
FirstChild,
|
||||
NextSibling,
|
||||
Page,
|
||||
Focus,
|
||||
HitTest,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Method {
|
||||
signature: endor_core::CallSignature,
|
||||
owner: ObjectRef,
|
||||
desktop: WeakObjectRef,
|
||||
query: Query,
|
||||
}
|
||||
|
||||
impl NativeCallable for Method {
|
||||
fn signature(&self) -> Option<endor_core::CallSignature> {
|
||||
Some(self.signature.clone())
|
||||
}
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::exact(
|
||||
if matches!(
|
||||
self.query,
|
||||
Query::HitTest | 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();
|
||||
if !mount.mounted
|
||||
&& matches!(
|
||||
self.query,
|
||||
Query::Bounds
|
||||
| Query::Focus
|
||||
| Query::HitTest
|
||||
| Query::ScrollTo
|
||||
| Query::ScrollBy
|
||||
| Query::ScrollIntoView
|
||||
| Query::ScrollPosition
|
||||
)
|
||||
{
|
||||
return Err(VmError::InvalidArgument("Mount is no longer attached"));
|
||||
}
|
||||
let arity = if matches!(
|
||||
self.query,
|
||||
Query::HitTest | 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::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::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 => {
|
||||
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()?;
|
||||
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
|
||||
}
|
||||
Query::HitTest => {
|
||||
if mount.layout.is_some() {
|
||||
return Err(VmError::InvalidArgument(
|
||||
"Mount hitTest is unavailable during layout",
|
||||
));
|
||||
}
|
||||
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!(),
|
||||
};
|
||||
weak.map(|weak| cx.upgrade(weak))
|
||||
.transpose()?
|
||||
.flatten()
|
||||
.map(Value::Object)
|
||||
.unwrap_or(Value::Nil)
|
||||
}
|
||||
};
|
||||
Ok(NativeResult::Return(value))
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
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::ScrollPosition => T::Any.into(),
|
||||
_ => T::Unit.into(),
|
||||
};
|
||||
let effect = if matches!(
|
||||
query,
|
||||
Query::ScrollTo | Query::ScrollBy | Query::ScrollIntoView | Query::Focus
|
||||
) {
|
||||
CallEffect::Mutating
|
||||
} else {
|
||||
CallEffect::ReadOnly
|
||||
};
|
||||
let parameters = if matches!(query, Query::HitTest | 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)]
|
||||
pub struct MountTable {
|
||||
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,
|
||||
preparing: bool,
|
||||
output: Arc<Mutex<HashMap<u64, WeakObjectRef>>>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct LifecycleCall {
|
||||
function: ObjectRef,
|
||||
block: ObjectRef,
|
||||
mount: ObjectRef,
|
||||
unmount: bool,
|
||||
}
|
||||
impl NativeCallable for LifecycleCall {
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::exact(0))
|
||||
}
|
||||
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> {
|
||||
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)],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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"))?;
|
||||
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))
|
||||
}
|
||||
|
||||
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();
|
||||
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();
|
||||
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)?;
|
||||
for (name, query) in [
|
||||
("bounds", Query::Bounds),
|
||||
("scrollTo", Query::ScrollTo),
|
||||
("scrollBy", Query::ScrollBy),
|
||||
("scrollPosition", Query::ScrollPosition),
|
||||
("scrollIntoView", Query::ScrollIntoView),
|
||||
("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);
|
||||
}
|
||||
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,
|
||||
layout: if self.preparing {
|
||||
Some(Arc::new(Mutex::new(crate::layout::Context::default())))
|
||||
} else {
|
||||
None
|
||||
},
|
||||
};
|
||||
let old = cx.store().payload::<Mount>(object, "Mount")?;
|
||||
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()),
|
||||
)?;
|
||||
}
|
||||
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.
|
||||
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();
|
||||
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")?);
|
||||
}
|
||||
}
|
||||
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>,
|
||||
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 = (|| {
|
||||
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>(())
|
||||
})();
|
||||
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)] {
|
||||
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 {
|
||||
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();
|
||||
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)? {
|
||||
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),
|
||||
};
|
||||
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?;
|
||||
}
|
||||
}
|
||||
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(())
|
||||
}
|
||||
|
||||
pub fn ordered(&self) -> Vec<WeakObjectRef> {
|
||||
self.order
|
||||
.iter()
|
||||
.filter_map(|id| self.active.get(id).copied())
|
||||
.collect()
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -0,0 +1,157 @@
|
||||
//! Managed indexed host results; values and the at method are traced edges.
|
||||
use endor_core::{
|
||||
ContextNativeFunction, NativeCallable, NativeContext, NativeResult, ObjectPayload, ObjectRef,
|
||||
Value, VmError,
|
||||
};
|
||||
#[derive(Debug)]
|
||||
struct ObjectList(Vec<ObjectRef>);
|
||||
impl ObjectPayload for ObjectList {
|
||||
fn reference_assignment_only(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
fn kind_name(&self) -> &'static str {
|
||||
"tessera-object-list"
|
||||
}
|
||||
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 signature(&self) -> Option<endor_core::CallSignature> {
|
||||
Some(endor_core::CallSignature::exact(
|
||||
vec![endor_core::AnnotationType::Number],
|
||||
endor_core::AnnotationType::Any,
|
||||
endor_core::CallEffect::ReadOnly,
|
||||
))
|
||||
}
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::exact(1))
|
||||
}
|
||||
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let [Value::Number(index)] = args else {
|
||||
return Err(VmError::InvalidArgument("object list at expects an index"));
|
||||
};
|
||||
let index = index
|
||||
.as_i64()
|
||||
.and_then(|v| usize::try_from(v).ok())
|
||||
.ok_or(VmError::InvalidArgument("invalid list index"))?;
|
||||
let mount = *cx
|
||||
.store()
|
||||
.payload::<ObjectList>(self.0, "Object list")?
|
||||
.0
|
||||
.get(index)
|
||||
.ok_or(VmError::InvalidArgument("list index out of range"))?;
|
||||
Ok(NativeResult::Return(Value::Object(mount)))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn collection(
|
||||
cx: &mut NativeContext<'_>,
|
||||
mounts: Vec<ObjectRef>,
|
||||
desktop: ObjectRef,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
build(cx, mounts, desktop, None)
|
||||
}
|
||||
|
||||
fn build(
|
||||
cx: &mut NativeContext<'_>,
|
||||
mounts: Vec<ObjectRef>,
|
||||
desktop: ObjectRef,
|
||||
definition: Option<ObjectRef>,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
if mounts.len() > 10_000 {
|
||||
return Err(VmError::InvalidArgument(
|
||||
"object list exceeds 10000 members",
|
||||
));
|
||||
}
|
||||
let first = mounts
|
||||
.first()
|
||||
.copied()
|
||||
.map(Value::Object)
|
||||
.unwrap_or(Value::Nil);
|
||||
let count = mounts.len();
|
||||
let set = cx.allocate(ObjectList(mounts))?;
|
||||
if let Some(definition) = definition {
|
||||
cx.attach_type(set, definition)?;
|
||||
} else {
|
||||
crate::ui_bridge::attach_desktop_type(cx, set, "ObjectList", desktop)?;
|
||||
}
|
||||
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]))?;
|
||||
crate::ui_bridge::attach_desktop_type(cx, at, "Function", desktop)?;
|
||||
cx.set_attr(set, "at", Value::Object(at))?;
|
||||
Ok(set)
|
||||
}
|
||||
|
||||
pub fn items(store: &endor_core::ObjectStore, list: ObjectRef) -> Result<&[ObjectRef], VmError> {
|
||||
Ok(&store.payload::<ObjectList>(list, "ObjectList")?.0)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Constructor {
|
||||
pub signature: Option<endor_core::CallSignature>,
|
||||
pub desktop: ObjectRef,
|
||||
}
|
||||
impl NativeCallable for Constructor {
|
||||
fn signature(&self) -> Option<endor_core::CallSignature> {
|
||||
self.signature.clone()
|
||||
}
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::range(1, usize::MAX))
|
||||
}
|
||||
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let [Value::Object(definition), values @ ..] = args else {
|
||||
return Err(VmError::InvalidArgument("ObjectList type argument"));
|
||||
};
|
||||
let fields = cx
|
||||
.store()
|
||||
.payload::<endor_core::EndorTypeObject>(*definition, "Type")?
|
||||
.fields()
|
||||
.to_vec();
|
||||
if fields
|
||||
.iter()
|
||||
.any(|field| matches!(field.name.as_str(), "count" | "first" | "at"))
|
||||
{
|
||||
return Err(VmError::InvalidArgument("reserved ObjectList field"));
|
||||
}
|
||||
let count = values
|
||||
.len()
|
||||
.checked_sub(fields.len())
|
||||
.ok_or(VmError::InvalidArgument(
|
||||
"missing ObjectList subclass fields",
|
||||
))?;
|
||||
cx.store()
|
||||
.check_class_field_arguments(*definition, &values[count..])?;
|
||||
let members = values[..count]
|
||||
.iter()
|
||||
.map(|value| {
|
||||
if let Value::Object(object) = value {
|
||||
Ok(*object)
|
||||
} else {
|
||||
Err(VmError::InvalidArgument(
|
||||
"ObjectList members must be objects",
|
||||
))
|
||||
}
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let list = build(cx, members, self.desktop, Some(*definition))?;
|
||||
for (field, value) in fields.iter().zip(&values[count..]) {
|
||||
cx.set_attr(list, &field.name, value.clone())?;
|
||||
}
|
||||
Ok(NativeResult::Return(Value::Object(list)))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
//! Per-window rendering state. Business objects and code remain in one VM.
|
||||
//! Registries and caches borrow checked identities; the managed desktop owns
|
||||
//! presentation roots through its pending/mount dictionaries.
|
||||
use crate::ui_bridge::UiNode;
|
||||
use endor_core::{ChangeBatch, NativeContext, ObjectRef, Vm, VmError, WeakObjectRef};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Presentation {
|
||||
pub desktop: ObjectRef,
|
||||
pub closing: bool,
|
||||
pub tabs: ObjectRef,
|
||||
pub active: Option<ObjectRef>,
|
||||
pub pending: Option<Option<ObjectRef>>,
|
||||
pub last_snapshot: Option<Arc<UiNode>>,
|
||||
pub tab_ids: Vec<(WeakObjectRef, u64)>,
|
||||
pub next_tab: u64,
|
||||
pub last_tabs: Vec<crate::tabs::Tab>,
|
||||
pub render_cache: crate::snapshot::RenderCache,
|
||||
pub layout: crate::layout::LayoutRuntime,
|
||||
pub mounts: crate::mount::MountTable,
|
||||
pub published_version: u64,
|
||||
pub force_frame: bool,
|
||||
pub paint_names: Vec<endor_core::ReadDependency>,
|
||||
pub layout_names: Vec<endor_core::ReadDependency>,
|
||||
pub paint_reads: std::collections::BTreeMap<ObjectRef, u64>,
|
||||
pub dependency_invalidations: usize,
|
||||
pub last_invalid_dependency: String,
|
||||
pub layout_reads: std::collections::BTreeMap<ObjectRef, u64>,
|
||||
pub measure_cache: crate::source_layout::Cache,
|
||||
pub snapshot_visited: usize,
|
||||
pub snapshot_reused: usize,
|
||||
}
|
||||
|
||||
impl Presentation {
|
||||
pub fn observe_changes(&mut self, vm: &Vm, changes: &ChangeBatch) {
|
||||
if let Some((phase, object, version)) = self
|
||||
.layout_reads
|
||||
.iter()
|
||||
.map(|(object, version)| ("layout", object, version))
|
||||
.chain(
|
||||
self.paint_reads
|
||||
.iter()
|
||||
.map(|(object, version)| ("paint", object, version)),
|
||||
)
|
||||
.find(|(_, object, version)| vm.change_version(**object).ok() != Some(**version))
|
||||
{
|
||||
self.force_frame = true;
|
||||
self.dependency_invalidations = self.dependency_invalidations.saturating_add(1);
|
||||
let kind = vm
|
||||
.object(*object)
|
||||
.map(|value| value.payload().kind_name())
|
||||
.unwrap_or("released");
|
||||
self.last_invalid_dependency = format!(
|
||||
"{phase} {kind} {object}: {version} -> {:?}",
|
||||
vm.change_version(*object).ok()
|
||||
);
|
||||
}
|
||||
if let Some((phase, dependency)) = self
|
||||
.layout_names
|
||||
.iter()
|
||||
.map(|dependency| ("layout", dependency))
|
||||
.chain(
|
||||
self.paint_names
|
||||
.iter()
|
||||
.map(|dependency| ("paint", dependency)),
|
||||
)
|
||||
.find(|(_, dependency)| !vm.object_store().read_dependency_valid(dependency))
|
||||
{
|
||||
self.force_frame = true;
|
||||
self.dependency_invalidations = self.dependency_invalidations.saturating_add(1);
|
||||
let name = match dependency {
|
||||
endor_core::ReadDependency::Name { name, .. } => name.as_str(),
|
||||
_ => "<dictionary kind>",
|
||||
};
|
||||
self.last_invalid_dependency = format!("{phase} name {}:{name}", dependency.object());
|
||||
}
|
||||
self.render_cache.invalidate(ChangeBatch {
|
||||
changes: changes.changes.clone(),
|
||||
rescan_required: changes.rescan_required,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn invalidate(
|
||||
&mut self,
|
||||
cx: &mut NativeContext<'_>,
|
||||
affected: &std::collections::HashSet<ObjectRef>,
|
||||
reason: &str,
|
||||
) -> Result<(), VmError> {
|
||||
if reason != "paint" {
|
||||
self.measure_cache.invalidate(affected);
|
||||
for block in affected {
|
||||
self.layout.invalidate(&block.to_string());
|
||||
}
|
||||
}
|
||||
if reason == "content" {
|
||||
self.render_cache
|
||||
.invalidate_objects(affected.iter().copied());
|
||||
}
|
||||
for weak in self.mounts.active.values() {
|
||||
if let Some(mount) = cx.upgrade(*weak)?
|
||||
&& affected.contains(
|
||||
&cx.store()
|
||||
.payload::<crate::mount::Mount>(mount, "Mount")?
|
||||
.block,
|
||||
)
|
||||
{
|
||||
self.force_frame = true;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn new(desktop: ObjectRef, tabs: ObjectRef) -> Self {
|
||||
Self {
|
||||
desktop,
|
||||
closing: false,
|
||||
tabs,
|
||||
active: None,
|
||||
pending: None,
|
||||
last_snapshot: None,
|
||||
tab_ids: Vec::new(),
|
||||
next_tab: 0,
|
||||
last_tabs: Vec::new(),
|
||||
render_cache: crate::snapshot::RenderCache::default(),
|
||||
layout: crate::layout::LayoutRuntime::default(),
|
||||
mounts: crate::mount::MountTable::default(),
|
||||
published_version: 0,
|
||||
force_frame: false,
|
||||
paint_names: Vec::new(),
|
||||
layout_names: Vec::new(),
|
||||
paint_reads: std::collections::BTreeMap::new(),
|
||||
dependency_invalidations: 0,
|
||||
last_invalid_dependency: String::new(),
|
||||
layout_reads: std::collections::BTreeMap::new(),
|
||||
measure_cache: crate::source_layout::Cache::default(),
|
||||
snapshot_visited: 0,
|
||||
snapshot_reused: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn split_reads(
|
||||
reads: Vec<endor_core::ReadDependency>,
|
||||
) -> (
|
||||
std::collections::BTreeMap<ObjectRef, u64>,
|
||||
Vec<endor_core::ReadDependency>,
|
||||
) {
|
||||
let mut objects = std::collections::BTreeMap::new();
|
||||
let mut names = Vec::new();
|
||||
for dependency in reads {
|
||||
match dependency {
|
||||
endor_core::ReadDependency::Object { object, version } => {
|
||||
objects.insert(object, version);
|
||||
}
|
||||
dependency => names.push(dependency),
|
||||
}
|
||||
}
|
||||
(objects, names)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{layout::Size, ui_bridge::UiKind};
|
||||
#[test]
|
||||
fn independent_view_geometry_and_shared_vm_reads_do_not_add_roots() {
|
||||
let mut vm = Vm::new().unwrap();
|
||||
let mut left = Presentation::new(vm.new_object().unwrap(), vm.new_dict().unwrap());
|
||||
let mut right = Presentation::new(vm.new_object().unwrap(), vm.new_dict().unwrap());
|
||||
left.layout.viewport = Some(Size {
|
||||
width: 100.0,
|
||||
height: 80.0,
|
||||
});
|
||||
right.layout.viewport = Some(Size {
|
||||
width: 200.0,
|
||||
height: 160.0,
|
||||
});
|
||||
let root = UiNode {
|
||||
flex: 0.0,
|
||||
flex_policy: crate::layout::FlexPolicy::default(),
|
||||
main_align: crate::layout::MainAlign::Start,
|
||||
block_id: "shared".into(),
|
||||
protocol_key: "rect".into(),
|
||||
slots: Vec::new(),
|
||||
interactive: false,
|
||||
kind: UiKind::Rect {
|
||||
width: 500.0,
|
||||
height: 500.0,
|
||||
radius: 0.0,
|
||||
color: "#237A45".into(),
|
||||
},
|
||||
};
|
||||
let left_frame = left.layout.frame(&root).unwrap();
|
||||
let right_frame = right.layout.frame(&root).unwrap();
|
||||
assert_eq!(left_frame.mounts[0].width, 100.0);
|
||||
assert_eq!(right_frame.mounts[0].width, 200.0);
|
||||
left.layout.clear_occurrences();
|
||||
let new_left = left.layout.frame(&root).unwrap();
|
||||
let same_right = right.layout.frame(&root).unwrap();
|
||||
assert_ne!(new_left.mounts[0].id, left_frame.mounts[0].id);
|
||||
assert_eq!(same_right.mounts[0].id, right_frame.mounts[0].id);
|
||||
let shared = vm.new_object().unwrap();
|
||||
let version = vm.change_version(shared).unwrap();
|
||||
left.paint_reads.insert(shared, version);
|
||||
right.layout_reads.insert(shared, version);
|
||||
vm.set_attr(shared, "value", endor_core::Value::Bool(true))
|
||||
.unwrap();
|
||||
let changes = vm.take_changes();
|
||||
left.observe_changes(&vm, &changes);
|
||||
right.observe_changes(&vm, &changes);
|
||||
assert!(left.force_frame && right.force_frame);
|
||||
let weak = vm.downgrade(shared).unwrap();
|
||||
vm.release(shared).unwrap();
|
||||
vm.collect_cycles();
|
||||
assert!(vm.upgrade(weak).unwrap().is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
//! Host capability definitions over Aster's explicit managed trait relations.
|
||||
use endor_core::{
|
||||
AnnotationType, CallArity, CallEffect, CallSignature, ObjectRef, TypedMethodRequirement, Value,
|
||||
Vm, VmError,
|
||||
};
|
||||
|
||||
pub fn install(
|
||||
vm: &mut Vm,
|
||||
roots: &mut Vec<ObjectRef>,
|
||||
desktop: ObjectRef,
|
||||
ui: ObjectRef,
|
||||
) -> Result<(), VmError> {
|
||||
let Value::Object(trait_type) = vm.get_attr(ui, "Trait")? else {
|
||||
return Err(VmError::InvalidArgument("missing Trait type"));
|
||||
};
|
||||
let Value::Object(types) = vm.get_attr(desktop, "types")? else {
|
||||
return Err(VmError::InvalidArgument("missing type registry"));
|
||||
};
|
||||
for (name, methods, owner) in [
|
||||
(
|
||||
"Visual",
|
||||
vec![("measure", 2), ("arrange", 2), ("paint", 2), ("hitTest", 2)],
|
||||
Some("Block"),
|
||||
),
|
||||
(
|
||||
"EventTarget",
|
||||
vec![("on", 3), ("dispatch", 2), ("onEvent", 1)],
|
||||
Some("Block"),
|
||||
),
|
||||
(
|
||||
"Children",
|
||||
vec![
|
||||
("append", 1),
|
||||
("insert", 2),
|
||||
("remove", 1),
|
||||
("replace", 2),
|
||||
("move", 2),
|
||||
("children", 0),
|
||||
],
|
||||
Some("ContainerBlock"),
|
||||
),
|
||||
("Presentable", vec![("present", 1)], None),
|
||||
] {
|
||||
let owner_definition = if let Some(owner) = owner {
|
||||
let Value::Object(definition) = vm.get_attr(ui, owner)? else {
|
||||
return Err(VmError::InvalidArgument("missing protocol owner"));
|
||||
};
|
||||
Some(definition)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut requirements = Vec::new();
|
||||
for (method, parameters) in methods {
|
||||
let mut signature = if let Some(owner) = owner_definition {
|
||||
let function = vm
|
||||
.object_store()
|
||||
.lookup_method(owner, method)?
|
||||
.ok_or(VmError::InvalidArgument("missing protocol method"))?;
|
||||
vm.object_store()
|
||||
.native_signature(function)?
|
||||
.ok_or(VmError::InvalidArgument(
|
||||
"protocol method lacks native types",
|
||||
))?
|
||||
} else {
|
||||
let window = crate::ui_bridge::desktop_type(vm.object_store(), "Window", desktop)?;
|
||||
let block = crate::ui_bridge::desktop_type(vm.object_store(), "Block", desktop)?;
|
||||
CallSignature::exact(
|
||||
vec![AnnotationType::Any, AnnotationType::Nominal(window)],
|
||||
AnnotationType::Nominal(block),
|
||||
CallEffect::External,
|
||||
)
|
||||
};
|
||||
signature.arity = CallArity::exact(parameters + 1);
|
||||
signature.parameters[0] = AnnotationType::Any.into();
|
||||
requirements.push(TypedMethodRequirement {
|
||||
name: method.into(),
|
||||
signature,
|
||||
});
|
||||
}
|
||||
let capability = vm.new_typed_trait(name, requirements)?;
|
||||
roots.push(capability);
|
||||
vm.attach_type(capability, trait_type)?;
|
||||
vm.set_attr(ui, name, Value::Object(capability))?;
|
||||
vm.dict_set(types, Value::Text(name.into()), Value::Object(capability))?;
|
||||
if let Some(owner) = owner_definition {
|
||||
vm.implement_trait(owner, capability)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
//! 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)]
|
||||
pub struct RenderCache {
|
||||
entries: HashMap<ObjectRef, Cached>,
|
||||
dependents: HashMap<Dependency, HashSet<ObjectRef>>,
|
||||
parents: HashMap<ObjectRef, HashSet<ObjectRef>>,
|
||||
dirty: HashSet<ObjectRef>,
|
||||
pub last_invalidation: String,
|
||||
pub visited: usize,
|
||||
pub reused: usize,
|
||||
}
|
||||
|
||||
impl RenderCache {
|
||||
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<Item = ObjectRef>) {
|
||||
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<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);
|
||||
}
|
||||
}
|
||||
}
|
||||
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) {
|
||||
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;
|
||||
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;
|
||||
}
|
||||
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 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 !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::<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);
|
||||
}
|
||||
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();
|
||||
}
|
||||
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::Row => 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 {
|
||||
flex: data.flex,
|
||||
flex_policy: data.flex_policy,
|
||||
main_align: data.main_align,
|
||||
block_id: block.to_string(),
|
||||
protocol_key,
|
||||
slots: data.children.iter().map(|c| c.slot).collect(),
|
||||
interactive: matches!(&data.kind, Kind::Button)
|
||||
|| 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"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,486 @@
|
||||
//! Managed window resources and versioned, coalesced native projections.
|
||||
//! The VM owns Page roots; only scalar commands cross to the GUI thread.
|
||||
use crate::{native_visual, object_list, ui_bridge::desktop_type};
|
||||
use endor_core::{
|
||||
ContextNativeFunction, NativeCallable, NativeContext, NativeResult, ObjectPayload, ObjectRef,
|
||||
ObjectStore, Value, Vm, VmError,
|
||||
};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
pub const MAIN_WINDOW: u64 = 1;
|
||||
pub const MAX_WINDOW_DIMENSION: f64 = 4096.0;
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Action {
|
||||
Resize { width: f64, height: f64 },
|
||||
SetTitle(String),
|
||||
MoveTo { x: i32, y: i32 },
|
||||
Focus,
|
||||
Close,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Command {
|
||||
pub window: u64,
|
||||
pub sequence: u64,
|
||||
pub action: Action,
|
||||
}
|
||||
impl Command {
|
||||
pub fn same_kind(&self, other: &Self) -> bool {
|
||||
self.window == other.window
|
||||
&& std::mem::discriminant(&self.action) == std::mem::discriminant(&other.action)
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Envelope {
|
||||
pub session: u64,
|
||||
pub command: Command,
|
||||
}
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ManagedWindow {
|
||||
pub id: u64,
|
||||
pub desktop: ObjectRef,
|
||||
pub closed: bool,
|
||||
pub tasks: Option<ObjectRef>,
|
||||
tabs: ObjectRef,
|
||||
pages: Vec<ObjectRef>,
|
||||
sequence: u64,
|
||||
// Transport state only. Draining it must not change a language object's
|
||||
// version or create a render-dependency feedback loop.
|
||||
outbox: Arc<Mutex<Vec<Command>>>,
|
||||
}
|
||||
impl ObjectPayload for ManagedWindow {
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
fn kind_name(&self) -> &'static str {
|
||||
"tessera-window"
|
||||
}
|
||||
fn allows_attributes(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn reference_assignment_only(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
|
||||
visit(self.desktop);
|
||||
if let Some(tasks) = self.tasks {
|
||||
visit(tasks);
|
||||
}
|
||||
visit(self.tabs);
|
||||
for page in &self.pages {
|
||||
visit(*page);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn invalid(message: &'static str) -> VmError {
|
||||
VmError::InvalidArgument(message)
|
||||
}
|
||||
fn screen_coordinate(value: &Value) -> Result<i32, VmError> {
|
||||
let Value::Number(value) = value else {
|
||||
return Err(invalid("screen position requires integer coordinates"));
|
||||
};
|
||||
value
|
||||
.as_i64()
|
||||
.filter(|number| (-1_000_000..=1_000_000).contains(number))
|
||||
.and_then(|number| i32::try_from(number).ok())
|
||||
.ok_or(invalid("screen position exceeds limits"))
|
||||
}
|
||||
fn scalar(value: &Value) -> Result<f64, VmError> {
|
||||
let Value::Number(value) = value else {
|
||||
return Err(invalid("window size requires numbers"));
|
||||
};
|
||||
let number = value
|
||||
.to_string()
|
||||
.parse::<f64>()
|
||||
.map_err(|_| invalid("invalid window size"))?;
|
||||
if !number.is_finite() || !(1.0..=MAX_WINDOW_DIMENSION).contains(&number) {
|
||||
return Err(invalid("window size exceeds limits"));
|
||||
}
|
||||
Ok(number)
|
||||
}
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum Operation {
|
||||
Id,
|
||||
Viewport,
|
||||
Pages,
|
||||
Resize,
|
||||
MoveTo,
|
||||
SetTitle,
|
||||
Focus,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct Method {
|
||||
signature: endor_core::CallSignature,
|
||||
operation: Operation,
|
||||
desktop: ObjectRef,
|
||||
}
|
||||
impl NativeCallable for Method {
|
||||
fn signature(&self) -> Option<endor_core::CallSignature> {
|
||||
Some(self.signature.clone())
|
||||
}
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::exact(match self.operation {
|
||||
Operation::Resize | Operation::MoveTo => 3,
|
||||
Operation::SetTitle => 2,
|
||||
_ => 1,
|
||||
}))
|
||||
}
|
||||
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let Some(Value::Object(owner)) = args.first() else {
|
||||
return Err(invalid("Window method requires a Window"));
|
||||
};
|
||||
let data = cx
|
||||
.store()
|
||||
.payload::<ManagedWindow>(*owner, "Window")?
|
||||
.clone();
|
||||
if data.closed && !matches!(self.operation, Operation::Id | Operation::Pages) {
|
||||
return Err(invalid("native window is closed"));
|
||||
}
|
||||
let expected = match self.operation {
|
||||
Operation::Resize | Operation::MoveTo => 3,
|
||||
Operation::SetTitle => 2,
|
||||
_ => 1,
|
||||
};
|
||||
if args.len() != expected {
|
||||
return Err(invalid("incorrect Window method argument count"));
|
||||
}
|
||||
let result = match self.operation {
|
||||
Operation::Id => Value::Number((data.id as i64).into()),
|
||||
Operation::Pages => {
|
||||
Value::Object(object_list::collection(cx, data.pages, self.desktop)?)
|
||||
}
|
||||
Operation::Viewport => {
|
||||
let Value::Object(input) = cx.store().get_attr(data.desktop, "viewport")? else {
|
||||
return Err(invalid("window viewport is unavailable"));
|
||||
};
|
||||
let width = cx.store().get_attr(input, "width")?;
|
||||
let height = cx.store().get_attr(input, "height")?;
|
||||
Value::Object(native_visual::record(
|
||||
cx,
|
||||
self.desktop,
|
||||
"MeasureResult",
|
||||
vec![("width", width), ("height", height)],
|
||||
)?)
|
||||
}
|
||||
operation => {
|
||||
if cx.store().is_read_only() {
|
||||
return Err(invalid(
|
||||
"window operations are forbidden during read-only rendering",
|
||||
));
|
||||
}
|
||||
let action = match operation {
|
||||
Operation::MoveTo => Action::MoveTo {
|
||||
x: screen_coordinate(&args[1])?,
|
||||
y: screen_coordinate(&args[2])?,
|
||||
},
|
||||
Operation::Resize => Action::Resize {
|
||||
width: scalar(&args[1])?,
|
||||
height: scalar(&args[2])?,
|
||||
},
|
||||
Operation::SetTitle => {
|
||||
let Value::Text(title) = &args[1] else {
|
||||
return Err(invalid("window title requires text"));
|
||||
};
|
||||
if title.len() > 4096 || title.chars().any(char::is_control) {
|
||||
return Err(invalid("invalid window title"));
|
||||
}
|
||||
Action::SetTitle(title.clone())
|
||||
}
|
||||
Operation::Focus => Action::Focus,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
enqueue(cx, *owner, action)?;
|
||||
Value::Nil
|
||||
}
|
||||
};
|
||||
Ok(NativeResult::Return(result))
|
||||
}
|
||||
}
|
||||
pub fn enqueue(
|
||||
cx: &mut NativeContext<'_>,
|
||||
owner: ObjectRef,
|
||||
action: Action,
|
||||
) -> Result<(), VmError> {
|
||||
let mut data = cx
|
||||
.store()
|
||||
.payload::<ManagedWindow>(owner, "Window")?
|
||||
.clone();
|
||||
data.sequence = data
|
||||
.sequence
|
||||
.checked_add(1)
|
||||
.ok_or(invalid("window command sequence exhausted"))?;
|
||||
let command = Command {
|
||||
window: data.id,
|
||||
sequence: data.sequence,
|
||||
action,
|
||||
};
|
||||
let queue = data.outbox.clone();
|
||||
let mut queue = queue
|
||||
.lock()
|
||||
.map_err(|_| invalid("window outbox poisoned"))?;
|
||||
// The heap barrier succeeds before any external transport state changes.
|
||||
cx.replace_payload(owner, data)?;
|
||||
queue.retain(|old| !old.same_kind(&command));
|
||||
queue.push(command);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn register_page(
|
||||
cx: &mut NativeContext<'_>,
|
||||
window: ObjectRef,
|
||||
page: ObjectRef,
|
||||
) -> Result<(), VmError> {
|
||||
if cx.store().is_read_only() {
|
||||
return Err(invalid(
|
||||
"opening a Page is forbidden during read-only rendering",
|
||||
));
|
||||
}
|
||||
let mut data = cx
|
||||
.store()
|
||||
.payload::<ManagedWindow>(window, "Window")?
|
||||
.clone();
|
||||
if data.closed {
|
||||
return Err(invalid("native window is closed"));
|
||||
}
|
||||
if !data.pages.contains(&page) {
|
||||
data.pages.push(page);
|
||||
cx.dict_set(
|
||||
data.tabs,
|
||||
Value::Text(page.to_string()),
|
||||
Value::Object(page),
|
||||
)?;
|
||||
cx.replace_payload(window, data)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn unregister_page(
|
||||
cx: &mut NativeContext<'_>,
|
||||
window: ObjectRef,
|
||||
page: ObjectRef,
|
||||
) -> Result<(), VmError> {
|
||||
if cx.store().is_read_only() {
|
||||
return Err(invalid(
|
||||
"closing a Page is forbidden during read-only rendering",
|
||||
));
|
||||
}
|
||||
let mut data = cx
|
||||
.store()
|
||||
.payload::<ManagedWindow>(window, "Window")?
|
||||
.clone();
|
||||
if !data.pages.contains(&page) {
|
||||
return Ok(());
|
||||
}
|
||||
data.pages.retain(|value| *value != page);
|
||||
cx.dict_delete(data.tabs, &Value::Text(page.to_string()))?;
|
||||
cx.replace_payload(window, data)?;
|
||||
Ok(())
|
||||
}
|
||||
/// Discard an unpublished Page registration without invoking guest callbacks.
|
||||
pub fn unregister_page_host(
|
||||
vm: &mut Vm,
|
||||
window: ObjectRef,
|
||||
page: ObjectRef,
|
||||
) -> Result<(), VmError> {
|
||||
let mut data = vm.payload::<ManagedWindow>(window, "Window")?.clone();
|
||||
if data.pages.contains(&page) {
|
||||
data.pages.retain(|value| *value != page);
|
||||
vm.dict_delete(data.tabs, &Value::Text(page.to_string()))?;
|
||||
vm.replace_payload(window, data)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn move_page(
|
||||
cx: &mut NativeContext<'_>,
|
||||
window: ObjectRef,
|
||||
page: ObjectRef,
|
||||
position: usize,
|
||||
) -> Result<(), VmError> {
|
||||
let mut data = cx
|
||||
.store()
|
||||
.payload::<ManagedWindow>(window, "Window")?
|
||||
.clone();
|
||||
if data.closed {
|
||||
return Err(invalid("native window is closed"));
|
||||
}
|
||||
let from = data
|
||||
.pages
|
||||
.iter()
|
||||
.position(|candidate| *candidate == page)
|
||||
.ok_or(invalid("Page is not open in this window"))?;
|
||||
if position >= data.pages.len() {
|
||||
return Err(invalid("tab position out of range"));
|
||||
}
|
||||
if cx.store().is_read_only() {
|
||||
return Err(invalid(
|
||||
"tab ordering is forbidden during read-only rendering",
|
||||
));
|
||||
}
|
||||
if from != position {
|
||||
let page = data.pages.remove(from);
|
||||
data.pages.insert(position, page);
|
||||
cx.replace_payload(window, data)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn pages(store: &ObjectStore, window: ObjectRef) -> Result<&[ObjectRef], VmError> {
|
||||
Ok(&store.payload::<ManagedWindow>(window, "Window")?.pages)
|
||||
}
|
||||
pub fn take_commands(vm: &Vm, window: ObjectRef) -> Result<Vec<Command>, VmError> {
|
||||
let data = vm.payload::<ManagedWindow>(window, "Window")?;
|
||||
let mut queue = data
|
||||
.outbox
|
||||
.lock()
|
||||
.map_err(|_| invalid("window outbox poisoned"))?;
|
||||
let mut commands = std::mem::take(&mut *queue);
|
||||
commands.sort_by_key(|command| command.sequence);
|
||||
Ok(commands)
|
||||
}
|
||||
pub fn install(
|
||||
vm: &mut Vm,
|
||||
roots: &mut Vec<ObjectRef>,
|
||||
desktop: ObjectRef,
|
||||
tabs: ObjectRef,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
let definition = desktop_type(vm.object_store(), "Window", desktop)?;
|
||||
let function_type = desktop_type(vm.object_store(), "Function", desktop)?;
|
||||
for (name, operation) in [
|
||||
("id", Operation::Id),
|
||||
("viewport", Operation::Viewport),
|
||||
("pages", Operation::Pages),
|
||||
("resize", Operation::Resize),
|
||||
("moveTo", Operation::MoveTo),
|
||||
("setTitle", Operation::SetTitle),
|
||||
("focus", Operation::Focus),
|
||||
] {
|
||||
use endor_core::{AnnotationType as T, CallEffect, CallSignature};
|
||||
let (parameters, returns, effect) = match operation {
|
||||
Operation::Id => (vec![], T::Number, CallEffect::ReadOnly),
|
||||
Operation::Pages => (
|
||||
vec![],
|
||||
T::Nominal(desktop_type(vm.object_store(), "ObjectList", desktop)?),
|
||||
CallEffect::ReadOnly,
|
||||
),
|
||||
Operation::Viewport => (
|
||||
vec![],
|
||||
T::Nominal(desktop_type(vm.object_store(), "MeasureResult", desktop)?),
|
||||
CallEffect::ReadOnly,
|
||||
),
|
||||
Operation::Resize | Operation::MoveTo => {
|
||||
(vec![T::Number, T::Number], T::Unit, CallEffect::Mutating)
|
||||
}
|
||||
Operation::SetTitle => (vec![T::String], T::Unit, CallEffect::Mutating),
|
||||
Operation::Focus => (vec![], T::Unit, CallEffect::Mutating),
|
||||
};
|
||||
let mut arguments = vec![T::Nominal(definition)];
|
||||
arguments.extend(parameters);
|
||||
let function = vm.allocate(ContextNativeFunction::new(
|
||||
name,
|
||||
Method {
|
||||
operation,
|
||||
desktop,
|
||||
signature: CallSignature::exact(arguments, returns, effect),
|
||||
},
|
||||
vec![desktop],
|
||||
))?;
|
||||
roots.push(function);
|
||||
vm.attach_type(function, function_type)?;
|
||||
vm.define_method(definition, name, function)?;
|
||||
}
|
||||
let window = vm.allocate(ManagedWindow {
|
||||
id: MAIN_WINDOW,
|
||||
desktop,
|
||||
closed: false,
|
||||
tasks: None,
|
||||
tabs,
|
||||
pages: Vec::new(),
|
||||
sequence: 0,
|
||||
outbox: Arc::new(Mutex::new(Vec::new())),
|
||||
})?;
|
||||
roots.push(window);
|
||||
vm.attach_type(window, definition)?;
|
||||
vm.set_attr(desktop, "window", Value::Object(window))?;
|
||||
let windows = vm.new_dict()?;
|
||||
vm.set_attr(desktop, "windows", Value::Object(windows))?;
|
||||
vm.dict_set(
|
||||
windows,
|
||||
Value::Text(MAIN_WINDOW.to_string()),
|
||||
Value::Object(window),
|
||||
)?;
|
||||
vm.release(windows)?;
|
||||
Ok(window)
|
||||
}
|
||||
|
||||
/// Create a managed native-window resource. The GUI creates the OS resource only
|
||||
/// after the owning candidate/input publishes its immutable projection.
|
||||
pub fn create(
|
||||
cx: &mut NativeContext<'_>,
|
||||
master: ObjectRef,
|
||||
id: u64,
|
||||
definition: ObjectRef,
|
||||
) -> Result<(ObjectRef, ObjectRef, ObjectRef), VmError> {
|
||||
if cx.store().is_read_only() {
|
||||
return Err(invalid(
|
||||
"window creation is forbidden during read-only rendering",
|
||||
));
|
||||
}
|
||||
let desktop = cx.new_object()?;
|
||||
let tabs = cx.new_dict()?;
|
||||
let types = cx.store().get_attr(master, "types")?;
|
||||
cx.set_attr(desktop, "types", types)?;
|
||||
cx.set_attr(desktop, "viewport", Value::Nil)?;
|
||||
cx.set_attr(desktop, "tabs", Value::Object(tabs))?;
|
||||
let window = cx.allocate(ManagedWindow {
|
||||
id,
|
||||
desktop,
|
||||
closed: false,
|
||||
tasks: None,
|
||||
tabs,
|
||||
pages: Vec::new(),
|
||||
sequence: 0,
|
||||
outbox: Arc::new(Mutex::new(Vec::new())),
|
||||
})?;
|
||||
cx.attach_type(window, definition)?;
|
||||
cx.set_attr(desktop, "window", Value::Object(window))?;
|
||||
let Value::Object(windows) = cx.store().get_attr(master, "windows")? else {
|
||||
return Err(invalid("window registry missing"));
|
||||
};
|
||||
cx.dict_set(windows, Value::Text(id.to_string()), Value::Object(window))?;
|
||||
Ok((window, desktop, tabs))
|
||||
}
|
||||
|
||||
pub fn close(cx: &mut NativeContext<'_>, window: ObjectRef) -> Result<(), VmError> {
|
||||
if cx.store().is_read_only() {
|
||||
return Err(invalid(
|
||||
"window close is forbidden during read-only rendering",
|
||||
));
|
||||
}
|
||||
let mut data = cx
|
||||
.store()
|
||||
.payload::<ManagedWindow>(window, "Window")?
|
||||
.clone();
|
||||
if data.closed {
|
||||
return Ok(());
|
||||
}
|
||||
crate::tasks::cancel_owner(cx, window)?;
|
||||
for page in data.pages.clone() {
|
||||
crate::tasks::cancel_owner(cx, page)?;
|
||||
unregister_page(cx, window, page)?;
|
||||
}
|
||||
data = cx
|
||||
.store()
|
||||
.payload::<ManagedWindow>(window, "Window")?
|
||||
.clone();
|
||||
data.closed = true;
|
||||
cx.replace_payload(window, data)?;
|
||||
enqueue(cx, window, Action::Close)
|
||||
}
|
||||
|
||||
/// Host teardown for a stopped VM: no binding, dispatch or source execution.
|
||||
pub fn retire(vm: &mut Vm, window: ObjectRef) -> Result<(), VmError> {
|
||||
let mut data = vm.payload::<ManagedWindow>(window, "Window")?.clone();
|
||||
vm.dict_clear(data.tabs)?;
|
||||
data.pages.clear();
|
||||
data.closed = true;
|
||||
vm.replace_payload(window, data)
|
||||
}
|
||||
Reference in New Issue
Block a user