Add per-Mount scrolling with shared paint and input clipping
Verify Tessera GUI / verify (push) Failing after 7m33s

This commit is contained in:
2026-10-21 22:05:08 +08:00
parent 7acc5783a5
commit 6e69c5e5ce
18 changed files with 784 additions and 33 deletions
+11
View File
@@ -29,6 +29,7 @@
| app.rs | Window events, logical viewport publication, 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 |
| system_ui/ | Host-only management widget library: stable IDs, interaction, theme and reusable control drawing |
| scroll.rs | Per-Mount offsets, nested scrollIntoView, shared geometry/clip projection and wheel ancestor selection |
| scene.rs | Page and developer-tools display-list composition |
| developer_tools.rs | Unified Console prompt/output stream, caret/IME mapping, full Sources, Network inspector, theme, scrolling, overlay splitters and focus |
| sources.rs | Disconnected cloud workspace and provider boundary for listing/opening complete source files |
@@ -115,3 +116,13 @@ current call budget, passes the current managed Window, and validates a real
Block result before opening it. Native base visual methods and runtime result
checks remain the rendering boundary. Matching present names without an explicit
implementation keep the summary fallback and do not execute guest methods.
ScrollBlock keeps viewport dimensions in the managed Block properties and keeps
scroll offsets on Mounts. Layout measures content without a finite viewport bound;
a post-layout projection clamps offsets, translates descendants and intersects
ancestor clips before committing Mount geometry. It rebuilds native commands and
per-command clips; source painting preserves the same clip table. Input, focus
outlines and public hit queries consume this projection. Wheel transport carries
finite signed deltas, validates the frame/window/session, and invokes the actual
Mount.scrollBy method without changing guest focus. Mount requests mark a
per-window projection refresh; snapshots/caches never own business objects.
+17 -5
View File
@@ -635,7 +635,13 @@ impl Worker {
};
if !matches!(
input.kind.as_str(),
"click" | "focus" | "tab-activate" | "tab-close" | "tab-detach" | "window-close"
"click"
| "focus"
| "scroll"
| "tab-activate"
| "tab-close"
| "tab-detach"
| "window-close"
) {
return error_response(StatusCode(400), "unsupported event kind");
}
@@ -684,10 +690,11 @@ impl Worker {
) {
!frame.tabs.iter().any(|tab| tab.id == input.mount)
} else {
!frame
.mounts
.iter()
.any(|mount| mount.id == input.mount && mount.interactive)
!frame.mounts.iter().any(|mount| {
mount.id == input.mount
&& (mount.interactive
|| input.kind == "scroll" && mount.scroll.is_some())
})
}
|| self.repl.as_ref().is_none_or(|(context, runtime)| {
*context != epoch
@@ -1042,6 +1049,10 @@ Source measure and arrange overrides execute bottom-up and top-down in one read-
Source paint overrides execute in the actual frame pipeline under a read-only heap policy. Source hitTest overrides similarly refine native pointer targets in VM paint order; Point.inside(bounds) and Point.inCircle(cx, cy, radius) provide primitive shape queries. Managed DisplayList/ObjectList/PaintCommand and Constraints/Bounds/Point results are ordinary runtime objects.
ScrollBlock(width,height,child) is a ContainerBlock with managed viewport dimensions and independent per-Mount offsets. mount.scrollTo(x,y), scrollBy(dx,dy), scrollPosition() and scrollIntoView() operate on actual occurrences. Position snapshots expose x/y/maxX/maxY from committed layout; relative requests accumulate and offsets clamp after content/viewport changes. Detached Mounts and read-only rendering mutations are rejected. scrollIntoView and requestFocus adjust nested scrollable ancestors. Native/source paint, focus outlines, hit testing and pointer selection share translated geometry and ancestor clips. Remounting starts a new offset. Paint x/y may be signed after scrolling; dimensions/radii remain nonnegative and coordinate budgets still apply. See examples/scroll.endor. Wheel chooses one eligible ancestor (not per-axis split); native scrollbar dragging, touch inertia and PageUp/PageDown remain pending.
Native wheel POST /events uses kind scroll with the normal window/session/layout_version, a scrollable mount ID, point=[x,y], delta=[dx,dy], and no press_point. Deltas are signed finite logical pixels within +/-1000000; positive moves toward the end of content. Other kinds must omit delta. Native Shift+wheel maps to horizontal. The host checks the active committed frame, target attachment and clipped viewport before invoking Mount.scrollBy. These fields are transport metadata; source code uses the Endor methods above.
Trait definitions Visual, EventTarget, Children and Presentable are managed nominal capabilities. ui.implement(type,capability) explicitly declares an implementation after required-method/positional-arity checks; ui.implements(type,capability) and ui.supports(value,capability) query it. Block declares Visual/EventTarget; ContainerBlock declares Children, inherited by Page. Same-name methods alone never declare an implementation. Source subclass construction and host method replacement validate inherited/affected descendant contracts. Native callable signatures are trusted; full parameter/return annotation and effect checks and formal trait syntax remain pending. EventTarget requires canonical on/dispatch/onEvent arities 3/2/1 after self; native optional convenience forms remain.
For a plain object explicitly implementing Presentable, present(self, window: Window): Block is invoked by ui.present(value) or ui.open(value), using the current managed Window and the same VM budget. The result must be an actual Block. Blocks pass through directly; unregistered values retain the summary fallback. Source views retain their business object via managed fields/callbacks/bindings, as in examples/presentable.endor. Viewing function definitions does not itself execute them. Rendering methods still run read-only with nominal result checks.
@@ -1217,6 +1228,7 @@ mod tests {
mount: 0,
kind: "window-close".into(),
point: None,
delta: None,
press_point: None,
},
1,
+39
View File
@@ -270,6 +270,7 @@ impl TesseraApp {
mount,
kind: "focus".into(),
point: None,
delta: None,
press_point: None,
});
}
@@ -398,6 +399,7 @@ impl TesseraApp {
mount: mount.id,
kind: "click".into(),
point: Some([point.x, point.y]),
delta: None,
press_point: Some([point.x, point.y]),
})
}
@@ -423,6 +425,7 @@ impl TesseraApp {
mount: frame.tabs[index].id,
kind: if close { "tab-close" } else { "tab-activate" }.into(),
point: None,
delta: None,
press_point: None,
})
});
@@ -457,6 +460,7 @@ impl TesseraApp {
mount: id,
kind: if close { "tab-close" } else { "tab-activate" }.into(),
point: None,
delta: None,
press_point: None,
})
}
@@ -505,6 +509,7 @@ impl TesseraApp {
mount: targets[index].id,
kind: "focus".into(),
point: None,
delta: None,
press_point: None,
})
});
@@ -725,6 +730,7 @@ impl ApplicationHandler<AppEvent> for TesseraApp {
mount: 0,
kind: "window-close".into(),
point: None,
delta: None,
press_point: None,
});
if let Some(input) = input {
@@ -839,6 +845,39 @@ impl ApplicationHandler<AppEvent> for TesseraApp {
dx = dy;
dy = 0.0;
}
if !self.guest_covered(self.pointer) {
let input = self.namespace.read().ok().and_then(|namespace| {
let frame = &namespace.document.frame;
let offset = crate::tabs::height(&frame.tabs);
if frame.session == 0
|| frame.fault.is_some()
|| self.pointer.y < offset
|| namespace.viewport.is_some_and(|s| {
self.pointer.x < 0.0
|| self.pointer.x >= s.width
|| self.pointer.y >= s.height
})
{
return None;
}
let point = Point::new(self.pointer.x, self.pointer.y - offset);
let delta = [-dx, -dy];
let mount = crate::scroll::wheel_target(frame, point, delta)?;
Some(crate::events::Input {
window: self.resource,
session: frame.session,
layout_version: frame.layout_version,
mount,
kind: "scroll".into(),
point: Some([point.x, point.y]),
press_point: None,
delta: Some(delta),
})
});
if let Some(input) = input {
self.send_guest(input);
}
}
self.developer_tools
.wheel(&self.layout.developer_tools, self.pointer, dx, dy);
window.request_redraw();
+10 -1
View File
@@ -26,6 +26,10 @@ pub enum Kind {
color: String,
},
Spacer(f32),
Scroll {
width: f32,
height: f32,
},
Row,
Column,
Button,
@@ -147,7 +151,7 @@ impl Data {
pub fn is_container(&self) -> bool {
matches!(
self.kind,
Kind::Row | Kind::Column | Kind::Button | Kind::Page
Kind::Row | Kind::Column | Kind::Button | Kind::Page | Kind::Scroll { .. }
)
}
}
@@ -317,6 +321,9 @@ pub fn native_properties(data: &Data) -> Vec<(&'static str, Value)> {
("radius", number(*radius)),
("color", Value::Text(color.clone())),
]),
Kind::Scroll { width, height } => {
fields.extend([("width", number(*width)), ("height", number(*height))])
}
Kind::Spacer(size) => fields.push(("size", number(*size))),
_ => {}
}
@@ -375,6 +382,8 @@ pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Resu
crate::document::parse_color(value).map_err(|_| bad())?;
color.clone_from(value);
}
(Kind::Scroll { width, .. }, "width") => *width = number()?,
(Kind::Scroll { height, .. }, "height") => *height = number()?,
(Kind::Rect { width, .. }, "width") => *width = number()?,
(Kind::Rect { height, .. }, "height") => *height = number()?,
(Kind::Rect { radius, .. }, "radius") => *radius = number()?,
+57 -5
View File
@@ -136,6 +136,14 @@ impl RenderDocument {
bail!("invalid window identity");
}
parse_color(&self.frame.background)?;
if !self.frame.command_clips.is_empty()
&& self.frame.command_clips.len() != self.frame.commands.len()
{
bail!("invalid command clip table");
}
for clip in self.frame.command_clips.iter().flatten() {
validate_rect(clip[0], clip[1], clip[2], clip[3], 0.0)?;
}
for command in &self.frame.commands {
command.validate()?;
}
@@ -159,6 +167,17 @@ impl RenderDocument {
bail!("invalid or duplicate mount identity");
}
validate_rect(mount.x, mount.y, mount.width, mount.height, 0.0)?;
if let Some(clip) = mount.clip {
validate_rect(clip[0], clip[1], clip[2], clip[3], 0.0)?;
}
if let Some(scroll) = mount.scroll
&& (!scroll.iter().all(|n| {
n.is_finite() && (0.0..=crate::ui_bridge::MAX_DIMENSION as f32).contains(n)
}) || scroll[0] > scroll[2]
|| scroll[1] > scroll[3])
{
bail!("invalid scroll projection");
}
}
for mount in &self.frame.mounts {
for linked in [mount.parent, mount.first_child, mount.next_sibling]
@@ -191,13 +210,27 @@ impl RenderDocument {
let frame = &self.frame;
let mut list = DisplayList::default();
list.push(DrawCommand::Clear(parse_color(&frame.background)?));
for command in &frame.commands {
for (index, command) in frame.commands.iter().enumerate() {
let clip = frame.command_clips.get(index).copied().flatten();
if let Some(clip) = clip {
list.push(DrawCommand::PushClip(scaled_rect(
clip[0], clip[1], clip[2], clip[3], scale,
)));
}
list.push(command.to_draw_command(scale)?);
if clip.is_some() {
list.push(DrawCommand::PopClip);
}
}
if let Some(focus) = frame
.focus
.and_then(|id| frame.mounts.iter().find(|m| m.id == id))
{
if let Some(c) = focus.clip {
list.push(DrawCommand::PushClip(scaled_rect(
c[0], c[1], c[2], c[3], scale,
)));
}
list.push(
RenderCommand::StrokeRoundedRect {
x: focus.x,
@@ -210,6 +243,9 @@ impl RenderDocument {
}
.to_draw_command(scale)?,
);
if focus.clip.is_some() {
list.push(DrawCommand::PopClip);
}
}
if let Some(error) = &frame.fault {
list.push(
@@ -292,6 +328,8 @@ pub struct Frame {
#[serde(default)]
pub commands: Vec<RenderCommand>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub command_clips: Vec<Option<[f32; 4]>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub mounts: Vec<MountGeometry>,
#[serde(default)]
pub layout_version: u64,
@@ -311,6 +349,7 @@ impl Default for Frame {
window: crate::window::MAIN_WINDOW,
background: default_background(),
commands: Vec::new(),
command_clips: Vec::new(),
mounts: Vec::new(),
layout_version: 0,
session: 0,
@@ -324,6 +363,10 @@ impl Default for Frame {
/// A position in a published frame. Identifiers are opaque data, never VM handles.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct MountGeometry {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub clip: Option<[f32; 4]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scroll: Option<[f32; 4]>,
pub id: u64,
pub block_id: String,
pub parent: Option<u64>,
@@ -336,15 +379,24 @@ pub struct MountGeometry {
pub interactive: bool,
}
impl MountGeometry {
pub fn contains(&self, point: Point) -> bool {
Rect::new(self.x, self.y, self.width, self.height).contains(point)
&& self.clip.is_none_or(|c| {
c[2] > 0.0 && c[3] > 0.0 && Rect::new(c[0], c[1], c[2], c[3]).contains(point)
})
}
}
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)
})
self.mounts
.iter()
.rev()
.find(|mount| mount.interactive && mount.contains(point))
}
}
+156
View File
@@ -1008,6 +1008,7 @@ mod tests {
mount,
kind: "click".into(),
point: None,
delta: None,
press_point: None
})
.is_err()
@@ -1190,6 +1191,7 @@ mod tests {
mount: initial.frame.tabs[0].id,
kind: "tab-activate".into(),
point: None,
delta: None,
press_point: None,
};
let selected = session.dispatch(&input).unwrap().document.unwrap();
@@ -1217,6 +1219,7 @@ mod tests {
mount: renamed.frame.tabs[1].id,
kind: "tab-close".into(),
point: None,
delta: None,
press_point: None,
})
.unwrap()
@@ -1431,6 +1434,7 @@ mod tests {
mount: mount.id,
kind: "click".into(),
point: None,
delta: None,
press_point: None,
})
.unwrap()
@@ -1757,6 +1761,7 @@ mod tests {
mount: circle.id,
kind: "click".into(),
point: Some(release),
delta: None,
press_point: Some(press),
})
.unwrap();
@@ -1800,6 +1805,7 @@ mod tests {
mount: circle.id,
kind: "click".into(),
point: Some([64.0, 64.0]),
delta: None,
press_point: Some([64.0, 64.0]),
})
.err()
@@ -2265,6 +2271,7 @@ mod tests {
mount: mount.id,
kind: "click".into(),
point: None,
delta: None,
press_point: None,
})
.unwrap()
@@ -2544,6 +2551,7 @@ mod tests {
mount: mount.id,
kind: "click".into(),
point: None,
delta: None,
press_point: None,
};
let updated = session.dispatch(&event).unwrap().document.unwrap();
@@ -2562,6 +2570,154 @@ mod tests {
assert!(!session.is_faulted());
}
#[test]
fn scroll_occurrences_are_independent_and_clipped_pointer_input_is_ignored() {
let (mut session, initial) =
ReplSession::load(include_str!("../examples/scroll.endor"), "app.main", 1, 240)
.unwrap();
let globals = session.candidate.globals.unwrap();
let Value::Object(middle) = session
.candidate
.vm
.dict_get(globals, &Value::Text("middle".into()))
.unwrap()
.unwrap()
else {
panic!("expected Block");
};
let target = initial
.frame
.mounts
.iter()
.find(|m| m.block_id == middle.to_string())
.unwrap();
let point = [
target.x + target.width / 2.0,
target.y + target.height / 2.0,
];
assert!(!target.contains(crate::geometry::Point::new(point[0], point[1])));
session
.dispatch(&crate::events::Input {
window: 1,
session: 240,
layout_version: initial.frame.layout_version,
mount: target.id,
kind: "click".into(),
point: Some(point),
press_point: Some(point),
delta: None,
})
.unwrap();
assert_eq!(
session.execute("count.value", "app.main").unwrap().value,
"0"
);
session.execute("saved = scroller.mounts().at(0)\nsaved.scrollTo(0,100)\nsaved.scrollBy(0,20)\nsaved.scrollBy(0,30)","app.main").unwrap();
assert_eq!(
session
.execute("saved.scrollPosition().y", "app.main")
.unwrap()
.value,
"150"
);
assert_eq!(
session
.execute("scroller.mounts().at(1).scrollPosition().y", "app.main")
.unwrap()
.value,
"0"
);
session
.execute("last.mounts().at(0).scrollIntoView()", "app.main")
.unwrap();
let Value::Object(last) = session
.candidate
.vm
.dict_get(globals, &Value::Text("last".into()))
.unwrap()
.unwrap()
else {
panic!("expected Block");
};
let frame = &session.documents[&crate::window::MAIN_WINDOW].frame;
let target = frame
.mounts
.iter()
.find(|m| m.block_id == last.to_string())
.unwrap();
assert!(target.contains(crate::geometry::Point::new(
target.x + target.width / 2.0,
target.y + target.height / 2.0
)));
assert_eq!(frame.command_clips.len(), frame.commands.len());
session
.execute("scroller.height = 1000", "app.main")
.unwrap();
assert_eq!(
session
.execute("saved.scrollPosition().y", "app.main")
.unwrap()
.value,
"0"
);
assert_eq!(
session
.execute("saved.scrollPosition().maxY", "app.main")
.unwrap()
.value,
"0"
);
}
#[test]
fn nested_scroll_into_view_and_source_paint_share_clipped_geometry() {
let mut session = ReplSession::new(241).unwrap();
let result = session
.execute(
r#"
class Painted: RectBlock {
function paint(self: Painted, mount: Mount, geometry: Bounds): DisplayList {
return RectBlock.paint(self,mount,geometry)
}
}
last = Button("last")
inner = ScrollBlock(160,100,Column(0,8,Painted(200,180),last))
outer = ScrollBlock(180,140,Column(0,8,RectBlock(180,180),inner))
page = Page()
page.render(outer)
"#,
"app.main",
)
.unwrap()
.document
.unwrap();
assert!(result.frame.command_clips.iter().any(Option::is_some));
session
.execute("last.mounts().at(0).scrollIntoView()", "app.main")
.unwrap();
assert_eq!(
session
.execute("inner.mounts().at(0).scrollPosition().y", "app.main")
.unwrap()
.value,
"128"
);
assert_eq!(
session
.execute("outer.mounts().at(0).scrollPosition().y", "app.main")
.unwrap()
.value,
"148"
);
assert_eq!(
session
.execute("last.mounts().at(0).hitTest(10,110)", "app.main")
.unwrap()
.value,
"true"
);
}
#[test]
fn presentable_dispatch_preserves_source_identity_and_reactive_display() {
let (mut session, initial) = ReplSession::load(
+20
View File
@@ -22,6 +22,8 @@ pub struct Input {
pub point: Option<[f32; 2]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub press_point: Option<[f32; 2]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub delta: Option<[f32; 2]>,
}
fn default_window() -> u64 {
@@ -33,6 +35,24 @@ impl Input {
if self.window == 0 {
return Err("window identity must be nonzero");
}
if self.kind == "scroll" {
return match (self.point, self.press_point, self.delta) {
(Some(point), None, Some(delta))
if point
.iter()
.all(|v| v.is_finite() && (0.0..=1_000_000.0).contains(v))
&& delta
.iter()
.all(|v| v.is_finite() && v.abs() <= 1_000_000.0) =>
{
Ok(())
}
_ => Err("scroll requires point and finite delta, with no press_point"),
};
}
if self.delta.is_some() {
return Err("delta is only accepted for scroll input");
}
match (self.point, self.press_point) {
(None, None) => Ok(()),
(Some(point), Some(press))
+7
View File
@@ -64,6 +64,9 @@ pub fn root_constraints(viewport: Option<Size>) -> [f32; 4] {
[0.0, 0.0, size.width, size.height]
}
pub fn child_constraints(node: &UiNode, parent: [f32; 4]) -> [f32; 4] {
if matches!(node.kind, UiKind::Scroll { .. }) {
return [0.0, 0.0, MAX_DIMENSION as f32, MAX_DIMENSION as f32];
}
match container(node) {
Some((true, padding, _)) => [
0.0,
@@ -90,6 +93,7 @@ pub fn constrained(size: Size, constraints: [f32; 4]) -> Size {
fn container(node: &UiNode) -> Option<(bool, f32, f32)> {
match &node.kind {
UiKind::Row { padding, gap, .. } => Some((true, *padding, *gap)),
UiKind::Scroll { padding, gap, .. } => Some((false, *padding, *gap)),
UiKind::Column { padding, gap, .. } | UiKind::Button { padding, gap, .. } => {
Some((false, *padding, *gap))
}
@@ -145,6 +149,7 @@ fn shape(node: &UiNode, children: Vec<Size>) -> Result<Shape> {
UiKind::Text { value, size, .. } => Shape::Text(value.clone(), *size),
UiKind::Rect { width, height, .. } => Shape::Rect(*width, *height),
UiKind::Spacer(size) => Shape::Rect(*size, *size),
UiKind::Scroll { width, height, .. } => Shape::Rect(*width, *height),
_ => {
let (row, padding, gap) = container(node).context("unknown native visual protocol")?;
Shape::Container(row, padding, gap, children)
@@ -345,6 +350,8 @@ impl LayoutRuntime {
bounded(y + size.height)?;
mounts.push(MountGeometry {
id: item.id,
clip: None,
scroll: None,
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),
+1
View File
@@ -19,6 +19,7 @@ mod object_list;
mod presentation;
mod protocols;
mod scene;
mod scroll;
mod snapshot;
mod software_renderer;
mod source_hit;
+64 -14
View File
@@ -18,6 +18,7 @@ pub struct Mount {
pub first_child: Option<WeakObjectRef>,
pub next_sibling: Option<WeakObjectRef>,
pub geometry: MountGeometry,
pub scroll_offset: [f32; 2],
pub version: u64,
pub mounted: bool,
// Private derived scratch, installed before the read-only layout call and
@@ -46,6 +47,10 @@ impl ObjectPayload for Mount {
#[derive(Debug, Clone, Copy)]
enum Query {
Bounds,
ScrollTo,
ScrollBy,
ScrollPosition,
ScrollIntoView,
Parent,
FirstChild,
NextSibling,
@@ -64,10 +69,24 @@ struct Method {
impl NativeCallable for Method {
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
let mount = cx.store().payload::<Mount>(self.owner, "Mount")?.clone();
if !mount.mounted && matches!(self.query, Query::Bounds | Query::Focus | Query::HitTest) {
if !mount.mounted
&& matches!(
self.query,
Query::Bounds
| Query::Focus
| Query::HitTest
| Query::ScrollTo
| Query::ScrollBy
| Query::ScrollIntoView
| Query::ScrollPosition
)
{
return Err(VmError::InvalidArgument("Mount is no longer attached"));
}
let arity = if matches!(self.query, Query::HitTest) {
let arity = if matches!(
self.query,
Query::HitTest | Query::ScrollTo | Query::ScrollBy
) {
2
} else {
0
@@ -76,6 +95,34 @@ impl NativeCallable for Method {
return Err(VmError::InvalidArgument("incorrect Mount method arity"));
}
let value = match self.query {
Query::ScrollTo | Query::ScrollBy => {
crate::scroll::set(
cx,
self.owner,
self.desktop,
[
crate::scroll::coordinate(&args[0])?,
crate::scroll::coordinate(&args[1])?,
],
matches!(self.query, Query::ScrollBy),
)?;
Value::Nil
}
Query::ScrollIntoView => {
crate::scroll::into_view(cx, self.owner, self.desktop)?;
Value::Nil
}
Query::ScrollPosition => {
let p = mount
.geometry
.scroll
.ok_or(VmError::InvalidArgument("Mount is not scrollable"))?;
let result = cx.new_object()?;
for (name, value) in [("x", p[0]), ("y", p[1]), ("maxX", p[2]), ("maxY", p[3])] {
cx.set_attr(result, name, Value::Number((value as f64).into()))?;
}
Value::Object(result)
}
Query::Bounds => {
let geometry = if let Some(layout) = &mount.layout {
layout
@@ -110,6 +157,7 @@ impl NativeCallable for Method {
Value::Object(bounds)
}
Query::Focus => {
crate::scroll::into_view(cx, self.owner, self.desktop)?;
if !mount.geometry.interactive {
return Err(VmError::InvalidArgument("Mount is not focusable"));
}
@@ -145,18 +193,10 @@ impl NativeCallable for Method {
}
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])?,
)),
)
Value::Bool(mount.geometry.contains(crate::geometry::Point::new(
number(&args[0])?,
number(&args[1])?,
)))
}
query => {
let weak = match query {
@@ -277,6 +317,7 @@ impl NativeCallable for Sync {
first_child: None,
next_sibling: None,
geometry: geometry.clone(),
scroll_offset: [0.0, 0.0],
version: self.frame.layout_version,
mounted: true,
layout: None,
@@ -284,6 +325,10 @@ impl NativeCallable for Sync {
crate::ui_bridge::attach_desktop_type(cx, object, "Mount", self.desktop)?;
for (name, query) in [
("bounds", Query::Bounds),
("scrollTo", Query::ScrollTo),
("scrollBy", Query::ScrollBy),
("scrollPosition", Query::ScrollPosition),
("scrollIntoView", Query::ScrollIntoView),
("parent", Query::Parent),
("firstChild", Query::FirstChild),
("nextSibling", Query::NextSibling),
@@ -322,6 +367,11 @@ impl NativeCallable for Sync {
first_child: link(geometry.first_child)?,
next_sibling: link(geometry.next_sibling)?,
geometry: geometry.clone(),
scroll_offset: if self.preparing {
cx.store().payload::<Mount>(object, "Mount")?.scroll_offset
} else {
geometry.scroll.map(|s| [s[0], s[1]]).unwrap_or([0.0, 0.0])
},
version: self.frame.layout_version,
mounted: true,
layout: if self.preparing {
+2 -2
View File
@@ -192,8 +192,8 @@ impl NativeCallable for Method {
)?)
}
Query::Paint => {
let x = number(cx, input, "x", false)?;
let y = number(cx, input, "y", false)?;
let x = number(cx, input, "x", true)?;
let y = number(cx, input, "y", true)?;
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 {
+241
View File
@@ -0,0 +1,241 @@
//! Per-occurrence scroll state and a single geometry/clip projection shared by
//! native paint, source paint and input. No business object is copied.
use crate::{
document::Frame,
geometry::Point,
layout::{self, Size},
mount::{Mount, MountTable},
ui_bridge::{UiKind, UiNode},
};
use anyhow::{Result, bail};
use endor_core::{NativeContext, ObjectRef, Value, Vm, VmError, WeakObjectRef};
use std::collections::HashMap;
fn intersection(a: [f32; 4], b: [f32; 4]) -> [f32; 4] {
let x = a[0].max(b[0]);
let y = a[1].max(b[1]);
[
x,
y,
(a[0] + a[2]).min(b[0] + b[2]).max(x) - x,
(a[1] + a[3]).min(b[1] + b[3]).max(y) - y,
]
}
pub fn project(vm: &mut Vm, table: &MountTable, root: &UiNode, frame: &mut Frame) -> Result<()> {
let mut nodes = HashMap::new();
let mut work = vec![root];
while let Some(node) = work.pop() {
nodes.insert(node.block_id.as_str(), node);
work.extend(node.children().iter().map(|node| node.as_ref()));
}
let indices: HashMap<_, _> = frame
.mounts
.iter()
.enumerate()
.map(|(i, m)| (m.id, i))
.collect();
let scrolling: Vec<_> = frame
.mounts
.iter()
.map(|m| matches!(nodes[m.block_id.as_str()].kind, UiKind::Scroll { .. }))
.collect();
let mut extent: Vec<_> = frame
.mounts
.iter()
.map(|m| {
let padding = match nodes[m.block_id.as_str()].kind {
UiKind::Scroll { padding, .. } => padding,
_ => 0.0,
};
(m.x + m.width - padding, m.y + m.height - padding)
})
.collect();
for i in (0..frame.mounts.len()).rev() {
let m = &frame.mounts[i];
if let Some(parent) = m.parent {
let parent = indices[&parent];
let e = if scrolling[i] {
(m.x + m.width, m.y + m.height)
} else {
extent[i]
};
extent[parent].0 = extent[parent].0.max(e.0);
extent[parent].1 = extent[parent].1.max(e.1);
}
}
let mut contexts = HashMap::<u64, (f32, f32, Option<[f32; 4]>)>::new();
frame.commands.clear();
frame.command_clips.clear();
for (i, m) in frame.mounts.iter_mut().enumerate() {
let (dx, dy, clip) = m
.parent
.and_then(|id| contexts.get(&id).copied())
.unwrap_or_default();
let padding = match nodes[m.block_id.as_str()].kind {
UiKind::Scroll { padding, .. } => padding,
_ => 0.0,
};
let limits = [
(extent[i].0 + padding - m.x - m.width).max(0.0),
(extent[i].1 + padding - m.y - m.height).max(0.0),
];
m.x -= dx;
m.y -= dy;
m.clip = clip;
let mut child = (dx, dy, clip);
if scrolling[i] {
let weak = table
.active
.get(&m.id)
.ok_or_else(|| anyhow::anyhow!("missing scroll Mount"))?;
let owner = vm
.upgrade(*weak)?
.ok_or_else(|| anyhow::anyhow!("expired scroll Mount"))?;
let offset = vm
.payload::<Mount>(owner, "Mount")
.map(|mount| mount.scroll_offset);
vm.release(owner)?;
let offset = offset?;
let x = offset[0].clamp(0.0, limits[0]);
let y = offset[1].clamp(0.0, limits[1]);
m.scroll = Some([x, y, limits[0], limits[1]]);
let viewport = [m.x, m.y, m.width, m.height];
child = (
dx + x,
dy + y,
Some(
clip.map(|clip| intersection(clip, viewport))
.unwrap_or(viewport),
),
);
}
contexts.insert(m.id, child);
if let Some(command) = layout::paint_native(
nodes[m.block_id.as_str()],
m.x,
m.y,
Size {
width: m.width,
height: m.height,
},
) {
frame.commands.push(command);
frame.command_clips.push(m.clip);
}
}
if frame.commands.len() > 10_000 {
bail!("scroll paint command budget exceeded");
}
Ok(())
}
pub fn coordinate(value: &Value) -> Result<f32, VmError> {
let Value::Number(value) = value else {
return Err(VmError::InvalidArgument(
"scroll coordinates must be numbers",
));
};
let n = value
.to_string()
.parse::<f32>()
.map_err(|_| VmError::InvalidArgument("invalid scroll coordinate"))?;
if !n.is_finite() || n.abs() > 1_000_000.0 {
return Err(VmError::InvalidArgument("scroll coordinate exceeds limits"));
}
Ok(n)
}
pub fn set(
cx: &mut NativeContext<'_>,
owner: ObjectRef,
desktop: WeakObjectRef,
point: [f32; 2],
relative: bool,
) -> Result<(), VmError> {
let mut mount = cx.store().payload::<Mount>(owner, "Mount")?.clone();
if !mount.mounted || mount.layout.is_some() {
return Err(VmError::InvalidArgument(
"scroll requires committed attached Mount",
));
}
let bounds = mount
.geometry
.scroll
.ok_or(VmError::InvalidArgument("Mount is not scrollable"))?;
let next = if relative {
[
mount.scroll_offset[0] + point[0],
mount.scroll_offset[1] + point[1],
]
} else {
point
};
mount.scroll_offset = [next[0].clamp(0.0, bounds[2]), next[1].clamp(0.0, bounds[3])];
let desktop = cx
.upgrade(desktop)?
.ok_or(VmError::InvalidArgument("Mount window expired"))?;
// Check the normal mutation barrier even when the clamped result is equal.
cx.replace_payload(owner, mount)?;
cx.set_attr(desktop, "scrollRequested", Value::Bool(true))
}
pub fn into_view(
cx: &mut NativeContext<'_>,
owner: ObjectRef,
desktop: WeakObjectRef,
) -> Result<(), VmError> {
let mount = cx.store().payload::<Mount>(owner, "Mount")?.clone();
if !mount.mounted || mount.layout.is_some() {
return Err(VmError::InvalidArgument(
"scrollIntoView requires committed attached Mount",
));
}
let mut rect = [
mount.geometry.x,
mount.geometry.y,
mount.geometry.width,
mount.geometry.height,
];
let mut parent = mount.parent;
while let Some(weak) = parent {
let Some(owner) = cx.upgrade(weak)? else {
break;
};
let mount = cx.store().payload::<Mount>(owner, "Mount")?.clone();
parent = mount.parent;
if let Some(offset) = mount.geometry.scroll {
let delta = |start: f32, length: f32, viewport: f32, size: f32| {
if start < viewport {
start - viewport
} else {
(start + length - viewport - size).max(0.0)
}
};
let dx = delta(rect[0], rect[2], mount.geometry.x, mount.geometry.width);
let dy = delta(rect[1], rect[3], mount.geometry.y, mount.geometry.height);
let x = (offset[0] + dx).clamp(0.0, offset[2]);
let y = (offset[1] + dy).clamp(0.0, offset[3]);
rect[0] -= x - offset[0];
rect[1] -= y - offset[1];
if x != offset[0] || y != offset[1] {
set(cx, owner, desktop, [x, y], false)?;
}
}
}
Ok(())
}
pub fn wheel_target(frame: &Frame, point: Point, delta: [f32; 2]) -> Option<u64> {
let indices: HashMap<_, _> = frame.mounts.iter().map(|mount| (mount.id, mount)).collect();
let mut current = frame
.mounts
.iter()
.rev()
.find(|mount| mount.contains(point));
while let Some(mount) = current {
if mount.scroll.is_some_and(|s| {
(s[0] + delta[0]).clamp(0.0, s[2]) != s[0] || (s[1] + delta[1]).clamp(0.0, s[3]) != s[1]
}) {
return Some(mount.id);
}
current = mount.parent.and_then(|id| indices.get(&id).copied());
}
None
}
+7
View File
@@ -236,6 +236,13 @@ impl RenderCache {
radius: *radius,
color: color.clone(),
},
Kind::Scroll { width, height } => UiKind::Scroll {
width: *width,
height: *height,
padding: data.padding,
gap: data.gap,
children,
},
Kind::Spacer(size) => UiKind::Spacer(*size),
Kind::Row => UiKind::Row {
padding: data.padding,
+6 -1
View File
@@ -62,7 +62,12 @@ fn selector(
.upgrade(*weak)?
.ok_or(VmError::InvalidArgument("pointer Mount expired"))?;
let target = cx.store().payload::<Mount>(mount, "Mount")?.clone();
if !target.mounted || !target.geometry.interactive {
if !target.mounted
|| !target.geometry.interactive
|| !target
.geometry
.contains(crate::geometry::Point::new(point[0], point[1]))
{
continue;
}
let geometry = &target.geometry;
+8 -1
View File
@@ -42,7 +42,10 @@ fn number(store: &ObjectStore, object: ObjectRef, name: &str) -> Result<f32, VmE
.to_string()
.parse::<f32>()
.map_err(|_| invalid("invalid paint number"))?;
if !value.is_finite() || !(0.0..=MAX_DIMENSION as f32).contains(&value) {
if !value.is_finite()
|| value.abs() > MAX_DIMENSION as f32
|| (!matches!(name, "x" | "y") && value < 0.0)
{
return Err(invalid("paint number exceeds bounds"));
}
Ok(value)
@@ -294,7 +297,9 @@ pub fn render(
pending.extend(node.children().iter().map(|node| node.as_ref()));
}
let mut commands = Vec::new();
let mut clips = Vec::new();
for mount in &frame.mounts {
let before = commands.len();
if let Some(custom) = output.commands.get(&mount.id) {
commands.extend(custom.iter().cloned());
} else {
@@ -313,11 +318,13 @@ pub fn render(
commands.push(command);
}
}
clips.extend(std::iter::repeat_n(mount.clip, commands.len() - before));
if commands.len() > 10_000 {
bail!("paint command budget exceeded");
}
}
frame.commands = commands;
frame.command_clips = clips;
let registry = object(vm.get_attr(desktop, "types")?)?;
Ok(reads
.into_iter()
+100 -2
View File
@@ -27,6 +27,7 @@ pub const TYPE_NAMES: &[&str] = &[
"Presentable",
"Block",
"ContainerBlock",
"ScrollBlock",
"TextBlock",
"RectBlock",
"Spacer",
@@ -69,7 +70,8 @@ impl UiNode {
match &self.kind {
UiKind::Column { children, .. }
| UiKind::Row { children, .. }
| UiKind::Button { children, .. } => children,
| UiKind::Button { children, .. }
| UiKind::Scroll { children, .. } => children,
_ => &[],
}
}
@@ -118,6 +120,22 @@ impl UiNode {
},
) => (a, b, c, d) == (e, f, g, h),
(UiKind::Spacer(a), UiKind::Spacer(b)) => a == b,
(
UiKind::Scroll {
width: a,
height: b,
padding: pa,
gap: ga,
children: _,
},
UiKind::Scroll {
width: c,
height: d,
padding: pb,
gap: gb,
children: _,
},
) => a == c && b == d && pa == pb && ga == gb && same_children(),
(
UiKind::Column {
padding: a, gap: b, ..
@@ -176,6 +194,13 @@ pub enum UiKind {
children: Vec<Arc<UiNode>>,
},
Spacer(f32),
Scroll {
width: f32,
height: f32,
padding: f32,
gap: f32,
children: Vec<Arc<UiNode>>,
},
}
#[derive(Debug)]
@@ -232,6 +257,7 @@ enum Operation {
Text,
Rect,
Spacer,
Scroll,
Row,
Column,
Button,
@@ -428,6 +454,7 @@ fn new_typed_block(
Kind::Text { .. } => "TextBlock",
Kind::Rect { .. } => "RectBlock",
Kind::Spacer(_) => "Spacer",
Kind::Scroll { .. } => "ScrollBlock",
Kind::Row => "Row",
Kind::Column => "Column",
Kind::Button => "Button",
@@ -659,6 +686,7 @@ impl NativeCallable for Function {
State | StateSet => (1, 1),
Increment => (0, 0),
TextOf => (2, 4),
Scroll => (3, 3),
Text => (1, 3),
Rect => (2, 4),
MoveWindow | OpenValue | Spacer | SetText | SetColor | Append | Remove | Render
@@ -931,6 +959,15 @@ impl NativeCallable for Function {
)?)));
}
let constructor = match self.operation {
Scroll => Some(Data::new(
Kind::Scroll {
width: dimension(args.first())?,
height: dimension(args.get(1))?,
},
vec![object(args.get(2))?],
0.0,
0.0,
)),
Text => Some(Data::new(
Kind::Text {
value: text(args.first())?,
@@ -1674,9 +1711,56 @@ impl UiBridge {
.ok_or_else(|| anyhow::anyhow!("Mount is no longer active"))?,
state.desktop,
state.mounts.ordered(),
state.layout.viewport,
state.layout.viewport.map(|size| crate::layout::Size {
width: size.width,
height: (size.height - crate::tabs::height(&state.last_tabs)).max(0.0),
}),
)
};
if input.kind == "scroll" {
let mount = vm
.upgrade(weak)?
.ok_or_else(|| anyhow::anyhow!("scroll Mount expired"))?;
let result = (|| {
let data = vm.payload::<crate::mount::Mount>(mount, "Mount")?;
let point = input
.point
.ok_or_else(|| anyhow::anyhow!("scroll has no pointer"))?;
if !data.mounted
|| data.version != input.layout_version
|| viewport
.is_some_and(|size| point[0] >= size.width || point[1] >= size.height)
|| !data
.geometry
.contains(crate::geometry::Point::new(point[0], point[1]))
{
bail!("scroll targets an obsolete or clipped Mount");
}
let delta = input
.delta
.ok_or_else(|| anyhow::anyhow!("scroll has no delta"))?;
let method = vm.bind_attr(mount, "scrollBy")?;
let result = match method {
Value::Object(function) => vm.call_with_limits(
function,
&[
Value::Number((delta[0] as f64).into()),
Value::Number((delta[1] as f64).into()),
],
endor_core::ExecutionLimits {
max_frames: 128,
max_instructions: 100_000,
},
),
_ => Err(invalid("scrollBy is not callable")),
};
vm.release_value(method)?;
vm.release_value(result?)?;
Ok(())
})();
vm.release(mount)?;
return result;
}
let mount = if let (Some(press), Some(release)) = (input.press_point, input.point) {
if viewport.is_some_and(|size| {
[press, release]
@@ -1830,6 +1914,10 @@ impl UiBridge {
let changed = state.pending.is_some()
|| !same
|| focus_changed
|| matches!(
vm.get_attr(state.desktop, "scrollRequested"),
Ok(Value::Bool(true))
)
|| state.force_frame
|| tabs != state.last_tabs;
if changed {
@@ -1863,6 +1951,7 @@ impl UiBridge {
}
vm.set_attr(state.desktop, "pending", Value::Nil)?;
vm.set_attr(state.desktop, "focusRequested", Value::Bool(false))?;
vm.set_attr(state.desktop, "scrollRequested", Value::Bool(false))?;
state.force_frame = false;
state.last_snapshot = snapshot;
state.last_tabs = frame.tabs.clone();
@@ -2025,6 +2114,13 @@ impl UiBridge {
&mut layout,
&mut cache,
)?;
{
let state = self
.session
.lock()
.map_err(|_| anyhow::anyhow!("UI session poisoned"))?;
crate::scroll::project(vm, &state.mounts, &root, &mut frame)?;
}
// Native layout may replace the structural Frame; attach chrome only
// after either layout path has produced the final page geometry.
frame.tabs = tabs;
@@ -2161,6 +2257,7 @@ pub fn install(vm: &mut Vm, roots: &mut Vec<ObjectRef>) -> Result<UiBridge> {
("TextBlock", "Block", Some("text")),
("RectBlock", "Block", Some("rect")),
("Spacer", "Block", Some("spacer")),
("ScrollBlock", "ContainerBlock", Some("scroll")),
("Row", "ContainerBlock", Some("row")),
("Column", "ContainerBlock", Some("column")),
("Button", "ContainerBlock", Some("button")),
@@ -2200,6 +2297,7 @@ pub fn install(vm: &mut Vm, roots: &mut Vec<ObjectRef>) -> Result<UiBridge> {
"text" => Operation::Text,
"rect" => Operation::Rect,
"spacer" => Operation::Spacer,
"scroll" => Operation::Scroll,
"row" => Operation::Row,
"column" => Operation::Column,
"button" => Operation::Button,