Connect native tab chrome to managed Page methods
Verify Tessera GUI / verify (push) Failing after 7m37s

This commit is contained in:
2026-10-21 17:29:54 +08:00
parent 76e293d3b8
commit 96319b13a3
13 changed files with 548 additions and 16 deletions
+5 -1
View File
@@ -202,7 +202,11 @@ A source subclass can override `measure(self, mount, constraints): MeasureResult
Mount.bounds() rejects reads during measurement, including old geometry on an existing Mount. The current occurrence's allocated Bounds become available while its arrange method runs. Structural contexts are prepared before layout, geometry is committed after successful layout, and onMount/onUnmount notifications then run before paint/publication. Both layout phases share one read-only VM call and instruction budget; temporary results can be modified, existing business state cannot. Read versions are captured before hooks, so a hook changing a measured dependency schedules another pass before publication. Dependencies are currently tracked per object. Source measurement results are cached by Mount identity, method, child sizes, constraints and actual object reads, including decoding an existing returned MeasureResult. Cache entries contain borrowed identities and versions, adding no GC roots. Mount-reading measurements currently bypass the cache conservatively because object-level tracking cannot distinguish layoutVersion/geometry from stable structure. Global dictionary writes or changes to another field on a read object can also cause conservative misses. Native measurements keep their shape cache, and arrangement still visits each active occurrence. ui.stats() exposes sourceMeasureHits/sourceMeasureMisses; diagnostic statistics are rejected inside read-only rendering because allocation/count observations are not stable layout inputs.
The current native shell is represented by a managed `Window: Object` resource. `ui.window()` returns it, and an open `page.window()` returns the same object; a closed/unregistered Page returns nil. `page.open(window)` explicitly targets this runtime's native window (omission or nil selects it). `window.pages()` returns a traced ObjectList in open order; closing removes the Page from both window-owned roots and reopening appends it. Window is a host resource, while displayed content remains Page/Block. The current host supplies one window; Window() construction, additional native windows and Tab chrome remain future work.
The current native shell is represented by a managed `Window: Object` resource. `ui.window()` returns it, and an open `page.window()` returns the same object; a closed/unregistered Page returns nil. `page.open(window)` explicitly targets this runtime's native window (omission or nil selects it). `window.pages()` returns a traced ObjectList in open order; closing removes the Page from both window-owned roots and reopening appends it. Window is a host resource, while displayed content remains Page/Block. The current host supplies one window; Window() construction and additional native windows remain future work.
Open Pages appear in the native shell tab bar. Set `page.title` to label a tab; omitted titles use their open-order number. Clicking a tab or its close control calls the actual Page's `activate()` or `close()` method in the existing VM; source overrides participate. Ctrl+Tab / Ctrl+Shift+Tab cycle pages, and Cmd/Ctrl+W closes the active page when the page has keyboard focus. Overflow arrows expose additional pages. Closed Pages follow managed references and GC; a retained Page can be reopened. The tab projection contains opaque session-local IDs and text, with weak reverse lookup in the runtime, and adds no Page roots. Requests carry the published layout version; an old tab event is rejected. Switching creates new presentation Mounts while preserving the business objects. See [tabs.endor](examples/tabs.endor).
The bar occupies 36 logical pixels when at least one Page is open. Page constraints use the remaining height; published Mount geometry and event coordinates remain relative to the content area. Window viewport snapshots continue to report the full native inner size. The host translates drawing and native pointer coordinates at this boundary. Console reset preserves the last picture with input disabled until a new live frame is published.
`window.resize(width, height)`, `setTitle(text)` and `focus()` project requests to the GUI thread. `id()` returns an opaque runtime resource ID and `viewport()` reports actual logical dimensions. Requests are asynchronous and coalesced by kind; queried dimensions change when the native window reports them, and platform bounds can adjust requested sizes. This host accepts sizes from 1 to 4096 logical pixels per axis, with a native minimum of 720 by 480. Titles are UTF-8 text up to 4096 bytes with no control characters. See [window.endor](examples/window.endor).
+1
View File
@@ -2,6 +2,7 @@
| File | Purpose |
| --- | --- |
| [tabs.endor](tabs.endor) | Three real Page tabs, shared counter state, source titles, native switching/closing and reopening through code. |
| [window.endor](window.endor) | A managed native Window resizes the actual shell; source callbacks update it and layout follows reported dimensions. |
| [layout-cache.endor](layout-cache.endor) | Per-occurrence source measurement caches, separate size/paint models, and a band using the logical viewport input. |
| [source-layout.endor](source-layout.endor) | Source measurement reads its initial Mount parent; source arrangement moves a child and a click updates the shared layout model. |
+17
View File
@@ -0,0 +1,17 @@
// Code and tab chrome operate the same Page objects.
first = Page()
first.title = "共享计数"
count = ui.state(0)
increment = Button("加一")
connection = increment.on("click", count.increment)
first.render(Column(24,16,TextBlock("切换页面后,计数对象继续存在"),ui.textOf(count,"value"),increment))
second = Page()
second.title = "另一个页面"
second.render(Column(24,16,TextBlock("点击上方 Tab 切换;× 关闭页面"),TextBlock("Ctrl+Tab 切换,Cmd/Ctrl+W 关闭;代码可调用 first.open() 重开")))
third = Page()
third.title = "窗口与布局"
third.render(Column(24,16,TextBlock("每个 Tab 都是同一个 VM 中的 Page 对象"),RectBlock(240,80,8,"#237A45")))
first.activate()
ui.window().setTitle("Endor Pages")
+1
View File
@@ -13,6 +13,7 @@
| 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 |
| tabs.rs | Immutable tab chrome, shared draw/hit geometry, overflow navigation and opaque published Page identities |
| window.rs | Managed native Window resource, ordered Page roots, read-only guards and coalesced scalar GUI projections |
| vm_sequence.rs | Shared validated call-sequence builder for event and lifecycle batches in the existing VM frame loop |
| source_layout.rs | Read-only source layout, per-Mount measurement caches with subcall dependencies, viewport constraints, typed/slot validation and occurrence geometry |
+14 -7
View File
@@ -532,7 +532,10 @@ impl Worker {
Ok(input) => input,
Err(error) => return error_response(StatusCode(400), error.to_string()),
};
if !matches!(input.kind.as_str(), "click" | "focus") {
if !matches!(
input.kind.as_str(),
"click" | "focus" | "tab-activate" | "tab-close"
) {
return error_response(StatusCode(400), "unsupported event kind");
}
if let Err(message) = input.validate() {
@@ -546,10 +549,14 @@ impl Worker {
if frame.session != input.session
|| frame.layout_version != input.layout_version
|| frame.fault.is_some()
|| !frame
.mounts
.iter()
.any(|mount| mount.id == input.mount && mount.interactive)
|| if matches!(input.kind.as_str(), "tab-activate" | "tab-close") {
!frame.tabs.iter().any(|tab| tab.id == input.mount)
} else {
!frame
.mounts
.iter()
.any(|mount| mount.id == input.mount && mount.interactive)
}
|| self.repl.as_ref().is_none_or(|(context, runtime)| {
*context != epoch || runtime.id != input.session
})
@@ -888,13 +895,13 @@ declarations, explicit first `self` parameters, positional field construction an
member assignment. Inherited methods bind the actual receiver; overridden methods
are dynamically selected through self. Concrete native visual subclasses reuse real native allocators; abstract bases remain unconstructible. Traits and annotation checking remain pending. Native Block/Page methods use the same type method tables and binding path.
Window is a host-provided managed resource: ui.window(), page.window(), page.open(window), window.pages()/id()/viewport(), resize(width,height), setTitle(text) and focus(). Requests project to the actual main native window only after successful input/candidate completion and carry the current runtime session. Resize is asynchronous and the reported viewport is authoritative; this host accepts 1..4096 logical dimensions with a native 720x480 minimum. Failed input/candidates discard pending requests and read-only rendering rejects window effects. Additional windows, Window() construction, tab UI and detach/move remain pending.
Window is a host-provided managed resource: ui.window(), page.window(), page.open(window), window.pages()/id()/viewport(), resize(width,height), setTitle(text) and focus(). Requests project to the actual main native window only after successful input/candidate completion and carry the current runtime session. Resize is asynchronous and the reported viewport is authoritative; this host accepts 1..4096 logical dimensions with a native 720x480 minimum. Failed input/candidates discard pending requests and read-only rendering rejects window effects. Open Pages appear in native tab chrome, with page.title, click activation/close, Ctrl+Tab cycling and Cmd/Ctrl+W close when page keyboard focus is active. Overflow arrows reach additional pages. These operations call actual Page methods in the same VM; tab IDs are weak runtime projections and add no GC roots. The 36-logical-pixel bar reduces Page constraint height; window/ui viewport reports the full inner size and native pointer positions are translated into content coordinates. Additional windows, Window() construction and detach/move remain pending.
Source measure and arrange overrides execute bottom-up and top-down in one read-only VM layout call. Structural Mount links exist before first measurement; bounds queries reject premature geometry. Native base layout uses current occurrence child measurements, and Arrangement must assign every stable child slot exactly once. Layout dependencies changed by lifecycle hooks trigger another pass before publication. Page constraints now use the current logical window viewport. Column/Button propagate cross-axis width and Row propagates cross-axis height; desired sizes are clamped. ui.viewport() provides a managed snapshot whose private input participates in rendering dependencies. Native resize updates are coalesced on the same worker without adding source inputs. Source measurement caches use Mount/method/children/constraints and actual subcall object reads, including returned-result decoding; Mount-reading methods conservatively bypass caching. ui.stats() exposes sourceMeasureHits/sourceMeasureMisses outside read-only rendering. General constraint negotiation, wrapping and scrolling remain pending.
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.
Native input POST /events is a transport envelope, not Endor source. The window
Native input POST /events is a transport envelope, not Endor source. Tab actions use kind tab-activate/tab-close and the mount wire field carries the opaque tab ID from frame.tabs; point/press_point must be omitted. All actions validate session and layout_version before dispatch. The window
sends current session, layout_version and Mount identity; stale positions fail without calling a callback. Pointer clicks also include point and press_point [x,y] in logical page coordinates. Both targets are resolved through read-only hitTest, with fallback behind a rejected candidate; a click is dispatched only when both resolve to the same Mount. Keyboard/code clicks omit coordinates and remain semantic activation. GET /code also exposes X-Tessera-Session and X-Tessera-Layout-Version headers for transport clients. Native mouse, Tab, Enter and Space delegate to the same
managed click/focus methods used by code. Events appear in Network, not Console source history.
+88 -5
View File
@@ -41,6 +41,7 @@ pub struct TesseraApp {
activity: Activity,
event_client: crate::events::Client,
guest_pressed: Option<crate::events::Input>,
tab_pressed: Option<crate::events::Input>,
guest_focus: Option<crate::events::Input>,
guest_key: Option<(NamedKey, crate::events::Input)>,
guest_keyboard: bool,
@@ -69,6 +70,7 @@ impl TesseraApp {
activity,
event_client,
guest_pressed: None,
tab_pressed: None,
guest_focus: None,
guest_key: None,
guest_keyboard: true,
@@ -158,6 +160,15 @@ impl TesseraApp {
}
fn handle_keyboard(&mut self, event: &winit::event::KeyEvent) {
if self.guest_keyboard && event.state == ElementState::Pressed && !event.repeat {
let close = (self.modifiers.super_key() || self.modifiers.control_key())
&& matches!(&event.logical_key, Key::Character(key) if key.eq_ignore_ascii_case("w"));
let cycle = self.modifiers.control_key()
&& matches!(event.logical_key, Key::Named(NamedKey::Tab));
if (close || cycle) && self.send_tab_shortcut(close) {
return;
}
}
if self.guest_keyboard && self.handle_guest_key(event) {
self.request_redraw();
return;
@@ -257,14 +268,75 @@ impl TesseraApp {
if frame.session == 0 {
return None;
}
let mount = frame.hit_test(self.pointer)?;
let offset = crate::tabs::height(&frame.tabs);
if self.pointer.y < offset {
return None;
}
let point = Point::new(self.pointer.x, self.pointer.y - offset);
let mount = frame.hit_test(point)?;
Some(crate::events::Input {
session: frame.session,
layout_version: frame.layout_version,
mount: mount.id,
kind: "click".into(),
point: Some([self.pointer.x, self.pointer.y]),
press_point: Some([self.pointer.x, self.pointer.y]),
point: Some([point.x, point.y]),
press_point: Some([point.x, point.y]),
})
}
fn send_tab_shortcut(&mut self, close: bool) -> bool {
let input = self.namespace.read().ok().and_then(|namespace| {
let frame = &namespace.document.frame;
if frame.session == 0 || frame.fault.is_some() || frame.tabs.is_empty() {
return None;
}
let active = frame.tabs.iter().position(|tab| tab.active).unwrap_or(0);
let index = if close {
active
} else if self.modifiers.shift_key() {
(active + frame.tabs.len() - 1) % frame.tabs.len()
} else {
(active + 1) % frame.tabs.len()
};
Some(crate::events::Input {
session: frame.session,
layout_version: frame.layout_version,
mount: frame.tabs[index].id,
kind: if close { "tab-close" } else { "tab-activate" }.into(),
point: None,
press_point: None,
})
});
if let Some(input) = input {
self.guest_pressed = None;
self.guest_key = None;
self.tab_pressed = None;
self.send_guest(input);
true
} else {
false
}
}
fn tab_hit(&self) -> Option<crate::events::Input> {
if self.guest_covered(self.pointer) {
return None;
}
let window = self.window.as_ref()?;
let namespace = self.namespace.read().ok()?;
let frame = &namespace.document.frame;
if frame.session == 0 || frame.fault.is_some() {
return None;
}
let width = window.inner_size().width as f32 / window.scale_factor() as f32;
let (id, close) = crate::tabs::hit(&frame.tabs, width, self.pointer)?;
Some(crate::events::Input {
session: frame.session,
layout_version: frame.layout_version,
mount: id,
kind: if close { "tab-close" } else { "tab-activate" }.into(),
point: None,
press_point: None,
})
}
@@ -341,7 +413,7 @@ impl TesseraApp {
}
fn redraw(&mut self) {
let guest_cursor = self.guest_hit().is_some();
let guest_cursor = self.guest_hit().is_some() || self.tab_hit().is_some();
let (Some(window), Some(surface)) = (self.window.as_ref(), self.surface.as_mut()) else {
return;
};
@@ -479,7 +551,7 @@ impl ApplicationHandler<AppEvent> for TesseraApp {
&self.layout.developer_tools,
window.inner_size().width as f32 / scale,
);
window.set_cursor(if self.guest_hit().is_some() {
window.set_cursor(if self.guest_hit().is_some() || self.tab_hit().is_some() {
winit::window::CursorIcon::Pointer
} else {
self.developer_tools
@@ -489,6 +561,7 @@ impl ApplicationHandler<AppEvent> for TesseraApp {
}
WindowEvent::CursorLeft { .. } => {
self.guest_pressed = None;
self.tab_pressed = None;
self.developer_tools.pointer_left();
window.set_cursor(winit::window::CursorIcon::Default);
window.request_redraw();
@@ -500,6 +573,7 @@ impl ApplicationHandler<AppEvent> for TesseraApp {
} => {
if state == ElementState::Pressed {
self.guest_keyboard = !self.guest_covered(self.pointer);
self.tab_pressed = self.tab_hit();
self.guest_pressed = self.guest_hit();
if self.guest_keyboard {
self.developer_tools.blur();
@@ -510,6 +584,15 @@ impl ApplicationHandler<AppEvent> for TesseraApp {
&self.activity,
);
} else {
if let Some(pressed) = self.tab_pressed.take()
&& let Some(released) = self.tab_hit()
&& released.session == pressed.session
&& released.layout_version == pressed.layout_version
&& released.mount == pressed.mount
&& released.kind == pressed.kind
{
self.send_guest(released);
}
if let Some(pressed) = self.guest_pressed.take()
&& let Some(mut released) = self.guest_hit()
&& released.session == pressed.session
+18
View File
@@ -63,6 +63,24 @@ impl DisplayList {
self.commands.push(command);
}
pub fn translate(&mut self, delta: Point) {
for command in &mut self.commands {
match command {
DrawCommand::PushClip(rect)
| DrawCommand::FillRoundedRect { rect, .. }
| DrawCommand::StrokeRoundedRect { rect, .. } => {
rect.x += delta.x;
rect.y += delta.y;
}
DrawCommand::Text { origin, .. } => {
origin.x += delta.x;
origin.y += delta.y;
}
DrawCommand::Clear(_) | DrawCommand::PopClip => {}
}
}
}
pub fn commands(&self) -> &[DrawCommand] {
&self.commands
}
+14
View File
@@ -119,6 +119,17 @@ impl RenderDocument {
if self.frame.mounts.len() > 10_000 {
bail!("frame exceeds the 10000 mount limit");
}
let mut tab_ids = HashSet::new();
if self.frame.tabs.len() > crate::ui_bridge::MAX_PAGES
|| self.frame.tabs.iter().filter(|tab| tab.active).count() > 1
|| self
.frame
.tabs
.iter()
.any(|tab| tab.id == 0 || !tab_ids.insert(tab.id) || tab.title.len() > 1024)
{
bail!("invalid tab projection");
}
let mut mount_ids = HashSet::new();
for mount in &self.frame.mounts {
if mount.id == 0 || mount.block_id.is_empty() || !mount_ids.insert(mount.id) {
@@ -263,6 +274,8 @@ pub struct Frame {
pub session: u64,
#[serde(default)]
pub focus: Option<u64>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tabs: Vec<crate::tabs::Tab>,
#[serde(default)]
pub fault: Option<String>,
}
@@ -276,6 +289,7 @@ impl Default for Frame {
layout_version: 0,
session: 0,
focus: None,
tabs: Vec::new(),
fault: None,
}
}
+74
View File
@@ -845,6 +845,80 @@ mod tests {
const EXAMPLE: &str = include_str!("../examples/hello.endor");
const PAGE: &str = include_str!("../examples/page.endor");
#[test]
fn tab_projection_uses_page_methods_and_rejects_old_presentations() {
let source = r#"first = Page()
first.title = "First"
first.render(TextBlock("one"))
second = Page()
second.title = "Second"
second.render(TextBlock("two"))"#;
let (mut session, initial) = ReplSession::load(source, "app.main", 120, 1).unwrap();
assert_eq!(initial.frame.tabs.len(), 2);
assert_eq!(initial.frame.tabs[0].title, "First");
assert!(initial.frame.tabs[1].active);
let input = crate::events::Input {
session: 120,
layout_version: initial.frame.layout_version,
mount: initial.frame.tabs[0].id,
kind: "tab-activate".into(),
point: None,
press_point: None,
};
let selected = session.dispatch(&input).unwrap().document.unwrap();
assert!(selected.frame.tabs[0].active);
assert!(selected.frame.layout_version > initial.frame.layout_version);
// Query the bridge directly: stale transport must be rejected before faulting a runtime.
assert!(
session
.bridge
.dispatch(&mut session.candidate.vm, &input)
.is_err()
);
let renamed = session
.execute(r#"second.title = "Renamed""#, "app.main")
.unwrap()
.document
.unwrap();
assert_eq!(renamed.frame.tabs[1].title, "Renamed");
assert_eq!(renamed.frame.tabs[0].id, initial.frame.tabs[0].id);
let closed = session
.dispatch(&crate::events::Input {
session: 120,
layout_version: renamed.frame.layout_version,
mount: renamed.frame.tabs[1].id,
kind: "tab-close".into(),
point: None,
press_point: None,
})
.unwrap()
.document
.unwrap();
assert_eq!(closed.frame.tabs.len(), 1);
assert!(closed.frame.tabs[0].active);
assert_eq!(
session
.execute("second.window()", "app.main")
.unwrap()
.value,
"nil"
);
let empty = session
.execute("first.close()", "app.main")
.unwrap()
.document
.unwrap();
assert!(empty.frame.tabs.is_empty());
assert!(empty.frame.layout_version > closed.frame.layout_version);
let reopened = session
.execute("second.open()", "app.main")
.unwrap()
.document
.unwrap();
assert_eq!(reopened.frame.tabs.len(), 1);
assert!(reopened.frame.tabs[0].id > initial.frame.tabs[1].id);
}
#[test]
fn managed_window_requests_are_coalesced_and_failed_input_discards_pending_requests() {
let mut session = ReplSession::new(111).unwrap();
+1
View File
@@ -23,6 +23,7 @@ mod source_layout;
mod source_paint;
mod sources;
mod system_ui;
mod tabs;
mod text;
mod ui_bridge;
mod vm_sequence;
+8
View File
@@ -23,6 +23,14 @@ pub fn build_scene(
.display_list(scale)
.expect("default document is valid")
});
let offset = crate::tabs::height(&document.frame.tabs);
display_list.translate(crate::geometry::Point::new(0.0, offset * scale));
crate::tabs::draw(
&mut display_list,
&document.frame.tabs,
width as f32 / scale,
scale,
);
let (developer_list, developer_layout) = developer_tools::build(
width,
height,
+179
View File
@@ -0,0 +1,179 @@
//! Immutable tab chrome. IDs are session-local projections, never heap handles.
use crate::{
display_list::{Color, DisplayList, DrawCommand},
geometry::{Point, Rect},
text::TextStyle,
};
use serde::{Deserialize, Serialize};
pub const HEIGHT: f32 = 36.0;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Tab {
pub id: u64,
pub title: String,
pub active: bool,
}
pub fn height(tabs: &[Tab]) -> f32 {
if tabs.is_empty() { 0.0 } else { HEIGHT }
}
struct Item<'a> {
tab: &'a Tab,
rect: Rect,
navigation: Option<&'static str>,
}
fn items(tabs: &[Tab], width: f32) -> Vec<Item<'_>> {
if tabs.is_empty() || width <= 0.0 {
return Vec::new();
}
let capacity = ((width - 64.0) / 160.0).floor().max(1.0) as usize;
let overflow = tabs.len() > capacity;
let count = if overflow { capacity } else { tabs.len() };
let active = tabs.iter().position(|tab| tab.active).unwrap_or(0);
let start = if overflow {
active.saturating_sub(count / 2).min(tabs.len() - count)
} else {
0
};
let margin = if overflow { 32.0 } else { 0.0 };
let tab_width = ((width - margin * 2.0) / count as f32).min(220.0);
let mut result = Vec::new();
if overflow && start > 0 {
result.push(Item {
tab: &tabs[start - 1],
rect: Rect::new(0.0, 0.0, 32.0, HEIGHT),
navigation: Some("‹"),
});
}
for (index, tab) in tabs[start..start + count].iter().enumerate() {
result.push(Item {
tab,
rect: Rect::new(margin + index as f32 * tab_width, 0.0, tab_width, HEIGHT),
navigation: None,
});
}
if overflow && start + count < tabs.len() {
result.push(Item {
tab: &tabs[start + count],
rect: Rect::new(width - 32.0, 0.0, 32.0, HEIGHT),
navigation: Some("›"),
});
}
result
}
fn close_rect(rect: Rect) -> Rect {
Rect::new(rect.x + rect.width - 27.0, 5.0, 24.0, 26.0)
}
pub fn hit(tabs: &[Tab], width: f32, point: Point) -> Option<(u64, bool)> {
if point.x < 0.0 || point.x >= width || point.y < 0.0 || point.y >= height(tabs) {
return None;
}
items(tabs, width)
.into_iter()
.find(|item| item.rect.contains(point))
.map(|item| {
(
item.tab.id,
item.navigation.is_none() && close_rect(item.rect).contains(point),
)
})
}
pub fn draw(list: &mut DisplayList, tabs: &[Tab], width: f32, scale: f32) {
if tabs.is_empty() {
return;
}
let scaled = |rect: Rect| {
Rect::new(
rect.x * scale,
rect.y * scale,
rect.width * scale,
rect.height * scale,
)
};
list.push(DrawCommand::FillRoundedRect {
rect: scaled(Rect::new(0.0, 0.0, width, HEIGHT)),
radius: 0.0,
color: Color::rgb(230, 232, 236),
});
for item in items(tabs, width) {
if item.tab.active && item.navigation.is_none() {
list.push(DrawCommand::FillRoundedRect {
rect: scaled(item.rect),
radius: 0.0,
color: Color::rgb(250, 250, 249),
});
list.push(DrawCommand::FillRoundedRect {
rect: scaled(Rect::new(item.rect.x, HEIGHT - 2.0, item.rect.width, 2.0)),
radius: 0.0,
color: Color::rgb(79, 111, 219),
});
}
let title = item.navigation.unwrap_or(&item.tab.title);
let text_rect = Rect::new(
item.rect.x + 10.0,
4.0,
(item.rect.width
- if item.navigation.is_some() {
12.0
} else {
42.0
})
.max(0.0),
28.0,
);
list.push(DrawCommand::PushClip(scaled(text_rect)));
list.push(DrawCommand::Text {
origin: Point::new((item.rect.x + 10.0) * scale, 8.0 * scale),
value: title.into(),
style: TextStyle::ui(1).scaled(scale),
color: Color::rgb(36, 36, 40),
});
list.push(DrawCommand::PopClip);
if item.navigation.is_none() {
list.push(DrawCommand::Text {
origin: Point::new((item.rect.x + item.rect.width - 22.0) * scale, 8.0 * scale),
value: "×".into(),
style: TextStyle::ui(1).scaled(scale),
color: Color::rgb(80, 82, 88),
});
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn overflow_keeps_active_page_visible_and_navigation_reaches_other_pages() {
let tabs: Vec<_> = (1..=64)
.map(|id| Tab {
id,
title: format!("Page {id}"),
active: id == 32,
})
.collect();
let visible = items(&tabs, 720.0);
assert!(
visible
.iter()
.any(|item| item.tab.active && item.navigation.is_none())
);
for item in &visible {
let point = Point::new(item.rect.x + 12.0, 18.0);
assert_eq!(hit(&tabs, 720.0, point), Some((item.tab.id, false)));
}
let tab = visible.iter().find(|item| item.tab.active).unwrap();
assert_eq!(
hit(
&tabs,
720.0,
Point::new(tab.rect.x + tab.rect.width - 15.0, 18.0)
),
Some((32, true))
);
assert_eq!(hit(&tabs, 720.0, Point::new(50.0, HEIGHT)), None);
}
}
+128 -3
View File
@@ -175,6 +175,9 @@ struct Session {
pending: Option<Option<ObjectRef>>,
nodes: Vec<WeakObjectRef>,
last_snapshot: Option<Arc<UiNode>>,
tab_ids: Vec<(WeakObjectRef, u64)>,
next_tab: u64,
last_tabs: Vec<crate::tabs::Tab>,
render_cache: crate::snapshot::RenderCache,
layout: crate::layout::LayoutRuntime,
mounts: crate::mount::MountTable,
@@ -991,7 +994,7 @@ impl NativeCallable for Function {
.map_err(|_| invalid("UI session poisoned"))?;
let window = object(Some(&cx.store().get_attr(session.desktop, "window")?))?;
crate::window::unregister_page(cx, window, owner)?;
if session.active == Some(owner) || session.pending == Some(Some(owner)) {
if session.pending.unwrap_or(session.active) == Some(owner) {
let next = crate::window::pages(cx.store(), window)?.first().copied();
cx.set_attr(
session.desktop,
@@ -1078,6 +1081,42 @@ pub struct UiBridge {
session: Shared,
}
fn project_tabs(vm: &Vm, state: &mut Session) -> Result<Vec<crate::tabs::Tab>> {
let window = object(Some(&vm.get_attr(state.desktop, "window")?))?;
let pages = crate::window::pages(vm.object_store(), window)?;
let active = state.pending.unwrap_or(state.active);
let mut live = Vec::new();
let mut tabs = Vec::new();
for (index, page) in pages.iter().copied().enumerate() {
let weak = vm.object_store().downgrade(page)?;
let id = if let Some((_, id)) = state.tab_ids.iter().find(|(w, _)| *w == weak) {
*id
} else {
state.next_tab = state
.next_tab
.checked_add(1)
.ok_or_else(|| anyhow::anyhow!("tab identities exhausted"))?;
state.next_tab
};
live.push((weak, id));
let title = match vm.get_attr(page, "title") {
Ok(Value::Text(title)) if !title.is_empty() => title
.chars()
.filter(|c| !c.is_control())
.take(120)
.collect(),
_ => format!("Page {}", index + 1),
};
tabs.push(crate::tabs::Tab {
id,
title,
active: active == Some(page),
});
}
state.tab_ids = live;
Ok(tabs)
}
impl UiBridge {
pub fn take_window_commands(&self, vm: &Vm) -> Result<Vec<crate::window::Command>> {
let desktop = self
@@ -1149,10 +1188,57 @@ impl UiBridge {
vm.release_value(page)?;
Ok(())
}
fn dispatch_tab(&self, vm: &mut Vm, input: &crate::events::Input) -> Result<()> {
let page = {
let state = self
.session
.lock()
.map_err(|_| anyhow::anyhow!("UI session poisoned"))?;
if state.published_version != input.layout_version {
bail!("event targets an obsolete presentation");
}
let weak = state
.tab_ids
.iter()
.find(|(_, id)| *id == input.mount)
.map(|(weak, _)| *weak)
.ok_or_else(|| anyhow::anyhow!("tab has expired"))?;
let window = object(Some(&vm.get_attr(state.desktop, "window")?))?;
crate::window::pages(vm.object_store(), window)?
.iter()
.copied()
.find(|page| vm.object_store().downgrade(*page).ok() == Some(weak))
.ok_or_else(|| anyhow::anyhow!("Page is no longer open"))?
};
let method = if input.kind == "tab-close" {
"close"
} else {
"activate"
};
let bound = vm.bind_attr(page, method)?;
let result = match &bound {
Value::Object(function) => vm.call_with_limits(
*function,
&[],
endor_core::ExecutionLimits {
max_frames: 128,
max_instructions: 1_000_000,
},
),
_ => Err(invalid("Page method is not callable")),
};
vm.release_value(bound)?;
vm.release_value(result?)?;
Ok(())
}
pub fn dispatch(&self, vm: &mut Vm, input: &crate::events::Input) -> Result<()> {
input
.validate()
.map_err(|message| anyhow::anyhow!(message))?;
if matches!(input.kind.as_str(), "tab-activate" | "tab-close") {
return self.dispatch_tab(vm, input);
}
let (weak, desktop, candidates, viewport) = {
let state = self
.session
@@ -1284,7 +1370,12 @@ impl UiBridge {
vm.get_attr(state.desktop, "focusRequested"),
Ok(Value::Bool(true))
);
let changed = state.pending.is_some() || !same || focus_changed || state.force_frame;
let tabs = project_tabs(vm, &mut state)?;
let changed = state.pending.is_some()
|| !same
|| focus_changed
|| state.force_frame
|| tabs != state.last_tabs;
if changed {
state.snapshot_visited = state.render_cache.visited;
state.snapshot_reused = state.render_cache.reused;
@@ -1318,6 +1409,7 @@ impl UiBridge {
vm.set_attr(state.desktop, "focusRequested", Value::Bool(false))?;
state.force_frame = false;
state.last_snapshot = snapshot;
state.last_tabs = frame.tabs.clone();
state.published_version = frame.layout_version;
// Hooks may call Page/container APIs; never hold the session mutex
// across user code. Publish only after the refresh loop settles.
@@ -1397,7 +1489,22 @@ impl UiBridge {
.map_err(|_| anyhow::anyhow!("UI session poisoned"))?
.layout_reads
.clear();
let frame = crate::document::Frame::default();
let frame = {
let mut state = self
.session
.lock()
.map_err(|_| anyhow::anyhow!("UI session poisoned"))?;
state.layout.version = state
.layout
.version
.checked_add(1)
.ok_or_else(|| anyhow::anyhow!("layout version exhausted"))?;
crate::document::Frame {
layout_version: state.layout.version,
tabs: project_tabs(vm, &mut state)?,
..crate::document::Frame::default()
}
};
self.commit_frame(vm, None, &frame)?;
return Ok(frame);
};
@@ -1414,6 +1521,17 @@ impl UiBridge {
state.nodes.clone(),
)
};
let tabs = {
let mut state = self
.session
.lock()
.map_err(|_| anyhow::anyhow!("UI session poisoned"))?;
project_tabs(vm, &mut state)?
};
let full_viewport = layout.viewport;
if let Some(size) = &mut layout.viewport {
size.height = (size.height - crate::tabs::height(&tabs)).max(0.0);
}
let mut frame = layout.structure(&root)?;
let (hooks, mounts) = {
let mut state = self
@@ -1435,6 +1553,9 @@ impl UiBridge {
&mut layout,
&mut cache,
)?;
// Native layout may replace the structural Frame; attach chrome only
// after either layout path has produced the final page geometry.
frame.tabs = tabs;
// Capture versions before lifecycle hooks can change a dependency.
let reads = reads
.into_iter()
@@ -1452,6 +1573,7 @@ impl UiBridge {
.session
.lock()
.map_err(|_| anyhow::anyhow!("UI session poisoned"))?;
layout.viewport = full_viewport;
state.layout = layout;
state.measure_cache = cache;
state.layout_reads = reads;
@@ -1507,6 +1629,9 @@ pub fn install(vm: &mut Vm, roots: &mut Vec<ObjectRef>) -> Result<UiBridge> {
pending: None,
nodes: vec![],
last_snapshot: None,
tab_ids: Vec::new(),
next_tab: 0,
last_tabs: Vec::new(),
render_cache: crate::snapshot::RenderCache::default(),
layout: crate::layout::LayoutRuntime::default(),
mounts: crate::mount::MountTable::default(),