Support stable insertion and managed tab placement
Verify Tessera GUI / verify (push) Failing after 7m40s
Verify Tessera GUI / verify (push) Failing after 7m40s
This commit is contained in:
@@ -172,7 +172,7 @@ source budgets and VM instruction limits are not a complete untrusted-code sandb
|
||||
## Developer tools
|
||||
|
||||
Native visual protocols are under active implementation: Text/Rect/Row/Column,
|
||||
container append/remove/replace/move, Page open/close/navigation, ui.present,
|
||||
container append/insert/remove/replace/move, Page open/close/navigation, ui.present,
|
||||
ui.state(value), ui.textOf(state, "value"), and button.onClick/click are available
|
||||
in the persistent Console. Method bodies can call other methods without a trailing
|
||||
return. Bound text tracks its source property; clean derived subtrees and unchanged measurements are reused. Buttons have a native background, focus ring and pointer/keyboard activation.
|
||||
@@ -196,7 +196,7 @@ Native visual methods are now available on Block: `measure(mount, Constraints(mi
|
||||
|
||||
Outside a renderer layout call, native measurement queries find intrinsic native subtree size and clamp it to the given constraints. During layout, native base methods use the staged measured children of that occurrence. Native Row/Column arrangement uses 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.
|
||||
|
||||
Visual, EventTarget, Children and Presentable are explicit managed Trait definitions. Block declares Visual (measure/arrange/paint/hitTest) and EventTarget (on/dispatch/onEvent); ContainerBlock declares Children (append/remove/replace/move/children), inherited by Page. `ui.supports(value, capability)` queries an instance; `ui.implements(type, capability)` queries a type. `ui.implement(type, capability)` checks required methods and establishes an explicit relation. Matching member names alone never declare a capability. Aster checks source positional parameter counts, including self, when registering, creating subclasses or replacing methods; declaration and ancestor updates also validate existing affected descendants. Native callable signatures remain trusted host declarations; source argument/return annotations are checked at invocation as described below. Native signature metadata, effect types and formal trait syntax remain pending.
|
||||
Visual, EventTarget, Children and Presentable are explicit managed Trait definitions. Block declares Visual (measure/arrange/paint/hitTest) and EventTarget (on/dispatch/onEvent); ContainerBlock declares Children (append/insert/remove/replace/move/children), inherited by Page. `ui.supports(value, capability)` queries an instance; `ui.implements(type, capability)` queries a type. `ui.implement(type, capability)` checks required methods and establishes an explicit relation. Matching member names alone never declare a capability. Aster checks source positional parameter counts, including self, when registering, creating subclasses or replacing methods; declaration and ancestor updates also validate existing affected descendants. Native callable signatures remain trusted host declarations; source argument/return annotations are checked at invocation as described below. Native signature metadata, effect types and formal trait syntax remain pending.
|
||||
|
||||
A plain source object can declare Presentable by implementing `present(self, window: Window): Block` and calling `ui.implement(MyType, Presentable)`. `ui.present(value)` invokes this method with the calling window and checks the returned actual Block; `ui.open(value)` also opens the result in a Page. Block values pass through directly. The existing summary viewer remains the fallback for unregistered values, and merely viewing a function does not execute it. Presentation runs through the same bounded VM call sequence; there is no recursive host evaluator. A source adapter can keep the original object through fields/callbacks/bindings; [presentable.endor](examples/presentable.endor) shows a source-preserving view and GUI calls to the original object's method. Presentation methods are ordinary calls; visual measure/arrange/paint/hitTest still run read-only and check their nominal results at runtime. Source implementations of EventTarget.on/dispatch must provide the contract's canonical 3/2 arguments after self; native methods retain their existing optional convenience arguments.
|
||||
|
||||
@@ -220,7 +220,13 @@ Mount.bounds() rejects reads during measurement, including old geometry on an ex
|
||||
|
||||
`Window: Object` represents a native window resource. `Window()` creates another window in the same Aster VM, up to 16 open windows per runtime. `ui.window()` returns the current event/render window, with the main window as the top-level Console default. `page.window()` reports its actual owner or nil. `page.open(window)` and `page.moveToWindow(window)` move the same Page, including navigation and business references, to that window. Omitting the open target keeps an existing owner; an unowned Page uses the calling view. `page.detachToWindow()` creates a new Window, moves the Page there and returns the resource. Dragging a Tab away from its strip invokes that same Page method. Moving a Page unmounts the old occurrence and creates destination Mounts. `window.pages()` returns a traced ObjectList in open order. See [windows.endor](examples/windows.endor).
|
||||
|
||||
`window.close()` and a secondary native close button call the same managed method. Closing first removes Page ownership, then commits unmounts and removes that context from the runtime registry; the native resource disappears after successful publication. Retained Pages can be opened in another live Window; otherwise Aster reclaims them normally. Window resource objects may remain referenced after closing, but reject resource operations; id/pages remain queryable. A retained leaf Mount uses a weak context link and cannot keep a closed window alive through its query methods. The primary shell still defines the application's lifetime: closing its OS window exits Tessera. Dragging onto another existing window and placement at the release point remain follow-up work.
|
||||
`container.insert(position, block)` inserts at a zero-based position from 0 through the current child count and returns a new stable slot. Existing slots and attached Mount identities survive insertion. Invalid positions and cyclic child graphs fail before replacing the child list. `page.moveTab(position)` moves the same Page to a final zero-based position in its owning window; a code reorder does not implicitly activate it.
|
||||
|
||||
Native dragging starts after 12 logical pixels and shows a blue insertion marker. Same-window drops call the actual Page `moveTab` and `activate`; cross-window drops first call `moveToWindow`. Source overrides participate. An override that declines or redirects the window move prevents the remaining destination reorder. Page identity and Page-owned tasks survive movement, while a cross-window move replaces Mounts and cancels old Mount tasks. Invalid source/target generations, layout versions or unpublished tab orders are rejected before callbacks. Callback failure stops the domain; earlier writes do not roll back. Escape cancels a drag. Overflow drops use visible gaps; drag auto-scroll remains pending. See [tab-placement.endor](examples/tab-placement.endor).
|
||||
|
||||
`window.moveTo(x, y)` queues a native outer-window origin in signed physical desktop pixels, within +/-1000000 per axis. A detached tab uses the release point and saved grab offset to place its new window. The window manager may adjust placement. Global coordinates are required for cross-window drops; unsupported native placement reports a diagnostic. This host tracks its own focus order when resolving overlapping windows; external-app occlusion and mixed-DPI dragging have not been fully verified.
|
||||
|
||||
`window.close()` and a secondary native close button call the same managed method. Closing first removes Page ownership, then commits unmounts and removes that context from the runtime registry; the native resource disappears after successful publication. Retained Pages can be opened in another live Window; otherwise Aster reclaims them normally. Window resource objects may remain referenced after closing, but reject resource operations; id/pages remain queryable. A retained leaf Mount uses a weak context link and cannot keep a closed window alive through its query methods. The primary shell still defines the application's lifetime: closing its OS window exits Tessera. Full application-exit notifications remain follow-up work.
|
||||
|
||||
A secondary window can also be closed after a callback/rendering failure or Console reset. A stopped VM uses host teardown to detach Mounts and release window-owned Page roots without invoking source close/unmount callbacks; it remains stopped. A preserved picture from a discarded generation is removed without touching a fresh Console VM, even when both generations use the same numeric window ID. Secondary viewport inputs are likewise scoped to their runtime generation. If host teardown fails, that VM is discarded and remaining pictures have input disabled. Native initialization and software-surface failures are reported instead of panicking; a failed secondary creation leaves its managed resource inspectable and closable from Console. Automatic retry and complete application-exit notifications remain future work.
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
class TrackedPage: Page {
|
||||
calls: Object
|
||||
function moveToWindow(self: TrackedPage, window: Window): Page {
|
||||
self.calls.increment()
|
||||
return Page.moveToWindow(self, window)
|
||||
}
|
||||
function moveTab(self: TrackedPage, position: Number): Page {
|
||||
self.calls.increment()
|
||||
return Page.moveTab(self, position)
|
||||
}
|
||||
}
|
||||
class Actions {
|
||||
list: Column
|
||||
function insert(self: Actions, event: Event): Unit {
|
||||
self.list.insert(1, TextBlock("插入的新对象"))
|
||||
}
|
||||
}
|
||||
calls = ui.state(0)
|
||||
list = Column(0, 8, TextBlock("第一个子项"), TextBlock("最后一个子项"))
|
||||
actions = Actions(list)
|
||||
button = Button("在位置 1 插入 Block")
|
||||
connection = button.on("click", actions.insert)
|
||||
shared = Column(24, 16, TextBlock("拖动 Tab 重排、移入另一个窗口,或拖出独立窗口"), TextBlock("Page 方法调用次数"), ui.textOf(calls,"value"), button, list)
|
||||
first = TrackedPage(calls)
|
||||
first.title = "A · 共享内容"
|
||||
first.render(shared)
|
||||
second = TrackedPage(calls)
|
||||
second.title = "B · 单独内容"
|
||||
second.render(Column(24, 16, TextBlock("这是 B,Page 身份随 Tab 移动保留")))
|
||||
third = TrackedPage(calls)
|
||||
third.title = "C · 同一对象"
|
||||
third.render(shared)
|
||||
other = Window()
|
||||
other.resize(720,520)
|
||||
other.setTitle("Tab Target")
|
||||
other.moveTo(1700,80)
|
||||
target = TrackedPage(calls)
|
||||
target.title = "目标窗口"
|
||||
target.render(shared)
|
||||
target.open(other)
|
||||
first.activate()
|
||||
ui.window().resize(800,600)
|
||||
ui.window().setTitle("Tab Source")
|
||||
ui.window().moveTo(50,80)
|
||||
ui.window().focus()
|
||||
+11
-9
@@ -3,22 +3,22 @@
|
||||
| Module | Responsibility |
|
||||
| --- | --- |
|
||||
| main.rs | Native window event loop, namespace state and API startup |
|
||||
| api.rs | Code CRUD, live Console/reset and compatibility evaluation endpoints, worker-owned session, request observation, coalesced native viewport/background-task updates, epoch checks and diagnostics |
|
||||
| api.rs | Code CRUD, live Console/reset and compatibility evaluation endpoints, worker-owned session, request observation, coalesced native viewport/background-task updates, epoch checks, stale source/destination tab-drop rejection and diagnostics |
|
||||
| activity.rs | Bounded in-memory HTTP exchanges with marked previews and allowlisted request headers |
|
||||
| endor_host.rs | Aster compilation, fresh PUT candidates retained after successful publication, shared Console/program VM, asynchronous completion/fault boundaries, bounded execution, root cleanup and AST developer tree for function/class/member assignment nodes |
|
||||
| endor_script.rs | Batch complete inputs for Aster's Interactive parser/compiler, retain Module entry, and rebase Aster spans to the original snapshot |
|
||||
| ui_bridge.rs | Inheritable native nominal constructors with source fields, shared type method tables and bound receiver dispatch, configured unified Function classification and source annotation checks, tab registry, Page lifecycle/navigation and immutable frame extraction |
|
||||
| ui_bridge.rs | Inheritable native nominal constructors with source fields, shared type method tables and bound receiver dispatch, configured unified Function classification and source annotation checks, tab registry, stable-slot insertion, source-dispatched tab reorder/drop, Page lifecycle/navigation and immutable frame extraction |
|
||||
| binding.rs | Target-owned managed property bindings, weak Subscription tokens, read-only compute and borrowed dependency/output caches |
|
||||
| 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 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 |
|
||||
| events.rs | Bounded native input transport with kind-specific tab-drop/desktop-position metadata 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 |
|
||||
| protocols.rs | Register explicit Visual/EventTarget/Children/Presentable managed traits and native type declarations |
|
||||
| protocols.rs | Register explicit Visual/EventTarget/Children (including insert)/Presentable managed traits and native type declarations |
|
||||
| presentation.rs | Per-window layout, Mount/focus/tab state and read dependencies; VM changes fan out before any view consumes work |
|
||||
| tasks.rs | Managed owner scopes and callbacks, weak timer index, request-key replacement, lifecycle cancellation and budgeted worker delivery |
|
||||
| tabs.rs | Immutable tab chrome, shared draw/hit geometry, overflow navigation and opaque published Page identities |
|
||||
| window.rs | Native Window construction/close, context ownership, ordered Page roots, read-only guards and coalesced GUI projections |
|
||||
| tabs.rs | Immutable tab chrome, shared draw/hit geometry, overflow navigation, drag gaps/anchors/insertion markers and opaque published Page identities |
|
||||
| window.rs | Native Window construction/close, context ownership, ordered Page roots, read-only guards, Page reordering, physical desktop placement and coalesced 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 |
|
||||
| source_hit.rs | Read-only source/native pointer target selectors, reverse paint order, strict Bool results and matching press/release targets |
|
||||
@@ -27,11 +27,11 @@
|
||||
| object_list.rs | Traced indexed results shared by Mount queries and visual protocol results |
|
||||
| layout.rs | Shared native geometry/paint functions, iterative measurement/arrangement, stable occurrence IDs, measurement cache and geometry budgets |
|
||||
| document.rs | Published source/AST/UI snapshot, revisions, invalidation, frame validation, single-line fault banner (full cause retained in Frame) and display commands |
|
||||
| app.rs | Window events, logical viewport publication, redraw and system widget pointer/keyboard/IME routing |
|
||||
| app.rs | Window events, logical viewport publication, redraw, native multi-window tab dragging 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 |
|
||||
| scene.rs | Page, tab-drop marker 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 |
|
||||
| display_list.rs | Rendering primitives and color representation |
|
||||
@@ -57,7 +57,7 @@ contain only immutable native data.
|
||||
|
||||
Tests in api.rs execute real HTTP CRUD, persistent Console/reset/PUT isolation and a controlled queued-PUT/DELETE race
|
||||
without opening a window. Tests in endor_host.rs cover lifecycle, direct script and
|
||||
module entry, page methods, multiline inputs, original source ranges, malformed input,
|
||||
module entry, page methods, stable-slot insertion and tab drop/override/stale-target behavior, multiline inputs, original source ranges, malformed input,
|
||||
owner/task cancellation, hidden-object delivery, stale request and callback failure, entry checks, source function annotation/function identity and REPL class redefinition, budgets, failure preservation, live object identity, explicit rendering,
|
||||
compile-before-execute behavior and stale-result invalidation. They
|
||||
run only in remote CI. Font tests in text.rs and software_renderer.rs cover real
|
||||
@@ -127,3 +127,5 @@ 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.
|
||||
|
||||
Tab drops validate source and destination window/session/layout plus the actual VM Page order before callbacks. The bridge invokes managed Page methods, respecting source overrides that decline or redirect a window move. Reordering within a window retains Mounts; moving windows retains Page identity and replaces Mounts. Native drag feedback is host state, with no additional managed roots. Desktop placement is an asynchronous physical outer-origin request, protected by the existing session/commit boundary. Regression sources cover the HTTP event allowlist, stale frame reuse, stable insertion, source overrides and signed positions; these were compiled, not locally executed.
|
||||
|
||||
+99
-4
@@ -643,6 +643,7 @@ impl Worker {
|
||||
| "tab-activate"
|
||||
| "tab-close"
|
||||
| "tab-detach"
|
||||
| "tab-drop"
|
||||
| "window-close"
|
||||
) {
|
||||
return error_response(StatusCode(400), "unsupported event kind");
|
||||
@@ -680,6 +681,33 @@ impl Worker {
|
||||
return self.close_inactive_window(&input, epoch, namespace, notify);
|
||||
}
|
||||
}
|
||||
if let Some(target) = &input.tab_drop {
|
||||
let target_frame = if target.window == crate::window::MAIN_WINDOW {
|
||||
Some(¤t.document.frame)
|
||||
} else {
|
||||
current
|
||||
.document
|
||||
.windows
|
||||
.get(&target.window)
|
||||
.map(|document| &document.frame)
|
||||
};
|
||||
if target_frame.is_none_or(|frame| {
|
||||
frame.window != target.window
|
||||
|| frame.session != input.session
|
||||
|| frame.layout_version != target.layout_version
|
||||
|| frame.fault.is_some()
|
||||
|| target.index > frame.tabs.len()
|
||||
}) || self
|
||||
.repl
|
||||
.as_ref()
|
||||
.is_none_or(|(_, runtime)| !runtime.accepts_tab_drop(&input))
|
||||
{
|
||||
return error_response(
|
||||
StatusCode(409),
|
||||
"drop targets an obsolete or inactive frame",
|
||||
);
|
||||
}
|
||||
}
|
||||
if frame.window != input.window
|
||||
|| frame.session != input.session
|
||||
|| (input.kind != "window-close" && frame.layout_version != input.layout_version)
|
||||
@@ -688,7 +716,7 @@ impl Worker {
|
||||
false
|
||||
} else if matches!(
|
||||
input.kind.as_str(),
|
||||
"tab-activate" | "tab-close" | "tab-detach"
|
||||
"tab-activate" | "tab-close" | "tab-detach" | "tab-drop"
|
||||
) {
|
||||
!frame.tabs.iter().any(|tab| tab.id == input.mount)
|
||||
} else {
|
||||
@@ -1051,7 +1079,9 @@ 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. Explicit traits and source parameter/return annotation checks are enabled; field-write constraints and static/effect typing 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 their actual 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. Window() now creates additional native windows in the same VM, up to 16 open resources. Page.open(window)/moveToWindow(window) preserve Page and business identity while replacing Mounts; detachToWindow() creates and returns a new Window. Dragging a tab away from its strip invokes the same method. Window.close()/secondary OS close remove Page roots, unmount, and retire the resource context; retained Pages can reopen in another live window, and closed Window resources reject viewport/resize/title/focus operations. Closing the primary OS shell exits the application. Secondary viewport inputs and frame publication use the same worker. Secondary close after callback/rendering failure uses host-only teardown without invoking source callbacks or resuming execution. After reset/discard, closing an old picture never touches a fresh VM resource with the same number; viewport inputs are also generation-scoped. A teardown failure discards the affected VM and disables remaining pictures. Native initialization/surface errors are reported rather than panicking; failed secondary creation leaves a managed resource closable from Console. Existing-window drag/drop, release-point placement and full application-exit notifications remain pending.
|
||||
Window is a host-provided managed resource: ui.window(), page.window(), page.open(window), window.pages()/id()/viewport(), resize(width,height), moveTo(x,y), setTitle(text) and focus(). Requests project to their actual 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. Window() now creates additional native windows in the same VM, up to 16 open resources. Page.open(window)/moveToWindow(window) preserve Page and business identity while replacing Mounts; detachToWindow() creates and returns a new Window. Dragging a tab away from its strip invokes the same method. Window.close()/secondary OS close remove Page roots, unmount, and retire the resource context; retained Pages can reopen in another live window, and closed Window resources reject viewport/resize/title/focus operations. Closing the primary OS shell exits the application. Secondary viewport inputs and frame publication use the same worker. Secondary close after callback/rendering failure uses host-only teardown without invoking source callbacks or resuming execution. After reset/discard, closing an old picture never touches a fresh VM resource with the same number; viewport inputs are also generation-scoped. A teardown failure discards the affected VM and disables remaining pictures. Native initialization/surface errors are reported rather than panicking; failed secondary creation leaves a managed resource closable from Console. Native tab reordering, existing-window drops and release-point placement use the managed methods described below. Full application-exit notifications remain pending.
|
||||
|
||||
ContainerBlock.insert(position,block) accepts a zero-based position through the current count, returns a new stable slot and preserves existing slots/Mounts. Invalid indices and child cycles fail before changing the child list. Page.moveTab(position) uses a final zero-based index in its owning window. Native drops invoke the actual Page moveToWindow/moveTab/activate methods; a declined or redirected window move skips destination reordering. A drop allows 300000 instructions per method. Source overrides participate; earlier writes do not roll back after failure. Window.moveTo(x,y) queues the physical desktop outer origin, with signed integers within +/-1000000. Detached placement preserves the saved grab offset; the window manager may adjust it and unsupported global placement reports a diagnostic. Dragging uses a 12-logical-pixel threshold, visible insertion marker and Escape cancellation. Overflow auto-scroll, external-app occlusion and mixed-DPI verification remain pending. See examples/tab-placement.endor.
|
||||
|
||||
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 and text wrapping remain pending; ScrollBlock scrolling is described below.
|
||||
|
||||
@@ -1071,7 +1101,7 @@ For a plain object explicitly implementing Presentable, present(self, window: Wi
|
||||
|
||||
Block.bind(property, compute) binds an existing managed Block field to a zero-argument function and returns Subscription (disconnect/isConnected). This includes source-defined fields and native TextBlock.text/size/color, RectBlock.width/height/radius/color, Spacer.size and container padding/gap. Native fields can also be assigned directly. The target content owns compute/captures; tokens and host registry are weak. Rebinding disconnects the old connection; disconnect keeps the last value. Actual read dependencies are tracked at object granularity, including conservative global reads; no explicit source-list parameter is required. Hidden retained Blocks update at successful input/event stabilization boundaries before all windows publish. Computes are read-only for existing objects and may allocate results. They have 100000 instructions/128 frames each, 128 active bindings per Block and a 10000-computation refresh limit that errors rather than truncates propagation. Binding failure stops the live VM and preserves published pictures. Non-Block targets, explicit dependency lists and general type/effect checking remain pending. See examples/property-bindings.endor.
|
||||
|
||||
Native input POST /events is a transport envelope, not Endor source. Each frame and input carries an opaque runtime window identity; omitted input window defaults to 1 for existing clients. GET /code exposes X-Tessera-Window. A window/session/layout identity mismatch is rejected before invoking code. Tab actions use kind tab-activate/tab-close/tab-detach and the mount wire field carries the opaque tab ID from frame.tabs; point/press_point must be omitted. All spatial/tab actions validate session and layout_version before dispatch. Resource window-close uses mount=0 and no points; it validates the live window/session rather than its old layout version. The window
|
||||
Native input POST /events is a transport envelope, not Endor source. Each frame and input carries an opaque runtime window identity; omitted input window defaults to 1 for existing clients. GET /code exposes X-Tessera-Window. A window/session/layout identity mismatch is rejected before invoking code. Tab actions use kind tab-activate/tab-close/tab-detach/tab-drop and the mount wire field carries the opaque tab ID from frame.tabs; point/press_point must be omitted. tab-drop additionally requires tab_drop={{window,layout_version,index}}, where index is a published destination gap from 0 through its tab count (at most 64). Both source and destination orders must still match their published frames. tab-detach alone accepts optional screen_position=[x,y] as signed integer physical desktop coordinates within +/-1000000; other kinds must omit it. All spatial/tab actions validate session and layout_version before dispatch. Resource window-close uses mount=0 and no points; it validates the live window/session rather than its old layout version. 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.
|
||||
|
||||
@@ -1102,7 +1132,7 @@ document. GET remains available while Aster executes. The window redraws from an
|
||||
owned snapshot; resize does not rerun Endor. Text uses system fonts, antialiasing
|
||||
and font fallback; Chinese needs an installed CJK font. Size 1 is 14 logical pixels
|
||||
with 20-pixel line height; larger sizes multiply both. Native Block methods include
|
||||
setText/setColor, container append/remove/replace/move, Page open/close/navigation,
|
||||
setText/setColor, container append/insert/remove/replace/move, Page open/close/navigation,
|
||||
and code-driven button.onClick/click. ui.state and ui.textOf provide explicit text
|
||||
binding. Mouse routing, tab chrome/multiple windows and incremental layout remain
|
||||
in progress; process isolation is future work. Console retains objects
|
||||
@@ -1242,6 +1272,8 @@ mod tests {
|
||||
point: None,
|
||||
delta: None,
|
||||
press_point: None,
|
||||
tab_drop: None,
|
||||
screen_position: None,
|
||||
},
|
||||
1,
|
||||
&namespace,
|
||||
@@ -1291,6 +1323,69 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_tab_drop_route_reorders_live_pages_and_rejects_reused_frames() {
|
||||
let server = Arc::new(Server::http("127.0.0.1:0").unwrap());
|
||||
let namespace = Arc::new(RwLock::new(NamespaceState::default()));
|
||||
let api = start_server(server.clone(), namespace.clone(), Arc::new(|| {})).unwrap();
|
||||
let client = TestServer {
|
||||
address: server.server_addr().to_ip().unwrap(),
|
||||
server,
|
||||
api: Some(api),
|
||||
};
|
||||
let source = r#"class Tracked: Page {
|
||||
calls: Object
|
||||
function moveTab(self: Tracked, position: Number): Page { self.calls.increment() return Page.moveTab(self,position) }
|
||||
}
|
||||
calls=ui.state(0)
|
||||
first=Tracked(calls)
|
||||
first.title="first"
|
||||
first.render(TextBlock("first"))
|
||||
second=Page()
|
||||
second.title="second"
|
||||
second.render(TextBlock("second"))
|
||||
first.activate()"#;
|
||||
let result = client.request("PUT", "/v1/namespaces/app.main/code", source);
|
||||
assert_eq!(result.0, 200, "{}", result.2);
|
||||
let input = {
|
||||
let current = namespace.read().unwrap();
|
||||
let frame = ¤t.document.frame;
|
||||
crate::events::Input {
|
||||
window: 1,
|
||||
session: frame.session,
|
||||
layout_version: frame.layout_version,
|
||||
mount: frame.tabs[0].id,
|
||||
kind: "tab-drop".into(),
|
||||
point: None,
|
||||
press_point: None,
|
||||
delta: None,
|
||||
screen_position: None,
|
||||
tab_drop: Some(crate::events::TabDrop {
|
||||
window: 1,
|
||||
layout_version: frame.layout_version,
|
||||
index: 2,
|
||||
}),
|
||||
}
|
||||
};
|
||||
let body = serde_json::to_string(&input).unwrap();
|
||||
let response = client.request("POST", "/v1/namespaces/app.main/events", &body);
|
||||
assert_eq!(response.0, 200, "{}", response.2);
|
||||
let response = client.request("POST", "/v1/namespaces/app.main/repl", "calls.value");
|
||||
let value: serde_json::Value = serde_json::from_str(&response.2).unwrap();
|
||||
assert_eq!(value["value"], "1");
|
||||
assert_eq!(
|
||||
namespace.read().unwrap().document.frame.tabs[1].title,
|
||||
"first"
|
||||
);
|
||||
assert_eq!(
|
||||
client
|
||||
.request("POST", "/v1/namespaces/app.main/events", &body)
|
||||
.0,
|
||||
409
|
||||
);
|
||||
assert!(namespace.read().unwrap().document.frame.fault.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn background_failure_preserves_its_cause_after_rejected_console_input() {
|
||||
let server = Arc::new(Server::http("127.0.0.1:0").unwrap());
|
||||
|
||||
+301
-2
@@ -48,6 +48,9 @@ pub struct TesseraApp {
|
||||
guest_pressed: Option<crate::events::Input>,
|
||||
tab_pressed: Option<crate::events::Input>,
|
||||
tab_drag_origin: Option<Point>,
|
||||
tab_drag_grab: Option<Point>,
|
||||
tab_drop_index: Option<usize>,
|
||||
window_order: Vec<u64>,
|
||||
guest_focus: Option<crate::events::Input>,
|
||||
guest_key: Option<(NamedKey, crate::events::Input)>,
|
||||
guest_keyboard: bool,
|
||||
@@ -83,6 +86,9 @@ impl TesseraApp {
|
||||
guest_pressed: None,
|
||||
tab_pressed: None,
|
||||
tab_drag_origin: None,
|
||||
tab_drag_grab: None,
|
||||
tab_drop_index: None,
|
||||
window_order: vec![crate::window::MAIN_WINDOW],
|
||||
guest_focus: None,
|
||||
guest_key: None,
|
||||
guest_keyboard: true,
|
||||
@@ -190,6 +196,17 @@ impl TesseraApp {
|
||||
let _ = window.request_inner_size(LogicalSize::new(width, height));
|
||||
}
|
||||
crate::window::Action::SetTitle(title) => window.set_title(&title),
|
||||
crate::window::Action::MoveTo { x, y } => {
|
||||
if window.outer_position().is_ok() {
|
||||
window.set_outer_position(PhysicalPosition::new(x, y));
|
||||
} else {
|
||||
let _ = self.proxy.send_event(AppEvent::RuntimeFailed {
|
||||
message: format!(
|
||||
"Window {id}: desktop placement is unsupported on this platform"
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
crate::window::Action::Focus => window.focus_window(),
|
||||
crate::window::Action::Close => {}
|
||||
}
|
||||
@@ -259,6 +276,16 @@ impl TesseraApp {
|
||||
if let Ok(namespace) = self.namespace.read() {
|
||||
self.developer_tools.document_updated(&namespace.document);
|
||||
let frame = &namespace.document.frame;
|
||||
if self.tab_pressed.as_ref().is_some_and(|pressed| {
|
||||
frame.session != pressed.session
|
||||
|| frame.fault.is_some()
|
||||
|| !frame.tabs.iter().any(|tab| tab.id == pressed.mount)
|
||||
}) {
|
||||
self.tab_pressed = None;
|
||||
self.tab_drag_origin = None;
|
||||
self.tab_drag_grab = None;
|
||||
self.tab_drop_index = None;
|
||||
}
|
||||
self.guest_focus =
|
||||
frame
|
||||
.focus
|
||||
@@ -272,6 +299,8 @@ impl TesseraApp {
|
||||
point: None,
|
||||
delta: None,
|
||||
press_point: None,
|
||||
tab_drop: None,
|
||||
screen_position: None,
|
||||
});
|
||||
}
|
||||
self.request_redraw();
|
||||
@@ -401,6 +430,8 @@ impl TesseraApp {
|
||||
point: Some([point.x, point.y]),
|
||||
delta: None,
|
||||
press_point: Some([point.x, point.y]),
|
||||
tab_drop: None,
|
||||
screen_position: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -427,6 +458,8 @@ impl TesseraApp {
|
||||
point: None,
|
||||
delta: None,
|
||||
press_point: None,
|
||||
tab_drop: None,
|
||||
screen_position: None,
|
||||
})
|
||||
});
|
||||
if let Some(input) = input {
|
||||
@@ -434,6 +467,7 @@ impl TesseraApp {
|
||||
self.guest_key = None;
|
||||
self.tab_pressed = None;
|
||||
self.tab_drag_origin = None;
|
||||
self.tab_drag_grab = None;
|
||||
self.send_guest(input);
|
||||
true
|
||||
} else {
|
||||
@@ -462,6 +496,8 @@ impl TesseraApp {
|
||||
point: None,
|
||||
delta: None,
|
||||
press_point: None,
|
||||
tab_drop: None,
|
||||
screen_position: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -511,6 +547,8 @@ impl TesseraApp {
|
||||
point: None,
|
||||
delta: None,
|
||||
press_point: None,
|
||||
tab_drop: None,
|
||||
screen_position: None,
|
||||
})
|
||||
});
|
||||
if let Some(next) = next {
|
||||
@@ -539,6 +577,260 @@ impl TesseraApp {
|
||||
false
|
||||
}
|
||||
|
||||
fn apps(&self) -> impl Iterator<Item = &Self> {
|
||||
std::iter::once(self).chain(self.children.values())
|
||||
}
|
||||
|
||||
fn drag_anchor(&self, input: &crate::events::Input) -> Option<Point> {
|
||||
let window = self.window.as_ref()?;
|
||||
let current = self.namespace.read().ok()?;
|
||||
crate::tabs::drag_anchor(
|
||||
¤t.document.frame.tabs,
|
||||
window.inner_size().width as f32 / window.scale_factor() as f32,
|
||||
input.mount,
|
||||
self.pointer,
|
||||
)
|
||||
}
|
||||
|
||||
fn clear_drag_feedback(&mut self, target: Option<(u64, usize)>) {
|
||||
let index = target
|
||||
.filter(|(window, _)| *window == self.resource)
|
||||
.map(|(_, index)| index);
|
||||
if self.tab_drop_index != index {
|
||||
self.tab_drop_index = index;
|
||||
self.request_redraw();
|
||||
}
|
||||
for child in self.children.values_mut() {
|
||||
child.clear_drag_feedback(target);
|
||||
}
|
||||
}
|
||||
|
||||
fn native_tab_drag(&mut self, window_id: WindowId, event: &WindowEvent) {
|
||||
if self.resource != crate::window::MAIN_WINDOW {
|
||||
return;
|
||||
}
|
||||
let Some(receiver) = self.apps().find(|app| {
|
||||
app.window
|
||||
.as_ref()
|
||||
.is_some_and(|window| window.id() == window_id)
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
let receiver_id = receiver.resource;
|
||||
if matches!(
|
||||
event,
|
||||
WindowEvent::Focused(true)
|
||||
| WindowEvent::MouseInput {
|
||||
state: ElementState::Pressed,
|
||||
button: MouseButton::Left,
|
||||
..
|
||||
}
|
||||
) {
|
||||
self.window_order.retain(|id| *id != receiver_id);
|
||||
self.window_order.push(receiver_id);
|
||||
}
|
||||
if matches!(
|
||||
event,
|
||||
WindowEvent::MouseInput {
|
||||
state: ElementState::Pressed,
|
||||
button: MouseButton::Left,
|
||||
..
|
||||
}
|
||||
) || matches!(event,WindowEvent::KeyboardInput { event,.. } if event.state==ElementState::Pressed && event.logical_key==Key::Named(NamedKey::Escape))
|
||||
{
|
||||
self.tab_pressed = None;
|
||||
self.tab_drag_origin = None;
|
||||
self.tab_drag_grab = None;
|
||||
for child in self.children.values_mut() {
|
||||
child.tab_pressed = None;
|
||||
child.tab_drag_origin = None;
|
||||
child.tab_drag_grab = None;
|
||||
}
|
||||
self.clear_drag_feedback(None);
|
||||
return;
|
||||
}
|
||||
let release = matches!(
|
||||
event,
|
||||
WindowEvent::MouseInput {
|
||||
state: ElementState::Released,
|
||||
button: MouseButton::Left,
|
||||
..
|
||||
}
|
||||
);
|
||||
if !release && !matches!(event, WindowEvent::CursorMoved { .. }) {
|
||||
return;
|
||||
}
|
||||
let Some(source) = self
|
||||
.apps()
|
||||
.find(|app| app.tab_pressed.is_some() && app.tab_drag_origin.is_some())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let source_id = source.resource;
|
||||
let source_window = source.window.as_ref().expect("dragging native window");
|
||||
let source_scale = source_window.scale_factor();
|
||||
let origin = source.tab_drag_origin.expect("drag origin");
|
||||
let receiver = self
|
||||
.apps()
|
||||
.find(|app| app.resource == receiver_id)
|
||||
.expect("event window");
|
||||
let receiver_window = receiver.window.as_ref().expect("event native window");
|
||||
let point = if let WindowEvent::CursorMoved { position, .. } = event {
|
||||
Point::new(
|
||||
(position.x / receiver_window.scale_factor()) as f32,
|
||||
(position.y / receiver_window.scale_factor()) as f32,
|
||||
)
|
||||
} else {
|
||||
receiver.pointer
|
||||
};
|
||||
let screen = receiver_window.inner_position().ok().map(|position| {
|
||||
[
|
||||
position.x as f64 + point.x as f64 * receiver_window.scale_factor(),
|
||||
position.y as f64 + point.y as f64 * receiver_window.scale_factor(),
|
||||
]
|
||||
});
|
||||
let distance = if let (Some(screen), Ok(start)) = (screen, source_window.inner_position()) {
|
||||
((screen[0] - start.x as f64 - origin.x as f64 * source_scale)
|
||||
.hypot(screen[1] - start.y as f64 - origin.y as f64 * source_scale)
|
||||
/ source_scale) as f32
|
||||
} else if source_id == receiver_id {
|
||||
(point.x - origin.x).hypot(point.y - origin.y)
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
if distance <= 12.0 {
|
||||
if release {
|
||||
self.clear_drag_feedback(None);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let mut input = source.tab_pressed.clone().expect("pressed tab");
|
||||
let valid = source.namespace.read().ok().is_some_and(|current| {
|
||||
let frame = ¤t.document.frame;
|
||||
if frame.session != input.session
|
||||
|| frame.fault.is_some()
|
||||
|| !frame.tabs.iter().any(|tab| tab.id == input.mount)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
// Opaque tab identities survive a redraw; use release-time geometry
|
||||
// while preserving the pressed Page and runtime identity.
|
||||
input.layout_version = frame.layout_version;
|
||||
true
|
||||
});
|
||||
if !valid {
|
||||
self.tab_pressed = None;
|
||||
self.tab_drag_origin = None;
|
||||
self.tab_drag_grab = None;
|
||||
for child in self.children.values_mut() {
|
||||
child.tab_pressed = None;
|
||||
child.tab_drag_origin = None;
|
||||
child.tab_drag_grab = None;
|
||||
}
|
||||
self.clear_drag_feedback(None);
|
||||
return;
|
||||
}
|
||||
let mut apps: Vec<_> = self.apps().collect();
|
||||
apps.sort_by_key(|app| {
|
||||
self.window_order
|
||||
.iter()
|
||||
.position(|id| *id == app.resource)
|
||||
.unwrap_or(0)
|
||||
});
|
||||
let front = apps.into_iter().rev().find_map(|app| {
|
||||
let window = app.window.as_ref()?;
|
||||
if window.is_visible() == Some(false) || window.is_minimized() == Some(true) {
|
||||
return None;
|
||||
}
|
||||
let relative = if let Some(screen) = screen {
|
||||
let start = window.inner_position().ok()?;
|
||||
Point::new(
|
||||
((screen[0] - start.x as f64) / window.scale_factor()) as f32,
|
||||
((screen[1] - start.y as f64) / window.scale_factor()) as f32,
|
||||
)
|
||||
} else if app.resource == source_id && receiver_id == source_id {
|
||||
point
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
let size = window.inner_size().to_logical::<f32>(window.scale_factor());
|
||||
let inside = relative.x >= 0.0
|
||||
&& relative.y >= 0.0
|
||||
&& relative.x < size.width
|
||||
&& relative.y < size.height;
|
||||
let chrome = screen
|
||||
.zip(window.outer_position().ok())
|
||||
.is_some_and(|(screen, outer)| {
|
||||
let size = window.outer_size();
|
||||
screen[0] >= outer.x as f64
|
||||
&& screen[1] >= outer.y as f64
|
||||
&& screen[0] < outer.x as f64 + size.width as f64
|
||||
&& screen[1] < outer.y as f64 + size.height as f64
|
||||
});
|
||||
(inside || chrome).then_some((app, relative, size, inside))
|
||||
});
|
||||
// An obscuring window (including its chrome/developer panel) prevents
|
||||
// dropping into a lower window that happens to share these coordinates.
|
||||
let target = front.and_then(|(app, relative, size, inside)| {
|
||||
if !inside || app.guest_covered(relative) {
|
||||
return None;
|
||||
}
|
||||
let current = app.namespace.read().ok()?;
|
||||
let frame = ¤t.document.frame;
|
||||
if frame.session != input.session || frame.fault.is_some() {
|
||||
return None;
|
||||
}
|
||||
let index = if frame.tabs.is_empty() {
|
||||
0
|
||||
} else {
|
||||
crate::tabs::insertion_index(&frame.tabs, size.width, relative)?
|
||||
};
|
||||
Some(crate::events::TabDrop {
|
||||
window: app.resource,
|
||||
layout_version: frame.layout_version,
|
||||
index,
|
||||
})
|
||||
});
|
||||
let position = screen.and_then(|point| {
|
||||
let anchor = source.tab_drag_grab?;
|
||||
let inner = source_window.inner_position().ok()?;
|
||||
let outer = source_window.outer_position().ok()?;
|
||||
let x = point[0] - anchor.x as f64 * source_scale - (inner.x - outer.x) as f64;
|
||||
let y = point[1] - anchor.y as f64 * source_scale - (inner.y - outer.y) as f64;
|
||||
[x, y]
|
||||
.iter()
|
||||
.all(|value| value.is_finite() && value.abs() <= 1_000_000.0)
|
||||
.then_some([x.round() as i32, y.round() as i32])
|
||||
});
|
||||
self.clear_drag_feedback(target.as_ref().map(|target| (target.window, target.index)));
|
||||
if !release {
|
||||
return;
|
||||
}
|
||||
input.kind = if target.is_some() {
|
||||
"tab-drop"
|
||||
} else {
|
||||
"tab-detach"
|
||||
}
|
||||
.into();
|
||||
input.tab_drop = target;
|
||||
input.screen_position = if input.tab_drop.is_none() {
|
||||
position
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let source = if self.resource == source_id {
|
||||
&mut *self
|
||||
} else {
|
||||
self.children.get_mut(&source_id).expect("drag source")
|
||||
};
|
||||
source.tab_pressed = None;
|
||||
source.tab_drag_origin = None;
|
||||
source.tab_drag_grab = None;
|
||||
source.guest_pressed = None;
|
||||
source.send_guest(input);
|
||||
self.clear_drag_feedback(None);
|
||||
}
|
||||
|
||||
fn create_native(&mut self, event_loop: &ActiveEventLoop) -> anyhow::Result<()> {
|
||||
if self.window.is_some() {
|
||||
return Ok(());
|
||||
@@ -622,6 +914,7 @@ impl TesseraApp {
|
||||
&namespace.document,
|
||||
&mut self.developer_tools,
|
||||
&self.activity,
|
||||
self.tab_drop_index,
|
||||
);
|
||||
drop(namespace);
|
||||
self.layout = scene.layout;
|
||||
@@ -698,6 +991,7 @@ impl ApplicationHandler<AppEvent> for TesseraApp {
|
||||
window_id: WindowId,
|
||||
event: WindowEvent,
|
||||
) {
|
||||
self.native_tab_drag(window_id, &event);
|
||||
let Some(window) = self.window.as_ref().cloned() else {
|
||||
return;
|
||||
};
|
||||
@@ -732,6 +1026,8 @@ impl ApplicationHandler<AppEvent> for TesseraApp {
|
||||
point: None,
|
||||
delta: None,
|
||||
press_point: None,
|
||||
tab_drop: None,
|
||||
screen_position: None,
|
||||
});
|
||||
if let Some(input) = input {
|
||||
self.send_guest(input);
|
||||
@@ -781,11 +1077,12 @@ impl ApplicationHandler<AppEvent> for TesseraApp {
|
||||
if state == ElementState::Pressed {
|
||||
self.guest_keyboard = !self.guest_covered(self.pointer);
|
||||
self.tab_pressed = self.tab_hit();
|
||||
self.tab_drag_origin = self
|
||||
self.tab_drag_grab = self
|
||||
.tab_pressed
|
||||
.as_ref()
|
||||
.filter(|input| input.kind == "tab-activate")
|
||||
.map(|_| self.pointer);
|
||||
.and_then(|input| self.drag_anchor(input));
|
||||
self.tab_drag_origin = self.tab_drag_grab.map(|_| self.pointer);
|
||||
self.guest_pressed = self.guest_hit();
|
||||
if self.guest_keyboard {
|
||||
self.developer_tools.blur();
|
||||
@@ -871,6 +1168,8 @@ impl ApplicationHandler<AppEvent> for TesseraApp {
|
||||
kind: "scroll".into(),
|
||||
point: Some([point.x, point.y]),
|
||||
press_point: None,
|
||||
tab_drop: None,
|
||||
screen_position: None,
|
||||
delta: Some(delta),
|
||||
})
|
||||
});
|
||||
|
||||
+246
-1
@@ -670,6 +670,10 @@ impl ReplSession {
|
||||
.reclaim(&mut self.candidate.vm, &mut self.candidate.roots)
|
||||
}
|
||||
|
||||
pub fn accepts_tab_drop(&self, input: &crate::events::Input) -> bool {
|
||||
self.bridge.accepts_tab_drop(&self.candidate.vm, input)
|
||||
}
|
||||
|
||||
pub fn accepts_window(&self, id: u64) -> bool {
|
||||
self.bridge.accepts_window(id)
|
||||
}
|
||||
@@ -685,6 +689,9 @@ impl ReplSession {
|
||||
if input.session != self.id {
|
||||
bail!("event belongs to another runtime session");
|
||||
}
|
||||
if !self.accepts_tab_drop(input) {
|
||||
bail!("drop targets an obsolete presentation");
|
||||
}
|
||||
self.bridge.select_window(input.window)?;
|
||||
let result = (|| {
|
||||
self.bridge.dispatch(&mut self.candidate.vm, input)?;
|
||||
@@ -986,6 +993,226 @@ mod tests {
|
||||
const EXAMPLE: &str = include_str!("../examples/hello.endor");
|
||||
const PAGE: &str = include_str!("../examples/page.endor");
|
||||
|
||||
#[test]
|
||||
fn positional_insert_preserves_existing_slots_and_mounts_and_rejects_invalid_graphs() {
|
||||
let source = r#"head=TextBlock("head")
|
||||
tail=TextBlock("tail")
|
||||
list=Column(24,8,head,tail)
|
||||
page=Page()
|
||||
page.render(list)"#;
|
||||
let (mut session, initial) = ReplSession::load(source, "app.main", 1, 200).unwrap();
|
||||
session
|
||||
.execute("held=tail.mounts().at(0)", "app.main")
|
||||
.unwrap();
|
||||
let id = session
|
||||
.execute("held.id", "app.main")
|
||||
.unwrap()
|
||||
.value
|
||||
.parse::<u64>()
|
||||
.unwrap();
|
||||
let old = initial
|
||||
.frame
|
||||
.mounts
|
||||
.iter()
|
||||
.find(|mount| mount.id == id)
|
||||
.unwrap();
|
||||
let inserted = session
|
||||
.execute("slot=list.insert(1,TextBlock(\"middle\"))", "app.main")
|
||||
.unwrap();
|
||||
assert_eq!(inserted.value, "2");
|
||||
let document = inserted.document.unwrap();
|
||||
let new = document
|
||||
.frame
|
||||
.mounts
|
||||
.iter()
|
||||
.find(|mount| mount.id == id)
|
||||
.unwrap();
|
||||
assert!(new.y > old.y);
|
||||
assert_eq!(
|
||||
session
|
||||
.execute("tail.mounts().at(0).id", "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
id.to_string()
|
||||
);
|
||||
for invalid in [
|
||||
"list.insert(4,head)",
|
||||
"list.insert(0,list)",
|
||||
"list.insert(-1,head)",
|
||||
] {
|
||||
assert!(session.execute(invalid, "app.main").is_err());
|
||||
assert!(!session.is_faulted());
|
||||
}
|
||||
assert_eq!(
|
||||
session.execute("held.mounted", "app.main").unwrap().value,
|
||||
"true"
|
||||
);
|
||||
session.execute("list.remove(slot)", "app.main").unwrap();
|
||||
assert_eq!(
|
||||
session
|
||||
.execute("tail.mounts().at(0).id", "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
id.to_string()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tab_drop_preserves_page_identity_calls_source_methods_and_rejects_stale_targets() {
|
||||
let (mut session, initial) = ReplSession::load(
|
||||
include_str!("../examples/tab-placement.endor"),
|
||||
"app.main",
|
||||
1,
|
||||
201,
|
||||
)
|
||||
.unwrap();
|
||||
session.take_window_commands().unwrap();
|
||||
let page = initial.frame.tabs[0].id;
|
||||
let input = crate::events::Input {
|
||||
window: 1,
|
||||
session: 201,
|
||||
layout_version: initial.frame.layout_version,
|
||||
mount: page,
|
||||
kind: "tab-drop".into(),
|
||||
point: None,
|
||||
press_point: None,
|
||||
delta: None,
|
||||
screen_position: None,
|
||||
tab_drop: Some(crate::events::TabDrop {
|
||||
window: 1,
|
||||
layout_version: initial.frame.layout_version,
|
||||
index: 3,
|
||||
}),
|
||||
};
|
||||
session
|
||||
.execute("held=list.mounts().at(0)", "app.main")
|
||||
.unwrap();
|
||||
let mount = session.execute("held.id", "app.main").unwrap().value;
|
||||
session.dispatch(&input).unwrap();
|
||||
assert_eq!(
|
||||
session.execute("calls.value", "app.main").unwrap().value,
|
||||
"1"
|
||||
);
|
||||
assert_eq!(
|
||||
session
|
||||
.execute("list.mounts().at(0).id", "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
mount
|
||||
);
|
||||
assert_eq!(
|
||||
session
|
||||
.execute("ui.window().pages().at(2)", "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
session.execute("first", "app.main").unwrap().value
|
||||
);
|
||||
let input = crate::events::Input {
|
||||
layout_version: session.documents[&1].frame.layout_version,
|
||||
tab_drop: Some(crate::events::TabDrop {
|
||||
window: 2,
|
||||
layout_version: session.documents[&2].frame.layout_version,
|
||||
index: 0,
|
||||
}),
|
||||
..input
|
||||
};
|
||||
let mut stale = input.clone();
|
||||
stale.tab_drop.as_mut().unwrap().layout_version += 1;
|
||||
assert!(!session.accepts_tab_drop(&stale));
|
||||
assert!(session.dispatch(&stale).is_err());
|
||||
assert!(!session.is_faulted());
|
||||
session.dispatch(&input).unwrap();
|
||||
assert_eq!(
|
||||
session.execute("calls.value", "app.main").unwrap().value,
|
||||
"3"
|
||||
);
|
||||
assert_eq!(
|
||||
session
|
||||
.execute("first.window().id()", "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
"2"
|
||||
);
|
||||
assert_eq!(
|
||||
session
|
||||
.execute("other.pages().at(0)", "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
session.execute("first", "app.main").unwrap().value
|
||||
);
|
||||
assert_eq!(
|
||||
session.execute("held.mounted", "app.main").unwrap().value,
|
||||
"false"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_respects_declined_source_moves_and_detach_queues_signed_desktop_position() {
|
||||
let source = r#"class Declining: Page {
|
||||
calls: Object
|
||||
function moveToWindow(self: Declining, window: Window): Page { self.calls.increment() return self }
|
||||
}
|
||||
calls=ui.state(0)
|
||||
page=Declining(calls)
|
||||
page.render(TextBlock("source"))
|
||||
other=Window()
|
||||
target=Page()
|
||||
target.render(TextBlock("target"))
|
||||
target.open(other)"#;
|
||||
let (mut session, initial) = ReplSession::load(source, "app.main", 1, 202).unwrap();
|
||||
session.take_window_commands().unwrap();
|
||||
let mut input = crate::events::Input {
|
||||
window: 1,
|
||||
session: 202,
|
||||
layout_version: initial.frame.layout_version,
|
||||
mount: initial.frame.tabs[0].id,
|
||||
kind: "tab-drop".into(),
|
||||
point: None,
|
||||
press_point: None,
|
||||
delta: None,
|
||||
screen_position: None,
|
||||
tab_drop: Some(crate::events::TabDrop {
|
||||
window: 2,
|
||||
layout_version: initial.windows[&2].frame.layout_version,
|
||||
index: 0,
|
||||
}),
|
||||
};
|
||||
session.dispatch(&input).unwrap();
|
||||
assert_eq!(
|
||||
session.execute("calls.value", "app.main").unwrap().value,
|
||||
"1"
|
||||
);
|
||||
assert_eq!(
|
||||
session
|
||||
.execute("page.window().id()", "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
"1"
|
||||
);
|
||||
assert_eq!(
|
||||
session
|
||||
.execute("other.pages().count", "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
"1"
|
||||
);
|
||||
input.kind = "tab-detach".into();
|
||||
input.tab_drop = None;
|
||||
input.screen_position = Some([-400, 120]);
|
||||
input.layout_version = session.documents[&1].frame.layout_version;
|
||||
session.dispatch(&input).unwrap();
|
||||
let commands = session.take_window_commands().unwrap();
|
||||
assert!(commands.iter().any(|command| command.window == 3
|
||||
&& command.action == crate::window::Action::MoveTo { x: -400, y: 120 }));
|
||||
assert_eq!(
|
||||
session
|
||||
.execute("page.window().id()", "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
"3"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owned_tasks_replace_cancel_and_update_unmounted_objects() {
|
||||
let source = r#"class Action {
|
||||
@@ -1305,7 +1532,9 @@ mod tests {
|
||||
kind: "click".into(),
|
||||
point: None,
|
||||
delta: None,
|
||||
press_point: None
|
||||
press_point: None,
|
||||
tab_drop: None,
|
||||
screen_position: None,
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
@@ -1489,6 +1718,8 @@ mod tests {
|
||||
point: None,
|
||||
delta: None,
|
||||
press_point: None,
|
||||
tab_drop: None,
|
||||
screen_position: None,
|
||||
};
|
||||
let selected = session.dispatch(&input).unwrap().document.unwrap();
|
||||
assert!(selected.frame.tabs[0].active);
|
||||
@@ -1517,6 +1748,8 @@ mod tests {
|
||||
point: None,
|
||||
delta: None,
|
||||
press_point: None,
|
||||
tab_drop: None,
|
||||
screen_position: None,
|
||||
})
|
||||
.unwrap()
|
||||
.document
|
||||
@@ -1732,6 +1965,8 @@ mod tests {
|
||||
point: None,
|
||||
delta: None,
|
||||
press_point: None,
|
||||
tab_drop: None,
|
||||
screen_position: None,
|
||||
})
|
||||
.unwrap()
|
||||
.document
|
||||
@@ -2059,6 +2294,8 @@ mod tests {
|
||||
point: Some(release),
|
||||
delta: None,
|
||||
press_point: Some(press),
|
||||
tab_drop: None,
|
||||
screen_position: None,
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
@@ -2103,6 +2340,8 @@ mod tests {
|
||||
point: Some([64.0, 64.0]),
|
||||
delta: None,
|
||||
press_point: Some([64.0, 64.0]),
|
||||
tab_drop: None,
|
||||
screen_position: None,
|
||||
})
|
||||
.err()
|
||||
.unwrap();
|
||||
@@ -2569,6 +2808,8 @@ mod tests {
|
||||
point: None,
|
||||
delta: None,
|
||||
press_point: None,
|
||||
tab_drop: None,
|
||||
screen_position: None,
|
||||
})
|
||||
.unwrap()
|
||||
.document
|
||||
@@ -2849,6 +3090,8 @@ mod tests {
|
||||
point: None,
|
||||
delta: None,
|
||||
press_point: None,
|
||||
tab_drop: None,
|
||||
screen_position: None,
|
||||
};
|
||||
let updated = session.dispatch(&event).unwrap().document.unwrap();
|
||||
updated.validate().unwrap();
|
||||
@@ -2901,6 +3144,8 @@ mod tests {
|
||||
kind: "click".into(),
|
||||
point: Some(point),
|
||||
press_point: Some(point),
|
||||
tab_drop: None,
|
||||
screen_position: None,
|
||||
delta: None,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
@@ -9,6 +9,14 @@ use std::{
|
||||
};
|
||||
use winit::event_loop::EventLoopProxy;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct TabDrop {
|
||||
pub window: u64,
|
||||
pub layout_version: u64,
|
||||
pub index: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Input {
|
||||
@@ -24,6 +32,10 @@ pub struct Input {
|
||||
pub press_point: Option<[f32; 2]>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub delta: Option<[f32; 2]>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub tab_drop: Option<TabDrop>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub screen_position: Option<[i32; 2]>,
|
||||
}
|
||||
|
||||
fn default_window() -> u64 {
|
||||
@@ -35,6 +47,32 @@ impl Input {
|
||||
if self.window == 0 {
|
||||
return Err("window identity must be nonzero");
|
||||
}
|
||||
if self.kind == "tab-drop" {
|
||||
let Some(target) = &self.tab_drop else {
|
||||
return Err("tab-drop requires target metadata");
|
||||
};
|
||||
if target.window == 0
|
||||
|| target.index > crate::ui_bridge::MAX_PAGES
|
||||
|| self.point.is_some()
|
||||
|| self.press_point.is_some()
|
||||
|| self.delta.is_some()
|
||||
|| self.screen_position.is_some()
|
||||
{
|
||||
return Err("invalid tab drop metadata");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if self.tab_drop.is_some() {
|
||||
return Err("tab_drop is only accepted for tab-drop");
|
||||
}
|
||||
if let Some(position) = self.screen_position
|
||||
&& (self.kind != "tab-detach"
|
||||
|| !position
|
||||
.iter()
|
||||
.all(|value| (-1_000_000..=1_000_000).contains(value)))
|
||||
{
|
||||
return Err("screen_position is only accepted for tab-detach with bounded coordinates");
|
||||
}
|
||||
if self.kind == "scroll" {
|
||||
return match (self.point, self.press_point, self.delta) {
|
||||
(Some(point), None, Some(delta))
|
||||
@@ -126,6 +164,23 @@ fn send(input: &Input) -> anyhow::Result<()> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn drop_metadata_is_scoped_to_its_event_kind_and_bounded() {
|
||||
let mut input:Input=serde_json::from_str(r#"{"window":1,"session":1,"layout_version":2,"mount":3,"kind":"tab-drop","tab_drop":{"window":2,"layout_version":4,"index":1}}"#).unwrap();
|
||||
assert!(input.validate().is_ok());
|
||||
input.kind = "click".into();
|
||||
assert!(input.validate().is_err());
|
||||
input.kind = "tab-drop".into();
|
||||
input.tab_drop.as_mut().unwrap().index = 65;
|
||||
assert!(input.validate().is_err());
|
||||
input.kind = "tab-detach".into();
|
||||
input.tab_drop = None;
|
||||
input.screen_position = Some([-400, 200]);
|
||||
assert!(input.validate().is_ok());
|
||||
input.screen_position = Some([i32::MIN, 0]);
|
||||
assert!(input.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_event_window_defaults_but_zero_is_never_a_resource() {
|
||||
let mut input: Input =
|
||||
|
||||
@@ -28,6 +28,7 @@ pub fn install(
|
||||
"Children",
|
||||
vec![
|
||||
("append", 1),
|
||||
("insert", 2),
|
||||
("remove", 1),
|
||||
("replace", 2),
|
||||
("move", 2),
|
||||
|
||||
@@ -17,6 +17,7 @@ pub fn build_scene(
|
||||
document: &RenderDocument,
|
||||
developer_tools_state: &mut DeveloperToolsState,
|
||||
activity: &Activity,
|
||||
tab_drop_index: Option<usize>,
|
||||
) -> DisplayScene {
|
||||
let mut display_list = document.display_list(scale).unwrap_or_else(|_| {
|
||||
RenderDocument::default()
|
||||
@@ -31,6 +32,15 @@ pub fn build_scene(
|
||||
width as f32 / scale,
|
||||
scale,
|
||||
);
|
||||
if let Some(index) = tab_drop_index {
|
||||
crate::tabs::draw_insertion(
|
||||
&mut display_list,
|
||||
&document.frame.tabs,
|
||||
width as f32 / scale,
|
||||
index,
|
||||
scale,
|
||||
);
|
||||
}
|
||||
let (developer_list, developer_layout) = developer_tools::build(
|
||||
width,
|
||||
height,
|
||||
|
||||
+96
@@ -81,6 +81,71 @@ pub fn hit(tabs: &[Tab], width: f32, point: Point) -> Option<(u64, bool)> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Gap index in the complete published order, including overflow-hidden tabs.
|
||||
pub fn insertion_index(tabs: &[Tab], width: f32, point: Point) -> Option<usize> {
|
||||
if point.x < 0.0 || point.x >= width || point.y < 0.0 || point.y >= HEIGHT {
|
||||
return None;
|
||||
}
|
||||
if tabs.is_empty() {
|
||||
return Some(0);
|
||||
}
|
||||
let visible: Vec<_> = items(tabs, width)
|
||||
.into_iter()
|
||||
.filter(|item| item.navigation.is_none())
|
||||
.collect();
|
||||
for item in &visible {
|
||||
if point.x < item.rect.x + item.rect.width / 2.0 {
|
||||
return tabs.iter().position(|tab| tab.id == item.tab.id);
|
||||
}
|
||||
}
|
||||
visible
|
||||
.last()
|
||||
.and_then(|last| tabs.iter().position(|tab| tab.id == last.tab.id))
|
||||
.map(|index| index + 1)
|
||||
}
|
||||
|
||||
pub fn drag_anchor(tabs: &[Tab], width: f32, id: u64, point: Point) -> Option<Point> {
|
||||
let item = items(tabs, width)
|
||||
.into_iter()
|
||||
.find(|item| item.tab.id == id && item.navigation.is_none() && item.rect.contains(point))?;
|
||||
(!close_rect(item.rect).contains(point)).then(|| Point::new(point.x - item.rect.x, point.y))
|
||||
}
|
||||
|
||||
pub fn draw_insertion(list: &mut DisplayList, tabs: &[Tab], width: f32, index: usize, scale: f32) {
|
||||
let visible: Vec<_> = items(tabs, width)
|
||||
.into_iter()
|
||||
.filter(|item| item.navigation.is_none())
|
||||
.collect();
|
||||
let x = if tabs.is_empty() {
|
||||
Some(8.0)
|
||||
} else {
|
||||
visible
|
||||
.iter()
|
||||
.find(|item| tabs.get(index).is_some_and(|tab| tab.id == item.tab.id))
|
||||
.map(|item| item.rect.x)
|
||||
.or_else(|| {
|
||||
visible
|
||||
.last()
|
||||
.filter(|item| {
|
||||
tabs.iter().position(|tab| tab.id == item.tab.id) == index.checked_sub(1)
|
||||
})
|
||||
.map(|item| item.rect.x + item.rect.width)
|
||||
})
|
||||
};
|
||||
if let Some(x) = x {
|
||||
list.push(DrawCommand::FillRoundedRect {
|
||||
rect: Rect::new(
|
||||
x.clamp(1.5, (width - 1.5).max(1.5)) * scale - 1.5 * scale,
|
||||
3.0 * scale,
|
||||
3.0 * scale,
|
||||
(HEIGHT - 6.0) * scale,
|
||||
),
|
||||
radius: scale,
|
||||
color: Color::rgb(56, 95, 220),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub fn draw(list: &mut DisplayList, tabs: &[Tab], width: f32, scale: f32) {
|
||||
if tabs.is_empty() {
|
||||
return;
|
||||
@@ -146,6 +211,37 @@ pub fn draw(list: &mut DisplayList, tabs: &[Tab], width: f32, scale: f32) {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn insertion_gaps_share_visible_tab_geometry_and_exclude_close_and_arrow_drags() {
|
||||
let tabs: Vec<_> = (1..=4)
|
||||
.map(|id| Tab {
|
||||
id,
|
||||
title: id.to_string(),
|
||||
active: id == 1,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
insertion_index(&tabs, 1000.0, Point::new(10.0, 18.0)),
|
||||
Some(0)
|
||||
);
|
||||
assert_eq!(
|
||||
insertion_index(&tabs, 1000.0, Point::new(215.0, 18.0)),
|
||||
Some(1)
|
||||
);
|
||||
assert_eq!(
|
||||
insertion_index(&tabs, 1000.0, Point::new(990.0, 18.0)),
|
||||
Some(4)
|
||||
);
|
||||
assert!(drag_anchor(&tabs, 1000.0, 1, Point::new(200.0, 18.0)).is_none());
|
||||
assert!(drag_anchor(&tabs, 1000.0, 1, Point::new(25.0, 18.0)).is_some());
|
||||
assert_eq!(
|
||||
insertion_index(&tabs, 1000.0, Point::new(20.0, HEIGHT)),
|
||||
None
|
||||
);
|
||||
assert!(drag_anchor(&tabs, 400.0, 3, Point::new(390.0, 18.0)).is_none());
|
||||
assert_eq!(insertion_index(&[], 720.0, Point::new(20.0, 18.0)), Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overflow_keeps_active_page_visible_and_navigation_reaches_other_pages() {
|
||||
let tabs: Vec<_> = (1..=64)
|
||||
|
||||
+188
-24
@@ -250,6 +250,7 @@ enum Operation {
|
||||
CloseWindow,
|
||||
Detach,
|
||||
MoveWindow,
|
||||
MoveTab,
|
||||
State,
|
||||
StateSet,
|
||||
Increment,
|
||||
@@ -266,6 +267,7 @@ enum Operation {
|
||||
SetText,
|
||||
SetColor,
|
||||
Append,
|
||||
Insert,
|
||||
Remove,
|
||||
Replace,
|
||||
Move,
|
||||
@@ -690,11 +692,11 @@ impl NativeCallable for Function {
|
||||
Scroll => (3, 3),
|
||||
Text => (1, 3),
|
||||
Rect => (2, 4),
|
||||
MoveWindow | OpenValue | Spacer | SetText | SetColor | Append | Remove | Render
|
||||
| Navigate | OnClick | Present => (1, 1),
|
||||
MoveTab | MoveWindow | OpenValue | Spacer | SetText | SetColor | Append | Remove
|
||||
| Render | Navigate | OnClick | Present => (1, 1),
|
||||
Row | Column => (2, MAX_UI_NODES + 2),
|
||||
Button => (1, 1),
|
||||
Replace | Move => (2, 2),
|
||||
Insert | Replace | Move => (2, 2),
|
||||
Page | Unmount | Close | Activate | Back | Forward | Children | NewWindow
|
||||
| CloseWindow | Detach => (0, 0),
|
||||
Open => (0, 1),
|
||||
@@ -1158,6 +1160,23 @@ impl NativeCallable for Function {
|
||||
)?,
|
||||
)));
|
||||
}
|
||||
if matches!(self.operation, MoveTab) {
|
||||
let position = usize::try_from(integer(args.first())?)
|
||||
.map_err(|_| invalid("tab position out of range"))?;
|
||||
let mut state = self
|
||||
.session
|
||||
.lock()
|
||||
.map_err(|_| invalid("UI session poisoned"))?;
|
||||
let id = page_window(cx.store(), &state, owner)?.ok_or(invalid("Page is not open"))?;
|
||||
let view = state
|
||||
.presentations
|
||||
.get_mut(&id)
|
||||
.ok_or(invalid("missing window"))?;
|
||||
let window = object(Some(&cx.store().get_attr(view.desktop, "window")?))?;
|
||||
crate::window::move_page(cx, window, owner, position)?;
|
||||
view.force_frame = true;
|
||||
return Ok(NativeResult::Return(Value::Object(owner)));
|
||||
}
|
||||
let (data_ref, data) = block::resolve(cx.store(), owner)?;
|
||||
let mut data = data.clone();
|
||||
let mut result = Value::Nil;
|
||||
@@ -1181,16 +1200,29 @@ impl NativeCallable for Function {
|
||||
}
|
||||
_ => return Err(invalid("this Block has no color")),
|
||||
},
|
||||
Append | Remove | Replace | Move => {
|
||||
Append | Insert | Remove | Replace | Move => {
|
||||
if !data.is_container() {
|
||||
return Err(invalid("expected a container Block"));
|
||||
}
|
||||
if matches!(self.operation, Append) {
|
||||
let child = object(args.first())?;
|
||||
if matches!(self.operation, Append | Insert) {
|
||||
let (position, argument) = if matches!(self.operation, Insert) {
|
||||
let position = usize::try_from(integer(args.first())?)
|
||||
.map_err(|_| invalid("child position out of range"))?;
|
||||
if position > data.children.len() {
|
||||
return Err(invalid("child position out of range"));
|
||||
}
|
||||
(position, args.get(1))
|
||||
} else {
|
||||
(data.children.len(), args.first())
|
||||
};
|
||||
let child = object(argument)?;
|
||||
block::validate(cx.store(), child, Some(data_ref))?;
|
||||
let slot = data.next_slot;
|
||||
data.next_slot = slot.checked_add(1).ok_or(VmError::IdentityExhausted)?;
|
||||
data.children.push(Child { slot, block: child });
|
||||
data.next_slot = slot
|
||||
.checked_add(1)
|
||||
.filter(|next| *next <= i64::MAX as u64)
|
||||
.ok_or(VmError::IdentityExhausted)?;
|
||||
data.children.insert(position, Child { slot, block: child });
|
||||
result = Value::Number((slot as i64).into());
|
||||
} else {
|
||||
let slot = integer(args.first())?;
|
||||
@@ -1209,7 +1241,8 @@ impl NativeCallable for Function {
|
||||
data.children[index].block = child;
|
||||
}
|
||||
Move => {
|
||||
let to = integer(args.get(1))? as usize;
|
||||
let to = usize::try_from(integer(args.get(1))?)
|
||||
.map_err(|_| invalid("child position out of range"))?;
|
||||
if to >= data.children.len() {
|
||||
return Err(invalid("child position out of range"));
|
||||
}
|
||||
@@ -1421,6 +1454,31 @@ pub struct UiBridge {
|
||||
tasks: crate::tasks::Scheduler,
|
||||
}
|
||||
|
||||
fn invoke_member(
|
||||
vm: &mut Vm,
|
||||
owner: ObjectRef,
|
||||
method: &str,
|
||||
arguments: &[Value],
|
||||
instruction_budget: usize,
|
||||
) -> Result<Value> {
|
||||
let bound = vm.bind_attr(owner, method)?;
|
||||
let result = match &bound {
|
||||
Value::Object(function) => vm
|
||||
.call_with_limits(
|
||||
*function,
|
||||
arguments,
|
||||
endor_core::ExecutionLimits {
|
||||
max_frames: 128,
|
||||
max_instructions: instruction_budget,
|
||||
},
|
||||
)
|
||||
.map_err(|error| crate::endor_host::runtime_error(vm, error)),
|
||||
_ => Err(anyhow::anyhow!("object method is not callable")),
|
||||
};
|
||||
vm.release_value(bound)?;
|
||||
result
|
||||
}
|
||||
|
||||
fn project_tabs(
|
||||
vm: &Vm,
|
||||
state: &mut crate::presentation::Presentation,
|
||||
@@ -1632,6 +1690,43 @@ impl UiBridge {
|
||||
.values()
|
||||
.any(|view| view.pending.flatten().is_some() || view.active.is_some()))
|
||||
}
|
||||
pub fn accepts_tab_drop(&self, vm: &Vm, input: &crate::events::Input) -> bool {
|
||||
let Some(target) = &input.tab_drop else {
|
||||
return true;
|
||||
};
|
||||
let Ok(state) = self.session.lock() else {
|
||||
return false;
|
||||
};
|
||||
for (id, version) in [
|
||||
(input.window, input.layout_version),
|
||||
(target.window, target.layout_version),
|
||||
] {
|
||||
let Some(view) = state.presentations.get(&id) else {
|
||||
return false;
|
||||
};
|
||||
if view.closing || view.published_version != version {
|
||||
return false;
|
||||
}
|
||||
let Ok(Value::Object(window)) = vm.get_attr(view.desktop, "window") else {
|
||||
return false;
|
||||
};
|
||||
let Ok(pages) = crate::window::pages(vm.object_store(), window) else {
|
||||
return false;
|
||||
};
|
||||
if view.tab_ids.len() != pages.len()
|
||||
|| !pages
|
||||
.iter()
|
||||
.zip(&view.tab_ids)
|
||||
.all(|(page, (weak, _))| vm.object_store().downgrade(*page).ok() == Some(*weak))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if id == target.window && target.index > pages.len() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
pub fn open_value(&self, vm: &mut Vm, value: &Value) -> Result<()> {
|
||||
let function = object(Some(&vm.get_attr(self.ui, "open")?))?;
|
||||
let page = vm.call(function, std::slice::from_ref(value))?;
|
||||
@@ -1660,25 +1755,92 @@ impl UiBridge {
|
||||
.find(|page| vm.object_store().downgrade(*page).ok() == Some(weak))
|
||||
.ok_or_else(|| anyhow::anyhow!("Page is no longer open"))?
|
||||
};
|
||||
if let Some(target) = &input.tab_drop {
|
||||
let window = {
|
||||
let state = self
|
||||
.session
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("UI session poisoned"))?;
|
||||
let view = state
|
||||
.presentations
|
||||
.get(&target.window)
|
||||
.ok_or_else(|| anyhow::anyhow!("drop window has closed"))?;
|
||||
if view.published_version != target.layout_version {
|
||||
bail!("drop targets an obsolete presentation");
|
||||
}
|
||||
object(Some(&vm.get_attr(view.desktop, "window")?))?
|
||||
};
|
||||
if target.window != input.window {
|
||||
let value =
|
||||
invoke_member(vm, page, "moveToWindow", &[Value::Object(window)], 300_000)?;
|
||||
vm.release_value(value)?;
|
||||
}
|
||||
// An override may deliberately decline or redirect the move. Do
|
||||
// not reorder an unrelated window after that source decision.
|
||||
let destination = {
|
||||
let state = self
|
||||
.session
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("UI session poisoned"))?;
|
||||
page_window(vm.object_store(), &state, page)?
|
||||
};
|
||||
if destination == Some(target.window) {
|
||||
let pages = crate::window::pages(vm.object_store(), window)?;
|
||||
let from = pages
|
||||
.iter()
|
||||
.position(|candidate| *candidate == page)
|
||||
.ok_or_else(|| anyhow::anyhow!("Page is no longer open"))?;
|
||||
let position = if input.window == target.window && from < target.index {
|
||||
target.index - 1
|
||||
} else {
|
||||
target.index
|
||||
};
|
||||
if position >= pages.len() {
|
||||
bail!("drop destination changed during Page method");
|
||||
}
|
||||
let value = invoke_member(
|
||||
vm,
|
||||
page,
|
||||
"moveTab",
|
||||
&[Value::Number((position as i64).into())],
|
||||
300_000,
|
||||
)?;
|
||||
vm.release_value(value)?;
|
||||
let value = invoke_member(vm, page, "activate", &[], 300_000)?;
|
||||
vm.release_value(value)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let method = match input.kind.as_str() {
|
||||
"tab-close" => "close",
|
||||
"tab-detach" => "detachToWindow",
|
||||
_ => "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?)?;
|
||||
let value = invoke_member(vm, page, method, &[], 1_000_000)?;
|
||||
let placed = (|| -> Result<()> {
|
||||
if input.kind == "tab-detach"
|
||||
&& let Some([x, y]) = input.screen_position
|
||||
&& let Value::Object(window) = &value
|
||||
&& vm
|
||||
.payload::<crate::window::ManagedWindow>(*window, "Window")
|
||||
.is_ok()
|
||||
{
|
||||
let result = invoke_member(
|
||||
vm,
|
||||
*window,
|
||||
"moveTo",
|
||||
&[
|
||||
Value::Number((x as i64).into()),
|
||||
Value::Number((y as i64).into()),
|
||||
],
|
||||
100_000,
|
||||
)?;
|
||||
vm.release_value(result)?;
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
vm.release_value(value)?;
|
||||
placed?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1720,7 +1882,7 @@ impl UiBridge {
|
||||
}
|
||||
if matches!(
|
||||
input.kind.as_str(),
|
||||
"tab-activate" | "tab-close" | "tab-detach"
|
||||
"tab-activate" | "tab-close" | "tab-detach" | "tab-drop"
|
||||
) {
|
||||
return self.dispatch_tab(vm, input);
|
||||
}
|
||||
@@ -2441,12 +2603,14 @@ pub fn install(vm: &mut Vm, roots: &mut Vec<ObjectRef>) -> Result<UiBridge> {
|
||||
("TextBlock", "setColor", Operation::SetColor),
|
||||
("RectBlock", "setColor", Operation::SetColor),
|
||||
("ContainerBlock", "append", Operation::Append),
|
||||
("ContainerBlock", "insert", Operation::Insert),
|
||||
("ContainerBlock", "remove", Operation::Remove),
|
||||
("ContainerBlock", "replace", Operation::Replace),
|
||||
("ContainerBlock", "move", Operation::Move),
|
||||
("ContainerBlock", "children", Operation::Children),
|
||||
("Window", "close", Operation::CloseWindow),
|
||||
("Page", "moveToWindow", Operation::MoveWindow),
|
||||
("Page", "moveTab", Operation::MoveTab),
|
||||
("Page", "detachToWindow", Operation::Detach),
|
||||
("Page", "render", Operation::Render),
|
||||
("Page", "unmount", Operation::Unmount),
|
||||
|
||||
+51
-1
@@ -13,6 +13,7 @@ pub const MAX_WINDOW_DIMENSION: f64 = 4096.0;
|
||||
pub enum Action {
|
||||
Resize { width: f64, height: f64 },
|
||||
SetTitle(String),
|
||||
MoveTo { x: i32, y: i32 },
|
||||
Focus,
|
||||
Close,
|
||||
}
|
||||
@@ -73,6 +74,16 @@ impl ObjectPayload for ManagedWindow {
|
||||
fn invalid(message: &'static str) -> VmError {
|
||||
VmError::InvalidArgument(message)
|
||||
}
|
||||
fn screen_coordinate(value: &Value) -> Result<i32, VmError> {
|
||||
let Value::Number(value) = value else {
|
||||
return Err(invalid("screen position requires integer coordinates"));
|
||||
};
|
||||
value
|
||||
.as_i64()
|
||||
.filter(|number| (-1_000_000..=1_000_000).contains(number))
|
||||
.and_then(|number| i32::try_from(number).ok())
|
||||
.ok_or(invalid("screen position exceeds limits"))
|
||||
}
|
||||
fn scalar(value: &Value) -> Result<f64, VmError> {
|
||||
let Value::Number(value) = value else {
|
||||
return Err(invalid("window size requires numbers"));
|
||||
@@ -92,6 +103,7 @@ enum Operation {
|
||||
Viewport,
|
||||
Pages,
|
||||
Resize,
|
||||
MoveTo,
|
||||
SetTitle,
|
||||
Focus,
|
||||
}
|
||||
@@ -113,7 +125,7 @@ impl NativeCallable for Method {
|
||||
return Err(invalid("native window is closed"));
|
||||
}
|
||||
let expected = match self.operation {
|
||||
Operation::Resize => 3,
|
||||
Operation::Resize | Operation::MoveTo => 3,
|
||||
Operation::SetTitle => 2,
|
||||
_ => 1,
|
||||
};
|
||||
@@ -145,6 +157,10 @@ impl NativeCallable for Method {
|
||||
));
|
||||
}
|
||||
let action = match operation {
|
||||
Operation::MoveTo => Action::MoveTo {
|
||||
x: screen_coordinate(&args[1])?,
|
||||
y: screen_coordinate(&args[2])?,
|
||||
},
|
||||
Operation::Resize => Action::Resize {
|
||||
width: scalar(&args[1])?,
|
||||
height: scalar(&args[2])?,
|
||||
@@ -247,6 +263,39 @@ pub fn unregister_page(
|
||||
cx.replace_payload(window, data)?;
|
||||
Ok(())
|
||||
}
|
||||
pub fn move_page(
|
||||
cx: &mut NativeContext<'_>,
|
||||
window: ObjectRef,
|
||||
page: ObjectRef,
|
||||
position: usize,
|
||||
) -> Result<(), VmError> {
|
||||
let mut data = cx
|
||||
.store()
|
||||
.payload::<ManagedWindow>(window, "Window")?
|
||||
.clone();
|
||||
if data.closed {
|
||||
return Err(invalid("native window is closed"));
|
||||
}
|
||||
let from = data
|
||||
.pages
|
||||
.iter()
|
||||
.position(|candidate| *candidate == page)
|
||||
.ok_or(invalid("Page is not open in this window"))?;
|
||||
if position >= data.pages.len() {
|
||||
return Err(invalid("tab position out of range"));
|
||||
}
|
||||
if cx.store().is_read_only() {
|
||||
return Err(invalid(
|
||||
"tab ordering is forbidden during read-only rendering",
|
||||
));
|
||||
}
|
||||
if from != position {
|
||||
let page = data.pages.remove(from);
|
||||
data.pages.insert(position, page);
|
||||
cx.replace_payload(window, data)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn pages(store: &ObjectStore, window: ObjectRef) -> Result<&[ObjectRef], VmError> {
|
||||
Ok(&store.payload::<ManagedWindow>(window, "Window")?.pages)
|
||||
}
|
||||
@@ -273,6 +322,7 @@ pub fn install(
|
||||
("viewport", Operation::Viewport),
|
||||
("pages", Operation::Pages),
|
||||
("resize", Operation::Resize),
|
||||
("moveTo", Operation::MoveTo),
|
||||
("setTitle", Operation::SetTitle),
|
||||
("focus", Operation::Focus),
|
||||
] {
|
||||
|
||||
Reference in New Issue
Block a user