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

This commit is contained in:
2026-10-21 01:49:35 +08:00
parent 757fa22d9b
commit 0d5e4b318d
21 changed files with 3295 additions and 892 deletions
+22 -18
View File
@@ -8,7 +8,7 @@ The initial page is empty.
## Source and library integration
`vendor/aster` is an unmodified Git submodule, pinned to an exact published commit.
`vendor/aster` is an independent Git submodule pinned to a published Aster commit.
Cargo path dependencies directly use its `frontend`, `compiler` and `core`
(library name `endor_core`) packages, which bring in `objects`. The Aster workspace
and history remain independent. See [vendor](vendor/README.md) for initialization
@@ -134,19 +134,16 @@ selected UI root, extracts native data, builds and validates the frame, then
cleans up all VM roots. The window receives no VM handles. It relays out the owned
native tree during redraw and display scale changes without rerunning Endor.
The existing callback interface has no allocator access. Tessera therefore
preallocates 4096 real UI node objects plus a separate 64-page pool with bound
render callbacks per candidate. Each occupied slot owns one live UI reference.
Constructors return those borrowed handles; Aster retains call results under its
existing rules. Native child data owns its own lifetime and contains no managed
VM edges. Each complete PUT gets a new pool. Console keeps live shared UI references
and page mounts. Native mount/child edges register explicit Aster retain/release
roots; unused VM pool slots are recycled only after no managed or native owner
needs them. A recycled slot gets a fresh native cell. Detached branches are freed
when their last owner disappears; reset releases the session's roots.
Aster's scoped NativeContext allocates actual managed Block objects on demand.
Blocks own managed Cells and data objects; child, history and forwarding edges
are traced by the same VM collector. Native methods capture their owner through
declared heap edges. No fixed node/page pool or separate mutable Arc graph remains.
The desktop's tab registry holds open Pages. close releases that registry edge;
referenced Pages remain usable and unreferenced cycles are collected between inputs.
The bridge's diagnostic object index uses non-owning WeakObjectRef values.
Limits are 1 MiB source, 10000 visited AST nodes with a 64-level visitor depth,
4096 constructed UI nodes, 64 pages, 64 UI levels, 10000 expanded layout visits
4096 retained visual objects, 64 retained pages, 10000 expanded graph/layout visits
and 16 KiB per text. Every execution has a 128-frame limit. Script inputs each
receive an equal share of a total 1000000-instruction allowance; function-only
module initialization and main execution each retain a 1000000-instruction budget. Repeated children count again during layout, preventing a
@@ -167,12 +164,20 @@ rejected queue entries do not invalidate accepted work. Failed builds do not
increment the committed revision. A worker-caught panic discards the entire
candidate and returns 500, retaining the previous document.
This stage supports live mounted UI in the Console VM and immutable window frames on the existing worker.
Event callbacks, window-size language inputs and process isolation are future work. Worker threads,
This stage supports live mounted UI for both complete programs and Console inputs, with immutable window frames on the existing worker.
Native mouse/keyboard activation and code-driven callbacks share onClick/click. Managed Mount objects expose each occurrence, and property dependencies and measurement caches avoid recomputing clean visual subtrees. Arrangement still traverses occurrences.
Tab chrome/multiple windows, native class allocation inheritance and trait definitions, window-size language inputs and process isolation are still being implemented. Worker threads,
source budgets and VM instruction limits are not a complete untrusted-code sandbox.
## Developer tools
Native visual protocols are under active implementation: Text/Rect/Row/Column,
container append/remove/replace/move, Page open/close/navigation, ui.present,
ui.state(value), ui.textOf(state, "value"), and button.onClick/click are available
in the persistent Console. Method bodies can call other methods without a trailing
return. Bound text tracks its source property; clean derived subtrees and unchanged measurements are reused. Buttons have a native background, focus ring and pointer/keyboard activation.
`Page()`, `TextBlock(...)`, `Row(...)`, `Column(...)` and `Button(...)` are callable managed type objects; `Page.base` is ContainerBlock and `page.type` is Page. `isInstance(page, Block)` and `isSubtype(Page, Block)` query nominal relations. Object and Type are explicitly bootstrapped in the same GC heap. Ordinary source class declarations, positional field construction, member assignment and inherited method dispatch are supported; native allocator subclasses and traits are still pending. Native visual methods now live on their nominal type tables and use the same receiver binding as source methods. See [managed-types.endor](examples/managed-types.endor) and [classes.endor](examples/classes.endor).
Toggle developer tools with Command-Option-I or F12 on macOS, Control-Shift-I or
F12 on Windows/Linux. The compact Console, Sources, Network and Settings tabs
share a draggable dock edge. The Sources tree/source
@@ -207,7 +212,7 @@ page.render(ui.column(24, 16, title, note, card))
```
Ordinary values keep normal name assignment. UI references opt into Aster's
`ObjectPayload::assign_from` protocol: assigning another UI object updates the
managed `ObjectPayload::assignment_cell` protocol: assigning another UI object updates the
existing shared reference and preserves its identity. Aliases and mounted parents
therefore observe the same replacement, including across function-local slots.
For example, after `other = card` and `page.render(other)`, assigning
@@ -239,11 +244,10 @@ statements from that input, while preserving the previously displayed page.
Reset session (`DELETE .../repl`) drops the VM and all bindings/objects, preserving
the displayed immutable frame. Clear only hides the transcript. Limits per session
are 256 executed inputs, 1 MiB transcript, 10000 cumulative AST nodes, 4096 UI nodes
and 64 retained pages. Unused slots are reclaimed between inputs; reset releases the whole session. Code and objects are never stored on disk.
and 64 retained pages. Unreachable objects and cycles are reclaimed between inputs; reset releases the whole session. Code and objects are never stored on disk.
Existing `PUT .../code` remains a complete program replacement with a fresh VM;
function-only source still invokes main. Accepted PUT/code DELETE invalidate the
Console context and older queued Console inputs. The compatibility `POST .../evaluate`
function-only source still invokes main. On success the new VM remains live for Console and GUI events; a failed replacement preserves the old VM. Accepted PUT/code DELETE invalidate older queued Console inputs. The compatibility `POST .../evaluate`
endpoint remains isolated for existing clients, but is not a Console mode. All use
the bounded eight-entry worker queue. GET /code returns the displayed source: exact
PUT source, or annotated Console transcript after a REPL render, distinguished by
+2
View File
@@ -2,6 +2,8 @@
| File | Purpose |
| --- | --- |
| [classes.endor](classes.endor) | Endor class fields, inheritance, overriding, a retained receiver and Event arguments; native keyboard input updates shared model properties. |
| [managed-types.endor](managed-types.endor) | Callable managed Endor types, one shared counter, two bound displays and a language callback invoked from native Button input. |
| [page.endor](page.endor) | Four top-level statements construct text, a rectangle and a page, then call page.render; no main wrapper. |
| [main.endor](main.endor) | The earlier function-entry form, producing the same frame as page.endor. |
| [hello.endor](hello.endor) | Richer function-entry example covering a helper, Row/Column and Spacer. |
+28
View File
@@ -0,0 +1,28 @@
class Counter {
value: Number
lastEvent: String
function activate(self: Counter, event: Event): Unit {
self.lastEvent = event.kind
self.change()
}
function change(self: Counter): Unit {
self.value = 10
}
}
class DemoCounter: Counter {
function change(self: DemoCounter): Unit {
self.value = 12
}
}
model = DemoCounter(9, "等待点击")
first = ui.textOf(model, "value", 2)
second = ui.textOf(model, "value", 2)
eventName = ui.textOf(model, "lastEvent")
button = Button("调用继承方法,再分派到覆盖方法")
button.onClick(model.activate)
page = Page()
page.render(Column(24, 16, TextBlock("Endor class:继承、self 与动态方法分派", 2), Row(0, 16, first, second), button, eventName))
+9
View File
@@ -0,0 +1,9 @@
counter = ui.state(9)
first = ui.textOf(counter, "value", 2)
second = ui.textOf(counter, "value", 2)
title = TextBlock("Endor:同一份对象,代码与 GUI 共同操作", 2)
button = Button("增加计数")
function increment(): Unit { counter.increment() }
button.onClick(increment)
page = Page()
page.render(Column(24, 16, title, Row(0, 16, first, second, button)))
+21 -21
View File
@@ -5,11 +5,14 @@
| main.rs | Native window event loop, namespace state and API startup |
| api.rs | Code CRUD, live Console/reset and compatibility evaluation endpoints, worker-owned session, request observation and diagnostics |
| activity.rs | Bounded in-memory HTTP exchanges with marked previews and allowlisted request headers |
| endor_host.rs | Aster compilation, fresh PUT candidates, worker-owned live REPL VM, bounded execution, root cleanup and AST developer tree |
| endor_host.rs | Aster compilation, fresh PUT candidates retained after successful publication, shared Console/program VM, bounded execution, root cleanup and AST developer tree for function/class/member assignment nodes |
| endor_script.rs | Batch complete inputs for Aster's Interactive parser/compiler, retain Module entry, and rebase Aster spans to the original snapshot |
| ui_bridge.rs | Tessera UI/page payloads and bound render methods, reusable node/page pools, explicit native-edge VM roots, live mounts/unmount and native frame extraction |
| live_ui.rs | Stable native UI references, alias-preserving replacement, cycle/depth checks and immutable frame extraction |
| layout.rs | Native UI tree to Frame; expanded-tree and coordinate budgets |
| ui_bridge.rs | Managed nominal type constructors, shared type method tables and bound receiver dispatch, tab registry, Page lifecycle/navigation and immutable frame extraction |
| block.rs | Aster-managed Block/Cell/data graph, stable child slots, shared assignment, cycle validation and explicit text bindings |
| snapshot.rs | Property dependencies, reverse parent links and cached immutable visual derivation |
| mount.rs | Managed per-occurrence contexts, weak reverse links, geometry and focus queries |
| events.rs | Managed Event marker and bounded native input transport to the owning VM |
| layout.rs | Iterative measurement/arrangement, stable occurrence IDs, measurement cache and geometry budgets |
| document.rs | Published source/AST/UI snapshot, revisions, invalidation, frame validation and display commands |
| app.rs | Window events, redraw and system widget pointer/keyboard/IME routing |
| clipboard.rs | UTF-8 macOS clipboard adapter independent of Finder locale, with strict decoding and surfaced errors |
@@ -23,22 +26,20 @@
| text.rs | Shared system font discovery, shaping, real measurements, antialiased glyphs and bounded caches |
| README.md | Module map |
Aster is an unmodified source submodule. Language parsing, AST definitions,
Aster is an independent source submodule pinned to the published managed type/native-call implementation. Language parsing, AST definitions,
compilation, bytecode and VM execution come from its libraries. Tessera implements
only host UI behavior and layout. No CLI, HTTP server or Docker process is needed
to execute Endor in the application.
A complete-PUT execution candidate owns all external VM roots, including the 4096-node pool
and 64 pages with bound render callbacks. Script units share one globals dictionary
inside the candidate; no variables or VM handles persist across successful PUTs.
Callbacks return borrowed, preallocated real VM objects. UI payloads opt into Aster
shared-reference assignment. Native live child/forward edges contain owned Arcs;
Console registers corresponding external VM roots through retain/release, without
mutable untraced VM edges in payloads. Window frames contain only immutable native data. Page rendering stores native root data in the build session;
the final render selects the snapshot after all script units succeed. Once
extraction finishes, release temporary results, clear
globals, release roots, collect cycles and require an empty VM. The window keeps
only source, developer metadata, frame commands and native UI data.
A complete-PUT candidate owns the desktop and UI service roots, with dynamic
Block allocation through scoped NativeContext. Block -> Cell -> data and all
child/history/forwarding references are managed VM edges. Native functions declare
their captured owner edges. The bridge holds only weak diagnostic references to
allocated Blocks; the tab registry owns open Pages. Closing a tab releases that
edge, without destroying a still-referenced Page. Console retains the actual VM;
a successful complete PUT also retains its candidate as the active program, accessible from Console and native input. Failed PUT preserves the previous heap. Cleanup releases
globals/service roots, collects cycles and requires an empty VM. Window frames
contain only immutable native data.
Tests in api.rs execute real HTTP CRUD, persistent Console/reset/PUT isolation and a controlled queued-PUT/DELETE race
without opening a window. Tests in endor_host.rs cover lifecycle, direct script and
@@ -66,13 +67,12 @@ interaction. It imports no Endor runtime or guest UI bridge; developer tools sup
typed actions and keep all execution/source behavior outside the widget layer.
Console sessions use `endor_host::ReplSession` on the same worker thread. Real VM
globals, UI pools and `_` survive between inputs. Parse/compile precede execution;
globals, live Blocks and `_` survive between inputs. Parse/compile precede execution;
only a successful input commits a pending mount or publishes changes to an existing mount.
Runtime-failed input can retain earlier completed bindings, but cannot publish its
pending render. Session budgets cover cumulative source/AST and fixed UI pools.
page.unmount releases a mount; unused node/page pool slots are reclaimed between inputs.
Explicit reset drops the VM; accepted PUT/code DELETE change the publication epoch
and invalidate the old context. Source snapshots carry annotated AST ranges for the
pending render. Session budgets cover cumulative source/AST and live Block counts.
page.unmount releases current content; unreachable object cycles are reclaimed between inputs.
Explicit reset drops the VM. Successful PUT replaces it with the fresh program; failed PUT restores the displayed program’s event epoch. Code DELETE invalidates the context. Source snapshots carry annotated AST ranges for the
actual Console transcript; source history is never rerun to reconstruct memory.
The Aster pin includes independent Assignment syntax and generic opt-in assign_from support.
Live reference tests cover alias updates, nested mounts, cycle rejection, detached branch release and unmount/remount.
+174 -16
View File
@@ -27,6 +27,7 @@ type Notify = Arc<dyn Fn() + Send + Sync>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum RequestKind {
Event,
Code,
Expression,
Repl,
@@ -91,9 +92,23 @@ fn start_server_observed(
.name("tessera-endor-worker".into())
.spawn(move || {
let mut worker = Worker::default();
for job in receiver {
let response = worker.run(&job, &worker_namespace, &worker_notify);
let _ = job.request.respond(response);
loop {
match receiver.recv_timeout(std::time::Duration::from_millis(100)) {
Ok(job) => {
let response = worker.run(&job, &worker_namespace, &worker_notify);
let _ = job.request.respond(response);
}
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
if worker.repl.as_ref().is_some_and(|(epoch, _)| {
worker_namespace
.read()
.is_ok_and(|current| current.submission != *epoch)
}) {
worker.repl = None;
}
}
}
}
})
.context("start Aster execution worker")?;
@@ -209,10 +224,13 @@ fn handle(
let evaluation = namespace_from_route(&path, "/evaluate");
let repl = namespace_from_route(&path, "/repl");
let event = namespace_from_route(&path, "/events");
let route = if method == Method::Put {
namespace_from_path(&path).map(|name| (name, RequestKind::Code))
} else if method == Method::Post {
repl.map(|name| (name, RequestKind::Repl))
event
.map(|name| (name, RequestKind::Event))
.or_else(|| repl.map(|name| (name, RequestKind::Repl)))
.or(evaluation.map(|name| (name, RequestKind::Expression)))
} else if method == Method::Delete {
repl.map(|name| (name, RequestKind::ResetRepl))
@@ -390,10 +408,10 @@ impl Worker {
namespace: &Arc<RwLock<NamespaceState>>,
notify: &Notify,
) -> Response<std::io::Cursor<Vec<u8>>> {
if matches!(job.kind, RequestKind::Code | RequestKind::Expression) {
if job.kind == RequestKind::Code {
self.repl = None;
}
if job.kind == RequestKind::Code {
return self.replace_program(job, namespace, notify);
}
if job.kind == RequestKind::Expression {
return build(job, namespace, notify);
}
let epoch = match namespace.read() {
@@ -405,11 +423,49 @@ impl Worker {
}
if job.kind == RequestKind::ResetRepl {
self.repl = None;
if let Ok(mut current) = namespace.write() {
current.document.frame.session = 0;
current.document.frame.focus = None;
}
notify();
return json(
StatusCode(200),
serde_json::json!({"ok":true,"execution":"repl-reset","persistent":true,"session_reset":true,"message":"Console memory cleared; displayed page preserved"}),
);
}
let event = if job.kind == RequestKind::Event {
let input: crate::events::Input = match serde_json::from_str(&job.source) {
Ok(input) => input,
Err(error) => return error_response(StatusCode(400), error.to_string()),
};
if !matches!(input.kind.as_str(), "click" | "focus") {
return error_response(StatusCode(400), "unsupported event kind");
}
let current = match namespace.read() {
Ok(current) => current,
Err(_) => return error_response(StatusCode(500), "namespace lock poisoned"),
};
let frame = &current.document.frame;
if frame.session != input.session
|| frame.layout_version != input.layout_version
|| frame.fault.is_some()
|| !frame
.mounts
.iter()
.any(|mount| mount.id == input.mount && mount.interactive)
|| self.repl.as_ref().is_none_or(|(context, runtime)| {
*context != epoch || runtime.id != input.session
})
{
return error_response(
StatusCode(409),
"event targets an obsolete or inactive frame",
);
}
Some(input)
} else {
None
};
if self
.repl
.as_ref()
@@ -424,8 +480,13 @@ impl Worker {
let session = &mut self.repl.as_mut().expect("initialized REPL").1;
let id = session.id;
let result = catch_unwind(AssertUnwindSafe(|| {
session.execute(&job.source, &job.namespace)
if let Some(event) = &event {
session.dispatch(event)
} else {
session.execute(&job.source, &job.namespace)
}
}));
let faulted = session.is_faulted();
let Ok(mut current) = namespace.write() else {
return error_response(StatusCode(500), "namespace lock is poisoned");
};
@@ -451,13 +512,27 @@ impl Worker {
}
json(
StatusCode(200),
serde_json::json!({"ok":true,"execution":"repl","persistent":true,"session":id,"input":result.input,"value":result.value,"bindings":result.bindings,"rendered":rendered,"revision":revision}),
serde_json::json!({"ok":true,"execution":if event.is_some() { "event" } else { "repl" },"persistent":true,"session":id,"input":result.input,"value":result.value,"bindings":result.bindings,"rendered":rendered,"revision":revision}),
)
}
Ok(Err(error)) => compile_error(error),
Ok(Err(error)) => {
if event.is_some() || faulted {
let mut document = current.document.clone();
document.frame.fault = Some(format!("{error:#}").chars().take(1024).collect());
let _ = current.commit(epoch, document);
drop(current);
notify();
}
compile_error(error)
}
Err(_) => {
let mut document = current.document.clone();
document.frame.fault =
Some("Runtime discarded after an internal execution failure".into());
let _ = current.commit(epoch, document);
drop(current);
self.repl = None;
notify();
json(
StatusCode(500),
serde_json::json!({"ok":false,"session_reset":true,"error":"Console execution failed internally; session discarded, displayed page preserved"}),
@@ -465,6 +540,66 @@ impl Worker {
}
}
}
fn replace_program(
&mut self,
job: &BuildRequest,
namespace: &Arc<RwLock<NamespaceState>>,
notify: &Notify,
) -> Response<std::io::Cursor<Vec<u8>>> {
if namespace
.read()
.is_ok_and(|current| current.submission != job.submission)
{
return superseded(job.submission);
}
self.next_session = match self.next_session.checked_add(1) {
Some(id) => id,
None => return error_response(StatusCode(500), "session identities exhausted"),
};
let id = self.next_session;
let result = catch_unwind(AssertUnwindSafe(|| {
endor_host::ReplSession::load(&job.source, &job.namespace, job.submission, id)
}));
let Ok(mut current) = namespace.write() else {
return error_response(StatusCode(500), "namespace lock poisoned");
};
if current.submission != job.submission {
return superseded(job.submission);
}
match result {
Ok(Ok((runtime, document))) => match current.commit(job.submission, document) {
Ok(Some(revision)) => {
self.repl = Some((job.submission, runtime));
drop(current);
notify();
json(
StatusCode(200),
serde_json::json!({"ok":true,"namespace":job.namespace,"submission":job.submission,"revision":revision,"diagnostics":[],"session":id,"persistent":true}),
)
}
Ok(None) => superseded(job.submission),
Err(error) => error_response(StatusCode(500), error.to_string()),
},
failed => {
// The candidate never mutated the displayed program's heap.
// Restore that program's event epoch when a replacement fails.
if let Some((epoch, runtime)) = &mut self.repl
&& current.document.frame.session == runtime.id
{
*epoch = job.submission;
}
drop(current);
match failed {
Ok(Err(error)) => compile_error(error),
_ => error_response(
StatusCode(500),
"candidate failed internally; previous runtime preserved",
),
}
}
}
}
}
fn build(
@@ -595,9 +730,10 @@ execution. On runtime error earlier statements in that input may remain live, bu
its pending render is discarded; previous displayed page is preserved.
Session limits: 256 executed inputs, 1 MiB transcript, 10000 cumulative AST nodes,
4096 retained UI nodes and 64 retained pages. Unused slots are reclaimed between inputs; reset releases the session. No VM handles cross to the window.
A newer accepted complete-source PUT or code DELETE invalidates queued Console
inputs and resets the live context. They retain their existing snapshot semantics.
4096 retained visual objects and 64 retained pages. Aster collects unreachable objects/cycles between inputs; there is no fixed UI pool. No VM handles cross to the window.
A newer accepted complete-source PUT or code DELETE invalidates queued Console inputs.
A successful PUT retains its fresh VM as the live program for Console and GUI events;
a failed PUT preserves the previous program. DELETE releases the live context.
GET /code returns the source of the displayed snapshot: exact submitted source for
PUT, an annotated Console transcript after a REPL render. X-Tessera-Source-Kind
identifies source-snapshot versus repl-transcript; a transcript is not a replay log.
@@ -608,6 +744,25 @@ It does not publish a page or change revision. Console does not use this endpoin
All execution endpoints share the eight-entry queue. These are in-process bounded
host executions, not a complete untrusted-code sandbox or a process-isolation design.
## Managed visual types
`Object`, `Type`, `Function`, `Block`, `ContainerBlock`, `TextBlock`, `RectBlock`,
`Spacer`, `Row`, `Column`, `Button`, `Page`, `Mount`, and `Event` are managed nominal
Type objects. Use `page = Page()` and `label = TextBlock("Hello")` in Endor source.
The existing ui constructors return these same typed objects. `page.type`,
`Page.base`, `Page.name`, `isInstance(page, Block)` and `isSubtype(Page, Block)`
expose actual type relations. Types, bases, instances and native constructors live
in the same GC graph. Ordinary source classes support `class Child: Base`, typed field
declarations, explicit first `self` parameters, positional field construction and
member assignment. Inherited methods bind the actual receiver; overridden methods
are dynamically selected through self. Native allocator subclasses and traits remain
pending. Native Block/Page methods use the same type method tables and binding path.
Native input POST /events is a transport envelope, not Endor source. The window
sends current session, layout_version and Mount identity; stale positions fail
without calling a callback. Native mouse, Tab, Enter and Space delegate to the same
managed click/focus methods used by code. Events appear in Network, not Console source history.
## UI host object
Positional arguments only:
@@ -634,8 +789,11 @@ work (409); a full eight-entry queue returns 503. DELETE immediately clears the
document. GET remains available while Aster executes. The window redraws from an
owned snapshot; resize does not rerun Endor. Text uses system fonts, antialiasing
and font fallback; Chinese needs an installed CJK font. Size 1 is 14 logical pixels
with 20-pixel line height; larger sizes multiply both. This first stage builds static UI;
event callbacks and process isolation remain future work. Console retains objects
with 20-pixel line height; larger sizes multiply both. Native Block methods include
setText/setColor, container append/remove/replace/move, Page open/close/navigation,
and code-driven button.onClick/click. ui.state and ui.textOf provide explicit text
binding. Mouse routing, tab chrome/multiple windows and incremental layout remain
in progress; process isolation is future work. Console retains objects
only in its explicitly resettable in-memory VM. It is not an untrusted-code sandbox.
"##,
name = namespace.name,
+168 -10
View File
@@ -24,6 +24,7 @@ use crate::{
#[derive(Clone, Debug)]
pub enum AppEvent {
RuntimeFailed { message: String },
DocumentUpdated,
ConsoleFailed { message: String, source: String },
}
@@ -38,6 +39,11 @@ pub struct TesseraApp {
pointer: Point,
modifiers: ModifiersState,
activity: Activity,
event_client: crate::events::Client,
guest_pressed: Option<crate::events::Input>,
guest_focus: Option<crate::events::Input>,
guest_key: Option<(NamedKey, crate::events::Input)>,
guest_keyboard: bool,
}
impl TesseraApp {
@@ -45,8 +51,9 @@ impl TesseraApp {
namespace: Arc<RwLock<NamespaceState>>,
activity: Activity,
proxy: EventLoopProxy<AppEvent>,
) -> Self {
Self {
) -> anyhow::Result<Self> {
let event_client = crate::events::Client::new(proxy.clone())?;
Ok(Self {
window: None,
context: None,
surface: None,
@@ -60,7 +67,12 @@ impl TesseraApp {
pointer: Point::default(),
modifiers: ModifiersState::default(),
activity,
}
event_client,
guest_pressed: None,
guest_focus: None,
guest_key: None,
guest_keyboard: true,
})
}
fn request_redraw(&self) {
@@ -73,17 +85,33 @@ impl TesseraApp {
if let Ok(namespace) = self.namespace.read() {
self.developer_tools.toggle(&namespace.document);
}
self.guest_keyboard = !self.developer_tools.open;
self.request_redraw();
}
fn document_updated(&mut self) {
if let Ok(namespace) = self.namespace.read() {
self.developer_tools.document_updated(&namespace.document);
let frame = &namespace.document.frame;
self.guest_focus =
frame
.focus
.filter(|_| frame.fault.is_none())
.map(|mount| crate::events::Input {
session: frame.session,
layout_version: frame.layout_version,
mount,
kind: "focus".into(),
});
}
self.request_redraw();
}
fn handle_keyboard(&mut self, event: &winit::event::KeyEvent) {
if self.guest_keyboard && self.handle_guest_key(event) {
self.request_redraw();
return;
}
if self.developer_tools.keyboard_control(
event,
self.modifiers.shift_key(),
@@ -150,7 +178,108 @@ impl TesseraApp {
self.request_redraw();
}
fn guest_covered(&self, point: Point) -> bool {
let panel = self.layout.developer_tools.panel;
self.developer_tools.open
&& crate::geometry::Rect::new(
panel.x - 6.0,
panel.y - 6.0,
panel.width + 12.0,
panel.height + 12.0,
)
.contains(point)
}
fn guest_hit(&self) -> Option<crate::events::Input> {
if self.guest_covered(self.pointer) {
return None;
}
let current = self.namespace.read().ok()?;
let frame = &current.document.frame;
if frame.session == 0 {
return None;
}
let mount = frame.hit_test(self.pointer)?;
Some(crate::events::Input {
session: frame.session,
layout_version: frame.layout_version,
mount: mount.id,
kind: "click".into(),
})
}
fn send_guest(&mut self, event: crate::events::Input) {
if !self.event_client.send(event) {
self.developer_tools.input_error = "Native event queue is unavailable or full".into();
self.developer_tools.open = true;
}
}
fn handle_guest_key(&mut self, event: &winit::event::KeyEvent) -> bool {
let Key::Named(key) = &event.logical_key else {
return false;
};
if *key == NamedKey::Tab {
if event.state == ElementState::Pressed && !event.repeat {
let next = self.namespace.read().ok().and_then(|namespace| {
let frame = &namespace.document.frame;
if frame.session == 0 || frame.fault.is_some() {
return None;
}
let targets: Vec<_> = frame
.mounts
.iter()
.filter(|mount| mount.interactive)
.collect();
if targets.is_empty() {
return None;
}
let current = self
.guest_focus
.as_ref()
.and_then(|focus| targets.iter().position(|mount| mount.id == focus.mount));
let index = if self.modifiers.shift_key() {
current
.map(|i| (i + targets.len() - 1) % targets.len())
.unwrap_or(targets.len() - 1)
} else {
current.map(|i| (i + 1) % targets.len()).unwrap_or(0)
};
Some(crate::events::Input {
session: frame.session,
layout_version: frame.layout_version,
mount: targets[index].id,
kind: "focus".into(),
})
});
if let Some(next) = next {
self.guest_key = None;
self.guest_focus = Some(next.clone());
self.send_guest(next);
return true;
}
return false;
}
return self.guest_focus.is_some();
}
if matches!(key, NamedKey::Enter | NamedKey::Space) && self.guest_focus.is_some() {
if event.state == ElementState::Pressed {
if !event.repeat {
self.guest_key = self.guest_focus.clone().map(|focus| (*key, focus));
}
} else if let Some((pressed, mut input)) = self.guest_key.take()
&& pressed == *key
{
input.kind = "click".into();
self.send_guest(input);
}
return true;
}
false
}
fn redraw(&mut self) {
let guest_cursor = self.guest_hit().is_some();
let (Some(window), Some(surface)) = (self.window.as_ref(), self.surface.as_mut()) else {
return;
};
@@ -174,10 +303,12 @@ impl TesseraApp {
);
drop(namespace);
self.layout = scene.layout;
window.set_cursor(
window.set_cursor(if guest_cursor {
winit::window::CursorIcon::Pointer
} else {
self.developer_tools
.cursor_kind(&self.layout.developer_tools),
);
.cursor_kind(&self.layout.developer_tools)
});
if self.developer_tools.repaint {
self.developer_tools.repaint = false;
window.request_redraw();
@@ -227,6 +358,13 @@ impl ApplicationHandler<AppEvent> for TesseraApp {
fn user_event(&mut self, _event_loop: &ActiveEventLoop, event: AppEvent) {
match event {
AppEvent::RuntimeFailed { message } => {
self.developer_tools.input_error = message;
self.developer_tools.open = true;
self.guest_pressed = None;
self.guest_key = None;
self.request_redraw();
}
AppEvent::DocumentUpdated => self.document_updated(),
AppEvent::ConsoleFailed { message, source } => {
self.developer_tools.input_error = format!("Request failed: {message}");
@@ -246,7 +384,7 @@ impl ApplicationHandler<AppEvent> for TesseraApp {
window_id: WindowId,
event: WindowEvent,
) {
let Some(window) = self.window.as_ref() else {
let Some(window) = self.window.as_ref().cloned() else {
return;
};
if window.id() != window_id {
@@ -272,13 +410,16 @@ impl ApplicationHandler<AppEvent> for TesseraApp {
&self.layout.developer_tools,
window.inner_size().width as f32 / scale,
);
window.set_cursor(
window.set_cursor(if self.guest_hit().is_some() {
winit::window::CursorIcon::Pointer
} else {
self.developer_tools
.cursor_kind(&self.layout.developer_tools),
);
.cursor_kind(&self.layout.developer_tools)
});
window.request_redraw();
}
WindowEvent::CursorLeft { .. } => {
self.guest_pressed = None;
self.developer_tools.pointer_left();
window.set_cursor(winit::window::CursorIcon::Default);
window.request_redraw();
@@ -289,12 +430,27 @@ impl ApplicationHandler<AppEvent> for TesseraApp {
..
} => {
if state == ElementState::Pressed {
self.guest_keyboard = !self.guest_covered(self.pointer);
self.guest_pressed = self.guest_hit();
if self.guest_keyboard {
self.developer_tools.blur();
}
self.developer_tools.press(
&self.layout.developer_tools,
self.pointer,
&self.activity,
);
} else {
if let Some(pressed) = self.guest_pressed.take()
&& self.guest_hit().is_some_and(|hit| {
hit.session == pressed.session
&& hit.layout_version == pressed.layout_version
&& hit.mount == pressed.mount
})
{
self.guest_focus = Some(pressed.clone());
self.send_guest(pressed);
}
self.developer_tools.release(
&self.layout.developer_tools,
self.pointer,
@@ -331,6 +487,8 @@ impl ApplicationHandler<AppEvent> for TesseraApp {
window.request_redraw();
}
WindowEvent::Focused(false) => {
self.guest_pressed = None;
self.guest_key = None;
self.developer_tools.blur();
self.modifiers = ModifiersState::default();
window.request_redraw();
+251
View File
@@ -0,0 +1,251 @@
//! 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),
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)]
pub struct Block {
pub state: ObjectRef,
pub page: bool,
}
impl ObjectPayload for Block {
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);
}
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 next_slot: u64,
pub history: Vec<ObjectRef>,
pub history_index: usize,
pub text_binding: Option<(ObjectRef, String)>,
pub click: 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,
next_slot,
history: vec![],
history_index: 0,
text_binding: None,
click: None,
}
}
pub fn is_container(&self) -> bool {
matches!(
self.kind,
Kind::Row | Kind::Column | Kind::Button | Kind::Page
)
}
}
impl ObjectPayload for Data {
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)) {
for child in &self.children {
visit(child.block);
}
for item in &self.history {
visit(*item);
}
if let Some((source, _)) = &self.text_binding {
visit(*source);
}
if let Some(handler) = self.click {
visit(handler);
}
}
}
pub fn allocate(cx: &mut NativeContext<'_>, data: Data) -> Result<ObjectRef, VmError> {
let page = matches!(data.kind, Kind::Page);
for child in &data.children {
validate(cx.store(), child.block, None)?;
}
let data = cx.allocate(data)?;
let state = cx.new_cell(Some(Value::Object(data)))?;
cx.allocate(Block { state, page })
}
/// 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)
}
+3 -1
View File
@@ -1024,6 +1024,7 @@ pub fn build(
records.iter().any(|r| {
r.id > state.console_after
&& matches!(r.method.as_str(), "PUT" | "POST" | "DELETE")
&& !r.path.ends_with("/events")
}),
);
p.button(
@@ -1049,6 +1050,7 @@ pub fn build(
for r in records.iter().filter(|r| {
r.id > state.console_after
&& (r.method == "PUT" || r.method == "POST" || r.method == "DELETE")
&& !r.path.ends_with("/events")
}) {
let kind = if r.path.ends_with("/repl") {
if r.method == "DELETE" {
@@ -1059,7 +1061,7 @@ pub fn build(
} else if r.path.ends_with("/evaluate") {
"ISOLATED API EVALUATION"
} else if r.method == "PUT" {
"FULL SOURCE · new run"
"FULL SOURCE · live program"
} else {
"CLEAR DOCUMENT"
};
+112 -6
View File
@@ -89,7 +89,36 @@ impl RenderDocument {
for command in &self.frame.commands {
command.validate()?;
}
if self.frame.mounts.len() > 10_000 {
bail!("frame exceeds the 10000 mount limit");
}
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)?;
}
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)?;
@@ -98,17 +127,52 @@ impl RenderDocument {
}
pub fn display_list(&self, scale: f32) -> Result<DisplayList> {
let relayout = self
.ui_root
.as_deref()
.map(crate::layout::frame)
.transpose()?;
let frame = relayout.as_ref().unwrap_or(&self.frame);
let frame = &self.frame;
let mut list = DisplayList::default();
list.push(DrawCommand::Clear(parse_color(&frame.background)?));
for command in &frame.commands {
list.push(command.to_draw_command(scale)?);
}
if let Some(focus) = frame
.focus
.and_then(|id| frame.mounts.iter().find(|m| m.id == id))
{
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 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}"),
size: 1,
color: "#A32D25".into(),
}
.to_draw_command(scale)?,
);
}
Ok(list)
}
@@ -164,6 +228,16 @@ pub struct Frame {
pub background: String,
#[serde(default)]
pub commands: Vec<RenderCommand>,
#[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)]
pub fault: Option<String>,
}
impl Default for Frame {
@@ -171,10 +245,42 @@ impl Default for Frame {
Self {
background: default_background(),
commands: Vec::new(),
mounts: Vec::new(),
layout_version: 0,
session: 0,
focus: None,
fault: None,
}
}
}
/// A position in a published frame. Identifiers are opaque data, never VM handles.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct MountGeometry {
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 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
&& Rect::new(mount.x, mount.y, mount.width, mount.height).contains(point)
})
}
}
fn default_background() -> String {
"#F7F7F5".to_owned()
}
+359 -54
View File
@@ -40,9 +40,7 @@ pub fn compile(source: &str, namespace: &str, submission: u64) -> Result<RenderD
candidate.globals = Some(globals);
candidate.roots.push(globals);
let bridge = ui_bridge::install(&mut candidate.vm, &mut candidate.roots)?;
candidate
.vm
.dict_set(globals, Value::Text("ui".into()), Value::Object(bridge.ui))?;
bridge.install_globals(&mut candidate.vm, globals)?;
let limits = match &plan {
SourcePlan::Module(_) => LIMITS,
SourcePlan::Script(_) => ExecutionLimits {
@@ -61,7 +59,7 @@ pub fn compile(source: &str, namespace: &str, submission: u64) -> Result<RenderD
}
let ui_root = match &plan {
SourcePlan::Script(_) => bridge
.rendered()?
.rendered(&candidate.vm)?
.ok_or_else(|| anyhow::anyhow!("script must call ui.page().render(root)"))?,
SourcePlan::Module(_) => {
let entry = candidate
@@ -77,10 +75,12 @@ pub fn compile(source: &str, namespace: &str, submission: u64) -> Result<RenderD
.vm
.call_with_limits(entry, &[], LIMITS)
.map_err(|error| runtime_error(&candidate.vm, error))?;
let snapshot = bridge.rendered().and_then(|rendered| match rendered {
Some(root) => Ok(root),
None => ui_bridge::snapshot(&candidate.vm, &value),
});
let snapshot = bridge
.rendered(&candidate.vm)
.and_then(|rendered| match rendered {
Some(root) => Ok(root),
None => ui_bridge::snapshot(&candidate.vm, &value),
});
candidate.vm.release_value(value)?;
snapshot?
}
@@ -141,7 +141,15 @@ pub fn evaluate(source: &str) -> Result<String> {
}
fn compile_plan(source: &SourceUnit, plan: &SourcePlan) -> Result<Vec<compiler::CompiledCode>> {
compile_plan_with_globals(source, plan, BTreeSet::from(["ui".to_owned()]))
compile_plan_with_globals(
source,
plan,
std::iter::once("ui")
.chain(ui_bridge::TYPE_NAMES.iter().copied())
.chain(ui_bridge::QUERY_NAMES.iter().copied())
.map(str::to_owned)
.collect(),
)
}
fn compile_plan_with_globals(
@@ -156,8 +164,11 @@ fn compile_plan_with_globals(
if let AstRoot::Interactive(input) = root {
for statement in &input.statements {
if let StmtKind::Declaration(decl) = &statement.kind {
let DeclKind::Function(function) = &decl.kind;
globals.insert(function.name.text.clone());
let name = match &decl.kind {
DeclKind::Function(function) => &function.name,
DeclKind::Class(class) => &class.name,
};
globals.insert(name.text.clone());
}
}
}
@@ -185,7 +196,7 @@ fn compile_plan_with_globals(
}
/// One real VM, owned only by the existing execution worker. No history replay.
/// The UI bridge's fixed pools are session-wide and reclaimed by explicit reset.
/// The UI bridge shares the same managed object heap and publishes atomic frames.
pub struct ReplSession {
candidate: Candidate,
bridge: ui_bridge::UiBridge,
@@ -194,6 +205,8 @@ pub struct ReplSession {
ast_nodes: usize,
source: String,
nodes: Vec<CodeNode>,
faulted: bool,
program_root: Option<CodeNode>,
}
pub struct ReplResult {
pub value: String,
@@ -202,15 +215,88 @@ pub struct ReplResult {
pub input: usize,
}
impl ReplSession {
/// Compile once into an isolated candidate, then keep its actual heap and
/// callback environments alive after the first successful publication.
pub fn load(
source: &str,
namespace: &str,
submission: u64,
id: u64,
) -> Result<(Self, RenderDocument)> {
if source.len() > MAX_SOURCE_BYTES {
bail!("source exceeds the 1 MiB limit");
}
let unit = EndorReader::from_text(format!("{namespace} [submission {submission}]"), source);
let plan = endor_script::parse(&unit)?;
let mut budget = AstBudget::default();
for ast in plan.roots() {
budget.visit_ast_root(ast)?;
}
let compiled = compile_plan(&unit, &plan)?;
let mut runtime = Self::new(id)?;
let globals = runtime.candidate.globals.expect("program globals");
let limits = if matches!(plan, SourcePlan::Script(_)) {
ExecutionLimits {
max_instructions: LIMITS.max_instructions / compiled.len().max(1),
..LIMITS
}
} else {
LIMITS
};
for template in &compiled {
let code = template.load(&mut runtime.candidate.vm)?;
let result = runtime
.candidate
.vm
.execute_with_limits(code, globals, limits)
.map_err(|error| runtime_error(&runtime.candidate.vm, error));
runtime.candidate.vm.release(code)?;
runtime.candidate.vm.release_value(result?)?;
}
if matches!(plan, SourcePlan::Module(_)) {
let main = runtime
.candidate
.vm
.dict_get(globals, &Value::Text("main".into()))?
.ok_or_else(|| anyhow::anyhow!("declare a main function"))?;
let Value::Object(main) = main else {
bail!("main must be callable");
};
let value = runtime
.candidate
.vm
.call_with_limits(main, &[], LIMITS)
.map_err(|error| runtime_error(&runtime.candidate.vm, error))?;
let opened = if runtime.bridge.has_page()? {
Ok(())
} else {
runtime.bridge.open_value(&mut runtime.candidate.vm, &value)
};
runtime.candidate.vm.release_value(value)?;
opened?;
}
if !runtime.bridge.has_page()? {
bail!("script must call page.render(root) or ui.open(value)");
}
runtime.source = source.into();
runtime.ast_nodes = budget.nodes;
runtime.program_root = Some(architecture(&unit, &plan, namespace, submission));
let document = runtime
.refresh_document()?
.ok_or_else(|| anyhow::anyhow!("program did not publish a Page"))?;
runtime
.bridge
.reclaim(&mut runtime.candidate.vm, &mut runtime.candidate.roots)?;
Ok((runtime, document))
}
pub fn new(id: u64) -> Result<Self> {
let mut candidate = Candidate::new()?;
let globals = candidate.vm.new_dict()?;
candidate.globals = Some(globals);
candidate.roots.push(globals);
let bridge = ui_bridge::install(&mut candidate.vm, &mut candidate.roots)?;
candidate
.vm
.dict_set(globals, Value::Text("ui".into()), Value::Object(bridge.ui))?;
bridge.install_globals(&mut candidate.vm, globals)?;
Ok(Self {
candidate,
bridge,
@@ -219,9 +305,16 @@ impl ReplSession {
ast_nodes: 0,
source: String::new(),
nodes: Vec::new(),
faulted: false,
program_root: None,
})
}
pub fn execute(&mut self, source: &str, namespace: &str) -> Result<ReplResult> {
if self.faulted {
bail!(
"runtime stopped after an event failure; reset the session or replace its program"
);
}
if source.len() > MAX_SOURCE_BYTES {
bail!("input exceeds 1 MiB");
}
@@ -257,11 +350,17 @@ impl ReplSession {
let compiled = compile_plan_with_globals(&source, &plan, names)?;
// Parsing/compilation finish before any new statement runs. Successful earlier
// statements in a runtime-failed input remain live, as in an ordinary REPL.
self.bridge.discard_pending()?;
self.bridge.discard_pending(&mut self.candidate.vm)?;
self.bridge
.reclaim(&mut self.candidate.vm, &mut self.candidate.roots)?;
self.inputs += 1;
self.ast_nodes += budget.nodes;
if let Some(root) = self.program_root.take() {
self.nodes.push(root);
}
if !self.source.is_empty() && !self.source.ends_with('\n') {
self.source.push('\n');
}
let offset = line_starts(&self.source).len();
self.source
.push_str(&format!("// Console input {}\n", self.inputs));
@@ -269,7 +368,12 @@ impl ReplSession {
if !self.source.ends_with('\n') {
self.source.push('\n');
}
let mut node = architecture(&source, &plan, namespace, self.inputs as u64);
let mut node = architecture(
&source,
&plan,
&format!("{namespace}:console-{}", self.id),
self.inputs as u64,
);
node.name = format!("Input {}", self.inputs);
shift_node_lines(&mut node, offset);
self.nodes.push(node);
@@ -315,30 +419,7 @@ impl ReplSession {
retained?;
rendered_value = repr?;
}
let document = if let Some(root) = self.bridge.prepare_frame()? {
let document = RenderDocument {
source: self.source.clone(),
root: Some(CodeNode {
id: format!("console-session-{}", self.id),
name: format!("Console session {}", self.id),
kind: "repl-session".into(),
start_line: 1,
end_line: self.source.lines().count(),
children: self.nodes.clone(),
}),
frame: root
.as_ref()
.map(|root| layout::frame(root))
.transpose()?
.unwrap_or_default(),
ui_root: root.clone(),
};
document.validate()?;
self.bridge.commit_frame(root)?;
Some(document)
} else {
None
};
let document = self.refresh_document()?;
Ok(ReplResult {
value: rendered_value,
document,
@@ -352,7 +433,7 @@ impl ReplSession {
})
})();
if result.is_err() {
self.bridge.discard_pending()?;
self.bridge.discard_pending(&mut self.candidate.vm)?;
if let Some(node) = self.nodes.last_mut() {
node.name
.push_str(" (error; earlier statements may remain live)");
@@ -362,6 +443,83 @@ impl ReplSession {
.reclaim(&mut self.candidate.vm, &mut self.candidate.roots)?;
result
}
fn refresh_document(&mut self) -> Result<Option<RenderDocument>> {
let mut last = None;
let mut work = 0;
let mut mutated_mounts = false;
let result = (|| loop {
let Some(root) = self.bridge.prepare_frame(&mut self.candidate.vm)? else {
return Ok(last);
};
let mut document = RenderDocument {
source: self.source.clone(),
root: Some(self.program_root.clone().unwrap_or_else(|| CodeNode {
id: format!("console-session-{}", self.id),
name: format!("Console session {}", self.id),
kind: "repl-session".into(),
start_line: 1,
end_line: self.source.lines().count(),
children: self.nodes.clone(),
})),
frame: root
.as_ref()
.map(|root| self.bridge.layout_frame(&self.candidate.vm, root))
.transpose()?
.unwrap_or_default(),
ui_root: root.clone(),
};
document.frame.session = self.id;
document.validate()?;
work += document.frame.mounts.len().max(1);
if work > 200_000 {
bail!("layout dependencies did not stabilize within the rendering work budget");
}
mutated_mounts = true;
self.bridge
.commit_frame(&mut self.candidate.vm, root, &document.frame)?;
last = Some(document);
})();
if result.is_err() && mutated_mounts {
self.faulted = true;
}
result
}
pub fn is_faulted(&self) -> bool {
self.faulted
}
pub fn dispatch(&mut self, input: &crate::events::Input) -> Result<ReplResult> {
if self.faulted {
bail!("runtime stopped after an event failure");
}
if input.session != self.id {
bail!("event belongs to another runtime session");
}
let result = (|| {
self.bridge.dispatch(&mut self.candidate.vm, input)?;
let document = self.refresh_document()?;
Ok(ReplResult {
value: "nil".into(),
document,
bindings: self
.candidate
.vm
.dict_items(self.candidate.globals.expect("live globals"))?
.len()
.saturating_sub(1),
input: self.inputs,
})
})();
if result.is_err() {
self.faulted = true;
self.bridge.discard_pending(&mut self.candidate.vm)?;
}
self.bridge
.reclaim(&mut self.candidate.vm, &mut self.candidate.roots)?;
result
}
}
fn shift_node_lines(node: &mut CodeNode, offset: usize) {
node.start_line += offset;
@@ -530,7 +688,21 @@ impl Architecture {
}
fn declaration(&mut self, declaration: &Decl) -> CodeNode {
let DeclKind::Function(function) = &declaration.kind;
match &declaration.kind {
DeclKind::Function(function) => self.function(function),
DeclKind::Class(class) => {
let mut children: Vec<_> = class
.fields
.iter()
.map(|field| self.node(field.name.text.clone(), "field", field.span, vec![]))
.collect();
children.extend(class.methods.iter().map(|method| self.function(method)));
self.node(class.name.text.clone(), "class", class.span, children)
}
}
}
fn function(&mut self, function: &frontend::ast::Function) -> CodeNode {
let children = function
.body
.statements
@@ -547,6 +719,16 @@ impl Architecture {
fn statement(&mut self, statement: &Stmt) -> CodeNode {
match &statement.kind {
StmtKind::MemberAssignment(assignment) => {
let object = self.expression(&assignment.object);
let value = self.expression(&assignment.value);
self.node(
assignment.name.text.clone(),
"member-assign",
statement.span,
vec![object, value],
)
}
StmtKind::Binding(binding) => {
let child = self.expression(&binding.value);
self.node(
@@ -613,6 +795,124 @@ mod tests {
const EXAMPLE: &str = include_str!("../examples/hello.endor");
const PAGE: &str = include_str!("../examples/page.endor");
#[test]
fn loaded_program_console_and_native_events_share_unique_source_ids() {
let (mut session, initial) = ReplSession::load(
include_str!("../examples/managed-types.endor"),
"app.main",
1,
1,
)
.unwrap();
initial.validate().unwrap();
assert_eq!(
session
.execute("isInstance(page, Block)", "app.main")
.unwrap()
.value,
"true"
);
let mount = initial
.frame
.mounts
.iter()
.find(|mount| mount.interactive)
.unwrap();
let event = crate::events::Input {
session: 1,
layout_version: initial.frame.layout_version,
mount: mount.id,
kind: "click".into(),
};
let updated = session.dispatch(&event).unwrap().document.unwrap();
updated.validate().unwrap();
assert_eq!(
updated
.frame
.commands
.iter()
.filter(|command| matches!(command,
RenderCommand::Text { value, .. } if value == "10"
))
.count(),
2
);
assert!(!session.is_faulted());
}
#[test]
fn native_method_callbacks_update_two_explicit_bindings() {
let mut session = ReplSession::new(21).unwrap();
session.execute("counter = ui.state(9)\nfirst = ui.textOf(counter, \"value\")\nsecond = ui.textOf(counter, \"value\")\nbutton = ui.button(\"increment\")\nfunction increment(): Unit { counter.increment() }\nbutton.onClick(increment)\npage = ui.page()\npage.render(ui.row(0, 8, first, second, button))", "app.main").unwrap();
let updated = session
.execute("button.click()", "app.main")
.unwrap()
.document
.unwrap();
let texts: Vec<_> = updated
.frame
.commands
.iter()
.filter_map(|command| match command {
RenderCommand::Text { value, .. } => Some(value.as_str()),
_ => None,
})
.collect();
assert_eq!(&texts[..2], &["10", "10"]);
}
#[test]
fn closing_a_page_releases_its_root_without_retaining_it_through_shared_content() {
let mut session = ReplSession::new(22).unwrap();
session
.execute(
"card = ui.rect(10, 20)\npage = ui.page()\npage.render(card)",
"app.main",
)
.unwrap();
let globals = session.candidate.globals.unwrap();
let Value::Object(page) = session
.candidate
.vm
.dict_get(globals, &Value::Text("page".into()))
.unwrap()
.unwrap()
else {
panic!("expected Page")
};
let weak = session.candidate.vm.downgrade(page).unwrap();
session.execute("page.close()", "app.main").unwrap();
session
.execute("card.setColor(\"#FFEEDD\")", "app.main")
.unwrap();
assert!(
session
.execute("page.open()", "app.main")
.unwrap()
.document
.is_some()
);
session.execute("page.close()", "app.main").unwrap();
session
.candidate
.vm
.dict_delete(globals, &Value::Text("page".into()))
.unwrap();
session
.bridge
.reclaim(&mut session.candidate.vm, &mut session.candidate.roots)
.unwrap();
assert!(session.candidate.vm.upgrade(weak).unwrap().is_none());
assert!(
session
.candidate
.vm
.dict_get(globals, &Value::Text("card".into()))
.unwrap()
.is_some()
);
}
#[test]
fn mounted_aliases_update_nested_positions_unmount_and_reject_cycles() {
let mut session = ReplSession::new(10).unwrap();
@@ -776,8 +1076,14 @@ mod tests {
assert_eq!(document.display_list(2.0).unwrap().commands().len(), 3);
let wrapped = compile(include_str!("../examples/main.endor"), "app.main", 10).unwrap();
assert_eq!(
serde_json::to_value(&document.frame).unwrap(),
serde_json::to_value(&wrapped.frame).unwrap()
serde_json::to_value(&document.frame.commands).unwrap(),
serde_json::to_value(&wrapped.frame.commands).unwrap()
);
// Separate VM instances render the same commands with independent
// managed object identities and presentation contexts.
assert_ne!(
document.frame.mounts[0].block_id,
wrapped.frame.mounts[0].block_id
);
}
@@ -874,7 +1180,7 @@ paint(ui.text("last"))"#;
}
#[test]
fn page_creation_has_a_separate_bounded_pool() {
fn page_creation_has_a_separate_live_object_budget() {
let mut source = String::new();
for index in 0..=ui_bridge::MAX_PAGES {
source.push_str(&format!("let page{index} = ui.page()\n"));
@@ -917,10 +1223,9 @@ paint(ui.text("last"))"#;
fn developer_selection_resets_to_the_new_source_snapshot() {
let first = compile(PAGE, "app.main", 1).unwrap();
let second = compile(PAGE, "app.main", 2).unwrap();
let mut tools = crate::developer_tools::DeveloperToolsState {
open: true,
selected_node_id: Some(first.root.as_ref().unwrap().children[0].id.clone()),
};
let mut tools = crate::developer_tools::DeveloperToolsState::default();
tools.open = true;
tools.selected_node_id = Some(first.root.as_ref().unwrap().children[0].id.clone());
tools.document_updated(&second);
assert_eq!(
tools.selected_node_id.as_deref(),
@@ -1060,13 +1365,13 @@ function main(): View { let child = ui.text("shared") return wrap(child) }"#;
assert!(error.to_string().contains("4096 node budget"), "{error:#}");
let error = compile(&nested_functions(14, true), "app.main", 2).unwrap_err();
assert!(
error.to_string().contains("expanded UI layout"),
error.to_string().contains("expanded Block graph"),
"{error:#}"
);
}
#[test]
fn ui_depth_is_bounded_independently_of_call_frames() {
fn managed_ui_depth_is_not_truncated_at_64_levels() {
let mut source = "function node0(): View { return ui.text(\"x\") }\n".to_owned();
for index in 1..=64 {
source.push_str(&format!(
@@ -1075,8 +1380,8 @@ function main(): View { let child = ui.text("shared") return wrap(child) }"#;
));
}
source.push_str("function main(): View { return node64() }");
let error = compile(&source, "app.main", 1).unwrap_err();
assert!(error.to_string().contains("64 levels"), "{error:#}");
let document = compile(&source, "app.main", 1).unwrap();
assert_eq!(document.frame.commands.len(), 1);
}
#[test]
+27 -1
View File
@@ -103,6 +103,12 @@ fn shift_statement(statement: &mut Stmt, offset: usize) {
shift_span(&mut assignment.name.span, offset);
shift_expression(&mut assignment.value, offset);
}
StmtKind::MemberAssignment(assignment) => {
shift_span(&mut assignment.span, offset);
shift_span(&mut assignment.name.span, offset);
shift_expression(&mut assignment.object, offset);
shift_expression(&mut assignment.value, offset);
}
StmtKind::Return(returned) => {
shift_span(&mut returned.span, offset);
if let Some(expression) = &mut returned.value {
@@ -116,7 +122,27 @@ fn shift_statement(statement: &mut Stmt, offset: usize) {
fn shift_declaration(declaration: &mut Decl, offset: usize) {
shift_span(&mut declaration.span, offset);
let DeclKind::Function(function) = &mut declaration.kind;
match &mut declaration.kind {
DeclKind::Function(function) => shift_function(function, offset),
DeclKind::Class(class) => {
shift_span(&mut class.span, offset);
shift_span(&mut class.name.span, offset);
if let Some(base) = &mut class.base {
shift_span(&mut base.span, offset);
}
for field in &mut class.fields {
shift_span(&mut field.span, offset);
shift_span(&mut field.name.span, offset);
shift_span(&mut field.type_name.span, offset);
}
for method in &mut class.methods {
shift_function(method, offset);
}
}
}
}
fn shift_function(function: &mut frontend::ast::Function, offset: usize) {
shift_span(&mut function.span, offset);
shift_span(&mut function.name.span, offset);
shift_span(&mut function.return_type.span, offset);
+88
View File
@@ -0,0 +1,88 @@
//! Native input transport. Only opaque frame/mount identities cross to the VM worker.
use endor_core::ObjectPayload;
use serde::{Deserialize, Serialize};
use std::{
io::{Read, Write},
net::TcpStream,
sync::mpsc::{SyncSender, sync_channel},
thread,
time::Duration,
};
use winit::event_loop::EventLoopProxy;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Input {
pub session: u64,
pub layout_version: u64,
pub mount: u64,
pub kind: String,
}
#[derive(Debug)]
pub struct Event;
impl ObjectPayload for Event {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn kind_name(&self) -> &'static str {
"tessera-event"
}
fn allows_attributes(&self) -> bool {
true
}
}
pub struct Client(SyncSender<Input>);
impl Client {
pub fn new(proxy: EventLoopProxy<crate::app::AppEvent>) -> anyhow::Result<Self> {
let (sender, receiver) = sync_channel::<Input>(8);
thread::Builder::new()
.name("tessera-native-events".into())
.spawn(move || {
for input in receiver {
if let Err(error) = send(&input) {
let _ = proxy.send_event(crate::app::AppEvent::RuntimeFailed {
message: error.to_string(),
});
}
}
})?;
Ok(Self(sender))
}
pub fn send(&self, input: Input) -> bool {
self.0.try_send(input).is_ok()
}
}
fn send(input: &Input) -> anyhow::Result<()> {
let body = serde_json::to_string(input)?;
let mut stream =
TcpStream::connect_timeout(&crate::api::API_ADDRESS.parse()?, Duration::from_secs(2))?;
stream.set_read_timeout(Some(Duration::from_secs(10)))?;
stream.set_write_timeout(Some(Duration::from_secs(2)))?;
write!(
stream,
"POST /v1/namespaces/app.main/events HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
body.len(),
body
)?;
let mut response = String::new();
stream.take(32768).read_to_string(&mut response)?;
let status = response.split_whitespace().nth(1).unwrap_or("");
// An old frame's event is deliberately discarded, with no automatic retry.
if status == "409" {
return Ok(());
}
if status != "200" {
let body = response
.split_once("\r\n\r\n")
.map(|(_, body)| body)
.unwrap_or(&response);
anyhow::bail!(
"Native event failed: {}",
body.chars().take(1024).collect::<String>()
);
}
Ok(())
}
+269 -107
View File
@@ -1,25 +1,50 @@
//! Layout consumes only owned native UI data, after the candidate VM is gone.
use anyhow::{Result, bail};
//! Iterative measure/arrange/paint over derived visual data. Every occurrence
//! has its own geometry; measurement caches never become semantic object state.
use crate::{
document::{Frame, RenderCommand},
document::{Frame, MountGeometry, RenderCommand},
text::{self, TextStyle},
ui_bridge::{MAX_DIMENSION, UiKind, UiNode},
};
use anyhow::{Context as _, Result, bail};
use std::collections::{HashMap, HashSet};
const MAX_LAYOUT_VISITS: usize = 10_000;
#[derive(Default, Clone, Copy)]
struct Size {
width: f32,
height: f32,
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct Size {
pub width: f32,
pub height: f32,
}
pub fn frame(root: &UiNode) -> Result<Frame> {
let mut frame = Frame::default();
let mut visits = 0;
layout(root, 0.0, 0.0, &mut frame.commands, &mut visits)?;
Ok(frame)
#[derive(Debug, Clone, PartialEq)]
enum Shape {
Text(String, u32),
Rect(f32, f32),
Container(bool, f32, f32, Vec<Size>),
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
struct Key {
parent: Option<u64>,
slot: u64,
block: String,
}
#[derive(Debug, Clone, Default)]
pub struct LayoutRuntime {
sizes: HashMap<String, (Shape, Size)>,
ids: HashMap<Key, u64>,
next_id: u64,
pub version: u64,
pub measured: usize,
pub arranged: usize,
}
struct Item<'a> {
node: &'a UiNode,
parent: Option<usize>,
children: Vec<usize>,
id: u64,
}
fn bounded(value: f32) -> Result<f32> {
@@ -29,99 +54,236 @@ fn bounded(value: f32) -> Result<f32> {
Ok(value)
}
fn layout(
node: &UiNode,
x: f32,
y: f32,
commands: &mut Vec<RenderCommand>,
visits: &mut usize,
) -> Result<Size> {
*visits += 1;
if *visits > MAX_LAYOUT_VISITS {
bail!("expanded UI layout exceeds 10000 nodes");
fn container(node: &UiNode) -> Option<(bool, f32, f32)> {
match &node.kind {
UiKind::Row { padding, gap, .. } => Some((true, *padding, *gap)),
UiKind::Column { padding, gap, .. } | UiKind::Button { padding, gap, .. } => {
Some((false, *padding, *gap))
}
_ => None,
}
bounded(x)?;
bounded(y)?;
let size = match &node.kind {
UiKind::Text { value, size, color } => {
commands.push(RenderCommand::Text {
x,
y,
value: value.clone(),
size: *size,
color: color.clone(),
});
let measured = text::measure(value, TextStyle::ui(*size));
Size {
width: measured.width,
height: measured.height,
}
}
UiKind::Rect {
width,
height,
radius,
color,
} => {
commands.push(RenderCommand::RoundedRect {
x,
y,
width: *width,
height: *height,
radius: *radius,
color: color.clone(),
});
Size {
width: *width,
height: *height,
}
}
UiKind::Spacer(size) => Size {
width: *size,
height: *size,
},
UiKind::Column {
padding,
gap,
children,
}
| UiKind::Row {
padding,
gap,
children,
} => {
let row = matches!(node.kind, UiKind::Row { .. });
let mut cursor = *padding;
let mut cross: f32 = 0.0;
for (index, child) in children.iter().enumerate() {
if index > 0 {
cursor = bounded(cursor + gap)?;
}
let (child_x, child_y) = if row {
(x + cursor, y + padding)
} else {
(x + padding, y + cursor)
};
let size = layout(child, child_x, child_y, commands, visits)?;
cursor = bounded(cursor + if row { size.width } else { size.height })?;
cross = cross.max(if row { size.height } else { size.width });
}
let along = bounded(cursor + padding)?;
let across = bounded(cross + padding * 2.0)?;
if row {
Size {
width: along,
height: across,
}
} else {
Size {
width: across,
height: along,
}
}
}
};
bounded(x + size.width)?;
bounded(y + size.height)?;
Ok(size)
}
impl LayoutRuntime {
pub fn clear_occurrences(&mut self) {
self.ids.clear();
}
pub fn frame(&mut self, root: &UiNode) -> Result<Frame> {
// Stage all cache/identity changes; a rejected frame leaves the last
// valid occurrence registry intact and never publishes partial geometry.
let mut next = self.clone();
let frame = next.build(root)?;
*self = next;
Ok(frame)
}
fn build(&mut self, root: &UiNode) -> Result<Frame> {
self.measured = 0;
self.arranged = 0;
let mut items = Vec::<Item<'_>>::new();
let mut work = vec![(root, None::<usize>, 0)];
let mut used = HashSet::new();
while let Some((node, parent, slot)) = work.pop() {
if items.len() >= MAX_LAYOUT_VISITS {
bail!("expanded UI layout exceeds 10000 nodes");
}
if node.slots.len() != node.children().len() {
bail!("invalid child slot table");
}
let key = Key {
parent: parent.map(|i| items[i].id),
slot,
block: node.block_id.clone(),
};
let id = if let Some(id) = self.ids.get(&key) {
*id
} else {
self.next_id = self
.next_id
.checked_add(1)
.context("Mount identity exhausted")?;
self.ids.insert(key.clone(), self.next_id);
self.next_id
};
if !used.insert(key) {
bail!("duplicate child slot in one presentation");
}
let index = items.len();
if let Some(parent) = parent {
items[parent].children.push(index);
}
items.push(Item {
node,
parent,
children: vec![],
id,
});
for (child, slot) in node.children().iter().zip(&node.slots).rev() {
work.push((child.as_ref(), Some(index), *slot));
}
}
let mut sizes = vec![Size::default(); items.len()];
for (index, item) in items.iter().enumerate().rev() {
let shape = match &item.node.kind {
UiKind::Text { value, size, .. } => Shape::Text(value.clone(), *size),
UiKind::Rect { width, height, .. } => Shape::Rect(*width, *height),
UiKind::Spacer(size) => Shape::Rect(*size, *size),
_ => {
let (row, padding, gap) =
container(item.node).context("unknown native visual protocol")?;
Shape::Container(
row,
padding,
gap,
item.children.iter().map(|i| sizes[*i]).collect(),
)
}
};
let size = if let Some((old_shape, size)) = self
.sizes
.get(&item.node.block_id)
.filter(|(old, _)| *old == shape)
{
let _ = old_shape;
*size
} else {
self.measured += 1;
let size = match &shape {
Shape::Text(value, size) => {
let result = text::measure(value, TextStyle::ui(*size));
Size {
width: result.width,
height: result.height,
}
}
Shape::Rect(width, height) => Size {
width: *width,
height: *height,
},
Shape::Container(row, padding, gap, children) => {
let along = children
.iter()
.map(|s| if *row { s.width } else { s.height })
.sum::<f32>()
+ padding * 2.0
+ gap * children.len().saturating_sub(1) as f32;
let cross = children
.iter()
.map(|s| if *row { s.height } else { s.width })
.fold(0.0_f32, f32::max)
+ padding * 2.0;
if *row {
Size {
width: along,
height: cross,
}
} else {
Size {
width: cross,
height: along,
}
}
}
};
bounded(size.width)?;
bounded(size.height)?;
self.sizes.insert(item.node.block_id.clone(), (shape, size));
size
};
sizes[index] = size;
}
let mut points = vec![(0.0_f32, 0.0_f32); items.len()];
let mut mounts = Vec::with_capacity(items.len());
let mut commands = Vec::new();
let mut siblings = vec![None; items.len()];
for item in &items {
for pair in item.children.windows(2) {
siblings[pair[0]] = Some(items[pair[1]].id);
}
}
for (index, item) in items.iter().enumerate() {
self.arranged += 1;
let (x, y) = points[index];
let size = sizes[index];
bounded(x)?;
bounded(y)?;
bounded(x + size.width)?;
bounded(y + size.height)?;
mounts.push(MountGeometry {
id: item.id,
block_id: item.node.block_id.clone(),
parent: item.parent.map(|i| items[i].id),
first_child: item.children.first().map(|i| items[*i].id),
next_sibling: siblings[index],
x,
y,
width: size.width,
height: size.height,
interactive: item.node.interactive,
});
match &item.node.kind {
UiKind::Text { value, size, color } => commands.push(RenderCommand::Text {
x,
y,
value: value.clone(),
size: *size,
color: color.clone(),
}),
UiKind::Rect { radius, color, .. } => commands.push(RenderCommand::RoundedRect {
x,
y,
width: size.width,
height: size.height,
radius: *radius,
color: color.clone(),
}),
UiKind::Button { .. } => commands.push(RenderCommand::RoundedRect {
x,
y,
width: size.width,
height: size.height,
radius: 7.0,
color: "#E3EAF7".into(),
}),
_ => {}
}
if let Some((row, padding, gap)) = container(item.node) {
let mut cursor = padding;
for child in &item.children {
points[*child] = if row {
(x + cursor, y + padding)
} else {
(x + padding, y + cursor)
};
cursor += if row {
sizes[*child].width
} else {
sizes[*child].height
};
cursor += gap;
}
}
}
self.ids.retain(|key, _| used.contains(key));
let blocks: HashSet<_> = items
.iter()
.map(|item| item.node.block_id.as_str())
.collect();
self.sizes
.retain(|block, _| blocks.contains(block.as_str()));
self.version = self
.version
.checked_add(1)
.context("layout version exhausted")?;
Ok(Frame {
commands,
mounts,
layout_version: self.version,
..Frame::default()
})
}
}
pub fn frame(root: &UiNode) -> Result<Frame> {
LayoutRuntime::default().frame(root)
}
-165
View File
@@ -1,165 +0,0 @@
//! Shared native UI references. No VM handles, source replay or variable-name tracking.
use crate::ui_bridge::{MAX_UI_DEPTH, UiKind, UiNode};
use anyhow::{Result, bail};
use std::sync::{Arc, RwLock};
#[derive(Debug, Clone)]
pub enum LiveKind {
Leaf(UiKind),
Column {
padding: f32,
gap: f32,
children: Vec<Arc<LiveNode>>,
},
Row {
padding: f32,
gap: f32,
children: Vec<Arc<LiveNode>>,
},
Forward(Arc<LiveNode>),
}
#[derive(Debug)]
pub struct LiveNode {
kind: RwLock<LiveKind>,
}
impl LiveNode {
pub fn new(kind: LiveKind) -> Arc<Self> {
Arc::new(Self {
kind: RwLock::new(kind),
})
}
fn kind(&self) -> Result<LiveKind> {
Ok(self
.kind
.read()
.map_err(|_| anyhow::anyhow!("UI reference is poisoned"))?
.clone())
}
pub fn replace(&self, target: Arc<Self>) -> Result<()> {
// Assigning an alias of this same reference is a no-op, not a forwarding cycle.
let mut current = target.clone();
for _ in 0..=MAX_UI_DEPTH {
if std::ptr::eq(self, current.as_ref()) {
return Ok(());
}
match current.kind()? {
LiveKind::Forward(next) => current = next,
_ => break,
}
}
let mut visits = 0;
inspect(
&target,
Some(self),
&mut vec![self as *const LiveNode],
&mut visits,
)?;
*self
.kind
.write()
.map_err(|_| anyhow::anyhow!("UI reference is poisoned"))? = LiveKind::Forward(target);
Ok(())
}
pub fn snapshot(&self) -> Result<Arc<UiNode>> {
let mut visits = 0;
inspect(self, None, &mut Vec::new(), &mut visits)
}
}
fn inspect(
node: &LiveNode,
forbidden: Option<&LiveNode>,
path: &mut Vec<*const LiveNode>,
visits: &mut usize,
) -> Result<Arc<UiNode>> {
*visits += 1;
if *visits > 10_000 {
bail!("expanded UI graph exceeds 10000 nodes");
}
if path.len() >= MAX_UI_DEPTH {
bail!("UI reference graph exceeds 64 levels");
}
let identity = node as *const LiveNode;
if forbidden.is_some_and(|old| std::ptr::eq(node, old)) || path.contains(&identity) {
bail!("UI assignment would create a reference cycle");
}
path.push(identity);
let kind = match node.kind()? {
LiveKind::Leaf(kind) => kind,
LiveKind::Forward(target) => {
let result = inspect(&target, forbidden, path, visits);
path.pop();
return result;
}
LiveKind::Column {
padding,
gap,
children,
} => UiKind::Column {
padding,
gap,
children: children
.iter()
.map(|child| inspect(child, forbidden, path, visits))
.collect::<Result<_>>()?,
},
LiveKind::Row {
padding,
gap,
children,
} => UiKind::Row {
padding,
gap,
children: children
.iter()
.map(|child| inspect(child, forbidden, path, visits))
.collect::<Result<_>>()?,
},
};
path.pop();
Ok(Arc::new(UiNode { kind }))
}
#[cfg(test)]
mod tests {
use super::*;
fn leaf(value: &str) -> Arc<LiveNode> {
LiveNode::new(LiveKind::Leaf(UiKind::Text {
value: value.into(),
size: 1,
color: "#243047".into(),
}))
}
#[test]
fn replacement_releases_detached_branch_and_preserves_aliases() {
let child = leaf("old");
let weak = Arc::downgrade(&child);
let root = LiveNode::new(LiveKind::Column {
padding: 0.0,
gap: 0.0,
children: vec![child],
});
let alias = root.clone();
root.replace(leaf("new")).unwrap();
assert!(weak.upgrade().is_none());
assert!(
matches!(&alias.snapshot().unwrap().kind, UiKind::Text { value, .. } if value == "new")
);
root.replace(alias).unwrap();
assert!(root.snapshot().is_ok());
}
#[test]
fn self_containing_replacement_is_rejected_before_mutation() {
let root = leaf("kept");
let cycle = LiveNode::new(LiveKind::Row {
padding: 0.0,
gap: 0.0,
children: vec![root.clone()],
});
assert!(root.replace(cycle).is_err());
assert!(
matches!(&root.snapshot().unwrap().kind, UiKind::Text { value, .. } if value == "kept")
);
}
}
+5 -2
View File
@@ -1,16 +1,19 @@
mod activity;
mod api;
mod app;
mod block;
mod clipboard;
mod developer_tools;
mod display_list;
mod document;
mod endor_host;
mod endor_script;
mod events;
mod geometry;
mod layout;
mod live_ui;
mod mount;
mod scene;
mod snapshot;
mod software_renderer;
mod sources;
mod system_ui;
@@ -29,7 +32,7 @@ fn main() -> Result<()> {
event_loop.set_control_flow(ControlFlow::Wait);
let namespace = Arc::new(RwLock::new(NamespaceState::default()));
let activity = api::start(namespace.clone(), event_loop.create_proxy())?;
let mut app = TesseraApp::new(namespace, activity, event_loop.create_proxy());
let mut app = TesseraApp::new(namespace, activity, event_loop.create_proxy())?;
event_loop.run_app(&mut app)?;
Ok(())
}
+390
View File
@@ -0,0 +1,390 @@
//! Managed presentation contexts. The active desktop owns the mount dictionary;
//! reverse links and the host registry are weak, so shared content cannot retain a Page.
use crate::document::{Frame, MountGeometry};
use endor_core::{
ContextNativeFunction, NativeCallable, NativeContext, NativeResult, ObjectPayload, ObjectRef,
Value, Vm, VmError, WeakObjectRef,
};
use std::{
collections::HashMap,
sync::{Arc, Mutex},
};
#[derive(Debug, Clone)]
pub struct Mount {
pub block: ObjectRef,
pub page: Option<WeakObjectRef>,
pub parent: Option<WeakObjectRef>,
pub first_child: Option<WeakObjectRef>,
pub next_sibling: Option<WeakObjectRef>,
pub geometry: MountGeometry,
pub version: u64,
pub mounted: bool,
}
impl ObjectPayload for Mount {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn kind_name(&self) -> &'static str {
"tessera-mount"
}
fn allows_attributes(&self) -> bool {
true
}
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
visit(self.block);
}
}
#[derive(Debug, Clone, Copy)]
enum Query {
Bounds,
Parent,
FirstChild,
NextSibling,
Page,
Focus,
HitTest,
}
#[derive(Debug)]
struct Method {
owner: ObjectRef,
desktop: ObjectRef,
query: Query,
}
impl NativeCallable for Method {
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
let mount = cx.store().payload::<Mount>(self.owner, "Mount")?.clone();
if !mount.mounted {
return Err(VmError::InvalidArgument("Mount is no longer attached"));
}
let arity = if matches!(self.query, Query::HitTest) {
2
} else {
0
};
if args.len() != arity {
return Err(VmError::InvalidArgument("incorrect Mount method arity"));
}
let value = match self.query {
Query::Bounds => {
let bounds = cx.new_object()?;
for (name, value) in [
("x", mount.geometry.x),
("y", mount.geometry.y),
("width", mount.geometry.width),
("height", mount.geometry.height),
] {
cx.set_attr(bounds, name, Value::Number((value as f64).into()))?;
}
cx.set_attr(
bounds,
"layoutVersion",
Value::Number((mount.version as i64).into()),
)?;
Value::Object(bounds)
}
Query::Focus => {
if !mount.geometry.interactive {
return Err(VmError::InvalidArgument("Mount is not focusable"));
}
cx.set_attr(
self.desktop,
"focus",
Value::Number((mount.geometry.id as i64).into()),
)?;
cx.set_attr(self.desktop, "focusRequested", Value::Bool(true))?;
Value::Nil
}
Query::HitTest => {
let number = |value: &Value| -> Result<f32, VmError> {
let Value::Number(number) = value else {
return Err(VmError::InvalidArgument(
"point coordinates must be numbers",
));
};
let number = number
.to_string()
.parse::<f32>()
.map_err(|_| VmError::InvalidArgument("invalid point coordinate"))?;
if !number.is_finite() {
return Err(VmError::InvalidArgument("invalid point coordinate"));
}
Ok(number)
};
Value::Bool(
crate::geometry::Rect::new(
mount.geometry.x,
mount.geometry.y,
mount.geometry.width,
mount.geometry.height,
)
.contains(crate::geometry::Point::new(
number(&args[0])?,
number(&args[1])?,
)),
)
}
query => {
let weak = match query {
Query::Parent => mount.parent,
Query::FirstChild => mount.first_child,
Query::NextSibling => mount.next_sibling,
Query::Page => mount.page,
_ => unreachable!(),
};
weak.map(|weak| cx.upgrade(weak))
.transpose()?
.flatten()
.map(Value::Object)
.unwrap_or(Value::Nil)
}
};
Ok(NativeResult::Return(value))
}
}
#[derive(Debug, Default, Clone)]
pub struct MountTable {
pub active: HashMap<u64, WeakObjectRef>,
}
#[derive(Debug)]
struct Sync {
desktop: ObjectRef,
page: Option<ObjectRef>,
nodes: Vec<WeakObjectRef>,
old: HashMap<u64, WeakObjectRef>,
frame: Frame,
output: Arc<Mutex<HashMap<u64, WeakObjectRef>>>,
}
impl NativeCallable for Sync {
fn invoke(&self, cx: &mut NativeContext<'_>, _args: &[Value]) -> Result<NativeResult, VmError> {
let mut blocks = HashMap::new();
for weak in &self.nodes {
if let Some(block) = cx.upgrade(*weak)? {
blocks.insert(block.to_string(), block);
}
}
let page = self
.page
.map(|page| cx.store().downgrade(page))
.transpose()?;
let mut objects = HashMap::new();
for geometry in &self.frame.mounts {
let block = *blocks
.get(&geometry.block_id)
.ok_or(VmError::InvalidArgument(
"frame references an unavailable Block",
))?;
let old = self
.old
.get(&geometry.id)
.map(|weak| cx.upgrade(*weak))
.transpose()?
.flatten();
let object = if let Some(old) = old {
old
} else {
let object = cx.allocate(Mount {
block,
page,
parent: None,
first_child: None,
next_sibling: None,
geometry: geometry.clone(),
version: self.frame.layout_version,
mounted: true,
})?;
crate::ui_bridge::attach_desktop_type(cx, object, "Mount", self.desktop)?;
for (name, query) in [
("bounds", Query::Bounds),
("parent", Query::Parent),
("firstChild", Query::FirstChild),
("nextSibling", Query::NextSibling),
("page", Query::Page),
("requestFocus", Query::Focus),
("hitTest", Query::HitTest),
] {
let function = cx.allocate(ContextNativeFunction::new(
name,
Method {
owner: object,
desktop: self.desktop,
query,
},
vec![object, self.desktop],
))?;
cx.set_attr(object, name, Value::Object(function))?;
}
cx.set_attr(object, "id", Value::Number((geometry.id as i64).into()))?;
cx.set_attr(object, "block", Value::Object(block))?;
object
};
objects.insert(geometry.id, object);
}
let root = cx.new_dict()?;
for geometry in &self.frame.mounts {
let object = objects[&geometry.id];
let link = |id: Option<u64>| -> Result<Option<WeakObjectRef>, VmError> {
id.map(|id| cx.store().downgrade(objects[&id])).transpose()
};
let mount = Mount {
block: blocks[&geometry.block_id],
page,
parent: link(geometry.parent)?,
first_child: link(geometry.first_child)?,
next_sibling: link(geometry.next_sibling)?,
geometry: geometry.clone(),
version: self.frame.layout_version,
mounted: true,
};
let old = cx.store().payload::<Mount>(object, "Mount")?;
if !old.mounted
|| old.geometry != mount.geometry
|| old.page != mount.page
|| old.parent != mount.parent
|| old.first_child != mount.first_child
|| old.next_sibling != mount.next_sibling
|| matches!(
cx.store().get_attr(object, "mounted"),
Err(VmError::AttributeNotFound(_))
)
{
cx.replace_payload(object, mount)?;
cx.set_attr(object, "mounted", Value::Bool(true))?;
cx.set_attr(
object,
"layoutVersion",
Value::Number((self.frame.layout_version as i64).into()),
)?;
}
cx.dict_set(
root,
Value::Text(geometry.id.to_string()),
Value::Object(object),
)?;
}
for (id, weak) in &self.old {
if !objects.contains_key(id)
&& let Some(object) = cx.upgrade(*weak)?
{
let mut mount = cx.store().payload::<Mount>(object, "Mount")?.clone();
mount.mounted = false;
mount.parent = None;
mount.first_child = None;
mount.next_sibling = None;
cx.replace_payload(object, mount)?;
cx.set_attr(object, "mounted", Value::Bool(false))?;
}
}
let weak = objects
.into_iter()
.map(|(id, object)| Ok((id, cx.store().downgrade(object)?)))
.collect::<Result<HashMap<_, _>, VmError>>()?;
cx.set_attr(self.desktop, "mounts", Value::Object(root))?;
*self
.output
.lock()
.map_err(|_| VmError::InvalidArgument("Mount registry poisoned"))? = weak;
Ok(NativeResult::Return(Value::Nil))
}
}
impl MountTable {
pub fn synchronize(
&mut self,
vm: &mut Vm,
desktop: ObjectRef,
page: Option<ObjectRef>,
nodes: Vec<WeakObjectRef>,
frame: &Frame,
) -> Result<(), VmError> {
let output = Arc::new(Mutex::new(HashMap::new()));
let mut captures = vec![desktop];
captures.extend(page);
let function = vm.allocate(ContextNativeFunction::new(
"mount-sync",
Sync {
desktop,
page,
nodes,
old: self.active.clone(),
frame: frame.clone(),
output: output.clone(),
},
captures,
))?;
let result = vm.call(function, &[]);
vm.release(function)?;
vm.release_value(result?)?;
self.active = std::mem::take(
&mut *output
.lock()
.map_err(|_| VmError::InvalidArgument("Mount registry poisoned"))?,
);
Ok(())
}
}
#[derive(Debug)]
struct MountSet(Vec<ObjectRef>);
impl ObjectPayload for MountSet {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn kind_name(&self) -> &'static str {
"tessera-mount-set"
}
fn allows_attributes(&self) -> bool {
true
}
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
for mount in &self.0 {
visit(*mount);
}
}
}
#[derive(Debug)]
struct At(ObjectRef);
impl NativeCallable for At {
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
let [Value::Number(index)] = args else {
return Err(VmError::InvalidArgument("mount set at expects an index"));
};
let index = index
.as_i64()
.and_then(|v| usize::try_from(v).ok())
.ok_or(VmError::InvalidArgument("invalid mount index"))?;
let mount = *cx
.store()
.payload::<MountSet>(self.0, "Mount set")?
.0
.get(index)
.ok_or(VmError::InvalidArgument("mount index out of range"))?;
Ok(NativeResult::Return(Value::Object(mount)))
}
}
pub fn collection(
cx: &mut NativeContext<'_>,
mounts: Vec<ObjectRef>,
) -> Result<ObjectRef, VmError> {
let first = mounts
.first()
.copied()
.map(Value::Object)
.unwrap_or(Value::Nil);
let count = mounts.len();
let set = cx.allocate(MountSet(mounts))?;
cx.set_attr(set, "first", first)?;
cx.set_attr(set, "count", Value::Number((count as i64).into()))?;
let at = cx.allocate(ContextNativeFunction::new("at", At(set), vec![set]))?;
cx.set_attr(set, "at", Value::Object(at))?;
Ok(set)
}
+237
View File
@@ -0,0 +1,237 @@
//! 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 visited: usize,
pub reused: usize,
}
impl RenderCache {
pub fn invalidate(&mut self, batch: ChangeBatch) {
let mut queue = VecDeque::new();
if batch.rescan_required {
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) {
queue.extend(owners);
}
}
}
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"));
}
}
let (data_ref, data, raw_dependencies) = block::resolve_tracked(store, block)?;
let mut dependencies: Vec<_> = raw_dependencies
.into_iter()
.map(|object| Dependency {
object,
property: None,
})
.collect();
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 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 {
dependencies.push(Dependency {
object: *source,
property: Some(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::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 {
block_id: block.to_string(),
slots: data.children.iter().map(|c| c.slot).collect(),
interactive: matches!(&data.kind, Kind::Button) || data.click.is_some(),
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"))
}
}
+1128 -489
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -3,7 +3,7 @@
| Entry | Purpose |
| --- | --- |
| `README.md` | Source checkout, version selection, and update instructions |
| [aster](aster/README.md) | Unmodified `endorphin-aster-vm` Git submodule; provides the Endor frontend, compiler, objects, and VM |
| [aster](aster/README.md) | `endorphin-aster-vm` source submodule; provides the Endor frontend, compiler, objects, and VM |
## Checkout
+1 -1