From dc61f5e33cc7c5b6664f8c702038d5ef42738254 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Wed, 21 Oct 2026 02:42:16 +0800 Subject: [PATCH] feat: expose native visual protocols and explicit invalidation --- README.md | 6 + examples/README.md | 1 + examples/visual-protocols.endor | 30 ++++ src/README.md | 4 +- src/endor_host.rs | 122 ++++++++++++++++ src/layout.rs | 187 +++++++++++++----------- src/main.rs | 2 + src/mount.rs | 58 +------- src/native_visual.rs | 244 ++++++++++++++++++++++++++++++++ src/object_list.rs | 65 +++++++++ src/snapshot.rs | 5 + src/ui_bridge.rs | 105 +++++++++++++- vendor/aster | 2 +- 13 files changed, 691 insertions(+), 140 deletions(-) create mode 100644 examples/visual-protocols.endor create mode 100644 src/native_visual.rs create mode 100644 src/object_list.rs diff --git a/README.md b/README.md index 01915b9..6ce295a 100644 --- a/README.md +++ b/README.md @@ -192,6 +192,12 @@ Mount synchronization queues hooks after links and geometry are coherent. Hooks Saved detached Mounts expose `mounted = false`, cleared parent/child/sibling links and a weak Page query for cleanup; geometry, focus and hit-test operations reject them. Reopening creates new contexts and never revives an old saved Mount. `layoutVersion` is refreshed even when only paint inputs change. See [mount-lifecycle.endor](examples/mount-lifecycle.endor). +Native visual methods are now available on Block: `measure(mount, Constraints(minWidth, minHeight, maxWidth, maxHeight))`, `arrange(mount, Bounds(x, y, width, height))`, `paint(mount, Bounds(...))` and `hitTest(mount, Point(x, y))`. The Mount must be live and belong to that exact Block occurrence. These query methods return managed MeasureResult, Arrangement and DisplayList objects, using the renderer's native geometry and painting functions. They do not publish geometry or pixels. Results are readable in Endor: `result.width`, `arrangement.children.at(0).x`, `drawing.commands.at(0).color`; indexed ObjectList results provide count, first and at(index), with traced references. Arrangement child bounds also carry their stable slot. Paint returns only that object's own commands; descendants are separate occurrences. + +Native measurement finds intrinsic subtree size and clamps the returned size to the given constraints. Native Row/Column arrangement uses intrinsic child sizes, padding and gaps; it does not stretch children to fill the supplied bounds. Hit testing uses local coordinates against the current Mount dimensions. Coordinates/dimensions must be finite and remain within the native layout limit. Width/height and constraint ranges cannot be negative or inverted. The value constructors preserve fields as ordinary objects; methods validate their contents when used, and global annotation type checking remains pending. + +`invalidate("paint")` requests a frame while retaining measurement caches; `invalidate("layout")` also clears affected intrinsic measurements; `invalidate("content")` also invalidates derived content and ancestor dependencies. The default reason is layout. Requests coalesce at the refresh boundary, cover all aliases/occurrences of the same current content and preserve Mount identities. Hidden objects do not force visible frames. See [visual-protocols.endor](examples/visual-protocols.endor). Source overrides are callable normally, but the renderer still selects native layout/paint directly: dispatching source visual overrides during rendering and preparing contexts before first measurement remain future work, so this is not the complete custom visual protocol. + 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 diff --git a/examples/README.md b/examples/README.md index 8dc9459..7bd8e8f 100644 --- a/examples/README.md +++ b/examples/README.md @@ -2,6 +2,7 @@ | File | Purpose | | --- | --- | +| [visual-protocols.endor](visual-protocols.endor) | Real source calls for constrained native measurement, arrangement and managed paint-command results from live Mounts. | | [mount-lifecycle.endor](mount-lifecycle.endor) | Source onMount/onUnmount methods, two occurrences of one object, ordered notifications and retained Mount lifetime. | | [events.endor](events.endor) | Managed event subscriptions, source onEvent override and numbered capture/target/bubble steps from native input. | | [native-subclasses.endor](native-subclasses.endor) | Real native TextBlock/Button/Page source subclasses, inherited fields, method overrides and shared field bindings. | diff --git a/examples/visual-protocols.endor b/examples/visual-protocols.endor new file mode 100644 index 0000000..48824c4 --- /dev/null +++ b/examples/visual-protocols.endor @@ -0,0 +1,30 @@ +class VisualResults { + width: Number + height: Number + childX: Number + childY: Number + color: String +} +class ProbeRect: RectBlock { + results: VisualResults + function onMount(self: ProbeRect, mount: Mount): Unit { + measured = self.measure(mount, Constraints(0, 0, 120, 80)) + self.results.width = measured.width + self.results.height = measured.height + drawing = self.paint(mount, Bounds(12, 18, 200, 60)) + self.results.color = drawing.commands.at(0).color + } +} +class ProbeColumn: Column { + results: VisualResults + function onMount(self: ProbeColumn, mount: Mount): Unit { + positions = self.arrange(mount, Bounds(20, 30, 500, 300)) + self.results.childX = positions.children.at(0).x + self.results.childY = positions.children.at(0).y + } +} +results = VisualResults(0, 0, 0, 0, "等待挂载") +rect = ProbeRect(200, 60, 12, "#DDEEFF", results) +root = ProbeColumn(24, 16, TextBlock("对象的原生视觉协议", 2), rect, TextBlock("约束测量宽度"), ui.textOf(results, "width"), TextBlock("绘制颜色"), ui.textOf(results, "color"), results) +page = Page() +page.render(root) diff --git a/src/README.md b/src/README.md index df513c7..92f3f7b 100644 --- a/src/README.md +++ b/src/README.md @@ -14,7 +14,9 @@ | events.rs | Bounded native input transport to the owning VM | | event_dispatch.rs | Managed Event, weak Subscription tokens, Block-owned connections and occurrence-specific capture/target/bubble through a budgeted VM driver | | vm_sequence.rs | Shared validated call-sequence builder for event and lifecycle batches in the existing VM frame loop | -| layout.rs | Iterative measurement/arrangement, stable occurrence IDs, measurement cache and geometry budgets | +| native_visual.rs | Managed native visual protocol queries with occurrence validation, value conversion and bounded results | +| object_list.rs | Traced indexed results shared by Mount queries and visual protocol results | +| layout.rs | Shared native geometry/paint functions, 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 | diff --git a/src/endor_host.rs b/src/endor_host.rs index 43de1af..a81ef8f 100644 --- a/src/endor_host.rs +++ b/src/endor_host.rs @@ -795,6 +795,128 @@ mod tests { const EXAMPLE: &str = include_str!("../examples/hello.endor"); const PAGE: &str = include_str!("../examples/page.endor"); + #[test] + fn native_visual_methods_use_managed_values_and_match_real_geometry() { + let (mut session, initial) = ReplSession::load( + include_str!("../examples/visual-protocols.endor"), + "app.main", + 61, + 1, + ) + .unwrap(); + initial.validate().unwrap(); + for (expression, expected) in [ + ("results.width", "120"), + ("results.height", "60"), + ("results.childX", "44"), + ("results.childY", "54"), + ("results.color", "\"#DDEEFF\""), + ] { + assert_eq!( + session.execute(expression, "app.main").unwrap().value, + expected + ); + } + assert!(initial.frame.commands.iter().any(|command| matches!(command, RenderCommand::RoundedRect { width: 200.0, height: 60.0, color, .. } if color == "#DDEEFF"))); + session + .execute("context = rect.mounts().at(0)", "app.main") + .unwrap(); + assert_eq!( + session + .execute("rect.hitTest(context, Point(1, 1))", "app.main") + .unwrap() + .value, + "true" + ); + assert_eq!( + session + .execute("rect.hitTest(context, Point(-1, 1))", "app.main") + .unwrap() + .value, + "false" + ); + assert!( + session + .execute( + "rect.measure(context, Constraints(200, 0, 100, 100))", + "app.main" + ) + .is_err() + ); + assert!( + session + .execute("root.paint(context, Bounds(0, 0, 10, 10))", "app.main") + .is_err() + ); + session.execute("page.close()", "app.main").unwrap(); + assert!( + session + .execute("rect.paint(context, Bounds(0, 0, 10, 10))", "app.main") + .is_err() + ); + } + + #[test] + fn explicit_invalidation_publishes_once_preserves_mount_and_remeasures_only_when_requested() { + let (mut session, _) = ReplSession::load( + include_str!("../examples/visual-protocols.endor"), + "app.main", + 62, + 1, + ) + .unwrap(); + session + .execute("context = rect.mounts().at(0)", "app.main") + .unwrap(); + let original = session.execute("context", "app.main").unwrap().value; + let update = session + .execute("rect.invalidate(\"paint\")", "app.main") + .unwrap() + .document + .unwrap(); + update.validate().unwrap(); + assert_eq!( + session + .execute("ui.stats().measured", "app.main") + .unwrap() + .value, + "0" + ); + assert!( + session + .execute("rect.invalidate(\"layout\")", "app.main") + .unwrap() + .document + .is_some() + ); + assert_eq!( + session + .execute("ui.stats().measured", "app.main") + .unwrap() + .value, + "1" + ); + assert_eq!( + session + .execute("rect.mounts().at(0)", "app.main") + .unwrap() + .value, + original + ); + assert!( + session + .execute("results.width", "app.main") + .unwrap() + .document + .is_none() + ); + assert!( + session + .execute("rect.invalidate(\"unknown\")", "app.main") + .is_err() + ); + } + #[test] fn mount_hooks_run_per_occurrence_settle_and_unmount_before_parent() { let (mut session, initial) = ReplSession::load( diff --git a/src/layout.rs b/src/layout.rs index 5d03c5c..137d800 100644 --- a/src/layout.rs +++ b/src/layout.rs @@ -64,7 +64,105 @@ fn container(node: &UiNode) -> Option<(bool, f32, f32)> { } } +fn measure_shape(shape: &Shape) -> Result { + 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)?; + Ok(size) +} + +pub fn paint_native(node: &UiNode, x: f32, y: f32, size: Size) -> Option { + match &node.kind { + UiKind::Text { value, size, color } => Some(RenderCommand::Text { + x, + y, + value: value.clone(), + size: *size, + color: color.clone(), + }), + UiKind::Rect { radius, color, .. } => Some(RenderCommand::RoundedRect { + x, + y, + width: size.width, + height: size.height, + radius: *radius, + color: color.clone(), + }), + UiKind::Button { .. } => Some(RenderCommand::RoundedRect { + x, + y, + width: size.width, + height: size.height, + radius: 7.0, + color: "#E3EAF7".into(), + }), + _ => None, + } +} + +pub fn arrange_native(node: &UiNode, x: f32, y: f32, children: &[Size]) -> Result> { + let Some((row, padding, gap)) = container(node) else { + return Ok(vec![]); + }; + let mut cursor = padding; + let mut points = Vec::with_capacity(children.len()); + for child in children { + let point = if row { + (x + cursor, y + padding) + } else { + (x + padding, y + cursor) + }; + bounded(point.0)?; + bounded(point.1)?; + bounded(point.0 + child.width)?; + bounded(point.1 + child.height)?; + points.push(point); + cursor += if row { child.width } else { child.height }; + cursor += gap; + } + Ok(points) +} + impl LayoutRuntime { + pub fn invalidate(&mut self, block: &str) { + self.sizes.remove(block); + } pub fn clear_occurrences(&mut self) { self.ids.clear(); } @@ -148,45 +246,7 @@ impl LayoutRuntime { *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)?; + let size = measure_shape(&shape)?; self.sizes.insert(item.node.block_id.clone(), (shape, size)); size }; @@ -221,47 +281,16 @@ impl LayoutRuntime { 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(command) = paint_native(item.node, x, y, size) { + commands.push(command); } - 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; - } + let child_sizes: Vec<_> = item.children.iter().map(|child| sizes[*child]).collect(); + for (child, point) in + item.children + .iter() + .zip(arrange_native(item.node, x, y, &child_sizes)?) + { + points[*child] = point; } } self.ids.retain(|key, _| used.contains(key)); diff --git a/src/main.rs b/src/main.rs index a99e0b7..9d81b93 100644 --- a/src/main.rs +++ b/src/main.rs @@ -13,6 +13,8 @@ mod events; mod geometry; mod layout; mod mount; +mod native_visual; +mod object_list; mod scene; mod snapshot; mod software_renderer; diff --git a/src/mount.rs b/src/mount.rs index 3256cb7..9f9c959 100644 --- a/src/mount.rs +++ b/src/mount.rs @@ -411,60 +411,4 @@ impl MountTable { } } -#[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) -} +pub use crate::object_list::collection; diff --git a/src/native_visual.rs b/src/native_visual.rs new file mode 100644 index 0000000..5e9358c --- /dev/null +++ b/src/native_visual.rs @@ -0,0 +1,244 @@ +//! Native visual protocol entry points. Values are ordinary managed Endor +//! objects; geometry is scoped to a live occurrence, never stored on a Block. +use crate::{ + block, + document::RenderCommand, + layout::{self, Size}, + mount::Mount, + ui_bridge::{MAX_DIMENSION, attach_desktop_type}, +}; +use endor_core::{ + ContextNativeFunction, NativeCallable, NativeContext, NativeResult, ObjectRef, Value, Vm, + VmError, +}; + +fn invalid(message: &'static str) -> VmError { + VmError::InvalidArgument(message) +} +fn object(value: &Value) -> Result { + if let Value::Object(object) = value { + Ok(*object) + } else { + Err(invalid("visual protocol requires objects")) + } +} +fn number( + cx: &NativeContext<'_>, + object: ObjectRef, + name: &str, + signed: bool, +) -> Result { + let Value::Number(value) = cx.store().get_attr(object, name)? else { + return Err(invalid("visual field must be a Number")); + }; + let value = value + .to_string() + .parse::() + .map_err(|_| invalid("invalid visual number"))?; + if !value.is_finite() || value.abs() > MAX_DIMENSION as f32 || (!signed && value < 0.0) { + return Err(invalid("visual number exceeds bounds")); + } + Ok(value) +} +fn value(value: f32) -> Value { + Value::Number((value as f64).into()) +} +fn record( + cx: &mut NativeContext<'_>, + desktop: ObjectRef, + kind: &str, + fields: Vec<(&str, Value)>, +) -> Result { + let object = cx.new_object()?; + attach_desktop_type(cx, object, kind, desktop)?; + for (key, value) in fields { + cx.set_attr(object, key, value)?; + } + Ok(object) +} +fn size(node: &crate::ui_bridge::UiNode) -> Result { + let frame = + layout::frame(node).map_err(|_| invalid("native measurement exceeds layout limits"))?; + let root = frame + .mounts + .first() + .ok_or(invalid("empty native measurement"))?; + Ok(Size { + width: root.width, + height: root.height, + }) +} +#[derive(Debug, Clone, Copy)] +enum Query { + Measure, + Arrange, + Paint, + HitTest, +} +#[derive(Debug)] +struct Method { + query: Query, + desktop: ObjectRef, +} +impl NativeCallable for Method { + fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result { + let [owner, context, input] = args else { + return Err(invalid("visual method expects a Mount and an input value")); + }; + let owner = object(owner)?; + let mount = cx.store().payload::(object(context)?, "Mount")?; + if !mount.mounted || mount.block != owner { + return Err(invalid( + "visual context is detached or belongs to another Block", + )); + } + let geometry = mount.geometry.clone(); + let input = object(input)?; + let node = block::snapshot(cx.store(), owner)?; + let result = match self.query { + Query::Measure => { + let min_w = number(cx, input, "minWidth", false)?; + let min_h = number(cx, input, "minHeight", false)?; + let max_w = number(cx, input, "maxWidth", false)?; + let max_h = number(cx, input, "maxHeight", false)?; + if min_w > max_w || min_h > max_h { + return Err(invalid("minimum exceeds maximum constraint")); + } + let size = size(&node)?; + Value::Object(record( + cx, + self.desktop, + "MeasureResult", + vec![ + ("width", value(size.width.clamp(min_w, max_w))), + ("height", value(size.height.clamp(min_h, max_h))), + ], + )?) + } + Query::Arrange => { + let x = number(cx, input, "x", false)?; + let y = number(cx, input, "y", false)?; + let width = number(cx, input, "width", false)?; + let height = number(cx, input, "height", false)?; + if x + width > MAX_DIMENSION as f32 || y + height > MAX_DIMENSION as f32 { + return Err(invalid("visual bounds exceed limits")); + } + let children: Vec<_> = node + .children() + .iter() + .map(|child| size(child)) + .collect::>()?; + let points = layout::arrange_native(&node, x, y, &children) + .map_err(|_| invalid("native arrangement exceeds limits"))?; + let mut result = Vec::new(); + for ((slot, size), (x, y)) in node.slots.iter().zip(children).zip(points) { + let bounds = record( + cx, + self.desktop, + "Bounds", + vec![ + ("x", value(x)), + ("y", value(y)), + ("width", value(size.width)), + ("height", value(size.height)), + ], + )?; + cx.set_attr(bounds, "slot", Value::Number((*slot as i64).into()))?; + result.push(bounds); + } + let result = crate::object_list::collection(cx, result, self.desktop)?; + Value::Object(record( + cx, + self.desktop, + "Arrangement", + vec![("children", Value::Object(result))], + )?) + } + Query::Paint => { + let x = number(cx, input, "x", false)?; + let y = number(cx, input, "y", false)?; + let width = number(cx, input, "width", false)?; + let height = number(cx, input, "height", false)?; + if x + width > MAX_DIMENSION as f32 || y + height > MAX_DIMENSION as f32 { + return Err(invalid("visual bounds exceed limits")); + } + let mut commands = Vec::new(); + if let Some(command) = layout::paint_native(&node, x, y, Size { width, height }) { + let fields = match command { + RenderCommand::Text { + x, + y, + value: text, + size, + color, + } => vec![ + ("kind", Value::Text("text".into())), + ("x", value(x)), + ("y", value(y)), + ("text", Value::Text(text)), + ("size", Value::Number((size as i64).into())), + ("color", Value::Text(color)), + ], + RenderCommand::RoundedRect { + x, + y, + width, + height, + radius, + color, + } => vec![ + ("kind", Value::Text("roundedRect".into())), + ("x", value(x)), + ("y", value(y)), + ("width", value(width)), + ("height", value(height)), + ("radius", value(radius)), + ("color", Value::Text(color)), + ], + _ => return Err(invalid("unsupported native paint command")), + }; + let command = record(cx, self.desktop, "PaintCommand", fields)?; + commands.push(command); + } + let commands = crate::object_list::collection(cx, commands, self.desktop)?; + Value::Object(record( + cx, + self.desktop, + "DisplayList", + vec![("commands", Value::Object(commands))], + )?) + } + Query::HitTest => { + let x = number(cx, input, "x", true)?; + let y = number(cx, input, "y", true)?; + Value::Bool(x >= 0.0 && y >= 0.0 && x < geometry.width && y < geometry.height) + } + }; + Ok(NativeResult::Return(result)) + } +} + +pub fn install( + vm: &mut Vm, + roots: &mut Vec, + desktop: ObjectRef, + block_type: ObjectRef, + function_type: ObjectRef, +) -> Result<(), VmError> { + for (name, query) in [ + ("measure", Query::Measure), + ("arrange", Query::Arrange), + ("paint", Query::Paint), + ("hitTest", Query::HitTest), + ] { + let function = vm.allocate(ContextNativeFunction::new( + name, + Method { query, desktop }, + vec![desktop], + ))?; + roots.push(function); + vm.attach_type(function, function_type)?; + vm.define_method(block_type, name, function)?; + } + Ok(()) +} diff --git a/src/object_list.rs b/src/object_list.rs new file mode 100644 index 0000000..375fd5a --- /dev/null +++ b/src/object_list.rs @@ -0,0 +1,65 @@ +//! Managed indexed host results; values and the at method are traced edges. +use endor_core::{ + ContextNativeFunction, NativeCallable, NativeContext, NativeResult, ObjectPayload, ObjectRef, + Value, VmError, +}; +#[derive(Debug)] +struct ObjectList(Vec); +impl ObjectPayload for ObjectList { + fn as_any(&self) -> &dyn std::any::Any { + self + } + fn kind_name(&self) -> &'static str { + "tessera-object-list" + } + fn allows_attributes(&self) -> bool { + true + } + fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) { + for mount in &self.0 { + visit(*mount); + } + } +} + +#[derive(Debug)] +struct At(ObjectRef); +impl NativeCallable for At { + fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result { + let [Value::Number(index)] = args else { + return Err(VmError::InvalidArgument("object list at expects an index")); + }; + let index = index + .as_i64() + .and_then(|v| usize::try_from(v).ok()) + .ok_or(VmError::InvalidArgument("invalid list index"))?; + let mount = *cx + .store() + .payload::(self.0, "Object list")? + .0 + .get(index) + .ok_or(VmError::InvalidArgument("list index out of range"))?; + Ok(NativeResult::Return(Value::Object(mount))) + } +} + +pub fn collection( + cx: &mut NativeContext<'_>, + mounts: Vec, + desktop: ObjectRef, +) -> Result { + let first = mounts + .first() + .copied() + .map(Value::Object) + .unwrap_or(Value::Nil); + let count = mounts.len(); + let set = cx.allocate(ObjectList(mounts))?; + crate::ui_bridge::attach_desktop_type(cx, set, "ObjectList", desktop)?; + cx.set_attr(set, "first", first)?; + cx.set_attr(set, "count", Value::Number((count as i64).into()))?; + let at = cx.allocate(ContextNativeFunction::new("at", At(set), vec![set]))?; + crate::ui_bridge::attach_desktop_type(cx, at, "Function", desktop)?; + cx.set_attr(set, "at", Value::Object(at))?; + Ok(set) +} diff --git a/src/snapshot.rs b/src/snapshot.rs index 2555fd5..3d727b4 100644 --- a/src/snapshot.rs +++ b/src/snapshot.rs @@ -51,6 +51,11 @@ impl RenderCache { } } } + self.invalidate_objects(queue); + } + + pub fn invalidate_objects(&mut self, objects: impl IntoIterator) { + let mut queue: VecDeque<_> = objects.into_iter().collect(); while let Some(block) = queue.pop_front() { if self.dirty.insert(block) && let Some(parents) = self.parents.get(&block) diff --git a/src/ui_bridge.rs b/src/ui_bridge.rs index 461e5d1..1f6eb56 100644 --- a/src/ui_bridge.rs +++ b/src/ui_bridge.rs @@ -32,6 +32,14 @@ pub const TYPE_NAMES: &[&str] = &[ "Mount", "Event", "Subscription", + "ObjectList", + "Constraints", + "MeasureResult", + "Bounds", + "Point", + "Arrangement", + "DisplayList", + "PaintCommand", ]; pub const QUERY_NAMES: &[&str] = &["isInstance", "isSubtype"]; @@ -168,6 +176,7 @@ struct Session { layout: crate::layout::LayoutRuntime, mounts: crate::mount::MountTable, published_version: u64, + force_frame: bool, snapshot_visited: usize, snapshot_reused: usize, } @@ -210,6 +219,7 @@ enum Operation { On, Dispatch, OnEvent, + Invalidate, OnMount, OnUnmount, Click, @@ -492,7 +502,7 @@ impl NativeCallable for Function { Button => (1, 1), Replace | Move => (2, 2), Page | Unmount | Open | Close | Activate | Back | Forward | Children => (0, 0), - Click => (0, 1), + Click | Invalidate => (0, 1), On => (2, 3), Dispatch => (1, 2), OnEvent | OnMount | OnUnmount => (1, 1), @@ -510,6 +520,56 @@ impl NativeCallable for Function { }; return Ok(NativeResult::Return(Value::Bool(value))); } + if matches!(self.operation, Invalidate) { + let reason = args + .first() + .map(|value| text(Some(value))) + .transpose()? + .unwrap_or_else(|| "layout".into()); + if !matches!(reason.as_str(), "paint" | "layout" | "content") { + return Err(invalid( + "invalidation reason must be paint, layout or content", + )); + } + let owner = self.owner.ok_or(invalid("invalidation requires a Block"))?; + let (data, _) = block::resolve(cx.store(), owner)?; + let mut session = self + .session + .lock() + .map_err(|_| invalid("UI session poisoned"))?; + let mut affected = std::collections::HashSet::new(); + for weak in &session.nodes { + if let Some(block) = cx.upgrade(*weak)? + && block::resolve(cx.store(), block)?.0 == data + { + affected.insert(block); + } + } + if reason != "paint" { + for block in &affected { + session.layout.invalidate(&block.to_string()); + } + } + if reason == "content" { + session + .render_cache + .invalidate_objects(affected.iter().copied()); + } + let mut visible = false; + for weak in session.mounts.active.values() { + if let Some(mount) = cx.upgrade(*weak)? + && affected.contains( + &cx.store() + .payload::(mount, "Mount")? + .block, + ) + { + visible = true; + } + } + session.force_frame |= visible; + return Ok(NativeResult::Return(Value::Nil)); + } if matches!(self.operation, Mounts) { let owner = self.owner.ok_or(invalid("mount query requires a Block"))?; let session = self @@ -532,6 +592,7 @@ impl NativeCallable for Function { let set = crate::mount::collection( cx, positions.into_iter().map(|(_, object)| object).collect(), + session.desktop, )?; return Ok(NativeResult::Return(Value::Object(set))); } @@ -1077,7 +1138,7 @@ impl UiBridge { vm.get_attr(state.desktop, "focusRequested"), Ok(Value::Bool(true)) ); - let changed = state.pending.is_some() || !same || focus_changed; + let changed = state.pending.is_some() || !same || focus_changed || state.force_frame; if changed { state.snapshot_visited = state.render_cache.visited; state.snapshot_reused = state.render_cache.reused; @@ -1107,6 +1168,7 @@ impl UiBridge { } vm.set_attr(state.desktop, "pending", Value::Nil)?; vm.set_attr(state.desktop, "focusRequested", Value::Bool(false))?; + state.force_frame = false; state.last_snapshot = snapshot; state.published_version = frame.layout_version; // Hooks may call Page/container APIs; never hold the session mutex @@ -1181,6 +1243,7 @@ pub fn install(vm: &mut Vm, roots: &mut Vec) -> Result { layout: crate::layout::LayoutRuntime::default(), mounts: crate::mount::MountTable::default(), published_version: 0, + force_frame: false, snapshot_visited: 0, snapshot_reused: 0, })); @@ -1235,6 +1298,7 @@ pub fn install(vm: &mut Vm, roots: &mut Vec) -> Result { ("Mount", "Object", None), ("Event", "Object", Some("event")), ("Subscription", "Object", None), + ("ObjectList", "Object", None), ] { let base = object(Some(&vm.get_attr(ui, base_name)?))?; let constructor = match constructor_name { @@ -1280,6 +1344,40 @@ pub fn install(vm: &mut Vm, roots: &mut Vec) -> Result { vm.set_attr(ui, name, Value::Object(definition))?; definitions.push((name, definition)); } + for (name, fields) in [ + ( + "Constraints", + vec!["minWidth", "minHeight", "maxWidth", "maxHeight"], + ), + ("MeasureResult", vec!["width", "height"]), + ("Bounds", vec!["x", "y", "width", "height"]), + ("Point", vec!["x", "y"]), + ("Arrangement", vec!["children"]), + ("DisplayList", vec!["commands"]), + ("PaintCommand", vec![]), + ] { + let fields = fields + .into_iter() + .map(|name| endor_core::ClassField { + name: name.into(), + type_name: if matches!(name, "children" | "commands") { + "Object" + } else { + "Number" + } + .into(), + }) + .collect(); + let definition = vm.new_class( + name, + root_types.object, + fields, + std::collections::BTreeMap::new(), + )?; + 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()?; @@ -1312,6 +1410,7 @@ pub fn install(vm: &mut Vm, roots: &mut Vec) -> Result { } for (type_name, name, operation) in [ ("Block", "mounts", Operation::Mounts), + ("Block", "invalidate", Operation::Invalidate), ("Block", "onClick", Operation::OnClick), ("Block", "on", Operation::On), ("Block", "dispatch", Operation::Dispatch), @@ -1350,6 +1449,8 @@ pub fn install(vm: &mut Vm, roots: &mut Vec) -> Result { vm.attach_type(method, function_type)?; vm.define_method(expected, name, method)?; } + let block_type = object(Some(&vm.get_attr(ui, "Block")?))?; + crate::native_visual::install(vm, roots, desktop, block_type, function_type)?; let event_type = object(Some(&vm.get_attr(ui, "Event")?))?; let token_type = object(Some(&vm.get_attr(ui, "Subscription")?))?; crate::event_dispatch::install(vm, roots, event_type, token_type, function_type)?; diff --git a/vendor/aster b/vendor/aster index 2b5539c..44a02c9 160000 --- a/vendor/aster +++ b/vendor/aster @@ -1 +1 @@ -Subproject commit 2b5539cd06f4f4068882e4e6d12d6deb9728bf6a +Subproject commit 44a02c9fd6b08515babe774486ef1c5050a859a1