Declare visual capabilities and dispatch explicit Presentable views
Verify Tessera GUI / verify (push) Failing after 7m41s

This commit is contained in:
2026-10-21 21:37:22 +08:00
parent 8d980745ea
commit 7acc5783a5
9 changed files with 363 additions and 4 deletions
+5 -1
View File
@@ -196,13 +196,17 @@ Native visual methods are now available on Block: `measure(mount, Constraints(mi
Outside a renderer layout call, native measurement queries find intrinsic native subtree size and clamp it to the given constraints. During layout, native base methods use the staged measured children of that occurrence. Native Row/Column arrangement uses child sizes, padding and gaps; it does not stretch children to fill the supplied bounds. Hit testing uses local coordinates against the current Mount dimensions. Coordinates/dimensions must be finite and remain within the native layout limit. Width/height and constraint ranges cannot be negative or inverted. The value constructors preserve fields as ordinary objects; methods validate their contents when used, and global annotation type checking remains pending.
Visual, EventTarget, Children and Presentable are explicit managed Trait definitions. Block declares Visual (measure/arrange/paint/hitTest) and EventTarget (on/dispatch/onEvent); ContainerBlock declares Children (append/remove/replace/move/children), inherited by Page. `ui.supports(value, capability)` queries an instance; `ui.implements(type, capability)` queries a type. `ui.implement(type, capability)` checks required methods and establishes an explicit relation. Matching member names alone never declare a capability. Aster checks source positional parameter counts, including self, when registering, creating subclasses or replacing methods; declaration and ancestor updates also validate existing affected descendants. Native callable signatures remain trusted host declarations; argument/return annotations, effect types and formal trait syntax are still pending.
A plain source object can declare Presentable by implementing `present(self, window: Window): Block` and calling `ui.implement(MyType, Presentable)`. `ui.present(value)` invokes this method with the calling window and checks the returned actual Block; `ui.open(value)` also opens the result in a Page. Block values pass through directly. The existing summary viewer remains the fallback for unregistered values, and merely viewing a function does not execute it. Presentation runs through the same bounded VM call sequence; there is no recursive host evaluator. A source adapter can keep the original object through fields/callbacks/bindings; [presentable.endor](examples/presentable.endor) shows a source-preserving view and GUI calls to the original object's method. Presentation methods are ordinary calls; visual measure/arrange/paint/hitTest still run read-only and check their nominal results at runtime. Source implementations of EventTarget.on/dispatch must provide the contract's canonical 3/2 arguments after self; native methods retain their existing optional convenience arguments.
`block.bind(property, compute)` binds an existing managed field to a zero-argument function and returns a Subscription with disconnect()/isConnected(). Targets are Block fields, including source-defined fields; arbitrary non-Block objects are not binding targets yet. Native visual fields are now ordinary attributes: TextBlock.text/size/color, RectBlock.width/height/radius/color, Spacer.size and container padding/gap. Direct assignments and native setters feed the same visual snapshot. Text size remains 1..8, geometry must be finite/nonnegative and within the existing limits, and colors use the existing color parser. Legacy textOf still owns its derived text until setText or a text binding replaces it.
The target's managed content owns its bindings; each binding traces the actual compute function and its captures. Tokens and the host registry hold weak references. Rebinding a field disconnects its previous binding; disconnecting leaves the last value in place. Hidden but still-referenced Blocks update at successful input/event/viewport stabilization boundaries. Functions run read-only against existing objects; they may construct result objects. Dependencies are recorded from actual VM reads, with object-level versions and conservative global-dictionary invalidation. This replaces the earlier candidate API's explicit source list. Binding results are settled before frame publication, including across windows and after lifecycle changes. Values read earlier in the same input precede this batch boundary. Explicit dependencies and property-level dependency precision remain future work.
One Block can have up to 128 active bindings. Each computation has 100000 instructions/128 frames, and a refresh rejects after 10000 computations if dependencies do not stabilize; it reports an error and preserves the published picture instead of silently truncating propagation. A live binding-computation failure stops that runtime. General type/effect checking remains pending. See [property-bindings.endor](examples/property-bindings.endor) for actual Endor source.
`invalidate("paint")` requests a frame while retaining measurement caches; `invalidate("layout")` also clears affected intrinsic measurements; `invalidate("content")` also invalidates derived content and ancestor dependencies. The default reason is layout. Requests coalesce at the refresh boundary, cover all aliases/occurrences of the same current content and preserve Mount identities. Hidden objects do not force visible frames. See [visual-protocols.endor](examples/visual-protocols.endor). Source measure/arrange overrides now participate in actual layout with structural Mount contexts available before first measurement. Source paint and hitTest also run in the frame/input pipeline. Explicit traits, full type/effect contracts, more precise context dependencies and general container constraint negotiation remain future work.
`invalidate("paint")` requests a frame while retaining measurement caches; `invalidate("layout")` also clears affected intrinsic measurements; `invalidate("content")` also invalidates derived content and ancestor dependencies. The default reason is layout. Requests coalesce at the refresh boundary, cover all aliases/occurrences of the same current content and preserve Mount identities. Hidden objects do not force visible frames. See [visual-protocols.endor](examples/visual-protocols.endor). Source measure/arrange overrides now participate in actual layout with structural Mount contexts available before first measurement. Source paint and hitTest also run in the frame/input pipeline. Full parameter/return type and effect contracts, more precise context dependencies and general container constraint negotiation remain future work.
A source subclass can override `measure(self, mount, constraints): MeasureResult` and `arrange(self, mount, geometry): Arrangement`. The persistent renderer creates stable Mount identities and parent/child/sibling links before measuring. Measurement proceeds bottom-up with the current logical viewport as the Page constraints (headless callers default to 0..1000000); native parents and explicit native base calls use the current occurrence's measured child sizes, including source overrides. Arrangement proceeds top-down; each child Bounds must be assigned exactly once using its stable slot, with nominal result types and finite geometry checked. Source arrangements can resize or move children; omission, duplicate/foreign slots and invalid geometry reject the frame. See [source-layout.endor](examples/source-layout.endor).
+27
View File
@@ -0,0 +1,27 @@
class Product {
name: String
color: String
function label(self: Product): String { return self.name }
function shade(self: Product): String { return self.color }
function update(self: Product, event: Event): Unit {
self.name = "原业务对象已更新"
self.color = "#237A45"
}
function present(self: Product, window: Window): Block {
title = TextBlock(self.name)
swatch = RectBlock(180,48,8,self.color)
titleBinding = title.bind("text",self.label)
colorBinding = swatch.bind("color",self.shade)
button = Button("调用业务对象方法")
connection = button.on("click",self.update)
result = Column(24,16,title,swatch,button)
result.source = self
result.contextWindow = window.id()
return result
}
}
ui.implement(Product,Presentable)
product = Product("普通对象的显式展示能力", "#526AC7")
view = ui.present(product)
page = ui.open(view)
page.title = "Presentable"
+9
View File
@@ -14,6 +14,7 @@
| mount.rs | Managed per-occurrence contexts, weak reverse links, ordered mount/unmount hooks, geometry and focus queries |
| events.rs | Bounded native input transport to the owning VM |
| event_dispatch.rs | Managed Event, weak Subscription tokens, Block-owned connections and occurrence-specific capture/target/bubble through a budgeted VM driver |
| protocols.rs | Register explicit Visual/EventTarget/Children/Presentable managed traits and native type declarations |
| presentation.rs | Per-window layout, Mount/focus/tab state and read dependencies; VM changes fan out before any view consumes work |
| tabs.rs | Immutable tab chrome, shared draw/hit geometry, overflow navigation and opaque published Page identities |
| window.rs | Native Window construction/close, context ownership, ordered Page roots, read-only guards and coalesced GUI projections |
@@ -106,3 +107,11 @@ read versions and borrowed output values for equality without adding GC roots;
cache updates do not mutate the connection's business version. Target content
traces the compute function. Subscription tokens are weak and also support bindings.
All binding work settles before published frames; compute failure stops the VM.
The host registers Trait definitions through Aster's checked nominal capability
API. Source subclasses validate inherited method arity before class publication.
Presentable dispatch uses a generated validated bytecode continuation inside the
current call budget, passes the current managed Window, and validates a real
Block result before opening it. Native base visual methods and runtime result
checks remain the rendering boundary. Matching present names without an explicit
implementation keep the summary fallback and do not execute guest methods.
+4
View File
@@ -1042,6 +1042,10 @@ Source measure and arrange overrides execute bottom-up and top-down in one read-
Source paint overrides execute in the actual frame pipeline under a read-only heap policy. Source hitTest overrides similarly refine native pointer targets in VM paint order; Point.inside(bounds) and Point.inCircle(cx, cy, radius) provide primitive shape queries. Managed DisplayList/ObjectList/PaintCommand and Constraints/Bounds/Point results are ordinary runtime objects.
Trait definitions Visual, EventTarget, Children and Presentable are managed nominal capabilities. ui.implement(type,capability) explicitly declares an implementation after required-method/positional-arity checks; ui.implements(type,capability) and ui.supports(value,capability) query it. Block declares Visual/EventTarget; ContainerBlock declares Children, inherited by Page. Same-name methods alone never declare an implementation. Source subclass construction and host method replacement validate inherited/affected descendant contracts. Native callable signatures are trusted; full parameter/return annotation and effect checks and formal trait syntax remain pending. EventTarget requires canonical on/dispatch/onEvent arities 3/2/1 after self; native optional convenience forms remain.
For a plain object explicitly implementing Presentable, present(self, window: Window): Block is invoked by ui.present(value) or ui.open(value), using the current managed Window and the same VM budget. The result must be an actual Block. Blocks pass through directly; unregistered values retain the summary fallback. Source views retain their business object via managed fields/callbacks/bindings, as in examples/presentable.endor. Viewing function definitions does not itself execute them. Rendering methods still run read-only with nominal result checks.
Block.bind(property, compute) binds an existing managed Block field to a zero-argument function and returns Subscription (disconnect/isConnected). This includes source-defined fields and native TextBlock.text/size/color, RectBlock.width/height/radius/color, Spacer.size and container padding/gap. Native fields can also be assigned directly. The target content owns compute/captures; tokens and host registry are weak. Rebinding disconnects the old connection; disconnect keeps the last value. Actual read dependencies are tracked at object granularity, including conservative global reads; no explicit source-list parameter is required. Hidden retained Blocks update at successful input/event stabilization boundaries before all windows publish. Computes are read-only for existing objects and may allocate results. They have 100000 instructions/128 frames each, 128 active bindings per Block and a 10000-computation refresh limit that errors rather than truncates propagation. Binding failure stops the live VM and preserves published pictures. Non-Block targets, explicit dependency lists and general type/effect checking remain pending. See examples/property-bindings.endor.
Native input POST /events is a transport envelope, not Endor source. Each frame and input carries an opaque runtime window identity; omitted input window defaults to 1 for existing clients. GET /code exposes X-Tessera-Window. A window/session/layout identity mismatch is rejected before invoking code. Tab actions use kind tab-activate/tab-close/tab-detach and the mount wire field carries the opaque tab ID from frame.tabs; point/press_point must be omitted. All spatial/tab actions validate session and layout_version before dispatch. Resource window-close uses mount=0 and no points; it validates the live window/session rather than its old layout version. The window
+110
View File
@@ -2562,6 +2562,116 @@ mod tests {
assert!(!session.is_faulted());
}
#[test]
fn presentable_dispatch_preserves_source_identity_and_reactive_display() {
let (mut session, initial) = ReplSession::load(
include_str!("../examples/presentable.endor"),
"app.main",
1,
230,
)
.unwrap();
assert!(initial.frame.commands.iter().any(|command| matches!(command,RenderCommand::Text { value, .. } if value == "普通对象的显式展示能力")));
let globals = session.candidate.globals.unwrap();
let Value::Object(product) = session
.candidate
.vm
.dict_get(globals, &Value::Text("product".into()))
.unwrap()
.unwrap()
else {
panic!("expected Product");
};
let Value::Object(view) = session
.candidate
.vm
.dict_get(globals, &Value::Text("view".into()))
.unwrap()
.unwrap()
else {
panic!("expected Block");
};
assert_eq!(
session.candidate.vm.get_attr(view, "source").unwrap(),
Value::Object(product)
);
assert_eq!(
session
.execute("ui.supports(product,Presentable)", "app.main")
.unwrap()
.value,
"true"
);
let changed = session
.execute("product.name = \"updated\"", "app.main")
.unwrap()
.document
.unwrap();
assert!(changed.frame.commands.iter().any(
|command| matches!(command,RenderCommand::Text { value, .. } if value == "updated")
));
assert!(session.execute("class Bad: RectBlock { function paint(self: Bad): DisplayList { return DisplayList(ObjectList()) } }","app.main").err().unwrap().to_string().contains("trait Visual method paint"));
assert!(!session.is_faulted());
}
#[test]
fn matching_present_method_does_not_implicitly_declare_presentable() {
let mut session = ReplSession::new(231).unwrap();
session
.execute(
r#"
class Data {
marker: Object
function present(self: Data, window: Window): Block {
self.marker.increment()
return TextBlock("custom")
}
}
marker = ui.state(0)
data = Data(marker)
fallback = ui.present(data)
"#,
"app.main",
)
.unwrap();
assert_eq!(
session.execute("marker.value", "app.main").unwrap().value,
"0"
);
assert_eq!(
session
.execute("ui.supports(data,Presentable)", "app.main")
.unwrap()
.value,
"false"
);
session
.execute(
"ui.implement(Data,Presentable)\ncustom = ui.open(data)",
"app.main",
)
.unwrap();
assert_eq!(
session.execute("marker.value", "app.main").unwrap().value,
"1"
);
let before = session.documents.clone();
assert!(
session
.execute(
"class Missing {}\nui.implement(Missing,Presentable)",
"app.main"
)
.is_err()
);
assert_eq!(
session.documents[&crate::window::MAIN_WINDOW]
.frame
.layout_version,
before[&crate::window::MAIN_WINDOW].frame.layout_version
);
}
#[test]
fn managed_property_bindings_update_hidden_objects_and_shared_window_geometry() {
let mut session = ReplSession::new(220).unwrap();
+1
View File
@@ -17,6 +17,7 @@ mod mount;
mod native_visual;
mod object_list;
mod presentation;
mod protocols;
mod scene;
mod snapshot;
mod software_renderer;
+60
View File
@@ -0,0 +1,60 @@
//! Host capability definitions over Aster's explicit managed trait relations.
use endor_core::{MethodRequirement, ObjectRef, 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),
("remove", 1),
("replace", 2),
("move", 2),
("children", 0),
],
Some("ContainerBlock"),
),
("Presentable", vec![("present", 1)], None),
] {
let requirements = methods
.into_iter()
.map(|(name, parameters)| MethodRequirement {
name: name.into(),
parameters,
})
.collect();
let capability = vm.new_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 {
let Value::Object(owner) = vm.get_attr(ui, owner)? else {
return Err(VmError::InvalidArgument("missing protocol owner"));
};
vm.implement_trait(owner, capability)?;
}
}
Ok(())
}
+146 -2
View File
@@ -20,6 +20,11 @@ pub const TYPE_NAMES: &[&str] = &[
"Object",
"Type",
"Function",
"Trait",
"Visual",
"EventTarget",
"Children",
"Presentable",
"Block",
"ContainerBlock",
"TextBlock",
@@ -42,7 +47,13 @@ pub const TYPE_NAMES: &[&str] = &[
"DisplayList",
"PaintCommand",
];
pub const QUERY_NAMES: &[&str] = &["isInstance", "isSubtype"];
pub const QUERY_NAMES: &[&str] = &[
"isInstance",
"isSubtype",
"implement",
"implements",
"supports",
];
#[derive(Debug, Clone, PartialEq)]
pub struct UiNode {
@@ -199,6 +210,9 @@ type Shared = Arc<Mutex<Session>>;
#[derive(Debug, Clone, Copy)]
enum Operation {
IsInstance,
Implement,
Implements,
Supports,
IsSubtype,
OpenValue,
Mounts,
@@ -565,6 +579,36 @@ fn show(cx: &mut NativeContext<'_>, page: ObjectRef, session: &Shared) -> Result
show_in(cx, page, session, None)
}
#[derive(Debug)]
struct PresentResult {
open: bool,
session: Shared,
}
impl NativeCallable for PresentResult {
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
let [Value::Object(root)] = args else {
return Err(invalid("Presentable.present must return a Block"));
};
let is_page = cx.store().payload::<block::Block>(*root, "Block")?.page;
let result = if self.open {
let page = if is_page {
*root
} else {
new_block(
cx,
Data::new(Kind::Page, vec![*root], 0.0, 0.0),
&self.session,
)?
};
show(cx, page, &self.session)?;
page
} else {
*root
};
Ok(NativeResult::Return(Value::Object(result)))
}
}
fn present_value(
cx: &mut NativeContext<'_>,
value: &Value,
@@ -610,7 +654,7 @@ impl NativeCallable for Function {
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
use Operation::*;
let (minimum, maximum) = match self.operation {
IsInstance | IsSubtype | Bind => (2, 2),
IsInstance | IsSubtype | Bind | Implement | Implements | Supports => (2, 2),
Stats | Viewport | Window | PageWindow | Mounts => (0, 0),
State | StateSet => (1, 1),
Increment => (0, 0),
@@ -633,6 +677,30 @@ impl NativeCallable for Function {
if !(minimum..=maximum).contains(&args.len()) {
return Err(invalid("incorrect UI method argument count"));
}
if matches!(self.operation, Implement | Implements | Supports) {
let capability = object(args.get(1))?;
let value = match self.operation {
Implement => {
cx.implement_trait(object(args.first())?, capability)?;
Value::Nil
}
Implements => Value::Bool(
cx.store()
.implements_trait(object(args.first())?, capability)?,
),
Supports => {
// Validate the contract even for immediate scalar values.
cx.store()
.payload::<endor_core::EndorTraitObject>(capability, "Trait")?;
Value::Bool(match args[0] {
Value::Object(value) => cx.store().supports(value, capability)?,
_ => false,
})
}
_ => unreachable!(),
};
return Ok(NativeResult::Return(value));
}
if matches!(self.operation, IsInstance | IsSubtype) {
let candidate = object(args.first())?;
let expected = object(args.get(1))?;
@@ -946,6 +1014,74 @@ impl NativeCallable for Function {
self.requested_type,
)?)));
}
if matches!(self.operation, OpenValue | Present)
&& let Value::Object(value) = args[0]
{
let (desktop, current) = {
let state = self
.session
.lock()
.map_err(|_| invalid("UI session poisoned"))?;
(state.master, state.desktop)
};
let capability = desktop_type(cx.store(), "Presentable", desktop)?;
if !cx
.store()
.object(value)?
.payload()
.as_any()
.is::<block::Block>()
&& cx.store().supports(value, capability)?
{
let definition = cx
.store()
.type_of(value)?
.ok_or(invalid("untyped Presentable"))?;
let function = cx
.store()
.lookup_method(definition, "present")?
.ok_or(invalid("missing present method"))?;
let window = object(Some(&cx.store().get_attr(current, "window")?))?;
let complete = cx.allocate(ContextNativeFunction::new(
"validate presentation",
PresentResult {
open: matches!(self.operation, OpenValue),
session: self.session.clone(),
},
vec![desktop],
))?;
let instructions = [
endor_core::Instruction::new(endor_core::Opcode::LoadConst, 0),
endor_core::Instruction::simple(endor_core::Opcode::PushNull),
endor_core::Instruction::new(endor_core::Opcode::LoadConst, 1),
endor_core::Instruction::simple(endor_core::Opcode::PushNull),
endor_core::Instruction::new(endor_core::Opcode::LoadConst, 2),
endor_core::Instruction::new(endor_core::Opcode::LoadConst, 3),
endor_core::Instruction::new(endor_core::Opcode::Call, 2),
endor_core::Instruction::new(endor_core::Opcode::Call, 1),
endor_core::Instruction::simple(endor_core::Opcode::ReturnValue),
];
let code = endor_core::EndorCode::from_instructions(
&instructions,
vec![
Value::Object(complete),
Value::Object(function),
Value::Object(value),
Value::Object(window),
],
endor_core::CodeLayout::default(),
)?
.with_location("Presentable.present", "<tessera>", 1);
let code = cx.allocate(endor_core::EndorCodeObject::new(code))?;
let globals = cx.new_dict()?;
let driver = cx.new_function("Presentable.present", code, globals)?;
attach_desktop_type(cx, driver, "Function", desktop)?;
return Ok(NativeResult::Invoke {
function: driver,
arguments: vec![],
});
}
}
if matches!(self.operation, OpenValue) {
let root = present_value(cx, &args[0], &self.session)?;
let page = if cx.store().payload::<block::Block>(root, "Block")?.page {
@@ -1976,6 +2112,9 @@ pub fn install(vm: &mut Vm, roots: &mut Vec<ObjectRef>) -> Result<UiBridge> {
retired_commands: Vec::new(),
}));
for (name, operation) in [
("implement", Operation::Implement),
("implements", Operation::Implements),
("supports", Operation::Supports),
("isInstance", Operation::IsInstance),
("isSubtype", Operation::IsSubtype),
("open", Operation::OpenValue),
@@ -2015,6 +2154,7 @@ pub fn install(vm: &mut Vm, roots: &mut Vec<ObjectRef>) -> Result<UiBridge> {
("Type", root_types.type_type),
];
for (name, base_name, constructor_name) in [
("Trait", "Object", None),
("Function", "Object", None),
("Block", "Object", None),
("ContainerBlock", "Block", None),
@@ -2149,6 +2289,9 @@ pub fn install(vm: &mut Vm, roots: &mut Vec<ObjectRef>) -> Result<UiBridge> {
"window",
"isInstance",
"isSubtype",
"implement",
"implements",
"supports",
] {
let function = object(Some(&vm.get_attr(ui, name)?))?;
vm.attach_type(function, function_type)?;
@@ -2205,6 +2348,7 @@ pub fn install(vm: &mut Vm, roots: &mut Vec<ObjectRef>) -> Result<UiBridge> {
let event_type = object(Some(&vm.get_attr(ui, "Event")?))?;
let token_type = object(Some(&vm.get_attr(ui, "Subscription")?))?;
crate::event_dispatch::install(vm, roots, event_type, token_type, function_type)?;
crate::protocols::install(vm, roots, desktop, ui)?;
Ok(UiBridge { ui, session })
}
+1 -1