diff --git a/README.md b/README.md index 2289bbc..0d8d982 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/examples/README.md b/examples/README.md index 94b4a02..1aa7854 100644 --- a/examples/README.md +++ b/examples/README.md @@ -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. | diff --git a/examples/classes.endor b/examples/classes.endor new file mode 100644 index 0000000..70f527d --- /dev/null +++ b/examples/classes.endor @@ -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)) diff --git a/examples/managed-types.endor b/examples/managed-types.endor new file mode 100644 index 0000000..91bc438 --- /dev/null +++ b/examples/managed-types.endor @@ -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))) diff --git a/src/README.md b/src/README.md index 1b0ba43..07f10db 100644 --- a/src/README.md +++ b/src/README.md @@ -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. diff --git a/src/api.rs b/src/api.rs index 20cc1ee..b846593 100644 --- a/src/api.rs +++ b/src/api.rs @@ -27,6 +27,7 @@ type Notify = Arc; #[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>, notify: &Notify, ) -> Response>> { - 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 = ¤t.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>, + notify: &Notify, + ) -> Response>> { + 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, diff --git a/src/app.rs b/src/app.rs index 13f0073..8a59f69 100644 --- a/src/app.rs +++ b/src/app.rs @@ -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, + guest_focus: Option, + guest_key: Option<(NamedKey, crate::events::Input)>, + guest_keyboard: bool, } impl TesseraApp { @@ -45,8 +51,9 @@ impl TesseraApp { namespace: Arc>, activity: Activity, proxy: EventLoopProxy, - ) -> Self { - Self { + ) -> anyhow::Result { + 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 { + if self.guest_covered(self.pointer) { + return None; + } + let current = self.namespace.read().ok()?; + let frame = ¤t.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 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 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 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 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 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(); diff --git a/src/block.rs b/src/block.rs new file mode 100644 index 0000000..b9dfa22 --- /dev/null +++ b/src/block.rs @@ -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, 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::() { + Ok(Some(value)) + } else { + store.payload::(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, VmError> { + if !store.object(source)?.payload().as_any().is::() { + return Ok(None); + } + if store.payload::(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, + pub padding: f32, + pub gap: f32, + pub next_slot: u64, + pub history: Vec, + pub history_index: usize, + pub text_binding: Option<(ObjectRef, String)>, + pub click: Option, +} + +impl Data { + pub fn new(kind: Kind, children: Vec, 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 { + 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), 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::(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::() { + dependencies.push(value); + return Ok(( + value, + store.payload::(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, +) -> 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")?.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::(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, VmError> { + crate::snapshot::RenderCache::default().snapshot(store, root) +} diff --git a/src/developer_tools.rs b/src/developer_tools.rs index e77b831..755d513 100644 --- a/src/developer_tools.rs +++ b/src/developer_tools.rs @@ -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" }; diff --git a/src/document.rs b/src/document.rs index 2ebefb7..7d89b41 100644 --- a/src/document.rs +++ b/src/document.rs @@ -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 { - 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, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub mounts: Vec, + #[serde(default)] + pub layout_version: u64, + #[serde(default)] + pub session: u64, + #[serde(default)] + pub focus: Option, + #[serde(default)] + pub fault: Option, } 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, + pub first_child: Option, + pub next_sibling: Option, + 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() } diff --git a/src/endor_host.rs b/src/endor_host.rs index 3271e4d..4d36bfc 100644 --- a/src/endor_host.rs +++ b/src/endor_host.rs @@ -40,9 +40,7 @@ pub fn compile(source: &str, namespace: &str, submission: u64) -> Result LIMITS, SourcePlan::Script(_) => ExecutionLimits { @@ -61,7 +59,7 @@ pub fn compile(source: &str, namespace: &str, submission: u64) -> Result 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 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 { } fn compile_plan(source: &SourceUnit, plan: &SourcePlan) -> Result> { - 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, + faulted: bool, + program_root: Option, } 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 { 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 { + 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> { + 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 { + 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] diff --git a/src/endor_script.rs b/src/endor_script.rs index 9c01907..af0bc4e 100644 --- a/src/endor_script.rs +++ b/src/endor_script.rs @@ -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); diff --git a/src/events.rs b/src/events.rs new file mode 100644 index 0000000..1703c8b --- /dev/null +++ b/src/events.rs @@ -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); +impl Client { + pub fn new(proxy: EventLoopProxy) -> anyhow::Result { + let (sender, receiver) = sync_channel::(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::() + ); + } + Ok(()) +} diff --git a/src/layout.rs b/src/layout.rs index f169e3d..5d03c5c 100644 --- a/src/layout.rs +++ b/src/layout.rs @@ -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 { - 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), +} + +#[derive(Debug, Clone, Hash, PartialEq, Eq)] +struct Key { + parent: Option, + slot: u64, + block: String, +} + +#[derive(Debug, Clone, Default)] +pub struct LayoutRuntime { + sizes: HashMap, + ids: HashMap, + next_id: u64, + pub version: u64, + pub measured: usize, + pub arranged: usize, +} + +struct Item<'a> { + node: &'a UiNode, + parent: Option, + children: Vec, + id: u64, } fn bounded(value: f32) -> Result { @@ -29,99 +54,236 @@ fn bounded(value: f32) -> Result { Ok(value) } -fn layout( - node: &UiNode, - x: f32, - y: f32, - commands: &mut Vec, - visits: &mut usize, -) -> Result { - *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 { + // 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 { + self.measured = 0; + self.arranged = 0; + let mut items = Vec::>::new(); + let mut work = vec![(root, None::, 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::() + + 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 { + LayoutRuntime::default().frame(root) } diff --git a/src/live_ui.rs b/src/live_ui.rs deleted file mode 100644 index 1455605..0000000 --- a/src/live_ui.rs +++ /dev/null @@ -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>, - }, - Row { - padding: f32, - gap: f32, - children: Vec>, - }, - Forward(Arc), -} - -#[derive(Debug)] -pub struct LiveNode { - kind: RwLock, -} -impl LiveNode { - pub fn new(kind: LiveKind) -> Arc { - Arc::new(Self { - kind: RwLock::new(kind), - }) - } - fn kind(&self) -> Result { - Ok(self - .kind - .read() - .map_err(|_| anyhow::anyhow!("UI reference is poisoned"))? - .clone()) - } - pub fn replace(&self, target: Arc) -> 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> { - 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> { - *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::>()?, - }, - LiveKind::Row { - padding, - gap, - children, - } => UiKind::Row { - padding, - gap, - children: children - .iter() - .map(|child| inspect(child, forbidden, path, visits)) - .collect::>()?, - }, - }; - path.pop(); - Ok(Arc::new(UiNode { kind })) -} - -#[cfg(test)] -mod tests { - use super::*; - fn leaf(value: &str) -> Arc { - 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") - ); - } -} diff --git a/src/main.rs b/src/main.rs index 0ba7e70..c18e775 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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(()) } diff --git a/src/mount.rs b/src/mount.rs new file mode 100644 index 0000000..a272e11 --- /dev/null +++ b/src/mount.rs @@ -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, + pub parent: Option, + pub first_child: Option, + pub next_sibling: Option, + 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 { + let mount = cx.store().payload::(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 { + let Value::Number(number) = value else { + return Err(VmError::InvalidArgument( + "point coordinates must be numbers", + )); + }; + let number = number + .to_string() + .parse::() + .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, +} + +#[derive(Debug)] +struct Sync { + desktop: ObjectRef, + page: Option, + nodes: Vec, + old: HashMap, + frame: Frame, + output: Arc>>, +} + +impl NativeCallable for Sync { + fn invoke(&self, cx: &mut NativeContext<'_>, _args: &[Value]) -> Result { + 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| -> Result, 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::(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::(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::, 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, + nodes: Vec, + 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); +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 { + 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::(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, +) -> Result { + 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) +} diff --git a/src/snapshot.rs b/src/snapshot.rs new file mode 100644 index 0000000..06dd997 --- /dev/null +++ b/src/snapshot.rs @@ -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, + dependencies: Vec, + children: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +struct Dependency { + object: ObjectRef, + property: Option, +} + +#[derive(Debug, Default)] +pub struct RenderCache { + entries: HashMap, + dependents: HashMap>, + parents: HashMap>, + dirty: HashSet, + 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 { + 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, VmError> { + self.visited = 0; + self.reused = 0; + let mut work = vec![(root, false)]; + let mut path = HashSet::new(); + let mut values = Vec::>::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")) + } +} diff --git a/src/ui_bridge.rs b/src/ui_bridge.rs index 1c5e014..63d536f 100644 --- a/src/ui_bridge.rs +++ b/src/ui_bridge.rs @@ -1,30 +1,136 @@ -//! Tessera-owned UI payloads using Aster's existing embedding interface. -use std::{ - any::Any, - collections::{HashMap, HashSet}, - sync::{Arc, Mutex}, -}; +//! Tessera's native visual protocols over Aster's managed object graph. +use std::sync::{Arc, Mutex}; use anyhow::{Result, bail}; -use endor_core::{EndorReal, ObjectPayload, ObjectRef, Value, Vm, VmError}; +use endor_core::{ + ContextNativeFunction, EndorReal, NativeCallable, NativeContext, NativeResult, ObjectRef, + TypeConstructor, Value, Vm, VmError, WeakObjectRef, +}; use crate::{ + block::{self, Child, Data, Kind}, document::parse_color, - live_ui::{LiveKind, LiveNode}, }; pub const MAX_UI_NODES: usize = 4096; -pub const MAX_UI_DEPTH: usize = 64; pub const MAX_PAGES: usize = 64; pub const MAX_DIMENSION: f64 = 1_000_000.0; +pub const TYPE_NAMES: &[&str] = &[ + "Object", + "Type", + "Function", + "Block", + "ContainerBlock", + "TextBlock", + "RectBlock", + "Spacer", + "Row", + "Column", + "Button", + "Page", + "Mount", + "Event", +]; +pub const QUERY_NAMES: &[&str] = &["isInstance", "isSubtype"]; + #[derive(Debug, Clone, PartialEq)] pub struct UiNode { + pub block_id: String, + pub slots: Vec, + pub interactive: bool, pub kind: UiKind, } +impl UiNode { + pub fn children(&self) -> &[Arc] { + match &self.kind { + UiKind::Column { children, .. } + | UiKind::Row { children, .. } + | UiKind::Button { children, .. } => children, + _ => &[], + } + } + + pub fn shallow_eq(&self, other: &Self) -> bool { + if self.block_id != other.block_id + || self.slots != other.slots + || self.interactive != other.interactive + { + return false; + } + let same_children = || { + self.children().len() == other.children().len() + && self + .children() + .iter() + .zip(other.children()) + .all(|(a, b)| Arc::ptr_eq(a, b)) + }; + match (&self.kind, &other.kind) { + ( + UiKind::Text { + value: a, + size: sa, + color: ca, + }, + UiKind::Text { + value: b, + size: sb, + color: cb, + }, + ) => a == b && sa == sb && ca == cb, + ( + UiKind::Rect { + width: a, + height: b, + radius: c, + color: d, + }, + UiKind::Rect { + width: e, + height: f, + radius: g, + color: h, + }, + ) => (a, b, c, d) == (e, f, g, h), + (UiKind::Spacer(a), UiKind::Spacer(b)) => a == b, + ( + UiKind::Column { + padding: a, gap: b, .. + }, + UiKind::Column { + padding: c, gap: d, .. + }, + ) + | ( + UiKind::Row { + padding: a, gap: b, .. + }, + UiKind::Row { + padding: c, gap: d, .. + }, + ) + | ( + UiKind::Button { + padding: a, gap: b, .. + }, + UiKind::Button { + padding: c, gap: d, .. + }, + ) => a == c && b == d && same_children(), + _ => false, + } + } +} + #[derive(Debug, Clone, PartialEq)] pub enum UiKind { + Button { + padding: f32, + gap: f32, + children: Vec>, + }, Text { value: String, size: u32, @@ -50,537 +156,1070 @@ pub enum UiKind { } #[derive(Debug)] -struct NodePayload(UiSlot); - -type UiSlot = Arc>>>; - -impl ObjectPayload for NodePayload { - fn as_any(&self) -> &dyn Any { - self - } - fn kind_name(&self) -> &'static str { - "tessera-ui-node" - } - fn assign_from(&self, source: &dyn ObjectPayload) -> Result { - let Some(source) = source.as_any().downcast_ref::() else { - return Ok(false); - }; - let old = self - .0 - .lock() - .map_err(|_| VmError::InvalidArgument("UI slot is poisoned"))? - .clone() - .ok_or(VmError::InvalidArgument("UI reference is uninitialized"))?; - let new = source - .0 - .lock() - .map_err(|_| VmError::InvalidArgument("UI slot is poisoned"))? - .clone() - .ok_or(VmError::InvalidArgument("UI source is uninitialized"))?; - old.replace(new).map_err(|_| { - VmError::InvalidArgument("UI assignment creates a cycle or exceeds graph limits") - })?; - Ok(true) - } -} - -#[derive(Debug)] -struct BuildSession { - // Borrowed handles only. Candidate owns every pool root until extraction - // and execution have finished. Native child edges contain Arc, - // never VM handles, so payload-owned GC edges remain empty and immutable. - pool: Vec<(ObjectRef, UiSlot)>, - indexes: HashMap, - free: Vec, - pages: Vec, - initialized_pages: Vec, - page_functions: Vec<(ObjectRef, ObjectRef)>, - native_roots: HashSet, - mounts: Vec>>, - active: Option, - pending: Option<(usize, Option>)>, +struct Session { + desktop: ObjectRef, + tabs: ObjectRef, + active: Option, + pending: Option>, + nodes: Vec, last_snapshot: Option>, + render_cache: crate::snapshot::RenderCache, + layout: crate::layout::LayoutRuntime, + mounts: crate::mount::MountTable, + published_version: u64, + snapshot_visited: usize, + snapshot_reused: usize, } - -impl BuildSession { - fn page(&mut self) -> Result { - let index = self - .initialized_pages - .iter() - .position(|used| !*used) - .ok_or(VmError::InvalidArgument( - "UI session exceeds 64 retained pages", - ))?; - self.initialized_pages[index] = true; - Ok(Value::Object(self.pages[index])) - } - fn child(&self, value: &Value) -> Result, VmError> { - let Value::Object(reference) = value else { - return Err(VmError::InvalidArgument("UI children must be UI nodes")); - }; - let index = self.indexes.get(reference).ok_or(VmError::InvalidArgument( - "UI child belongs to another session", - ))?; - self.pool[*index] - .1 - .lock() - .map_err(|_| VmError::InvalidArgument("UI slot is poisoned"))? - .clone() - .ok_or(VmError::InvalidArgument("UI child is uninitialized")) - } - fn emit(&mut self, kind: LiveKind) -> Result { - let node = LiveNode::new(kind); - node.snapshot() - .map_err(|_| VmError::InvalidArgument("UI graph exceeds depth or node limits"))?; - let index = self.free.pop().ok_or(VmError::InvalidArgument( - "UI session exceeds 4096 retained nodes", - ))?; - let (reference, slot) = &self.pool[index]; - *slot - .lock() - .map_err(|_| VmError::InvalidArgument("UI slot is poisoned"))? = Some(node); - Ok(Value::Object(*reference)) - } -} +type Shared = Arc>; #[derive(Debug, Clone, Copy)] -enum Constructor { +enum Operation { + IsInstance, + IsSubtype, + OpenValue, + Mounts, + Stats, + State, + StateSet, + Increment, + TextOf, Text, Rect, - Column, - Row, Spacer, + Row, + Column, + Button, Page, -} - -impl Constructor { - fn name(self) -> &'static str { - match self { - Self::Text => "text", - Self::Rect => "rect", - Self::Column => "column", - Self::Row => "row", - Self::Spacer => "spacer", - Self::Page => "page", - } - } + SetText, + SetColor, + Append, + Remove, + Replace, + Move, + Children, + Render, + Unmount, + Open, + Close, + Activate, + Navigate, + Back, + Forward, + OnClick, + Click, + Present, } #[derive(Debug)] -struct UiConstructor { - constructor: Constructor, - session: Arc>, +struct Function { + operation: Operation, + owner: Option, + session: Shared, } -impl ObjectPayload for UiConstructor { - fn as_any(&self) -> &dyn Any { - self - } - fn kind_name(&self) -> &'static str { - "tessera-ui-constructor" - } +/// One shared implementation on the nominal type. The VM binds receivers; +/// individual Blocks no longer allocate owner-capturing method closures. +#[derive(Debug)] +struct TypeMethod { + operation: Operation, + expected: ObjectRef, + session: Shared, +} - fn call(&self, arguments: &[Value]) -> Result { - let constructor = self.constructor; - let (required, maximum) = match constructor { - Constructor::Text => (1, 3), - Constructor::Rect => (2, 4), - Constructor::Column | Constructor::Row => (2, MAX_UI_NODES + 2), - Constructor::Spacer => (1, 1), - Constructor::Page => (0, 0), - }; - if !(required..=maximum).contains(&arguments.len()) { - return Err(VmError::ArgumentCount { - name: format!("ui.{}", constructor.name()), - required, - maximum, - provided: arguments.len(), - }); +impl NativeCallable for TypeMethod { + fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result { + let owner = object(args.first())?; + if !cx.store().is_instance(owner, self.expected)? { + return Err(invalid("incorrect receiver type for visual method")); } - let mut session = self - .session - .lock() - .map_err(|_| VmError::InvalidArgument("UI build session is poisoned"))?; - let kind = match constructor { - Constructor::Text => { - let Value::Text(value) = &arguments[0] else { - return Err(VmError::InvalidArgument("ui.text expects a string")); - }; - if value.len() > 16_384 { - return Err(VmError::InvalidArgument("UI text exceeds 16 KiB")); + Function { + operation: self.operation, + owner: Some(owner), + session: self.session.clone(), + } + .invoke(cx, &args[1..]) + } +} + +fn invalid(message: &'static str) -> VmError { + VmError::InvalidArgument(message) +} +fn object(value: Option<&Value>) -> Result { + match value { + Some(Value::Object(value)) => Ok(*value), + _ => Err(invalid("expected an object")), + } +} +fn text(value: Option<&Value>) -> Result { + match value { + Some(Value::Text(value)) => Ok(value.clone()), + _ => Err(invalid("expected text")), + } +} +fn integer(value: Option<&Value>) -> Result { + match value { + Some(Value::Number(value)) => value + .as_i64() + .and_then(|v| u64::try_from(v).ok()) + .ok_or(invalid("expected a nonnegative integer")), + _ => Err(invalid("expected a nonnegative integer")), + } +} +fn color(value: Option<&Value>, default: &str) -> Result { + let value = value + .map(|v| text(Some(v))) + .transpose()? + .unwrap_or_else(|| default.into()); + parse_color(&value).map_err(|_| invalid("color must use #RRGGBB or #RRGGBBAA"))?; + Ok(value) +} +fn dimension(value: Option<&Value>) -> Result { + let Some(Value::Number(number)) = value else { + return Err(invalid("expected a finite nonnegative dimension")); + }; + let value = match number.as_real() { + Some(EndorReal::Integer(v)) => v.to_string().parse::().ok(), + Some(EndorReal::Decimal(v)) => v.literal().parse::().ok(), + Some(EndorReal::BinaryFloat(v)) => Some(f64::from_bits(*v)), + _ => None, + } + .filter(|v| v.is_finite() && (0.0..=MAX_DIMENSION).contains(v)) + .ok_or(invalid("dimension exceeds limits"))?; + Ok(value as f32) +} + +fn bind( + cx: &mut NativeContext<'_>, + owner: ObjectRef, + name: &'static str, + operation: Operation, + session: &Shared, +) -> Result<(), VmError> { + let desktop = session + .lock() + .map_err(|_| invalid("UI session poisoned"))? + .desktop; + let function = cx.allocate(ContextNativeFunction::new( + name, + Function { + operation, + owner: Some(owner), + session: session.clone(), + }, + vec![owner, desktop], + ))?; + attach_desktop_type(cx, function, "Function", desktop)?; + cx.set_attr(owner, name, Value::Object(function)) +} + +fn new_block( + cx: &mut NativeContext<'_>, + data: Data, + session: &Shared, +) -> Result { + let type_name = match data.kind { + Kind::Text { .. } => "TextBlock", + Kind::Rect { .. } => "RectBlock", + Kind::Spacer(_) => "Spacer", + Kind::Row => "Row", + Kind::Column => "Column", + Kind::Button => "Button", + Kind::Page => "Page", + }; + let page = matches!(data.kind, Kind::Page); + let block = block::allocate(cx, data)?; + attach_named_type(cx, block, type_name, session)?; + { + let mut state = session.lock().map_err(|_| invalid("UI session poisoned"))?; + if state.nodes.len() >= MAX_UI_NODES { + return Err(VmError::ExecutionLimit("4096 node budget")); + } + if page { + let mut pages = 0; + for weak in &state.nodes { + if let Some(node) = cx.upgrade(*weak)? + && cx.store().payload::(node, "Block")?.page + { + pages += 1; } - let size = if let Some(value) = arguments.get(1) { - let Value::Number(number) = value else { - return Err(VmError::InvalidArgument( - "text size must be an integer from 1 to 8", - )); - }; - number - .as_i64() - .filter(|size| (1..=8).contains(size)) - .ok_or(VmError::InvalidArgument( - "text size must be an integer from 1 to 8", - ))? as u32 - } else { - 1 - }; - LiveKind::Leaf(UiKind::Text { - value: value.clone(), - size, - color: color(arguments.get(2), "#242422")?, - }) } - Constructor::Rect => LiveKind::Leaf(UiKind::Rect { - width: dimension(&arguments[0])?, - height: dimension(&arguments[1])?, - radius: arguments.get(2).map(dimension).transpose()?.unwrap_or(0.0), - color: color(arguments.get(3), "#DCE8FF")?, - }), - Constructor::Column | Constructor::Row => { - let padding = dimension(&arguments[0])?; - let gap = dimension(&arguments[1])?; - let children = arguments[2..] + if pages >= MAX_PAGES { + return Err(VmError::ExecutionLimit("64 page budget")); + } + } + state.nodes.push(cx.store().downgrade(block)?); + } + Ok(block) +} + +fn show(cx: &mut NativeContext<'_>, page: ObjectRef, session: &Shared) -> Result<(), VmError> { + let mut state = session.lock().map_err(|_| invalid("UI session poisoned"))?; + cx.dict_set( + state.tabs, + Value::Text(page.to_string()), + Value::Object(page), + )?; + cx.set_attr(state.desktop, "pending", Value::Object(page))?; + state.pending = Some(Some(page)); + Ok(()) +} + +fn present_value( + cx: &mut NativeContext<'_>, + value: &Value, + session: &Shared, +) -> Result { + if let Value::Object(block) = value + && cx + .store() + .object(*block)? + .payload() + .as_any() + .is::() + { + return Ok(*block); + } + let value = match value { + Value::Nil => "nil".into(), + Value::Bool(v) => v.to_string(), + Value::Number(v) => v.to_string(), + Value::Text(v) => v.clone(), + Value::Object(v) => cx.store().repr(*v)?, + }; + if value.len() > 16_384 { + return Err(invalid("presentation exceeds 16 KiB")); + } + new_block( + cx, + Data::new( + Kind::Text { + value, + size: 1, + color: "#242422".into(), + }, + vec![], + 0.0, + 0.0, + ), + session, + ) +} + +impl NativeCallable for Function { + fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result { + use Operation::*; + let (minimum, maximum) = match self.operation { + IsInstance | IsSubtype => (2, 2), + Stats | Mounts => (0, 0), + State | StateSet => (1, 1), + Increment => (0, 0), + TextOf => (2, 4), + Text => (1, 3), + Rect => (2, 4), + OpenValue | Spacer | SetText | SetColor | Append | Remove | Render | Navigate + | OnClick | Present => (1, 1), + Row | Column => (2, MAX_UI_NODES + 2), + Button => (1, 1), + Replace | Move => (2, 2), + Page | Unmount | Open | Close | Activate | Back | Forward | Children => (0, 0), + Click => (0, 1), + }; + if !(minimum..=maximum).contains(&args.len()) { + return Err(invalid("incorrect UI method argument count")); + } + if matches!(self.operation, IsInstance | IsSubtype) { + let candidate = object(args.first())?; + let expected = object(args.get(1))?; + let value = if matches!(self.operation, IsInstance) { + cx.store().is_instance(candidate, expected)? + } else { + cx.store().is_subtype(candidate, expected)? + }; + return Ok(NativeResult::Return(Value::Bool(value))); + } + if matches!(self.operation, Mounts) { + let owner = self.owner.ok_or(invalid("mount query requires a Block"))?; + let session = self + .session + .lock() + .map_err(|_| invalid("UI session poisoned"))?; + let mut positions = Vec::new(); + for (id, weak) in &session.mounts.active { + if let Some(object) = cx.upgrade(*weak)? + && cx + .store() + .payload::(object, "Mount")? + .block + == owner + { + positions.push((*id, object)); + } + } + positions.sort_unstable_by_key(|(id, _)| *id); + let set = crate::mount::collection( + cx, + positions.into_iter().map(|(_, object)| object).collect(), + )?; + return Ok(NativeResult::Return(Value::Object(set))); + } + if matches!(self.operation, Stats) { + let session = self + .session + .lock() + .map_err(|_| invalid("UI session poisoned"))?; + let mut blocks = 0_i64; + let mut pages = 0_i64; + for weak in &session.nodes { + if let Some(object) = cx.upgrade(*weak)? { + blocks += 1; + if cx.store().payload::(object, "Block")?.page { + pages += 1; + } + } + } + let objects = cx.store().object_count() as i64; + let tabs = cx.store().dict_items(session.tabs)?.len() as i64; + let stats = cx.new_object()?; + for (name, value) in [ + ("objects", objects), + ("blocks", blocks), + ("pages", pages), + ("tabs", tabs), + ("mounts", session.mounts.active.len() as i64), + ("snapshotVisited", session.snapshot_visited as i64), + ("snapshotReused", session.snapshot_reused as i64), + ("measured", session.layout.measured as i64), + ("arranged", session.layout.arranged as i64), + ] { + cx.set_attr(stats, name, Value::Number(value.into()))?; + } + return Ok(NativeResult::Return(Value::Object(stats))); + } + if matches!(self.operation, State) { + let state = cx.new_object()?; + attach_named_type(cx, state, "Object", &self.session)?; + cx.set_attr(state, "value", args[0].clone())?; + bind(cx, state, "set", StateSet, &self.session)?; + bind(cx, state, "increment", Increment, &self.session)?; + return Ok(NativeResult::Return(Value::Object(state))); + } + if matches!(self.operation, StateSet | Increment) { + let owner = self.owner.ok_or(invalid("state method has no owner"))?; + let value = if matches!(self.operation, StateSet) { + args[0].clone() + } else { + let Value::Number(value) = cx.store().get_attr(owner, "value")? else { + return Err(invalid("increment requires an integer state")); + }; + let next = value + .as_i64() + .and_then(|n| n.checked_add(1)) + .ok_or(invalid("integer state increment exceeds its range"))?; + Value::Number(next.into()) + }; + cx.set_attr(owner, "value", value)?; + return Ok(NativeResult::Return(Value::Nil)); + } + if matches!(self.operation, TextOf) { + let source = object(args.first())?; + let field = text(args.get(1))?; + cx.store().get_attr(source, &field)?; + let size = args + .get(2) + .map(|v| integer(Some(v))) + .transpose()? + .unwrap_or(1); + if !(1..=8).contains(&size) { + return Err(invalid("text size must be 1 through 8")); + } + let mut data = Data::new( + Kind::Text { + value: String::new(), + size: size as u32, + color: color(args.get(3), "#242422")?, + }, + vec![], + 0.0, + 0.0, + ); + data.text_binding = Some((source, field)); + return Ok(NativeResult::Return(Value::Object(new_block( + cx, + data, + &self.session, + )?))); + } + let constructor = match self.operation { + Text => Some(Data::new( + Kind::Text { + value: text(args.first())?, + size: args + .get(1) + .map(|v| integer(Some(v))) + .transpose()? + .unwrap_or(1) + .try_into() + .map_err(|_| invalid("text size exceeds limits"))?, + color: color(args.get(2), "#242422")?, + }, + vec![], + 0.0, + 0.0, + )), + Rect => Some(Data::new( + Kind::Rect { + width: dimension(args.first())?, + height: dimension(args.get(1))?, + radius: args + .get(2) + .map(|v| dimension(Some(v))) + .transpose()? + .unwrap_or(0.0), + color: color(args.get(3), "#DCE8FF")?, + }, + vec![], + 0.0, + 0.0, + )), + Spacer => Some(Data::new( + Kind::Spacer(dimension(args.first())?), + vec![], + 0.0, + 0.0, + )), + Row | Column => Some(Data::new( + if matches!(self.operation, Row) { + Kind::Row + } else { + Kind::Column + }, + args[2..] .iter() - .map(|value| session.child(value)) - .collect::, _>>()?; - if matches!(constructor, Constructor::Column) { - LiveKind::Column { - padding, - gap, - children, + .map(|v| object(Some(v))) + .collect::>()?, + dimension(args.first())?, + dimension(args.get(1))?, + )), + Page => Some(Data::new(Kind::Page, vec![], 0.0, 0.0)), + Button => { + let label = new_block( + cx, + Data::new( + Kind::Text { + value: text(args.first())?, + size: 1, + color: "#243047".into(), + }, + vec![], + 0.0, + 0.0, + ), + &self.session, + )?; + Some(Data::new(Kind::Button, vec![label], 10.0, 0.0)) + } + _ => None, + }; + if let Some(data) = constructor { + if let Kind::Text { size, value, .. } = &data.kind + && (!(1..=8).contains(size) || value.len() > 16_384) + { + return Err(invalid("text exceeds size limits")); + } + return Ok(NativeResult::Return(Value::Object(new_block( + cx, + data, + &self.session, + )?))); + } + if matches!(self.operation, OpenValue) { + let root = present_value(cx, &args[0], &self.session)?; + let page = if cx.store().payload::(root, "Block")?.page { + root + } else { + new_block( + cx, + Data::new(Kind::Page, vec![root], 0.0, 0.0), + &self.session, + )? + }; + show(cx, page, &self.session)?; + return Ok(NativeResult::Return(Value::Object(page))); + } + if matches!(self.operation, Present) { + return Ok(NativeResult::Return(Value::Object(present_value( + cx, + &args[0], + &self.session, + )?))); + } + let owner = self.owner.ok_or(invalid("method has no owner"))?; + let (data_ref, data) = block::resolve(cx.store(), owner)?; + let mut data = data.clone(); + let mut result = Value::Nil; + match self.operation { + SetText => match &mut data.kind { + Kind::Text { value, .. } => { + let next = text(args.first())?; + if next.len() > 16_384 { + return Err(invalid("text exceeds 16 KiB")); } + *value = next; + data.text_binding = None; + } + _ => return Err(invalid("setText requires a text Block")), + }, + SetColor => match &mut data.kind { + Kind::Text { color: value, .. } | Kind::Rect { color: value, .. } => { + *value = color(args.first(), "#242422")? + } + _ => return Err(invalid("this Block has no color")), + }, + Append | Remove | Replace | Move => { + if !data.is_container() { + return Err(invalid("expected a container Block")); + } + if matches!(self.operation, Append) { + let child = object(args.first())?; + block::validate(cx.store(), child, Some(data_ref))?; + let slot = data.next_slot; + data.next_slot = slot.checked_add(1).ok_or(VmError::IdentityExhausted)?; + data.children.push(Child { slot, block: child }); + result = Value::Number((slot as i64).into()); } else { - LiveKind::Row { - padding, - gap, - children, + let slot = integer(args.first())?; + let index = data + .children + .iter() + .position(|v| v.slot == slot) + .ok_or(invalid("child slot does not exist"))?; + match self.operation { + Remove => { + data.children.remove(index); + } + Replace => { + let child = object(args.get(1))?; + block::validate(cx.store(), child, Some(data_ref))?; + data.children[index].block = child; + } + Move => { + let to = integer(args.get(1))? as usize; + if to >= data.children.len() { + return Err(invalid("child position out of range")); + } + let child = data.children.remove(index); + data.children.insert(to, child); + } + _ => unreachable!(), } } } - Constructor::Spacer => LiveKind::Leaf(UiKind::Spacer(dimension(&arguments[0])?)), - Constructor::Page => return session.page(), - }; - session.emit(kind) - } -} - -#[derive(Debug)] -struct PagePayload; - -impl ObjectPayload for PagePayload { - fn as_any(&self) -> &dyn Any { - self - } - fn kind_name(&self) -> &'static str { - "tessera-page" - } - fn allows_attributes(&self) -> bool { - true - } -} - -#[derive(Debug)] -struct PageRender { - page: usize, - session: Arc>, -} - -impl ObjectPayload for PageRender { - fn as_any(&self) -> &dyn Any { - self - } - fn kind_name(&self) -> &'static str { - "tessera-page-render" - } - fn call(&self, arguments: &[Value]) -> Result { - if arguments.len() != 1 { - return Err(VmError::ArgumentCount { - name: "page.render".into(), - required: 1, - maximum: 1, - provided: arguments.len(), - }); + Children => { + let result = cx.new_dict()?; + for child in data.children { + cx.dict_set( + result, + Value::Text(child.slot.to_string()), + Value::Object(child.block), + )?; + } + return Ok(NativeResult::Return(Value::Object(result))); + } + Render | Navigate => { + if !matches!(data.kind, Kind::Page) { + return Err(invalid("expected a Page")); + } + let root = object(args.first())?; + block::validate(cx.store(), root, Some(data_ref))?; + if matches!(self.operation, Navigate) { + if data.history.is_empty() { + if let Some(old) = data.children.first() { + data.history.push(old.block); + } + } else { + data.history.truncate(data.history_index + 1); + } + data.history.push(root); + data.history_index = data.history.len() - 1; + } + data.children = vec![Child { + slot: 0, + block: root, + }]; + data.next_slot = data.next_slot.max(1); + show(cx, owner, &self.session)?; + } + Back | Forward => { + if data.history.is_empty() { + return Ok(NativeResult::Return(Value::Nil)); + } + let next = if matches!(self.operation, Back) { + data.history_index.saturating_sub(1) + } else { + (data.history_index + 1).min(data.history.len() - 1) + }; + data.history_index = next; + data.children = vec![Child { + slot: 0, + block: data.history[next], + }]; + show(cx, owner, &self.session)?; + } + Open | Activate => { + show(cx, owner, &self.session)?; + return Ok(NativeResult::Return(Value::Object(owner))); + } + Unmount => { + data.children.clear(); + } + Close => { + let mut session = self + .session + .lock() + .map_err(|_| invalid("UI session poisoned"))?; + cx.dict_delete(session.tabs, &Value::Text(owner.to_string()))?; + if session.active == Some(owner) || session.pending == Some(Some(owner)) { + let next = + cx.store() + .dict_items(session.tabs)? + .first() + .and_then(|(_, value)| { + if let Value::Object(page) = value { + Some(*page) + } else { + None + } + }); + cx.set_attr( + session.desktop, + "pending", + next.map(Value::Object).unwrap_or(Value::Nil), + )?; + session.pending = Some(next); + } + return Ok(NativeResult::Return(Value::Nil)); + } + OnClick => { + let handler = object(args.first())?; + data.click = Some(handler); + result = Value::Object(owner); + } + Click => { + let Some(handler) = data.click else { + return Ok(NativeResult::Return(Value::Nil)); + }; + let event = cx.allocate(crate::events::Event)?; + attach_named_type(cx, event, "Event", &self.session)?; + cx.set_attr(event, "kind", Value::Text("click".into()))?; + cx.set_attr(event, "target", Value::Object(owner))?; + let context = if let Some(value) = args.first() { + let mount = object(Some(value))?; + let data = cx.store().payload::(mount, "Mount")?; + if !data.mounted || data.block != owner { + return Err(invalid("click context does not belong to this Block")); + } + Value::Object(mount) + } else { + Value::Nil + }; + cx.set_attr(event, "mount", context)?; + let arguments = if cx + .store() + .positional_parameter_count(handler)? + .is_some_and(|count| count > 0) + { + vec![Value::Object(event)] + } else { + vec![] + }; + return Ok(NativeResult::Invoke { + function: handler, + arguments, + }); + } + _ => return Err(invalid("unsupported Block operation")), } - let mut session = self - .session - .lock() - .map_err(|_| VmError::InvalidArgument("UI build session is poisoned"))?; - if !session.initialized_pages[self.page] { - return Err(VmError::InvalidArgument("page is not initialized")); - } - let root = session.child(&arguments[0])?; - session.pending = Some((self.page, Some(root))); - Ok(Value::Nil) - } -} - -#[derive(Debug)] -struct PageUnmount { - page: usize, - session: Arc>, -} -impl ObjectPayload for PageUnmount { - fn as_any(&self) -> &dyn Any { - self - } - fn kind_name(&self) -> &'static str { - "tessera-page-unmount" - } - fn call(&self, arguments: &[Value]) -> Result { - if !arguments.is_empty() { - return Err(VmError::InvalidArgument("page.unmount takes no arguments")); - } - let mut session = self - .session - .lock() - .map_err(|_| VmError::InvalidArgument("UI session is poisoned"))?; - if session.active == Some(self.page) - || session - .pending - .as_ref() - .is_some_and(|(page, _)| *page == self.page) - { - session.pending = Some((self.page, None)); - } else { - session.mounts[self.page] = None; - } - Ok(Value::Nil) + cx.replace_payload(data_ref, data)?; + Ok(NativeResult::Return(result)) } } pub struct UiBridge { - /// Borrowed from the candidate's external roots; never crosses VM lifetime. pub ui: ObjectRef, - session: Arc>, + session: Shared, } impl UiBridge { - /// Native mount/child edges retain explicit Aster roots. Drop those roots - /// when the native edge disappears, then recycle only pool-only VM slots. - pub fn reclaim(&self, vm: &mut Vm, roots: &mut Vec) -> Result<()> { - let mut session = self - .session - .lock() - .map_err(|_| anyhow::anyhow!("UI session is poisoned"))?; - loop { - let mut freed = false; - for index in 0..session.pool.len() { - let handle = session.pool[index].0; - let referenced = session.pool[index] - .1 - .lock() - .map_err(|_| anyhow::anyhow!("UI slot is poisoned"))? - .as_ref() - .is_some_and(|node| Arc::strong_count(node) > 1); - if referenced && !session.native_roots.contains(&index) { - vm.retain(handle)?; - roots.push(handle); - session.native_roots.insert(index); - } else if !referenced && session.native_roots.remove(&index) { - let at = roots - .iter() - .rposition(|root| *root == handle) - .expect("native edge owns a root"); - roots.remove(at); - vm.release(handle)?; - } - if !referenced && vm.ref_count(handle)? == 1 { - let removed = session.pool[index] - .1 - .lock() - .map_err(|_| anyhow::anyhow!("UI slot is poisoned"))? - .take() - .is_some(); - if removed { - session.free.push(index); - freed = true; - } - } - } - if !freed { - break; - } - } - for index in 0..session.pages.len() { - let (render, unmount) = session.page_functions[index]; - if session.initialized_pages[index] - && session.active != Some(index) - && session.mounts[index].is_none() - && session - .pending - .as_ref() - .is_none_or(|(page, _)| *page != index) - && vm.ref_count(session.pages[index])? == 1 - && vm.ref_count(render)? == 2 - && vm.ref_count(unmount)? == 2 - { - session.initialized_pages[index] = false; - } + pub fn install_globals(&self, vm: &mut Vm, globals: ObjectRef) -> Result<()> { + vm.dict_set(globals, Value::Text("ui".into()), Value::Object(self.ui))?; + for name in TYPE_NAMES.iter().chain(QUERY_NAMES) { + let value = vm.get_attr(self.ui, name)?; + vm.dict_set(globals, Value::Text((*name).into()), value)?; } Ok(()) } - pub fn discard_pending(&self) -> Result<()> { - self.session - .lock() - .map_err(|_| anyhow::anyhow!("UI session is poisoned"))? - .pending = None; - Ok(()) - } - /// Commit a mount only when layout/publication can succeed. Return None for - /// unchanged pages, Some(None) for an unmounted page, or an updated snapshot. - pub fn prepare_frame(&self) -> Result>>> { - let session = self + pub fn has_page(&self) -> Result { + Ok(self .session .lock() - .map_err(|_| anyhow::anyhow!("UI session is poisoned"))?; - let root = match &session.pending { - Some((_, root)) => root.as_ref(), - None => session - .active - .and_then(|index| session.mounts[index].as_ref()), - }; - let snapshot = root.map(|root| root.snapshot()).transpose()?; - let changed = session.pending.is_some() || snapshot != session.last_snapshot; - Ok(changed.then_some(snapshot)) - } - pub fn commit_frame(&self, snapshot: Option>) -> Result<()> { - let mut session = self - .session - .lock() - .map_err(|_| anyhow::anyhow!("UI session is poisoned"))?; - if let Some((page, root)) = session.pending.take() { - session.active = root.as_ref().map(|_| page); - session.mounts[page] = root; - } - session.last_snapshot = snapshot; - Ok(()) - } - pub fn rendered(&self) -> Result>> { - let session = self - .session - .lock() - .map_err(|_| anyhow::anyhow!("UI session is poisoned"))?; - session + .map_err(|_| anyhow::anyhow!("UI session poisoned"))? .pending - .as_ref() - .and_then(|(_, root)| root.as_ref()) - .map(|root| root.snapshot()) - .transpose() + .flatten() + .is_some()) } -} - -fn color(value: Option<&Value>, default: &str) -> Result { - let value = match value { - Some(Value::Text(value)) => value.as_str(), - None => default, - _ => return Err(VmError::InvalidArgument("UI color must be a string")), - }; - parse_color(value) - .map_err(|_| VmError::InvalidArgument("UI color must use #RRGGBB or #RRGGBBAA"))?; - Ok(value.to_owned()) -} - -fn dimension(value: &Value) -> Result { - let invalid = - || VmError::InvalidArgument("UI dimensions must be finite numbers between 0 and 1000000"); - let Value::Number(number) = value else { - return Err(invalid()); - }; - // Conversion belongs to the UI boundary. Aster's exact Number is unchanged. - let value = match number.as_real() { - Some(EndorReal::Integer(value)) => { - value.to_string().parse::().map_err(|_| invalid())? + pub fn open_value(&self, vm: &mut Vm, value: &Value) -> Result<()> { + let function = object(Some(&vm.get_attr(self.ui, "open")?))?; + let page = vm.call(function, std::slice::from_ref(value))?; + vm.release_value(page)?; + Ok(()) + } + pub fn dispatch(&self, vm: &mut Vm, input: &crate::events::Input) -> Result<()> { + let (weak, desktop) = { + let state = self + .session + .lock() + .map_err(|_| anyhow::anyhow!("UI session poisoned"))?; + if state.published_version != input.layout_version { + bail!("event targets an obsolete presentation"); + } + ( + *state + .mounts + .active + .get(&input.mount) + .ok_or_else(|| anyhow::anyhow!("Mount is no longer active"))?, + state.desktop, + ) + }; + let mount = vm + .upgrade(weak)? + .ok_or_else(|| anyhow::anyhow!("Mount has expired"))?; + let result = (|| { + let data = vm.payload::(mount, "Mount")?.clone(); + if !data.mounted { + bail!("event targets an obsolete presentation"); + } + if !data.geometry.interactive { + bail!("Mount does not accept input"); + } + vm.set_attr(desktop, "focus", Value::Number((input.mount as i64).into()))?; + vm.set_attr(desktop, "focusRequested", Value::Bool(true))?; + let (owner, name, args) = match input.kind.as_str() { + "click" => (data.block, "click", vec![Value::Object(mount)]), + "focus" => (mount, "requestFocus", vec![]), + _ => bail!("unsupported native event"), + }; + let bound = vm.bind_attr(owner, name)?; + let result = match &bound { + Value::Object(function) => vm.call_with_limits( + *function, + &args, + endor_core::ExecutionLimits { + max_frames: 128, + max_instructions: 1_000_000, + }, + ), + _ => Err(invalid("event method is not callable")), + }; + vm.release_value(bound)?; + vm.release_value(result?)?; + Ok(()) + })(); + vm.release(mount)?; + result + } + pub fn reclaim(&self, vm: &mut Vm, _roots: &mut Vec) -> Result<()> { + vm.collect_cycles(); + let mut state = self + .session + .lock() + .map_err(|_| anyhow::anyhow!("UI session poisoned"))?; + let mut live = Vec::new(); + for weak in &state.nodes { + if let Some(object) = vm.upgrade(*weak)? { + vm.release(object)?; + live.push(*weak); + } } - Some(EndorReal::Decimal(value)) => value.literal().parse::().map_err(|_| invalid())?, - Some(EndorReal::BinaryFloat(bits)) => f64::from_bits(*bits), - _ => return Err(invalid()), - }; - if !value.is_finite() || !(0.0..=MAX_DIMENSION).contains(&value) { - return Err(invalid()); + state.nodes = live; + state.render_cache.prune(vm.object_store()); + Ok(()) + } + pub fn discard_pending(&self, vm: &mut Vm) -> Result<()> { + let mut state = self + .session + .lock() + .map_err(|_| anyhow::anyhow!("UI session poisoned"))?; + state.pending = None; + vm.set_attr(state.desktop, "pending", Value::Nil)?; + if state.active.is_some_and(|v| vm.object(v).is_err()) { + state.active = None; + } + Ok(()) + } + pub fn prepare_frame(&self, vm: &mut Vm) -> Result>>> { + let changes = vm.take_changes(); + let mut state = self + .session + .lock() + .map_err(|_| anyhow::anyhow!("UI session poisoned"))?; + let active = state.pending.unwrap_or(state.active); + state.render_cache.invalidate(changes); + let root = active + .map(|v| state.render_cache.snapshot(vm.object_store(), v)) + .transpose()?; + let same = match (&root, &state.last_snapshot) { + (Some(a), Some(b)) => Arc::ptr_eq(a, b), + (None, None) => true, + _ => false, + }; + let focus_changed = matches!( + vm.get_attr(state.desktop, "focusRequested"), + Ok(Value::Bool(true)) + ); + let changed = state.pending.is_some() || !same || focus_changed; + if changed { + state.snapshot_visited = state.render_cache.visited; + state.snapshot_reused = state.render_cache.reused; + } + Ok(changed.then_some(root)) + } + pub fn commit_frame( + &self, + vm: &mut Vm, + snapshot: Option>, + frame: &crate::document::Frame, + ) -> Result<()> { + let mut state = self + .session + .lock() + .map_err(|_| anyhow::anyhow!("UI session poisoned"))?; + let page = state.pending.unwrap_or(state.active); + let desktop = state.desktop; + let nodes = state.nodes.clone(); + state.mounts.synchronize(vm, desktop, page, nodes, frame)?; + if snapshot.is_none() { + state.layout.clear_occurrences(); + } + if let Some(page) = state.pending.take() { + state.active = page; + } + vm.set_attr(state.desktop, "pending", Value::Nil)?; + vm.set_attr(state.desktop, "focusRequested", Value::Bool(false))?; + state.last_snapshot = snapshot; + state.published_version = frame.layout_version; + Ok(()) + } + pub fn layout_frame(&self, vm: &Vm, root: &UiNode) -> Result { + let mut state = self + .session + .lock() + .map_err(|_| anyhow::anyhow!("UI session poisoned"))?; + let mut frame = state.layout.frame(root)?; + frame.focus = match vm.get_attr(state.desktop, "focus") { + Ok(Value::Number(id)) => id.as_i64().and_then(|n| u64::try_from(n).ok()), + _ => None, + }; + frame.focus = frame + .focus + .filter(|id| frame.mounts.iter().any(|m| m.id == *id && m.interactive)); + Ok(frame) + } + pub fn rendered(&self, vm: &Vm) -> Result>> { + let state = self + .session + .lock() + .map_err(|_| anyhow::anyhow!("UI session poisoned"))?; + state + .pending + .flatten() + .map(|v| block::snapshot(vm.object_store(), v)) + .transpose() + .map_err(Into::into) } - Ok(value as f32) } -/// All allocation roots go to the candidate, including partial installation. pub fn install(vm: &mut Vm, roots: &mut Vec) -> Result { - let mut pool = Vec::with_capacity(MAX_UI_NODES); - let mut indexes = HashMap::with_capacity(MAX_UI_NODES); - for index in 0..MAX_UI_NODES { - let slot = Arc::new(Mutex::new(None)); - let reference = vm.allocate(NodePayload(slot.clone()))?; - roots.push(reference); - indexes.insert(reference, index); - pool.push((reference, slot)); - } - let session = Arc::new(Mutex::new(BuildSession { - pool, - indexes, - free: (0..MAX_UI_NODES).rev().collect(), - pages: Vec::with_capacity(MAX_PAGES), - initialized_pages: vec![false; MAX_PAGES], - page_functions: Vec::with_capacity(MAX_PAGES), - native_roots: HashSet::new(), - mounts: vec![None; MAX_PAGES], - active: None, - pending: None, - last_snapshot: None, - })); - for page in 0..MAX_PAGES { - let reference = vm.allocate(PagePayload)?; - roots.push(reference); - let render = vm.allocate(PageRender { - page, - session: session.clone(), - })?; - roots.push(render); - vm.set_attr(reference, "render", Value::Object(render))?; - let unmount = vm.allocate(PageUnmount { - page, - session: session.clone(), - })?; - roots.push(unmount); - vm.set_attr(reference, "unmount", Value::Object(unmount))?; - session - .lock() - .map_err(|_| anyhow::anyhow!("UI session is poisoned"))? - .page_functions - .push((render, unmount)); - - session - .lock() - .map_err(|_| anyhow::anyhow!("UI build session is poisoned"))? - .pages - .push(reference); - } + let desktop = vm.new_object()?; + roots.push(desktop); + let tabs = vm.new_dict()?; + roots.push(tabs); + vm.set_attr(desktop, "tabs", Value::Object(tabs))?; let ui = vm.new_object()?; roots.push(ui); - for constructor in [ - Constructor::Text, - Constructor::Rect, - Constructor::Column, - Constructor::Row, - Constructor::Spacer, - Constructor::Page, + let session = Arc::new(Mutex::new(Session { + desktop, + tabs, + active: None, + pending: None, + nodes: vec![], + last_snapshot: None, + render_cache: crate::snapshot::RenderCache::default(), + layout: crate::layout::LayoutRuntime::default(), + mounts: crate::mount::MountTable::default(), + published_version: 0, + snapshot_visited: 0, + snapshot_reused: 0, + })); + for (name, operation) in [ + ("isInstance", Operation::IsInstance), + ("isSubtype", Operation::IsSubtype), + ("open", Operation::OpenValue), + ("text", Operation::Text), + ("rect", Operation::Rect), + ("spacer", Operation::Spacer), + ("row", Operation::Row), + ("column", Operation::Column), + ("button", Operation::Button), + ("page", Operation::Page), + ("present", Operation::Present), + ("state", Operation::State), + ("textOf", Operation::TextOf), + ("stats", Operation::Stats), ] { - let function = vm.allocate(UiConstructor { - constructor, - session: session.clone(), - })?; + let function = vm.allocate(ContextNativeFunction::new( + name, + Function { + operation, + owner: None, + session: session.clone(), + }, + vec![desktop], + ))?; roots.push(function); - vm.set_attr(ui, constructor.name(), Value::Object(function))?; + vm.set_attr(ui, name, Value::Object(function))?; + } + let root_types = vm.bootstrap_types()?; + roots.extend([root_types.object, root_types.type_type]); + vm.set_attr(ui, "Object", Value::Object(root_types.object))?; + vm.set_attr(ui, "Type", Value::Object(root_types.type_type))?; + let mut definitions = vec![ + ("Object", root_types.object), + ("Type", root_types.type_type), + ]; + for (name, base_name, constructor_name) in [ + ("Function", "Object", None), + ("Block", "Object", None), + ("ContainerBlock", "Block", None), + ("TextBlock", "Block", Some("text")), + ("RectBlock", "Block", Some("rect")), + ("Spacer", "Block", Some("spacer")), + ("Row", "ContainerBlock", Some("row")), + ("Column", "ContainerBlock", Some("column")), + ("Button", "ContainerBlock", Some("button")), + ("Page", "ContainerBlock", Some("page")), + ("Mount", "Object", None), + ("Event", "Object", None), + ] { + let base = object(Some(&vm.get_attr(ui, base_name)?))?; + let constructor = match constructor_name { + Some(name) => TypeConstructor::Native(object(Some(&vm.get_attr(ui, name)?))?), + None => TypeConstructor::Abstract, + }; + let definition = vm.new_type(name, base, constructor)?; + roots.push(definition); + vm.set_attr(ui, name, Value::Object(definition))?; + definitions.push((name, definition)); + } + // The desktop owns the registry through ordinary traced attributes. The + // Rust session only borrows handles and adds no hidden lifetime roots. + let types = vm.new_dict()?; + roots.push(types); + for (name, definition) in definitions { + vm.dict_set(types, Value::Text(name.into()), Value::Object(definition))?; + } + vm.set_attr(desktop, "types", Value::Object(types))?; + vm.attach_type(desktop, root_types.object)?; + vm.attach_type(ui, root_types.object)?; + let function_type = object(Some(&vm.get_attr(ui, "Function")?))?; + for name in [ + "open", + "text", + "rect", + "spacer", + "row", + "column", + "button", + "page", + "present", + "state", + "textOf", + "stats", + "isInstance", + "isSubtype", + ] { + let function = object(Some(&vm.get_attr(ui, name)?))?; + vm.attach_type(function, function_type)?; + } + for (type_name, name, operation) in [ + ("Block", "mounts", Operation::Mounts), + ("Block", "onClick", Operation::OnClick), + ("Block", "click", Operation::Click), + ("TextBlock", "setText", Operation::SetText), + ("TextBlock", "setColor", Operation::SetColor), + ("RectBlock", "setColor", Operation::SetColor), + ("ContainerBlock", "append", Operation::Append), + ("ContainerBlock", "remove", Operation::Remove), + ("ContainerBlock", "replace", Operation::Replace), + ("ContainerBlock", "move", Operation::Move), + ("ContainerBlock", "children", Operation::Children), + ("Page", "render", Operation::Render), + ("Page", "unmount", Operation::Unmount), + ("Page", "open", Operation::Open), + ("Page", "close", Operation::Close), + ("Page", "activate", Operation::Activate), + ("Page", "navigate", Operation::Navigate), + ("Page", "back", Operation::Back), + ("Page", "forward", Operation::Forward), + ] { + let expected = object(Some(&vm.get_attr(ui, type_name)?))?; + let method = vm.allocate(ContextNativeFunction::new( + name, + TypeMethod { + operation, + expected, + session: session.clone(), + }, + vec![expected, desktop], + ))?; + roots.push(method); + vm.attach_type(method, function_type)?; + vm.define_method(expected, name, method)?; } Ok(UiBridge { ui, session }) } -pub fn snapshot(vm: &Vm, result: &Value) -> Result> { - let Value::Object(reference) = result else { - bail!("main must return a UI node"); - }; - vm.payload::(*reference, "Tessera UI node")? - .0 +fn attach_named_type( + cx: &mut NativeContext<'_>, + object: ObjectRef, + name: &str, + session: &Shared, +) -> Result<(), VmError> { + let desktop = session .lock() - .map_err(|_| anyhow::anyhow!("UI slot is poisoned"))? - .as_ref() - .ok_or_else(|| anyhow::anyhow!("main returned an uninitialized UI node"))? - .snapshot() + .map_err(|_| invalid("UI session poisoned"))? + .desktop; + attach_desktop_type(cx, object, name, desktop) +} + +pub fn attach_desktop_type( + cx: &mut NativeContext<'_>, + instance: ObjectRef, + name: &str, + desktop: ObjectRef, +) -> Result<(), VmError> { + let types = object(Some(&cx.store().get_attr(desktop, "types")?))?; + let definition = object( + cx.store() + .dict_get(types, &Value::Text(name.into()))? + .as_ref(), + )?; + cx.attach_type(instance, definition) +} + +pub fn snapshot(vm: &Vm, value: &Value) -> Result> { + let Value::Object(root) = value else { + bail!("main must return a Block"); + }; + block::snapshot(vm.object_store(), *root).map_err(Into::into) } diff --git a/vendor/README.md b/vendor/README.md index f0ddcc4..828e80b 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -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 diff --git a/vendor/aster b/vendor/aster index 7c84278..a970fd7 160000 --- a/vendor/aster +++ b/vendor/aster @@ -1 +1 @@ -Subproject commit 7c842789c0f64629b6c0b4b4424fd61a41529a58 +Subproject commit a970fd7707009951c0290b3d6155e71702ffb4a6