diff --git a/README.md b/README.md index 6ce295a..9f51d0c 100644 --- a/README.md +++ b/README.md @@ -196,7 +196,11 @@ Native visual methods are now available on Block: `measure(mount, Constraints(mi 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. +`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 paint overrides now run during actual frame publication; measure/arrange/hitTest overrides during layout/input and contexts before first measurement remain future work, so this is not the complete custom visual protocol. + +A source subclass can override `paint(self, mount, geometry): DisplayList`. The renderer invokes that method for each occurrence, after Mount synchronization and hooks, using current logical Bounds. Its commands replace that occurrence's native paint in preorder. Calling `RectBlock.paint(self, mount, geometry)` or another native base method obtains a fresh result that can be modified before returning. `DisplayList(ObjectList(command, ...))` builds multiple commands; ObjectList accepts objects and has a 10000-member bound. PaintCommand fields use kind (`roundedRect`, `strokeRoundedRect` or `text`), x/y/color and the corresponding width/height/radius, strokeWidth, or text/size fields. Commands must pass the same native validation and a total 10000-command frame limit. See [source-paint.endor](examples/source-paint.endor), including a Button source method that updates the same tint field used by two occurrences. + +Paint runs in a read-only Aster call: existing heap objects cannot be modified; fresh result graphs may be allocated and filled. Existing globals, model fields, containers, Mounts and types remain protected. invalidate is rejected in this phase. All overrides share one VM budget. Read dependencies are currently recorded per object, with versions used to detect changes without depending on bounded change-notification delivery. Native frames keep their existing dependency/cache behavior. Derived allocations do not produce application change notifications, preventing temporary results from causing redraw feedback. This protects managed heap writes; trusted Rust host implementations must also respect read-only calls for external state and I/O. Paint errors stop the affected runtime before publication; failed PUT candidates preserve the previously running heap and frame. 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 diff --git a/examples/README.md b/examples/README.md index 7bd8e8f..1d75037 100644 --- a/examples/README.md +++ b/examples/README.md @@ -2,6 +2,7 @@ | File | Purpose | | --- | --- | +| [source-paint.endor](source-paint.endor) | Source paint overrides render checked commands in the window; a source Button method updates the shared tint model. | | [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. | diff --git a/examples/source-paint.endor b/examples/source-paint.endor new file mode 100644 index 0000000..a8ba888 --- /dev/null +++ b/examples/source-paint.endor @@ -0,0 +1,36 @@ +class TintRect: RectBlock { + tint: String + function paint(self: TintRect, mount: Mount, geometry: Bounds): DisplayList { + drawing = RectBlock.paint(self, mount, geometry) + drawing.commands.at(0).color = self.tint + return drawing + } +} +class Badge: TextBlock { + background: String + function paint(self: Badge, mount: Mount, geometry: Bounds): DisplayList { + fill = PaintCommand() + fill.kind = "roundedRect" + fill.x = geometry.x + fill.y = geometry.y + fill.width = geometry.width + fill.height = geometry.height + fill.radius = 6 + fill.color = self.background + text = TextBlock.paint(self, mount, geometry).commands.at(0) + text.color = "#FFFFFF" + return DisplayList(ObjectList(fill, text)) + } +} +class RecolorButton: Button { + target: TintRect + function onEvent(self: RecolorButton, event: Event): Unit { + self.target.tint = "#526AC7" + } +} +rect = TintRect(200, 60, 12, "#DDEEFF", "#ED6A5A") +badge = Badge("Endor 源码正在绘制这个背景", 2, "#237A45") +button = RecolorButton("通过对象方法改变绘制颜色", rect) +root = Column(24, 16, TextBlock("源码 paint 进入真实窗口", 2), rect, rect, badge, button) +page = Page() +page.render(root) diff --git a/src/README.md b/src/README.md index 92f3f7b..c67fdec 100644 --- a/src/README.md +++ b/src/README.md @@ -9,11 +9,12 @@ | 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 | Inheritable native nominal constructors with source fields, 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, content-owned field storage, shared assignment, cycle validation and explicit text bindings | -| snapshot.rs | Property dependencies across shared field-storage paths, reverse parent links and cached immutable visual derivation | +| snapshot.rs | Property and visual-method identity dependencies across shared field-storage paths, reverse parent links and cached immutable visual derivation | | mount.rs | Managed per-occurrence contexts, weak reverse links, ordered mount/unmount hooks, geometry and focus queries | | events.rs | Bounded native input transport to the owning VM | | event_dispatch.rs | Managed Event, weak Subscription tokens, Block-owned connections and occurrence-specific capture/target/bubble through a budgeted VM driver | | vm_sequence.rs | Shared validated call-sequence builder for event and lifecycle batches in the existing VM frame loop | +| source_paint.rs | Read-only source paint dispatch, shared VM budget, checked command conversion and versioned object dependencies | | 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 | diff --git a/src/document.rs b/src/document.rs index 7d89b41..6bb7a47 100644 --- a/src/document.rs +++ b/src/document.rs @@ -319,7 +319,7 @@ pub enum RenderCommand { } impl RenderCommand { - fn validate(&self) -> Result<()> { + pub(crate) fn validate(&self) -> Result<()> { match self { Self::RoundedRect { x, diff --git a/src/endor_host.rs b/src/endor_host.rs index a81ef8f..96a8589 100644 --- a/src/endor_host.rs +++ b/src/endor_host.rs @@ -477,7 +477,13 @@ impl ReplSession { } mutated_mounts = true; self.bridge - .commit_frame(&mut self.candidate.vm, root, &document.frame)?; + .commit_frame(&mut self.candidate.vm, root.clone(), &document.frame)?; + self.bridge.paint_frame( + &mut self.candidate.vm, + root.as_deref(), + &mut document.frame, + )?; + document.validate()?; last = Some(document); })(); if result.is_err() && mutated_mounts { @@ -795,6 +801,102 @@ mod tests { const EXAMPLE: &str = include_str!("../examples/hello.endor"); const PAGE: &str = include_str!("../examples/page.endor"); + #[test] + fn source_paint_overrides_native_commands_and_reacts_to_heap_field_writes() { + let (mut session, initial) = ReplSession::load( + include_str!("../examples/source-paint.endor"), + "app.main", + 71, + 1, + ) + .unwrap(); + initial.validate().unwrap(); + assert_eq!(initial.frame.commands.iter().filter(|command| matches!(command, RenderCommand::RoundedRect { color, .. } if color == "#ED6A5A")).count(), 2); + assert!(initial.frame.commands.iter().any( + |command| matches!(command, RenderCommand::Text { color, .. } if color == "#FFFFFF") + )); + let globals = session.candidate.globals.unwrap(); + let Value::Object(rect) = session + .candidate + .vm + .dict_get(globals, &Value::Text("rect".into())) + .unwrap() + .unwrap() + else { + panic!("Block") + }; + // No Console/global binding writes or focus changes: only the property + // read by paint changes, proving the paint dependency is sufficient. + session + .candidate + .vm + .set_attr(rect, "tint", Value::Text("#526AC7".into())) + .unwrap(); + let updated = session.refresh_document().unwrap().unwrap(); + assert_eq!(updated.frame.commands.iter().filter(|command| matches!(command, RenderCommand::RoundedRect { color, .. } if color == "#526AC7")).count(), 2); + assert!(session.refresh_document().unwrap().is_none()); + } + + #[test] + fn source_paint_rejects_business_mutation_before_it_happens_and_restores_scope() { + let source = r##"class BadPaint: RectBlock { + tint: String + function paint(self: BadPaint, mount: Mount, geometry: Bounds): DisplayList { + self.tint = "#000000" + return RectBlock.paint(self, mount, geometry) + } + } + rect = BadPaint(100, 40, 0, "#DDEEFF", "#FF0000") + page = Page() + page.render(rect)"##; + let mut session = ReplSession::new(72).unwrap(); + assert!( + session + .execute(source, "app.main") + .err() + .unwrap() + .to_string() + .contains("read-only") + ); + assert!(session.is_faulted()); + let globals = session.candidate.globals.unwrap(); + let Value::Object(rect) = session + .candidate + .vm + .dict_get(globals, &Value::Text("rect".into())) + .unwrap() + .unwrap() + else { + panic!("Block") + }; + assert_eq!( + session.candidate.vm.get_attr(rect, "tint").unwrap(), + Value::Text("#FF0000".into()) + ); + session + .candidate + .vm + .set_attr(rect, "tint", Value::Text("#526AC7".into())) + .unwrap(); + let bad_color = + include_str!("../examples/source-paint.endor").replace("#ED6A5A", "invalid color"); + assert!(ReplSession::load(&bad_color, "app.main", 73, 1).is_err()); + } + + #[test] + fn source_paint_is_stable_when_mount_notifications_overflow_the_change_batch() { + let fixture = include_str!("../examples/source-paint.endor"); + let mut source = fixture[..fixture.find("root = Column").unwrap()].to_owned(); + source.push_str("root = Column(0, 0"); + for _ in 0..1100 { + source.push_str(", rect"); + } + source.push_str(")\npage = Page()\npage.render(root)"); + let (mut session, document) = ReplSession::load(&source, "app.main", 74, 1).unwrap(); + assert_eq!(document.frame.commands.len(), 1100); + assert!(session.refresh_document().unwrap().is_none()); + } + #[test] fn native_visual_methods_use_managed_values_and_match_real_geometry() { let (mut session, initial) = ReplSession::load( diff --git a/src/main.rs b/src/main.rs index 9d81b93..25b9397 100644 --- a/src/main.rs +++ b/src/main.rs @@ -18,6 +18,7 @@ mod object_list; mod scene; mod snapshot; mod software_renderer; +mod source_paint; mod sources; mod system_ui; mod text; diff --git a/src/object_list.rs b/src/object_list.rs index 375fd5a..12bb234 100644 --- a/src/object_list.rs +++ b/src/object_list.rs @@ -48,6 +48,20 @@ pub fn collection( mounts: Vec, desktop: ObjectRef, ) -> Result { + build(cx, mounts, desktop, None) +} + +fn build( + cx: &mut NativeContext<'_>, + mounts: Vec, + desktop: ObjectRef, + definition: Option, +) -> Result { + if mounts.len() > 10_000 { + return Err(VmError::InvalidArgument( + "object list exceeds 10000 members", + )); + } let first = mounts .first() .copied() @@ -55,7 +69,11 @@ pub fn collection( .unwrap_or(Value::Nil); let count = mounts.len(); let set = cx.allocate(ObjectList(mounts))?; - crate::ui_bridge::attach_desktop_type(cx, set, "ObjectList", desktop)?; + if let Some(definition) = definition { + cx.attach_type(set, definition)?; + } else { + crate::ui_bridge::attach_desktop_type(cx, set, "ObjectList", desktop)?; + } cx.set_attr(set, "first", first)?; cx.set_attr(set, "count", Value::Number((count as i64).into()))?; let at = cx.allocate(ContextNativeFunction::new("at", At(set), vec![set]))?; @@ -63,3 +81,53 @@ pub fn collection( cx.set_attr(set, "at", Value::Object(at))?; Ok(set) } + +pub fn items(store: &endor_core::ObjectStore, list: ObjectRef) -> Result<&[ObjectRef], VmError> { + Ok(&store.payload::(list, "ObjectList")?.0) +} + +#[derive(Debug)] +pub struct Constructor { + pub desktop: ObjectRef, +} +impl NativeCallable for Constructor { + fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result { + let [Value::Object(definition), values @ ..] = args else { + return Err(VmError::InvalidArgument("ObjectList type argument")); + }; + let fields = cx + .store() + .payload::(*definition, "Type")? + .fields() + .to_vec(); + if fields + .iter() + .any(|field| matches!(field.name.as_str(), "count" | "first" | "at")) + { + return Err(VmError::InvalidArgument("reserved ObjectList field")); + } + let count = values + .len() + .checked_sub(fields.len()) + .ok_or(VmError::InvalidArgument( + "missing ObjectList subclass fields", + ))?; + let members = values[..count] + .iter() + .map(|value| { + if let Value::Object(object) = value { + Ok(*object) + } else { + Err(VmError::InvalidArgument( + "ObjectList members must be objects", + )) + } + }) + .collect::, _>>()?; + let list = build(cx, members, self.desktop, Some(*definition))?; + for (field, value) in fields.iter().zip(&values[count..]) { + cx.set_attr(list, &field.name, value.clone())?; + } + Ok(NativeResult::Return(Value::Object(list))) + } +} diff --git a/src/snapshot.rs b/src/snapshot.rs index 3d727b4..b7f60d0 100644 --- a/src/snapshot.rs +++ b/src/snapshot.rs @@ -142,6 +142,25 @@ impl RenderCache { continue; } path.remove(&data_ref); + let mut protocol_key = String::new(); + if let Some(definition) = store.type_of(block)? { + protocol_key.push_str(&definition.to_string()); + for name in ["measure", "arrange", "paint", "hitTest"] { + if let Some(method) = store.lookup_method(definition, name)? { + protocol_key.push_str(&format!("/{method}")); + } + } + let mut current = Some(definition); + while let Some(definition) = current { + dependencies.push(Dependency { + object: definition, + property: None, + }); + current = store + .payload::(definition, "Type")? + .base(); + } + } let children = values.split_off(values.len() - data.children.len()); let kind = match &data.kind { Kind::Text { value, size, color } => { @@ -205,6 +224,7 @@ impl RenderCache { }; let next = UiNode { block_id: block.to_string(), + protocol_key, slots: data.children.iter().map(|c| c.slot).collect(), interactive: matches!(&data.kind, Kind::Button) || data.click.is_some(), kind, diff --git a/src/source_paint.rs b/src/source_paint.rs new file mode 100644 index 0000000..99fefb8 --- /dev/null +++ b/src/source_paint.rs @@ -0,0 +1,332 @@ +//! Source paint dispatch produces checked immutable commands. One read-only VM +//! call sequences all overrides, sharing a single instruction/frame budget. +use crate::{ + document::{Frame, RenderCommand}, + layout::{self, Size}, + mount::Mount, + object_list, + ui_bridge::{MAX_DIMENSION, UiNode, attach_desktop_type}, +}; +use anyhow::{Result, bail}; +use endor_core::{ + CodeLayout, ContextNativeFunction, EndorCode, EndorCodeObject, Instruction, NativeCallable, + NativeContext, NativeResult, ObjectRef, ObjectStore, Opcode, Value, Vm, VmError, WeakObjectRef, +}; +use std::{ + collections::{BTreeMap, BTreeSet, HashMap}, + sync::{Arc, Mutex}, +}; + +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("paint must return managed objects")) + } +} +fn text(store: &ObjectStore, object: ObjectRef, name: &str) -> Result { + if let Value::Text(value) = store.get_attr(object, name)? { + Ok(value) + } else { + Err(invalid("paint field must be text")) + } +} +fn number(store: &ObjectStore, object: ObjectRef, name: &str) -> Result { + let Value::Number(value) = store.get_attr(object, name)? else { + return Err(invalid("paint field must be a Number")); + }; + let value = value + .to_string() + .parse::() + .map_err(|_| invalid("invalid paint number"))?; + if !value.is_finite() || !(0.0..=MAX_DIMENSION as f32).contains(&value) { + return Err(invalid("paint number exceeds bounds")); + } + Ok(value) +} +fn named_type(store: &ObjectStore, desktop: ObjectRef, name: &str) -> Result { + let registry = object(store.get_attr(desktop, "types")?)?; + object( + store + .dict_get(registry, &Value::Text(name.into()))? + .ok_or(invalid("missing paint type"))?, + ) +} +fn decode( + store: &ObjectStore, + command: ObjectRef, + expected: ObjectRef, +) -> Result { + if !store.is_instance(command, expected)? { + return Err(invalid("paint commands must be PaintCommand instances")); + } + let x = number(store, command, "x")?; + let y = number(store, command, "y")?; + let color = text(store, command, "color")?; + let kind = text(store, command, "kind")?; + let result = match kind.as_str() { + "roundedRect" | "strokeRoundedRect" => { + let width = number(store, command, "width")?; + let height = number(store, command, "height")?; + let radius = number(store, command, "radius")?; + if x + width > MAX_DIMENSION as f32 || y + height > MAX_DIMENSION as f32 { + return Err(invalid("paint rectangle exceeds bounds")); + } + if kind == "roundedRect" { + RenderCommand::RoundedRect { + x, + y, + width, + height, + radius, + color, + } + } else { + RenderCommand::StrokeRoundedRect { + x, + y, + width, + height, + radius, + color, + stroke_width: number(store, command, "strokeWidth")?, + } + } + } + "text" => { + let size = number(store, command, "size")?; + if size.fract() != 0.0 || !(1.0..=8.0).contains(&size) { + return Err(invalid("paint text size must be an integer from 1 to 8")); + } + RenderCommand::Text { + x, + y, + value: text(store, command, "text")?, + size: size as u32, + color, + } + } + _ => return Err(invalid("unsupported paint command kind")), + }; + result + .validate() + .map_err(|_| invalid("invalid paint command geometry, text or color"))?; + Ok(result) +} + +#[derive(Debug, Default)] +struct PaintOutput { + commands: BTreeMap>, + count: usize, +} +type Output = Arc>; +#[derive(Debug)] +struct Collect { + desktop: ObjectRef, + mount: u64, + output: Output, +} +impl NativeCallable for Collect { + fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result { + let [Value::Object(result)] = args else { + return Err(invalid("paint must return a DisplayList")); + }; + if !cx.store().is_instance( + *result, + named_type(cx.store(), self.desktop, "DisplayList")?, + )? { + return Err(invalid("paint must return a DisplayList")); + } + let commands = object(cx.store().get_attr(*result, "commands")?)?; + let expected = named_type(cx.store(), self.desktop, "PaintCommand")?; + let commands = object_list::items(cx.store(), commands)? + .iter() + .map(|command| decode(cx.store(), *command, expected)) + .collect::, _>>()?; + let mut output = self + .output + .lock() + .map_err(|_| invalid("paint output poisoned"))?; + if output.count + commands.len() > 10_000 { + return Err(invalid("paint command budget exceeded")); + } + output.count += commands.len(); + output.commands.insert(self.mount, commands); + Ok(NativeResult::Return(Value::Nil)) + } +} +#[derive(Debug)] +struct Prepare { + desktop: ObjectRef, + mounts: Vec<(u64, WeakObjectRef)>, + output: Output, +} +impl NativeCallable for Prepare { + fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result { + let block_type = named_type(cx.store(), self.desktop, "Block")?; + let native = cx + .store() + .lookup_method(block_type, "paint")? + .ok_or(invalid("missing native paint"))?; + let mut constants = Vec::new(); + let mut instructions = Vec::new(); + for (id, weak) in &self.mounts { + let mount = cx + .upgrade(*weak)? + .ok_or(invalid("paint Mount has expired"))?; + let data = cx.store().payload::(mount, "Mount")?.clone(); + if !data.mounted { + return Err(invalid("paint Mount is detached")); + } + let definition = cx + .store() + .type_of(data.block)? + .ok_or(invalid("untyped paint target"))?; + let function = cx + .store() + .lookup_method(definition, "paint")? + .ok_or(invalid("missing paint method"))?; + if function == native { + continue; + } + let bounds = cx.new_object()?; + attach_desktop_type(cx, bounds, "Bounds", self.desktop)?; + for (name, value) in [ + ("x", data.geometry.x), + ("y", data.geometry.y), + ("width", data.geometry.width), + ("height", data.geometry.height), + ] { + cx.set_attr(bounds, name, Value::Number((value as f64).into()))?; + } + let collector = cx.allocate(ContextNativeFunction::new( + "collect source paint", + Collect { + desktop: self.desktop, + mount: *id, + output: self.output.clone(), + }, + vec![self.desktop], + ))?; + let start = constants.len() as u32; + constants.extend([ + Value::Object(collector), + Value::Object(function), + Value::Object(data.block), + Value::Object(mount), + Value::Object(bounds), + ]); + instructions.extend([ + Instruction::new(Opcode::LoadConst, start), + Instruction::simple(Opcode::PushNull), + Instruction::new(Opcode::LoadConst, start + 1), + Instruction::simple(Opcode::PushNull), + Instruction::new(Opcode::LoadConst, start + 2), + Instruction::new(Opcode::LoadConst, start + 3), + Instruction::new(Opcode::LoadConst, start + 4), + Instruction::new(Opcode::Call, 3), + Instruction::new(Opcode::Call, 1), + Instruction::simple(Opcode::PopTop), + ]); + } + if instructions.is_empty() { + return Ok(NativeResult::Return(Value::Nil)); + } + let index = constants.len() as u32; + constants.push(Value::Nil); + instructions.extend([ + Instruction::new(Opcode::LoadConst, index), + Instruction::simple(Opcode::ReturnValue), + ]); + let code = EndorCode::from_instructions(&instructions, constants, CodeLayout::default())? + .with_location("", "", 1); + let code = cx.allocate(EndorCodeObject::new(code))?; + let globals = cx.new_dict()?; + let driver = cx.new_function("source paint", code, globals)?; + Ok(NativeResult::Invoke { + function: driver, + arguments: vec![], + }) + } +} + +pub fn render( + vm: &mut Vm, + desktop: ObjectRef, + mounts: Vec<(u64, WeakObjectRef)>, + root: Option<&UiNode>, + frame: &mut Frame, +) -> Result> { + let output = Arc::new(Mutex::new(PaintOutput::default())); + let prepare = vm.allocate(ContextNativeFunction::new( + "prepare source paint", + Prepare { + desktop, + mounts, + output: output.clone(), + }, + vec![desktop], + ))?; + let result = vm.call_read_only_with_limits( + prepare, + &[], + endor_core::ExecutionLimits { + max_frames: 128, + max_instructions: 1_000_000, + }, + ); + vm.release(prepare)?; + let (value, reads) = result.map_err(|error| crate::endor_host::runtime_error(vm, error))?; + vm.release_value(value)?; + let output = output + .lock() + .map_err(|_| anyhow::anyhow!("paint output poisoned"))?; + if output.commands.is_empty() { + return Ok(BTreeSet::new()); + } + let mut nodes = HashMap::new(); + let mut pending: Vec<_> = root.into_iter().collect(); + while let Some(node) = pending.pop() { + nodes.insert(node.block_id.as_str(), node); + pending.extend(node.children().iter().map(|node| node.as_ref())); + } + let mut commands = Vec::new(); + for mount in &frame.mounts { + if let Some(custom) = output.commands.get(&mount.id) { + commands.extend(custom.iter().cloned()); + } else { + let node = nodes + .get(mount.block_id.as_str()) + .ok_or_else(|| anyhow::anyhow!("paint projection has no node"))?; + if let Some(command) = layout::paint_native( + node, + mount.x, + mount.y, + Size { + width: mount.width, + height: mount.height, + }, + ) { + commands.push(command); + } + } + if commands.len() > 10_000 { + bail!("paint command budget exceeded"); + } + } + frame.commands = commands; + let registry = object(vm.get_attr(desktop, "types")?)?; + Ok(reads + .into_iter() + .filter(|object| { + *object != desktop + && *object != registry + && vm + .object(*object) + .is_ok_and(|object| !object.payload().as_any().is::()) + }) + .collect()) +} diff --git a/src/ui_bridge.rs b/src/ui_bridge.rs index 1f6eb56..c591972 100644 --- a/src/ui_bridge.rs +++ b/src/ui_bridge.rs @@ -46,6 +46,7 @@ pub const QUERY_NAMES: &[&str] = &["isInstance", "isSubtype"]; #[derive(Debug, Clone, PartialEq)] pub struct UiNode { pub block_id: String, + pub protocol_key: String, pub slots: Vec, pub interactive: bool, pub kind: UiKind, @@ -63,6 +64,7 @@ impl UiNode { pub fn shallow_eq(&self, other: &Self) -> bool { if self.block_id != other.block_id + || self.protocol_key != other.protocol_key || self.slots != other.slots || self.interactive != other.interactive { @@ -177,6 +179,7 @@ struct Session { mounts: crate::mount::MountTable, published_version: u64, force_frame: bool, + paint_reads: std::collections::BTreeMap, snapshot_visited: usize, snapshot_reused: usize, } @@ -521,6 +524,11 @@ impl NativeCallable for Function { return Ok(NativeResult::Return(Value::Bool(value))); } if matches!(self.operation, Invalidate) { + if cx.store().is_read_only() { + return Err(invalid( + "invalidation is forbidden during read-only rendering", + )); + } let reason = args .first() .map(|value| text(Some(value))) @@ -1125,6 +1133,13 @@ impl UiBridge { .lock() .map_err(|_| anyhow::anyhow!("UI session poisoned"))?; let active = state.pending.unwrap_or(state.active); + if state + .paint_reads + .iter() + .any(|(object, version)| vm.change_version(*object).ok() != Some(*version)) + { + state.force_frame = true; + } state.render_cache.invalidate(changes); let root = active .map(|v| state.render_cache.snapshot(vm.object_store(), v)) @@ -1195,6 +1210,44 @@ impl UiBridge { result } + pub fn paint_frame( + &self, + vm: &mut Vm, + root: Option<&UiNode>, + frame: &mut crate::document::Frame, + ) -> Result<()> { + let (desktop, mounts) = { + let state = self + .session + .lock() + .map_err(|_| anyhow::anyhow!("UI session poisoned"))?; + let mounts = frame + .mounts + .iter() + .map(|mount| { + state + .mounts + .active + .get(&mount.id) + .copied() + .map(|weak| (mount.id, weak)) + .ok_or_else(|| anyhow::anyhow!("paint Mount is unavailable")) + }) + .collect::>>()?; + (state.desktop, mounts) + }; + let reads = crate::source_paint::render(vm, desktop, mounts, root, frame)?; + let reads = reads + .into_iter() + .map(|object| vm.change_version(object).map(|version| (object, version))) + .collect::, _>>()?; + self.session + .lock() + .map_err(|_| anyhow::anyhow!("UI session poisoned"))? + .paint_reads = reads; + Ok(()) + } + pub fn layout_frame(&self, vm: &Vm, root: &UiNode) -> Result { let mut state = self .session @@ -1244,6 +1297,7 @@ pub fn install(vm: &mut Vm, roots: &mut Vec) -> Result { mounts: crate::mount::MountTable::default(), published_version: 0, force_frame: false, + paint_reads: std::collections::BTreeMap::new(), snapshot_visited: 0, snapshot_reused: 0, })); @@ -1298,10 +1352,21 @@ pub fn install(vm: &mut Vm, roots: &mut Vec) -> Result { ("Mount", "Object", None), ("Event", "Object", Some("event")), ("Subscription", "Object", None), - ("ObjectList", "Object", None), + ("ObjectList", "Object", Some("object-list")), ] { let base = object(Some(&vm.get_attr(ui, base_name)?))?; let constructor = match constructor_name { + Some("object-list") => { + let factory = vm.allocate(ContextNativeFunction::new( + "object-list", + crate::object_list::Constructor { desktop }, + vec![desktop], + ))?; + roots.push(factory); + let function_type = object(Some(&vm.get_attr(ui, "Function")?))?; + vm.attach_type(factory, function_type)?; + TypeConstructor::NativeTyped(factory) + } Some("event") => { let factory = vm.allocate(ContextNativeFunction::new( "event", diff --git a/vendor/aster b/vendor/aster index 44a02c9..ff49f26 160000 --- a/vendor/aster +++ b/vendor/aster @@ -1 +1 @@ -Subproject commit 44a02c9fd6b08515babe774486ef1c5050a859a1 +Subproject commit ff49f266a23801898321d780dbf0879e9f479b11