40 Commits

Author SHA1 Message Date
codex-bot 723e41706b fix: keep current Aster API when updating performance study 2026-11-12 02:21:34 +08:00
codex-bot caea8c62a2 Merge remote-tracking branch 'origin/main' into codex/scene-performance 2026-11-12 02:13:08 +08:00
Zayden-Jung 0b1394e407 Merge pull request 'docs: 为 Tessera 本体补充中文源码注释与阅读索引' (#7) from codex/code-comments into main
Reviewed-on: #7
2026-11-11 16:29:49 +00:00
codex-bot 1fedd21d3c docs: explain Tessera modules and execution flows in Chinese 2026-11-11 23:36:03 +08:00
codex-bot 534f6e03c1 perf: add repeatable scene benchmarks and validate borrowed dictionary keys 2026-11-11 15:50:10 +08:00
Zayden-Jung 4c3fc8b5dd Merge pull request 'feat: compose nested UI layouts with 2D and 3D scene viewports' (#5) from codex/page-surfaces into main
Reviewed-on: #5
2026-11-10 17:02:25 +00:00
codex-bot 741977c3fb docs: record verified scene delivery and manual merge status 2026-11-11 00:55:35 +08:00
codex-bot 32d5da5528 feat: bound scene visibility rendering and continuous native input 2026-11-11 00:53:21 +08:00
codex-bot 15fc01542c feat: compose interactive world ui across nested 3d viewports 2026-11-11 00:08:23 +08:00
codex-bot ad2c01bc29 feat: render programmable 3d scenes cameras and picking 2026-11-10 23:19:26 +08:00
codex-bot 040b779f5f feat: separate 2d scenes viewports and explicit cameras 2026-11-10 22:42:56 +08:00
codex-bot 32d7ada3ab feat: implement nested border-box layout and alignment 2026-11-10 22:17:19 +08:00
codex-bot 525097a0b2 Merge remote-tracking branch 'origin/main' into codex/page-surfaces 2026-11-10 21:55:47 +08:00
Zayden-Jung dff84f2b27 Merge pull request 'Add a workspace dashboard script example' (#3) from codex/workspace-dashboard-example into main
Reviewed-on: #3
2026-11-10 08:27:10 +00:00
Zayden-Jung 7007835541 Merge pull request 'chore: remove CI/CD and document local development' (#4) from codex/local-development into main
Reviewed-on: #4
2026-11-10 08:26:58 +00:00
codex-bot 82f9256a84 feat: add page surfaces and collapsible sidebar 2026-11-10 16:18:47 +08:00
codex-bot e0eff7755f chore: remove CI/CD and document local development 2026-11-10 15:17:47 +08:00
codex-bot 1e57e908d4 Add a workspace dashboard script example 2026-11-05 00:53:30 +08:00
Zayden-Jung 303c823eb0 Merge pull request 'test: 修正窗口 chrome 引入后的布局测试尺寸预期' (#2) from codex/fix-layout-ci into main
Verify Tessera GUI / verify (push) Successful in 3m36s
Reviewed-on: #2
2026-10-29 20:28:36 +00:00
Zayden-Jung f787ff25e0 Merge pull request 'ci: 仅 main 分支执行 CI/CD' (#1) from codex/main-only-cicd into main
Verify Tessera GUI / verify (push) Has been cancelled
Reviewed-on: #1
2026-10-29 20:28:29 +00:00
codex-bot 1fb6dc3b8f test: account for window chrome in viewport layout assertions 2026-10-30 03:45:21 +08:00
codex-bot 714d257058 ci: restrict workflows to main branch 2026-10-30 03:43:57 +08:00
codex-bot 21439d4c4d docs: render UML diagrams and embed portable previews
Verify Tessera GUI / verify (push) Failing after 1m30s
2026-10-25 22:09:47 +08:00
codex-bot 18376793b0 refactor: organize host modules and document architecture with UML
Verify Tessera GUI / verify (push) Failing after 2m2s
2026-10-25 21:25:43 +08:00
codex-bot 48fcb96f42 fix: connect toolbar double clicks to native window zoom
Verify Tessera GUI / verify (push) Failing after 1m33s
2026-10-25 15:22:24 +08:00
codex-bot 050f777e33 fix: ease tab hover colors without delaying selection
Verify Tessera GUI / verify (push) Failing after 1m35s
2026-10-25 15:15:16 +08:00
codex-bot 7b769b1477 fix: restore comfortable tab height with native control alignment
Verify Tessera GUI / verify (push) Failing after 1m39s
2026-10-25 15:01:32 +08:00
codex-bot 846c99a991 fix: align compact tabs and scroll overflow continuously
Verify Tessera GUI / verify (push) Failing after 1m52s
2026-10-25 14:46:29 +08:00
codex-bot 38ddb80b7c docs: record Endor campus modeling and shared-state walkthrough
Verify Tessera GUI / verify (push) Failing after 1m34s
2026-10-25 00:30:19 +08:00
codex-bot e54264f23b example: add multi-page Endor campus learning environment
Verify Tessera GUI / verify (push) Failing after 1m32s
2026-10-25 00:13:22 +08:00
codex-bot 3a4a91d5b6 example: add interactive Endor student grades center
Verify Tessera GUI / verify (push) Failing after 2m35s
2026-10-24 23:50:53 +08:00
codex-bot 8881650d4f design: simplify the Endor start page into quiet action rows 2026-10-24 23:23:17 +08:00
codex-bot cd092a9fed fix: increase contrast between workspace chrome and content 2026-10-24 20:41:56 +08:00
codex-bot 952fc2eff2 feat: build functional Endor start page and balance compact tabs 2026-10-24 20:12:02 +08:00
codex-bot 3cb44b96eb fix: preserve source focus across native chrome activation 2026-10-24 19:50:31 +08:00
codex-bot d3165b1224 docs: record workspace behavior and complete requirement audit 2026-10-24 19:37:56 +08:00
codex-bot 656522edfe feat: unify window chrome and managed workspace tabs 2026-10-24 19:36:01 +08:00
codex-bot 3220544777 refactor: separate runtime regression sources from production host 2026-10-24 19:35:50 +08:00
codex-bot 193c5bca89 docs: distinguish ready VM work from idle provider polling
Verify Tessera GUI / verify (push) Successful in 1m42s
2026-10-24 02:27:51 +08:00
codex-bot fa6dfa7062 perf: run ready VM quanta without per-quantum timer delays 2026-10-24 02:27:51 +08:00
148 changed files with 26528 additions and 15018 deletions
-8
View File
@@ -1,8 +0,0 @@
.git
**/.git
target
**/target
**/AGENTS.md
**/work
**/ci-output
.env
-26
View File
@@ -1,26 +0,0 @@
# Tessera GUI automation
[workflows](workflows/README.md) contains repository workflows.
## CI source checkout
All workflows use `runs-on: ces-control`; no shared Runner configuration is changed.
`actions/checkout@v4` reads source over HTTPS using Gitea's automatically supplied
`GITEA_TOKEN`. No additional SSH key or known_hosts secrets are required, and
`persist-credentials: false` prevents credentials from being retained for later
build steps.
Consumer workflows read the exact Aster commit from the checked-out project's
`vendor/aster` gitlink, then use another standard checkout into that directory and
verify the resulting HEAD. They do not follow Aster main automatically. Aster is
currently a public repository, so reading it does not require private cross-repo
authorization. If that visibility changes, diagnose the job token's read access
instead of assuming an SSH key must be distributed.
The SSH URL in `.gitmodules` is retained for developer Git operations, which
continue to use the dedicated codex-bot identity. CI's built-in job token is
separate from local developer credentials.
Workflow definitions do not prove CI passed. CI/deployment state is not queried
automatically. Local runtime checks are not performed for Aster, Lyra or Hestia;
Tessera permits local native builds/window runs, with automated tests in CI.
-42
View File
@@ -1,42 +0,0 @@
# Tessera GUI workflows
[ci.yml](ci.yml) verifies this project on main pushes, pull requests and manual dispatch. It runs on ces-control, with a 60-minute timeout. HTTPS checkout and job token details are in [the parent README](../README.md).
There is no production service deployment in this workflow.
The container includes the Endor examples used by the live guide and tests. It
validates the actual Aster-backed source-to-UI path, snapshot lifetime, layout and
execution budgets, failed-update preservation and stale-result invalidation, in
addition to the existing rendering checks and Clippy. Cargo uses official sources.
The primary example now executes top-level let statements and ui.page().render
through Aster's Interactive interface. Function-entry compatibility, original
source positions, page methods and page budgets are also checked. The workflow
checks the macOS packaging script's syntax without running it on Linux.
Docker is used only in this remote workflow; local compilation is native.
The test image installs DejaVu Sans/Mono and Noto CJK for font metrics and Chinese
fallback checks. Text regression tests inspect glyph selection, measured advances,
fractional scale, multiline bounds, Unicode truncation and antialiased opacity.
## Incremental verification
Gitea 1.26 concurrency groups cancel superseded runs on the same ref. Markdown-only
pushes and pull requests skip verification; executable Endor examples and Rust
files (including embedded guide strings) still trigger checks. Manual dispatch
always runs verification. Existing queued runs created from older workflow
revisions retain their old behavior.
The workflow invokes [verify-ci.sh](../../scripts/verify-ci.sh). Docker builds the
Rust 1.91.1/system/font toolchain from Dockerfile.ci over stdin, without sending a
source build context. The checkout is mounted read-only at /build. Named volumes
persist Cargo registry/git downloads and /cargo-target across container removal,
including failed tests and cancelled runs. Main/manual runs and each PR have
separate cache scopes. Changing Rust/toolchain compatibility requires updating
the image and cache prefix in the script. Cargo lockfiles and fingerprints decide
which dependencies/artifacts are reusable; caches do not bypass checks.
A host flock serializes each scope's writable target cache. Signal handling
removes only the current run's named container; it never prunes shared Docker
resources or deletes cache volumes. The first run populates caches; later runs
still execute fmt, all tests and Clippy. Cargo compilation remains single-job to
limit memory pressure on the shared host. No CPU-time guarantee is implied.
-53
View File
@@ -1,53 +0,0 @@
name: Verify Tessera GUI
on:
push:
branches: [main]
paths-ignore: ["**/*.md"]
pull_request:
paths-ignore: ["**/*.md"]
workflow_dispatch:
concurrency:
group: tessera-${{ gitea.workflow }}-${{ gitea.ref }}
cancel-in-progress: true
jobs:
verify:
runs-on: ces-control
timeout-minutes: 60
env:
DOCKER_BUILDKIT: "0"
steps:
- name: Checkout project
id: checkout_project
uses: actions/checkout@v4
with:
github-server-url: ${{ gitea.server_url }}
persist-credentials: false
- name: Read pinned Aster revision
id: aster_revision
run: |
set -eu
aster_sha=$(git ls-tree HEAD -- vendor/aster | awk '$1 == "160000" && $2 == "commit" && $4 == "vendor/aster" { print $3 }')
case "$aster_sha" in *[!0-9a-f]*|'') echo "Invalid Aster gitlink" >&2; exit 1;; esac
test "${#aster_sha}" -eq 40
printf 'sha=%s\n' "$aster_sha" >> "$GITHUB_OUTPUT"
- name: Checkout pinned Aster
id: checkout_aster
uses: actions/checkout@v4
with:
github-server-url: ${{ gitea.server_url }}
repository: Zayden-Jung/endorphin-aster-vm
ref: ${{ steps.aster_revision.outputs.sha }}
path: vendor/aster
persist-credentials: false
- name: Verify Aster revision
env:
EXPECTED_ASTER_SHA: ${{ steps.aster_revision.outputs.sha }}
run: test "$(git -C vendor/aster rev-parse HEAD)" = "$EXPECTED_ASTER_SHA"
- name: Verify portable GUI code with persistent Cargo caches
env:
CI_CACHE_SCOPE: ${{ gitea.event_name == 'pull_request' && format('pr-{0}', gitea.event.pull_request.number) || 'main' }}
run: sh scripts/verify-ci.sh
Generated
+3
View File
@@ -1652,6 +1652,9 @@ dependencies = [
"core",
"cosmic-text",
"frontend",
"objc2 0.5.2",
"objc2-app-kit",
"objc2-foundation 0.2.2",
"serde",
"serde_json",
"softbuffer",
+6 -1
View File
@@ -12,13 +12,18 @@ compiler = { path = "vendor/aster/crates/compiler" }
cosmic-text = "0.19"
endor_core = { package = "core", path = "vendor/aster/crates/core" }
frontend = { path = "vendor/aster/crates/frontend" }
serde = { version = "1.0", features = ["derive"] }
serde = { version = "1.0", features = ["derive", "rc"] }
serde_json = "1.0"
softbuffer = "0.4.8"
tiny_http = "0.12"
unicode-segmentation = "1.12"
winit = "0.30.13"
[target.'cfg(target_os = "macos")'.dependencies]
objc2 = "0.5.2"
objc2-app-kit = { version = "0.2.2", default-features = false, features = ["NSApplication", "NSButton", "NSEvent", "NSView", "NSWindow"] }
objc2-foundation = { version = "0.2.2", default-features = false, features = ["NSGeometry", "NSString", "NSUserDefaults"] }
[profile.release]
lto = "thin"
codegen-units = 1
-8
View File
@@ -1,8 +0,0 @@
FROM rust:1.91.1-bookworm
WORKDIR /build
RUN apt-get update && apt-get install -y --no-install-recommends pkg-config libx11-dev libxkbcommon-dev libwayland-dev libudev-dev libegl1-mesa-dev libgbm-dev fonts-dejavu-core fonts-noto-cjk \
&& rm -rf /var/lib/apt/lists/* \
&& rustup component add rustfmt clippy
ENV CARGO_BUILD_JOBS=1 CARGO_PROFILE_DEV_DEBUG=0 CARGO_PROFILE_TEST_DEBUG=0
ENV CARGO_TARGET_DIR=/cargo-target
CMD ["sh", "-eu", "-c", "cargo fmt --check && cargo test --locked && cargo clippy --all-targets --locked -- -D warnings"]
+60 -37
View File
@@ -4,7 +4,10 @@ Tessera is a native desktop UI host embedding [Aster](vendor/aster/README.md).
Agents submit ordinary Endor scripts through a local namespace API. Aster parses,
compiles and executes them; `ui.page().render(root)` selects a Tessera UI tree. Tessera extracts a
native tree, lays it out and draws it using the existing software renderer.
The initial page is empty.
The application starts with one managed New tab, implemented in Endor.
For the current architecture, UML diagrams and implementation status, start with
the [中文架构与进展导览](docs/architecture/README.md).
## Source and library integration
@@ -34,8 +37,9 @@ Cargo compiles the required Aster libraries together with Tessera. No separate
Aster build, service or deployment is required. Local builds download dependencies
from official crates.io by default. A temporary dependency mirror may be used
when the official source is unavailable, without changing global configuration.
Docker and automated tests
are not used locally. The command above produces a native executable. To create a
Builds and validation run locally using the native Rust toolchain; no CI/CD
workflow or Docker toolchain is configured. The command above produces a native
executable. To create a
Finder-launchable development app on macOS, run:
```bash
@@ -110,9 +114,10 @@ not Endor keyword argument syntax.
| `ui.page` | No arguments; creates a page with a bound `render(root)` member |
Colors are `#RRGGBB` or `#RRGGBBAA`. Dimensions are finite numbers in 0..1000000.
A namespace has one displayed page. If a script creates several pages or renders
more than once, its final successful render selects the visible root. Rendering
does not publish partial execution: a later error rejects the entire submission.
A namespace retains one active program with multiple managed Pages and windows.
Each window projects its ordered Page registry and currently selected Page.
Rendering an existing Page updates that Page without replacing shared business
objects. A complete-source PUT does not publish partial execution: a later error rejects the entire submission.
Aster keeps its exact numeric representation; conversion occurs only at the UI
boundary. Text is shaped and antialiased with COSMIC Text and Swash, using
@@ -123,7 +128,7 @@ is 14 logical pixels with a 20-pixel line height; size 2 is 28/40. Row/Column la
uses measured text advances and multiline height. Device scale remains fractional,
and glyphs are rasterized at the actual display resolution rather than enlarged.
The application does not bundle proprietary OS fonts. Linux installations need
fonts such as DejaVu Sans/Mono and Noto CJK; the remote test image installs these.
fonts such as DejaVu Sans/Mono and Noto CJK installed locally.
## Candidate execution and publication
@@ -166,7 +171,9 @@ candidate and returns 500, retaining the previous document.
This stage supports live mounted UI for both complete programs and Console inputs, with immutable window frames on the existing worker.
Native mouse/keyboard activation and code-driven callbacks share onClick/click. Managed Mount objects expose each occurrence, and property dependencies and measurement caches avoid recomputing clean visual subtrees. Arrangement still traverses occurrences.
Tab chrome/multiple windows, trait definitions and complete visual type/effect contracts and process isolation are still being implemented. Worker threads,
Sidebar page navigation and multiple windows are available. Typed capability contracts
are installed for host protocols; the complete language/type/effect surface and
process isolation remain incomplete. Worker threads,
source budgets and VM instruction limits are not a complete untrusted-code sandbox.
## Developer tools
@@ -228,13 +235,13 @@ The solver detects a previously visited nonconsecutive state as a cycle. It has
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.
`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: 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. 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).
`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).
The version-checked tab-drop transport remains available for managed Page movement. Same-window requests call moveTab/activate and cross-window requests call moveToWindow first. Source overrides participate; generation/layout mismatches reject before callbacks. The sidebar currently supports selection/closure, with pointer dragging deferred. 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.moveTo(x, y)` queues a native outer-window origin in signed physical desktop pixels, within +/-1000000 per axis. The window manager can adjust placement; unsupported native placement reports a diagnostic. Sidebar cross-window pointer dragging and mixed-DPI gestures remain unverified.
`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.
@@ -242,9 +249,9 @@ A secondary window can also be closed after a callback/rendering failure or Cons
Each window has its own Presentation, layout/Mount/focus state, caches and native viewport. A single VM change batch fans out to all views, all affected frames settle before publication, and shared business references are never copied. Frames and native inputs carry window/session/layout identities; stale requests are rejected. Existing event clients default to window 1, exposed by X-Tessera-Window. Secondary native resize feeds the same worker and updates only its window constraints. Console reset preserves all old pictures with input disabled; replacement sessions discard the old native resources before projecting new resources with the same numeric IDs.
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).
Open Pages appear in the left sidebar. Set `page.title` to label a page; clicking its row or close control calls the actual Page `activate()` or `close()` method in the same VM. Ctrl+Tab / Ctrl+Shift+Tab cycle pages, Cmd/Ctrl+T creates one and Cmd/Ctrl+W closes the active page. Sidebar rows scroll when needed. Source overrides, managed references, GC and stale-event rejection remain in use. 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.
The host has one collapsible left sidebar, with page navigation and Console/Sources/Network/Settings. Cmd/Ctrl+B toggles it. Collapsed, the host draws only its expand button alongside the three real macOS window controls; content fills the native inner window with no top strip or surrounding inset. Only this small control area intercepts page input. `ui.viewport()` / `window.viewport()` and the API viewport headers report the available page area, including the width recovered when the sidebar collapses. Page drawings and hit tests share one camera transform. See [page surfaces](docs/page-surfaces.md).
`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).
@@ -252,7 +259,9 @@ Native creation and commands remain local until the input/candidate succeeds. Fa
The native window publishes its current logical content size to the existing VM worker on startup, resize and scale changes. The worker coalesces the latest size, updates the managed viewport input, and refreshes the same runtime without adding Console source/history entries. ui.viewport() returns a fresh managed width/height snapshot; reads during rendering depend on the private input object. User changes to a returned snapshot do not resize the window. Unchanged sizes cause no frame; a fresh or unopened Console runtime updates its inputs without replacing a preserved displayed page. Failed resize layouts stop the affected runtime and preserve the displayed frame.
The default Column/Button policy propagates available cross-axis width minus padding and leaves height unconstrained; Row propagates available height and leaves width unconstrained. Page uses both viewport bounds. Native and source desired sizes are clamped to their supplied constraints, while source arrange can still allocate explicit child bounds. The window clips overflow and pointer targeting to its extent; TextBlock wraps to its available width; source layout now settles constraints over repeated measurement/arrangement passes as described below. See [layout-cache.endor](examples/layout-cache.endor). GET code also exposes X-Tessera-Viewport-Width/Height headers without evaluating source.
Row, Column and Overlay can nest with main/cross alignment, per-child alignment, margin, asymmetric border/padding, fixed/auto/fill sizes and min/max constraints. Page owns the root; scrolling is a finite ScrollView around ordinary layout. Scene2D owns world positions and CanvasViewport provides a finite UI box with an explicit Camera2D. Multiple views can share a scene while retaining independent cameras; assigning the same camera explicitly shares navigation. The old `Page.mode` API remains for compatibility. See [scene architecture](docs/scene-architecture.md), [box layout](examples/box-layout.endor) and [scene viewports](examples/scene-viewports.endor).
Scene3D, Group3D, mesh geometry, lights and programmable perspective/orthographic cameras render through finite Viewport3D boxes. OrbitController handles rotation, pan and zoom and can be replaced by an Endor controller. Ray picking and world-space Panel3D UI use the same transforms and depth visibility. A panel can contain ordinary UI, a 2D canvas or another 3D viewport. Rendering currently uses the existing CPU compositor with bounded depth/texture surfaces; this is not a GPU renderer. See [3D scenes](examples/scene3d.endor) and [world UI](examples/world-ui.endor).
Native pointer clicks now resolve source `hitTest(self, mount, point): Bool` overrides in reverse paint order, then dispatch through the existing capture/target/bubble route. The Point is local to that occurrence; `point.inside(bounds)` uses a half-open rectangle and `point.inCircle(cx, cy, radius)` includes the circle boundary. Each candidate is first restricted to its Mount rectangle, so hit shapes can refine that area, but cannot expand it. A rejected target falls through to another interactive occurrence, including a parent. Ordinary Blocks become interactive through a live click subscription or a source onEvent override; disconnecting the final click subscription updates that status. See [source-hit.endor](examples/source-hit.endor).
@@ -268,13 +277,20 @@ A source subclass can override `paint(self, mount, geometry): DisplayList`. The
Renderer-dispatched paint runs in a read-only Aster call: existing heap objects cannot be modified; fresh result graphs may be allocated and filled. Existing globals, model fields, containers, Mounts and types remain protected. invalidate is rejected in this phase. All overrides share one VM budget. Read dependencies are currently recorded per object, with versions used to detect changes without depending on bounded change-notification delivery. Native frames keep their existing dependency/cache behavior. Derived allocations do not produce application change notifications, preventing temporary results from causing redraw feedback. This protects managed heap writes; trusted Rust host implementations must also respect read-only calls for external state and I/O. Paint errors stop the affected runtime before publication; failed PUT candidates preserve the previously running heap and frame.
Toggle developer tools with Command-Option-I or F12 on macOS, Control-Shift-I or
F12 on Windows/Linux. The compact Console, Sources, Network and Settings tabs
share a draggable dock edge. The Sources tree/source
boundary and Network's request/details boundary can also be dragged. Each content
area has independent vertical and horizontal scrolling, draggable scrollbar thumbs,
and trackpad support. Shift-wheel scrolls horizontally. Layout uses logical pixels
and the actual display scale; resize clamps pane sizes to keep controls reachable.
The application starts with an Endor Page containing a Scene2D and CanvasViewport. Its four actions demonstrate a window-sized layout, vertically scrolling Column, horizontally scrolling Row and independent canvas. The default page is implemented in [start_page.endor](src/bridge/ui_bridge/start_page.endor), compiled once per VM in a private namespace. `ui.newTab()` and the sidebar New page action use the same factory. Cards, copy, layout, actions and the shared-state example are Endor objects. The host owns the sidebar and native window controls.
Console, Sources, Network and Settings are independent managed Pages with separate
view modules and window-local input/focus/scroll/selection state. They are not
opened by default; the left sidebar provides their launchers. Existing integrations can call
`ui.developerTools("Console")`, `"Sources"`, `"Network"` or `"Settings"`.
F12, Cmd-Option-I and Cmd-Shift-I on macOS, or Ctrl-Shift-I elsewhere,
open/focus Console. Page closure, placement and GC use the ordinary Page methods.
Sources supports read-only drag selection, select-all/copy, and Shift+arrow
selection; source line numbers are excluded from copied text. The Console prompt
only captures pointer hits over its actual input lines.
See [the UI requirement audit](docs/ui-workspace-audit.md) for the full change
scope, design references, native verification and outstanding evidence.
Console is one live execution context: statements, function definitions and
expressions use the same VM and globals dictionary across submissions. There is no
@@ -352,7 +368,7 @@ Sources shows the full source snapshot or Console transcript with line numbers,
AST and selected source ranges. Selecting an AST node scrolls to its location while
keeping the entire file available. Cloud files has a separate file navigator and
source viewer, initially disconnected. The `CloudSourceProvider` boundary in
`src/sources.rs` supplies file identities/paths and full source on open; there is no
`src/shell/sources.rs` supplies file identities/paths and full source on open; there is no
cloud backend, fake file listing or source persistence in this release.
Network observes only HTTP requests handled by this Tessera process on
@@ -370,7 +386,7 @@ Very bright custom colors are darkened to keep accents visible on white. Executi
separators, selected tabs and focus indicators use the accent, while text keeps its
readable neutral/error/success colors. Settings and source remain in memory only.
Management controls use the internal [Tessera System UI](src/system_ui/README.md)
Management controls use the internal [Tessera System UI](src/shell/system_ui/README.md)
widget library, independent of Endor-controlled page widgets. Buttons, tabs,
toggles, rows, input fields, color swatches and drag handles share hover, pressed,
selected, focus and disabled presentation. Buttons activate on release inside;
@@ -383,17 +399,24 @@ UTF-8 even when launched from Finder, and decoding errors are surfaced.
## Validation
Local native builds and window runs are allowed; do not run local automated tests
or Docker. [Remote CI](.gitea/README.md) on ces-control runs the existing renderer
checks and the new Aster script/module execution, page rendering, UI layout, source-range, lifetime, budget,
failed-update and deletion-invalidation regressions, plus Clippy.
The API regressions use actual HTTP requests, including DELETE while the worker
is occupied and a queued PUT is superseded.
Linux CI does not verify macOS window presentation. Aster has no standalone CI/CD; Lyra CI
explicitly validates the pinned engine itself. CI uses official Cargo sources
and standard HTTPS checkout without custom SSH secrets. Font checks cover
proportional/monospace advances, fractional scaling, multiline height, Chinese
fallback, grapheme-safe truncation, antialiasing and alpha blending.
Run checks from the repository root after initializing the pinned Aster submodule:
```bash
cargo fmt --check
cargo test --locked
cargo clippy --all-targets --locked -- -D warnings
sh -n scripts/build-macos-app.sh
```
The existing tests cover rendering, Aster execution, page layout, source ranges,
lifetime, budgets, failed-update preservation and deletion invalidation. API tests
use loopback HTTP, so allow local socket access. Font checks use installed system
fonts. Automated checks do not replace native window verification: launch Tessera
and check the start page, shared-object example, tab creation/closure and developer
tools. Build the macOS bundle separately with `sh scripts/build-macos-app.sh`.
There is no repository CI/CD workflow. Commits and pull requests do not trigger
builds or deployment; record the actual local check results with each delivery.
### Source function types
@@ -510,7 +533,7 @@ UiBridge::begin_layout_frame/resume_layout_frame now expose PendingLayout around
ReplSession now owns a resumable RefreshWork containing window traversal, pending bridge layout, unpublished per-window documents and the cumulative refresh work budget. poll_refresh advances one refresh stage or VM quantum; only a complete stable pass replaces the session's full document map. Synchronous callers drain the same state machine. Failure stops the domain, releases any pending bridge work and preserves the externally published picture. refreshYields counts cooperative refresh returns, not wall-clock time. Only still-pending Mount preparation is rolled back; completed callbacks remain committed.
Viewport refresh now advances through ReplSession's saved refresh state on worker idle turns. A turn advances one traversal stage or a 256-instruction layout quantum; a pending job shortens the next worker wait to 1 ms. Tasks/window commands and document publication wait for complete refresh. ui.stats().refreshYields reports cooperative idle returns. Mutating requests wait across worker turns for the existing job, so they cannot run inside its read-only scope. Mutating requests are serialized; newer viewport targets coalesce by cancelling unpublished layout. Initial source execution remains atomic; its layout can park across worker turns. Explicit REPL/event refresh can park across worker turns. Idle task delivery starts at most one ready callback per turn and parks its subsequent layout; callbacks themselves and individual Rust measurement/paint calls remain atomic.
Viewport refresh now advances through ReplSession's saved refresh state on worker idle turns. A turn advances one traversal stage or a 256-instruction layout quantum; ready layout/paint or coroutine work checks the request queue without a timed wait and yields to other ready OS threads between turns. An accepted pending input/candidate also yields without adding a fixed millisecond delay per VM quantum; control, epoch and viewport checks still run on every turn. When only external completion/timers are pending, the normal idle wait remains 100 ms. Tasks/window commands and document publication wait for complete refresh. ui.stats().refreshYields reports cooperative idle returns. Mutating requests wait across worker turns for the existing job, so they cannot run inside its read-only scope. Mutating requests are serialized; newer viewport targets coalesce by cancelling unpublished layout. Initial source execution remains atomic; its layout can park across worker turns. Explicit REPL/event refresh can park across worker turns. Idle task delivery starts at most one ready callback per turn and parks its subsequent layout; callbacks themselves and individual Rust measurement/paint calls remain atomic.
Runtime mutation entry points reject direct calls while refresh work is pending, before executing source or changing metadata; task polling defers. The API worker drains the saved refresh before accepting those mutations, keeping the runtime usable. Incremental refresh keeps the prior complete document map until a stable pass, including across window traversal boundaries where no VM read-only frame is currently active.
@@ -569,10 +592,10 @@ ui.spawn(owner,key,function) creates an owner-scoped cooperative Task for a zero
Inside a function run by ui.spawn, `value = await task` waits for any timer/file/network/spawn Task and resumes at the same expression with its retained result. A source function may return a Number, String, managed Object or Unit; normal source annotations still apply. Task.result() and await share the result. `ui.sleep(owner,key,milliseconds)` creates a callback-free timer Task returning Unit. Plain calls/REPL can await an already completed Task; a pending await requires a coroutine and fails explicitly rather than blocking. There is no new async function declaration: ui.spawn explicitly schedules an ordinary Endor function. See examples/await-file.endor.
A waiting coroutine retains its evaluated operand and frames as managed edges; waiting performs no VM execution or active 1ms spin. Source side effects and IO initiation before await are not replayed. When the dependency completes, the owning VM worker resumes the waiter through the existing fair quantum scheduler. Cancelling/replacing/closing the waiter releases its frames and operand; it does not automatically cancel an independently owned or shared dependency. Dependency cancellation propagates cancellation to its waiters without running the remainder. An unhandled dependency failure becomes a source await error (with the original provider message), fails the waiter and follows the existing shared-runtime fault rule; provider failure alone still only fails its own Task. Self-await and cyclic Task waits fail explicitly. Read-only layout/paint cannot await. Waiting state is reported as running, while active() remains true; result() is unavailable until completion. These APIs do not introduce try/finally or change the existing exception model.
A waiting coroutine retains its evaluated operand and frames as managed edges; waiting performs no VM execution or active polling. Source side effects and IO initiation before await are not replayed. When the dependency completes, the owning VM worker resumes the waiter through the existing fair quantum scheduler. Cancelling/replacing/closing the waiter releases its frames and operand; it does not automatically cancel an independently owned or shared dependency. Dependency cancellation propagates cancellation to its waiters without running the remainder. An unhandled dependency failure becomes a source await error (with the original provider message), fails the waiter and follows the existing shared-runtime fault rule; provider failure alone still only fails its own Task. Self-await and cyclic Task waits fail explicitly. Read-only layout/paint cannot await. Waiting state is reported as running, while active() remains true; result() is unavailable until completion. These APIs do not introduce try/finally or change the existing exception model.
While a native tab drag is held over an overflow arrow area, the strip waits 350ms then reveals one hidden tab every 120ms, including in a compatible destination window. The preview scroll does not activate Pages or change business state. Drawing, hit testing and insertion gaps share the same transient visible range; release uses its full-order insertion index. Leaving the strip stops the timer; release, Escape, a new press or runtime generation change restores the normal active-tab-centered strip. A resize or changing tab count clamps the range. Native drag/mixed-DPI behavior still requires platform validation; application-exit cleanup is described below.
The former horizontal tab-strip gestures and animation have been replaced by sidebar page navigation. Page.moveTab, moveToWindow and detachToWindow remain available through Endor/API; sidebar pointer drag/reorder and cross-window drag are not implemented in this revision.
Application exit now uses a private VM-worker control channel, independent of HTTP queue capacity. Main native close and a managed primary Window.close request asynchronous cleanup; duplicate requests coalesce and mutation requests are rejected with 503 while exiting. An unpublished candidate/input refresh is cancelled without replay. The current VM cancels all Task entries, closes managed windows, detaches occurrences child-before-parent per window, and invokes normal onUnmount hooks once. It does not run layout/paint during shutdown. All windows are closed before hooks run; new windows and tasks are forbidden. A stopped/faulted VM detaches without source hooks; reset/discarded pictures cannot revive an old VM. A hook error aborts remaining source hooks, releases prepared hook roots, drops the VM and reports failure before native exit. Completed shutdown is acknowledged to the GUI, which then ends the event loop. An OS exit bypassing CloseRequested uses a five-second bounded final fallback; non-cooperative native calls remain atomic and force-kill/crash cannot guarantee notifications. Native stderr records the window/mount/task-entry counts and whether source hooks were enabled, or the cleanup error. See examples/exit-lifecycle.endor. Cross-platform exit/drag validation remains broader follow-up work.
+58
View File
@@ -0,0 +1,58 @@
# 01 · 模块、依赖与部署
## 项目目录
```text
Tessera/
├── Cargo.toml / Cargo.lock Rust 依赖和固定解析结果
├── src/
│ ├── main.rs 组合入口、事件循环和共享发布状态
│ ├── shell/ 原生窗口、可收起侧栏、开发工具、管理控件
│ ├── runtime/ 本机 API、VM worker、执行、事件与异步任务
│ ├── model/ 托管对象、挂载、绑定、依赖和发布数据
│ ├── render/ 布局、绘制、命中、字体与软件光栅化
│ └── bridge/ Endor 与宿主 UI 类型及行为的连接
├── examples/ Endor 示例程序,保留原文件名与入口
├── docs/
│ ├── architecture/ 本套架构说明和 UML 源文件
│ └── media/ 已有建模视频与字幕
├── scripts/ 本地原生打包及 UML 文档渲染
└── vendor/aster/ 独立 Git 子模块:语言、编译器、VM
```
`target/` 是忽略的构建产物,不是源码目录。示例与媒体保留原位置,避免破坏已有引用。完整源码职责见 [逐文件清单](file-map.md)。
## 组件关系
箭头表示主要运行时调用/数据流,不宣称是无环的 Rust import 图。
![组件与主要数据流](uml/rendered/components.png)
[放大 SVG](uml/rendered/components.svg) · [编辑 UML 源码](uml/components.puml)
标准 UML 组件表示见 [components.puml](uml/components.puml)。`System UI` 只依赖低层几何、文本和画图,不导入 Endor VM 或 guest bridge;开发工具的执行逻辑由外层提供。
## 线程与进程
| 执行位置 | 核心所有物 | 交互方式 |
| --- | --- | --- |
| GUI / winit 主线程 | TesseraApp、原生 Window、Surface、侧栏、页面视角交互 | 读已发布快照;发 viewport、输入和窗口命令 |
| `tessera-agent-api` | tiny_http 接收循环、请求观察 | 对写入做校验并进入最多 8 条的构建队列;读取当前发布状态 |
| `tessera-endor-worker` | 活跃 ReplSession、候选 VM、托管对象图 | 串行执行程序、回调、布局/绘制协议及任务完成交付 |
| 输入发送线程 | 有界输入客户端 | 把原生输入转为本机 HTTP 请求;不执行 VM |
| 按需 I/O 池 | 文件/HTTP 工作及取消控制 | 不持有托管根;通过 mailbox 回传文本/错误 |
| 系统 curl 子进程 | `fetchText` 的实际 HTTP 传输 | 有超时、大小和协议限制;不是业务服务 |
![进程与线程部署](uml/rendered/deployment.png)
[放大 SVG](uml/rendered/deployment.svg) · [编辑 UML 源码](uml/deployment.puml)
可编辑部署图:[deployment.puml](uml/deployment.puml)。Aster 作为 Cargo path dependency 编译到同一应用,不是额外 VM 服务;Lyra 和 Hestia 不在应用依赖链中。
## 入口定位
- 启动:`src/main.rs` → `runtime/api::start` → `shell/app::TesseraApp`。
- 请求路由和有界队列:`runtime/api.rs`;VM 所有权与发布:`runtime/api/worker.rs`。
- 启动 Endor 主程序/Console:`runtime/endor_host.rs`。
- 类型安装:`bridge/ui_bridge/bootstrap.rs`;原生 Block 方法:`calls.rs`。
- 组合最终画面:`render/scene.rs`;写入像素:`render/software_renderer.rs`。
+43
View File
@@ -0,0 +1,43 @@
# 02 · 对象模型、展示位置与所有权
## 托管语义与原生快照是两种东西
业务对象、Block、Window、Mount、Task 等语义对象位于 Aster 堆中。Rust 的 `ObjectRef` 只是受检查的堆身份;能否存活由 VM 根及 `trace` 边决定。窗口侧的 `Arc<UiNode>`、Frame、Tab 是提取后的原生值,不能用来复活或直接修改语义对象。
下面是简化 UML 类图;实线关联表示有强引用/直接持有,虚线标明弱引用或派生关系。它省略类型表、回调捕获边和桌面的内部字典,不能当成完整 GC 根枚举。
![对象模型与引用关系](uml/rendered/domain.png)
[放大 SVG](uml/rendered/domain.svg) · [编辑 UML 源码](uml/domain.puml)
可编辑来源:[domain.puml](uml/domain.puml)。`Page` 是具有 Page 行为的托管 Block,不是另一棵浏览器 DOM;`ManagedWindow` 是 VM 中的窗口语义,和 winit 的原生 Window 有对应关系,但不是同一对象。
## 同一对象的两次出现
例如两个成绩页都引用同一个课程对象,并通过 `ui.textOf(course, "grade")` 展示字段。字段改变后,两处绑定都能更新。即使同一个可视 Block 出现两次,也必须分别布局:这两次出现对应不同 Mount,具有不同坐标、父位置、滚动偏移和焦点上下文。
`Child.slot` 是稳定的子出现标识,不能简单用数组下标替代。插入、移动子项时,这有助于保持原来的展示身份,而不是把所有后续位置都当作新出现。
## 谁保留什么
| 关系 | 保留/释放含义 |
| --- | --- |
| Candidate 的 globals / service roots | 保持当前程序全局对象和宿主服务可达 |
| Block → Cell → Data,或 Cell → Block | 支持共享赋值与别名;内容变化不会要求窗口侧重建对象身份 |
| Data → children / bindings / callbacks / history | 实际托管强边,交给 Aster GC 追踪 |
| Window 的 Page registry | 打开的 Page 被保留;关闭标签释放 registry 边 |
| 桌面内部 mount 字典 → Mount | 保留活跃展示位置;Mount 强引用其 Block |
| Mount → page / parent / siblings | 弱反向边,避免共享内容把 Page 留住 |
| MountTable、对象诊断索引、任务索引 | 使用弱身份,不单独延长对象寿命 |
| Subscription token → connection | 弱引用;丢弃 token 不等于取消监听,需 disconnect |
| 原生 Frame / Tab / DrawCommand | 无 VM handles;只是绘制和交互所需的值 |
关闭标签不必然销毁 Page:脚本仍引用它时可以重新打开。反之,关闭后不可达的对象图可以回收;没有“固定页面池”。重置 Console、删除程序或成功替换程序会触发活跃运行时的清理路径。
## 三种版本号不能混用
- `submission`:已接受写入工作的先后次序,用于撤销旧候选的发布资格。
- `revision`:已提交文档的修订,失败构建不应冒充成功修订。
- `runtime_session` / Frame.session 与 `layout_version`:界面输入属于哪一代运行时、哪份布局;旧点击和旧拖放不能作用到新对象。
对象模型源文件集中在 `src/model/`。实际分配、根清理和回调预算由 `runtime/endor_host.rs` 与 bridge 协作完成。
+50
View File
@@ -0,0 +1,50 @@
# 03 · Endor 执行、并发请求与发布
## 完整程序提交的时序
![完整程序执行与发布时序](uml/rendered/publication.png)
[放大 SVG](uml/rendered/publication.svg) · [编辑 UML 源码](uml/publication.puml)
图简化了 HTTP Response 的持有:原始请求在入队后由 worker 完成响应,不是 GUI 执行 HTTP 请求。可编辑来源:[publication.puml](uml/publication.puml)。
## 不同入口的语义
| 入口 | VM / 发布行为 |
| --- | --- |
| `GET /agent` | 按当前 namespace 生成使用指南,不执行 Endor |
| `GET .../code` | 读取最后成功发布的源码文本 |
| `PUT .../code` | 新候选执行;成功后接替活跃运行时,失败保留原程序 |
| `POST .../repl` | 在活跃 Console/程序 VM 内执行,不靠重放历史恢复对象 |
| `DELETE .../repl` | 清理 Console 上下文,重新建立可用会话 |
| `DELETE .../code` | 清空并使旧工作失去发布资格 |
| `POST .../events` | 校验窗口、运行时代际与布局身份,再在拥有对象的 VM 中分发 |
| `POST .../evaluate` | 独立表达式求值;不是替换当前页面的入口 |
在线契约以 `GET http://127.0.0.1:4737/agent` 为准,静态正文实现位于 `runtime/api/guide.rs`。
Console 的编译错误发生在执行前;运行期错误则可能保留此前已经完成的赋值,所以它**不是数据库事务回滚**。故障运行时有单独的停用/清理规则;完整 PUT 的隔离候选和 REPL 的活对象修改不能混为一谈。
## 代际与失败边界
![候选与活跃运行时状态](uml/rendered/runtime.png)
[放大 SVG](uml/rendered/runtime.svg) · [编辑 UML 源码](uml/runtime.puml)
这是候选和活跃运行时的概念状态图,并非源码中一个同名 enum。刷新具体由 `RefreshWork`、`PendingLayout`、paint Work 与 worker 的 PendingRequest 协作,不能在挂起时换一个 VM 恢复。
## 异步任务
`ui.after`、`ui.readText`、`ui.fetchText` 和协作任务由托管 Task 表示。回调及 scope 是 VM 强边,调度索引保留弱身份。I/O 池只接收路径/URL等原生数据、取消控制及完成消息,不拿着 ObjectRef 在其他线程调用 VM。
![异步任务状态](uml/rendered/tasks.png)
[放大 SVG](uml/rendered/tasks.svg) · [编辑 UML 源码](uml/tasks.puml)
源码的 Task 状态为 pending、running、completed、cancelled、failed;具体 provider 可能在 Pending 期间已开展后台 I/O,图中的 Running 不表示后台 I/O 一定此时才启动。见 [tasks.puml](uml/tasks.puml)。
## 预算与实际边界
源码上限 1 MiB;AST 访问上限 10000、深度 64;VM 栈帧上限 128;指令预算、UI 对象和页面预算各有上限。完整脚本各输入共享分摊总指令额度;Console 还检查累计来源与活对象限制。队列上限是 8,不是无限吞吐。
这些预算帮助限制失控工作,**不构成执行任意不可信代码的安全沙箱**。当前程序仍运行在桌面进程内,文件和网络能力没有完成产品级权限治理。
+38
View File
@@ -0,0 +1,38 @@
# 04 · 布局、绘制、输入与刷新
## 一帧不是重新执行整个程序
活跃 VM 中的属性修改先被依赖系统观察,必要时刷新绑定、派生 UiNode、布局、paint 和 Mount 几何,再发布原生 Frame。干净的派生子树和测量结果可以复用;这不意味着所有帧都只访问变化节点,arrange、出现遍历和版本校验仍有成本。
| 环节 | 文件 | 产物 / 约束 |
| --- | --- | --- |
| 绑定与变化依赖 | `model/binding.rs`、`snapshot.rs`、`presentation.rs` | 属性/方法身份依赖、缓存失效 |
| 不可变视觉提取 | `bridge/ui_bridge/tree.rs`、`model/block.rs` | 无 VM handles 的 UiNode 树,可有共享子树 |
| native 布局 | `render/layout.rs` | 测量、排列、稳定出现身份与预算 |
| source 布局协议 | `render/source_layout.rs`、`native_visual.rs` | 只读 measure/arrange 调用、约束和缓存 |
| source/native 绘制 | `render/source_paint.rs` | 检查绘制命令、文字换行界限、依赖与预算 |
| 滚动 / 命中 | `render/scroll.rs`、`source_hit.rs` | 每 Mount 偏移、剪裁、逆绘制顺序选目标 |
| 窗口画面合成 | `render/scene.rs` | guest 页面 + 标签 + 当前开发工具 |
| 文本 / 光栅化 | `render/text.rs`、`software_renderer.rs` | 系统字体 shaping、抗锯齿 glyph、像素和嵌套剪裁 |
GUI 在 redraw 时组合已发布的画面和宿主 chrome,并按实际屏幕倍率写入 softbuffer。需要运行 source 方法的布局或 paint 由 worker 处理;viewport 变化也会送回 worker,GUI 线程不执行这些 VM 方法。
## 点击如何回到对象
![原生输入与事件分发时序](uml/rendered/input.png)
[放大 SVG](uml/rendered/input.svg) · [编辑 UML 源码](uml/input.puml)
可编辑来源:[input.puml](uml/input.puml)。没有 Mount 的代码主动 dispatch 只访问目标;有 Mount 的事件沿该次出现的父路径传播。事件监听器连接由 Block 保留,Subscription token 是弱控制句柄。
`stopPropagation`、`stopImmediatePropagation`、`preventDefault` 有各自语义;`preventDefault` 目前没有额外宿主默认动作可取消。原生输入不应绕过同一分发器直接调用另一个回调机制。
## 为什么 Mount、剪裁与 source 协议必须一起看
一个 Block 在两个容器出现时,源方法接收不同 Mount 的约束和几何。滚动需要更新该次出现的坐标、剪裁和祖先选择;命中顺序必须对应画出来的顺序。仅修改 paint 而不修改 hit/layout 会导致“看得到点不到”,反过来也会产生不可见点击区域。
只读协议及签名约束用于保护这些阶段,但不应表述为语言的所有 effect/trait 特性都已完成。当前具体原生签名和检查见 `bridge/ui_bridge/signatures.rs`、`model/protocols.rs` 及 Aster 固定版本。
## 刷新中的过时工作
尺寸、对象内容或运行时代际在刷新中变化时,旧 layout/paint 可以取消或重启。worker 负责完成当前清理并重新对齐 viewport,不能把旧 Mount 几何发布为新布局。当前刷新主协调仍在 `runtime/endor_host.rs` 与 `bridge/ui_bridge.rs`,后续可继续拆出独立 coordinator;本次没有改变该调度算法。
+39
View File
@@ -0,0 +1,39 @@
# 05 · 标签、窗口、默认页与开发工具
## 三层身份
| 层次 | 负责什么 | 不负责什么 |
| --- | --- | --- |
| 托管 Page / ManagedWindow | 页面内容、打开/关闭、所属窗口、脚本覆盖行为和对象可达性 | 像素级 hover、原生按钮位置 |
| 已发布 Tab / Frame / Window Envelope | 传输不透明 ID、标题、活动状态、窗口命令和版本 | 保留 VM 堆对象 |
| TesseraApp / tabs::Motion / winit Window | 绘制、命中、拖动、滚动、原生资源及即时交互 | 执行业务回调、复制业务对象图 |
![页面展示与可达性状态](uml/rendered/windows.png)
[放大 SVG](uml/rendered/windows.svg) · [编辑 UML 源码](uml/windows.puml)
该图是**可达性与展示状态的说明**,不是一个源码 enum。关闭原生窗口、移除 Page 展示和回收对象不是同一动作。跨窗口拖放携带来源/目标窗口、布局版本、插入位置等元数据,worker 拒绝过期目标,再更新托管 registry;GUI 不直接移动堆对象。可编辑来源:[windows.puml](uml/windows.puml)。
## 已完成的标签行为
- 启动有一个默认 Page;`+`、Cmd/Ctrl+T 新建,Cmd/Ctrl+W 关闭活动页。
- 顶部与左侧宿主区域共用背景;内容区单独作为页面表面,未实现用户暂不需要的左右页面分栏。
- 40 逻辑像素栏高、32 像素标签、88–208 像素宽度;保留高密度和鼠标/触控板滚动,移除两侧点击箭头。
- 非活动标签之间有短竖线,活动/hover 邻边按状态隐藏或渐变。
- 新建/关闭/自动揭示使用独立几何动画;hover 背景、关闭按钮和分隔线使用 160ms 颜色过渡,点击选中即时生效。
- macOS 原生红黄绿保留系统行为,并与标签中心线对齐;工具栏空白处可拖动和双击放大/还原。
`native_chrome.rs` 通过 AppKit 操作现有窗口与系统按钮。双击使用 NSEvent.clickCount 和 NSWindow.performZoom,而不是画一个假的最大化动画。读取系统偏好:最小化/禁用遵循分支;Fill 目前映射到公开 zoom API,没有调用 Chrome 使用的私有 `_zoomFill`,不保证复刻所有新系统平铺边距。
## 默认页与四个工具页
默认页源码是 [start_page.endor](../../src/bridge/ui_bridge/start_page.endor),位于独立私有模块;创建页、共享计数和组合示例都是真实 Endor 对象操作。它不覆盖用户程序 globals,也没有把四个工具页当作默认内容。
Console、Sources、Network、Settings 各自有独立页面实现和窗口内交互状态。目前通过 `ui.developerTools("Console")` 等入口与现有快捷键进入,工具发现菜单仍延后。四页不是新平台业务模块,也不代表已经接入云服务。
- Console:真实 VM 输入、输出和本机请求活动;不是只显示介绍的文本区域。
- Sources:当前源码/Console transcript、AST 与选择;云文件 provider 默认未连接。
- Network:仅本 Tessera API 请求的有界记录,不是浏览器或操作系统抓包。
- Settings:内存内主题强调色;没有跨进程持久化。
源码位置:`shell/developer_tools/`。宿主管理控件在 `shell/system_ui/`,和 guest 的 Button/Block 类型有明确区别。
+53
View File
@@ -0,0 +1,53 @@
# 06 · 当前进展、限制与验证
截至 2026-10-25,可以用 Endor 建立共享对象、多 Page 的原生交互应用,在 Console 中持续修改它们,并用已有开发工具观察源码和本机 API。这是可工作的桌面宿主及语言 UI 集成阶段,不是完整 LMS、浏览器或云 IDE。
## 进展矩阵
| 领域 | 已有实现与证据位置 | 尚未完成 / 不能据此推断 |
| --- | --- | --- |
| 语言运行 | 固定版本 Aster Reader、Parser、Compiler、VM;完整程序和持久 Console,`runtime/endor_host.rs` | 不等于 Endor 全语言、全部数值指令或所有 trait/effect 语法均已完整实现 |
| 对象与类型 | 托管 Block/Cell/Data、原生名义类型、源类与原生子类、方法签名和能力检查,`bridge` / `model` | 仍受当前 Aster 版本的表达式、注解和 effect 实现子集限制 |
| 活界面 | 共享对象绑定、Mount、source/native measure/arrange/paint/hitTest、缓存及刷新预算 | 不保证每次刷新只做局部 O(变更数) 工作;无 GPU 渲染后端 |
| 页面/窗口 | 默认页、真实多 Page、标签关闭重开、原生多窗口、带代际校验的拖放 | 混合 DPI 跨屏、真实触屏与动画帧时序没有完整硬件验收 |
| 桌面交互 | 统一 chrome、原生按钮对齐、双击 zoom/restore、高密度滚动、hover 淡入淡出 | Fill 并未接 macOS 私有精确平铺接口;非 macOS 构建本轮未验证 |
| 事件 | capture/target/bubble、代码/native 共用分发、Subscription、Mount 生命周期回调 | preventDefault 尚无额外宿主默认动作可取消 |
| 异步 | timer、文件读取、fetchText、协作调度、owner/key 取消 | 不是完整浏览器网络栈;fetchText 使用系统 curl,无完整产品权限体系 |
| 开发工具 | Console/Sources/Network/Settings 四个独立 Page | 云 source provider 默认断开;工具发现 UI 延后;状态不持久化 |
| 示例 | 学生成绩示例、七页 Campus LMS、共享提交/成绩更新、建模录屏 | 全部虚构数据;预设评分,不连接 Canvas,不具备真实认证/上传/成绩计算服务 |
| 本机 API | 仅 loopback、有界队列、版本和失败保留,`runtime/api*` | loopback 不是完整授权系统,执行预算不是不可信代码沙箱 |
| 分发 | 可构建 Finder 可启动的 macOS 开发 bundle | 没有发行签名、公证、安装器和本轮跨平台发布验证 |
## 推荐看这几个实物
1. [默认页源码](../../src/bridge/ui_bridge/start_page.endor):理解“页面本身就是 Endor 程序”。
2. 默认页的“共享对象示例”入口:展示一个状态对象的两处绑定;更多源码见 [examples README](../../examples/README.md)。
3. [Campus LMS 源码](../../examples/campus-lms.endor) 与 [操作说明](../campus-lms-demo.md):七个真实 Page 共享课程和提交对象。
4. [建模视频](../media/endor-campus-modeling.mp4) 与 [中文字幕](../media/endor-campus-modeling.zh.srt):已有实际窗口操作记录,静音、采样帧率有说明。
5. `GET /agent`:运行中的实时 API 指南,优先于长期静态样例推断接口。
## 当前本地开发方式(2026-11-10)
页面/宿主设计更新:支持 window、vertical、horizontal、canvas 四种空间;顶部标签条由可收起左侧栏替代。实现、测试与原生验收边界见 [页面空间说明](../page-surfaces.md)。下文 150 项测试及原窗口结构属于前一次移除 CI 的交付记录。
项目已移除 CI/CD 工作流、Docker 工具链定义及远程验证脚本。开发、构建、现有测试与原生窗口验收改在本机执行,命令见 [项目验证说明](../../README.md#validation)。以下保留 2026-10-25 整理时的验收记录,不代表本次检查结果。
本次使用 macOS / Rust 1.91.1:格式检查、150 项现有测试、all-target Clippy(拒绝 warnings)、打包脚本语法检查及 release app 构建均通过。应用已启动,`GET /agent` 与 `GET /code` 返回正常,窗口报告 1280 × 800 的逻辑 viewport;通过实际 REPL 创建/关闭临时标签页,页面数为 1 → 2 → 1。首次页面查询误用了不存在的 `ui.pages()`,返回 422;改为 `ui.window().pages().count` 后通过。原生 UI 检查工具启动失败,本次没有窗口外观、真实鼠标交互或跨屏验收证据。Aster 保持固定版本,未修改源码或 gitlink。
下一步优先补齐真实窗口的共享对象、标签拖放和退出清理验收,然后定义本地 `.endor` 文件的打开、保存及重启恢复方式。当前 Sources 的云文件 provider 默认断开,源码/设置尚不持久化。此外,在线 API 指南仍有旧的标签高度、overflow 箭头和增量布局状态说明,需要与现有实现及测试统一。
## 2026-10-25 整理验证方式
本轮是整理,不扩展业务功能。沿用工作约定:格式、`cargo clippy --all-targets --offline -- -D warnings`、原生 release 打包、真实窗口和少量人工 API 操作;不执行 cargo test、自动 smoke 脚本或 Docker。Clippy 会编译检查已有测试代码,但不代表测试已经执行。
最终实际执行结果见 [整理清单的验收记录](file-map.md#验收记录)。架构图已用官方 PlantUML JavaScript 引擎在本地生成 SVG 和 PNG,并检查实际图片。渲染工具临时安装在仓库外,不需要 Java、原生 Graphviz 或在线服务;详见 [UML 图册的重建步骤](uml/README.md#重新生成)。
## 后续建议顺序
以下是后续建议,不是本轮已经实现或已承诺排期的功能。
1. 把多 Page、关闭重开、跨窗拖放、共享字段刷新作为固定人工验收场景,优先暴露状态与生命周期问题。
2. 沿稳定接口继续拆分 `ui_bridge` 的刷新协调和 `app` 的输入路由,减少大模块;不要仅为“分层”额外复制对象模型。
3. 明确保存/恢复与文件 provider 的产品语义,再选择持久化格式和后端。
4. 根据真实应用需求推进 Aster 运算与类型能力,避免用 UI 层预设值冒充完整业务计算。
5. 在增加可信外部运行能力前明确权限、执行隔离与分发机制。
+30
View File
@@ -0,0 +1,30 @@
# 07 · 本轮整理的设计决策
## 职责目录,不冒充已经解耦的层
采用 `shell / runtime / model / render / bridge` 是为了让入口、对象、执行和绘制更容易定位。当前仍是一个 Rust binary crate:model 需要 bridge 派生类型与 render 几何,bridge 需要 model 和 render,runtime/API 也会通知 shell 的 AppEvent。组件图因此画的是主要行为流,不是严格单向依赖约束。
`main.rs` 的 `pub(crate) use` 是内部路径兼容门面,使现有 `crate::block` 等调用继续指向新目录。它不增加公共库 API、不产生第二份对象,也不隐藏多份实现。代价是调用路径暂时不能单独反映目录所属;需要打开 `main.rs` 或源码导航确定归属。后续若要拆 crate,应先定义跨边界协议并梳理实际循环依赖,而不是机械删掉别名。
## 拆分的是职责,不是复制代码
- API 的 worker 负责活跃 VM、候选请求、增量执行、发布与关闭;HTTP 路由和活动记录仍在 `api.rs`。
- 在线 agent 指南独立到 `api/guide.rs`,仍由当前 NamespaceState 生成;嵌入例子的相对路径已随目录调整。
- bridge 的 `tree.rs` 只放无托管句柄的派生画面数据;`signatures.rs` 负责规范签名;`calls.rs` 实现 NativeCallable;`bootstrap.rs` 安装类型表及 globals。
- bridge 主模块保留 Session、窗口 Presentation 和挂起布局等协调。这里仍接近 2000 行;本轮没有声称已把全部大模块拆完。
- 原有 tests.rs 随所属模块移动,保持原测试含义,只修正编译时样例文件路径。没有删减现有测试来让检查通过。
这些子模块共享父模块的内部类型;`use super::*` 表达它们是同一实现单元的拆分,而不是独立公共服务。worker 只向 API 父作用域暴露必要协调接口和现有测试所需状态;其他请求处理细节继续私有。
## 本轮保持的边界
- 不更改 Endor 示例、API 路由、语法、运行时预算、窗口视觉参数和交互效果。
- 不更新 Aster 子模块,不改变 vendor 历史。
- 不移动构建产物、已有示例与媒体目录,不修改用户未提交的示例工作。
- 不引入新的产品依赖或在线 UML 渲染服务。文档图片由仓库外的临时 Node 工具生成,应用构建不依赖它。
## 文档的可信度
本套 UML 以实际 Rust 类型、线程名、队列、方法和引用语义为依据。`.puml` 是图的唯一可编辑来源,PNG/SVG 由 `scripts/render-uml.mjs` 生成;文档直接引用生成图像。概念状态机、主要调用流及省略字段都在图旁标明;它们不是自动从源码生成的完整模型。进展矩阵区分代码已有、此前人工验证、本轮验证及未完成项。
更改执行/生命周期语义后应同步更新 `02/03/04` 与对应 `.puml`;更改 shell 交互后更新 `05`;发布阶段结果更新 `06` 和本轮验收记录。逐文件清单是本次迁移快照,不要求以后每次新增模块都伪装成同一轮迁移。
+37
View File
@@ -0,0 +1,37 @@
# Tessera 架构与进展导览
核对日期:2026-10-25。范围:本仓库当前实现;Aster 子模块固定在 `f3e1670`,本次不更新其代码或版本。
Tessera 目前是**运行 Endor 对象程序的原生桌面宿主**。Endor 程序创建和共享对象,Page 把对象组织成可交互界面;Tessera 负责窗口、输入、布局、绘制、调试入口和本机 API。它已经能运行多页面示例,但还不是带持久化、权限和业务后端的完整应用平台。
建议按下面顺序阅读。图表示真实结构或经过标注的简化流程,不把后续计划画成已经存在的组件。
| 文档 | 回答的问题 |
| --- | --- |
| [01 模块与部署](01-modules.md) | 目录为什么这样分?有哪些线程与外部依赖? |
| [02 对象模型与所有权](02-object-model.md) | Block、Page、Window、Mount 分别是什么?谁保留对象? |
| [03 执行与发布](03-runtime.md) | Endor 如何变成界面?错误和过期请求怎么处理? |
| [04 布局、绘制与输入](04-rendering.md) | 修改对象后如何刷新?点击如何回到同一个 VM? |
| [05 桌面工作区](05-workspace.md) | 标签、原生窗口、默认页、开发工具如何配合? |
| [06 当前进展](06-progress.md) | 已经做到什么?还有哪些限制?怎样复现? |
| [07 设计决策](07-decisions.md) | 为什么使用这些边界?整理还没有解决什么? |
| [逐文件整理清单](file-map.md) | 每个文件迁移到哪里、负责什么,本次拆出了什么? |
UML 已渲染为普通 PNG 图片,直接嵌入各篇说明,不依赖 Mermaid 或 PlantUML 插件。需要放大可打开 SVG;八张图的图片、SVG 和可编辑源码集中在 [UML 图册](uml/README.md)。图像由本地脚本从 `.puml` 生成,不使用在线渲染服务。
![组件与主要数据流](uml/rendered/components.png)
[放大组件图 SVG](uml/rendered/components.svg)
## 先抓住四个概念
1. **对象是程序状态**:共享内容留在 Aster 管理的对象堆内;切换标签不靠重放源码恢复对象。
2. **Mount 是一次展示位置**:同一个 Block 可以在不同位置出现,每个位置有自己的几何、滚动和焦点上下文。
3. **Frame 是发布给窗口的值**:窗口收到命令、文本、标量 ID 等原生数据,不拿到 VM 堆引用。
4. **Page 和标签不是两套页面系统**:标签是托管 Page 的窗口侧投影;默认页也是 Endor Page。
## 本轮整理结果
`src` 的实现收进 `shell / runtime / model / render / bridge` 五个目录,根目录保留启动入口和源码导航。`api.rs` 从约 1800 行拆成请求处理、worker 与在线指南;`ui_bridge.rs` 从约 3450 行拆出画面树、签名、原生方法调用和类型初始化,主文件保留会话与展示刷新协调。
这些目录是**职责分组,不是已经隔离的五个 crate**。目前 model、bridge、render 仍有协作依赖,主窗口事件与 worker 之间也有协议耦合。根目录保留 crate 私有模块别名,让本次迁移不同时改写全部调用路径;详见设计决策。
+144
View File
@@ -0,0 +1,144 @@
# 逐文件整理清单
本轮仅重排 Tessera 宿主实现;以下覆盖所有迁移源码、测试和默认页文件。未修改 `vendor/aster`、用户已有的 `examples/README.md` 改动及未跟踪的 `examples/workspace.endor`。
主入口 `src/main.rs` 改为五组目录模块及 crate 私有兼容别名;`src/README.md` 改为中文源码导航;根 `README.md` 更新架构入口、实际初始页/多页面状态和迁移后的路径。既有 Endor 示例、媒体和打包脚本保留原位置。
## shell
| 原路径 | 新路径 | 用途与本次变化 |
| --- | --- | --- |
| `src/activity.rs` | [src/shell/activity.rs](../../src/shell/activity.rs) | 有界 HTTP 活动记录与允许的头部预览 |
| `src/app.rs` | [src/shell/app.rs](../../src/shell/app.rs) | GUI 事件循环、窗口/viewport、输入与 chrome 调度 |
| `src/clipboard.rs` | [src/shell/clipboard.rs](../../src/shell/clipboard.rs) | 原生 UTF-8 剪贴板适配 |
| `src/developer_tools.rs` | [src/shell/developer_tools.rs](../../src/shell/developer_tools.rs) | 四个工具 Page 的状态、焦点与管理交互协调 |
| `src/developer_tools/console.rs` | [src/shell/developer_tools/console.rs](../../src/shell/developer_tools/console.rs) | Console 提示符、执行输出与输入布局 |
| `src/developer_tools/network.rs` | [src/shell/developer_tools/network.rs](../../src/shell/developer_tools/network.rs) | 本机 API Network 检查视图 |
| `src/developer_tools/painter.rs` | [src/shell/developer_tools/painter.rs](../../src/shell/developer_tools/painter.rs) | 工具页面绘制辅助 |
| `src/developer_tools/selection.rs` | [src/shell/developer_tools/selection.rs](../../src/shell/developer_tools/selection.rs) | 文本选择和光标几何 |
| `src/developer_tools/settings.rs` | [src/shell/developer_tools/settings.rs](../../src/shell/developer_tools/settings.rs) | 内存内主题设置视图 |
| `src/developer_tools/sources.rs` | [src/shell/developer_tools/sources.rs](../../src/shell/developer_tools/sources.rs) | 源码、AST 和文件来源视图 |
| `src/native_chrome.rs` | [src/shell/native_chrome.rs](../../src/shell/native_chrome.rs) | macOS 原生按钮对齐和工具栏双击系统动作 |
| `src/sources.rs` | [src/shell/sources.rs](../../src/shell/sources.rs) | 默认断开的云文件 provider 接口及工作区 |
| `src/system_ui/README.md` | [src/shell/system_ui/README.md](../../src/shell/system_ui/README.md) | 管理控件职责说明及更新后的源码路径 |
| `src/system_ui/interaction.rs` | [src/shell/system_ui/interaction.rs](../../src/shell/system_ui/interaction.rs) | 宿主管理控件的 ID、命中、焦点和交互状态 |
| `src/system_ui/mod.rs` | [src/shell/system_ui/mod.rs](../../src/shell/system_ui/mod.rs) | 管理控件模块导出 |
| `src/system_ui/theme.rs` | [src/shell/system_ui/theme.rs](../../src/shell/system_ui/theme.rs) | 管理表面颜色和主题 |
| `src/system_ui/widgets.rs` | [src/shell/system_ui/widgets.rs](../../src/shell/system_ui/widgets.rs) | 宿主可复用控件绘制 |
| `src/tabs.rs` | [src/shell/tabs.rs](../../src/shell/tabs.rs) | 共享标签绘制/命中、密集布局、滚动、拖放及动画 |
| `src/tabs/hover.rs` | [src/shell/tabs/hover.rs](../../src/shell/tabs/hover.rs) | 标签、关闭和加号的颜色过渡 |
| `src/tabs/motion.rs` | [src/shell/tabs/motion.rs](../../src/shell/tabs/motion.rs) | 标签布局动画及 hover 重绘期限 |
## runtime
| 原路径 | 新路径 | 用途与本次变化 |
| --- | --- | --- |
| `src/api.rs` | [src/runtime/api.rs](../../src/runtime/api.rs) | HTTP 请求路由、队列、请求观察和响应;worker/指南拆为子模块 |
| `src/api/tests.rs` | [src/runtime/api/tests.rs](../../src/runtime/api/tests.rs) | 保留原 API 测试;只调整嵌入示例路径,不执行测试 |
| `src/endor_host.rs` | [src/runtime/endor_host.rs](../../src/runtime/endor_host.rs) | 候选/活跃 VM、编译执行、增量刷新、清理和诊断 |
| `src/endor_host/tests.rs` | [src/runtime/endor_host/tests.rs](../../src/runtime/endor_host/tests.rs) | 保留原宿主测试;只调整嵌入示例路径,不执行测试 |
| `src/endor_script.rs` | [src/runtime/endor_script.rs](../../src/runtime/endor_script.rs) | 组织 Aster Script/Module 输入及原始源码范围 |
| `src/event_dispatch.rs` | [src/runtime/event_dispatch.rs](../../src/runtime/event_dispatch.rs) | 托管事件、订阅和 capture/target/bubble 分发 |
| `src/events.rs` | [src/runtime/events.rs](../../src/runtime/events.rs) | 原生输入的有界 loopback 传输 |
| `src/io_tasks.rs` | [src/runtime/io_tasks.rs](../../src/runtime/io_tasks.rs) | 有界文件/HTTP provider、纯数据完成消息和取消 |
| `src/tasks.rs` | [src/runtime/tasks.rs](../../src/runtime/tasks.rs) | 托管 Task、owner/key 取消和协作任务调度 |
| `src/vm_sequence.rs` | [src/runtime/vm_sequence.rs](../../src/runtime/vm_sequence.rs) | 共享 VM 调用序列及同帧迭代驱动 |
## model
| 原路径 | 新路径 | 用途与本次变化 |
| --- | --- | --- |
| `src/binding.rs` | [src/model/binding.rs](../../src/model/binding.rs) | 属性依赖、只读计算与托管绑定 |
| `src/block.rs` | [src/model/block.rs](../../src/model/block.rs) | Block/Cell/Data 语义、稳定子 slot 和共享赋值 |
| `src/document.rs` | [src/model/document.rs](../../src/model/document.rs) | NamespaceState、RenderDocument、Frame、发布校验与原生命令 |
| `src/mount.rs` | [src/model/mount.rs](../../src/model/mount.rs) | 每次展示出现的托管上下文、生命周期及弱索引 |
| `src/object_list.rs` | [src/model/object_list.rs](../../src/model/object_list.rs) | 托管结果集合的类型封装与只读访问 |
| `src/presentation.rs` | [src/model/presentation.rs](../../src/model/presentation.rs) | 逐窗口布局、Mount、缓存、读依赖和失效状态 |
| `src/protocols.rs` | [src/model/protocols.rs](../../src/model/protocols.rs) | Visual/EventTarget/Children/Presentable 能力契约安装 |
| `src/snapshot.rs` | [src/model/snapshot.rs](../../src/model/snapshot.rs) | 变化依赖和不可变视觉提取缓存 |
| `src/window.rs` | [src/model/window.rs](../../src/model/window.rs) | 托管 Window、Page registry、命令及生命周期 |
## render
| 原路径 | 新路径 | 用途与本次变化 |
| --- | --- | --- |
| `src/display_list.rs` | [src/render/display_list.rs](../../src/render/display_list.rs) | 原生绘制原语和颜色 |
| `src/geometry.rs` | [src/render/geometry.rs](../../src/render/geometry.rs) | 点和矩形值 |
| `src/layout.rs` | [src/render/layout.rs](../../src/render/layout.rs) | 原生测量、排列、出现几何及预算 |
| `src/native_visual.rs` | [src/render/native_visual.rs](../../src/render/native_visual.rs) | 托管原生视觉协议、值转换和签名检查 |
| `src/scene.rs` | [src/render/scene.rs](../../src/render/scene.rs) | 页面、标签、插入标记和开发工具画面合成 |
| `src/scroll.rs` | [src/render/scroll.rs](../../src/render/scroll.rs) | 逐 Mount 偏移、嵌套滚动和剪裁投影 |
| `src/software_renderer.rs` | [src/render/software_renderer.rs](../../src/render/software_renderer.rs) | 软件光栅化、抗锯齿覆盖和嵌套剪裁 |
| `src/source_hit.rs` | [src/render/source_hit.rs](../../src/render/source_hit.rs) | 源/原生命中协议与匹配目标 |
| `src/source_layout.rs` | [src/render/source_layout.rs](../../src/render/source_layout.rs) | 源 measure/arrange、约束、挂起工作和测量缓存 |
| `src/source_paint.rs` | [src/render/source_paint.rs](../../src/render/source_paint.rs) | 源 paint 调用、受限命令转换和依赖 |
| `src/text.rs` | [src/render/text.rs](../../src/render/text.rs) | 系统字体、shaping、字形和测量缓存 |
## bridge
| 原路径 | 新路径 | 用途与本次变化 |
| --- | --- | --- |
| `src/ui_bridge.rs` | [src/bridge/ui_bridge.rs](../../src/bridge/ui_bridge.rs) | Endor 宿主类型、窗口展示会话、布局/绘制发布协调;本次拆出四个实现子模块 |
| `src/ui_bridge/developer_pages.rs` | [src/bridge/ui_bridge/developer_pages.rs](../../src/bridge/ui_bridge/developer_pages.rs) | 托管默认页与工具页的建立入口 |
| `src/ui_bridge/start_page.endor` | [src/bridge/ui_bridge/start_page.endor](../../src/bridge/ui_bridge/start_page.endor) | 默认页和共享/组合交互的 Endor 源码 |
## 新增模块与拆分
| 新文件 | 职责 / 来源 |
| --- | --- |
| `src/shell/mod.rs` | 声明 shell 组内模块,形成明确的目录所有权 |
| `src/runtime/mod.rs` | 声明 runtime 组内模块,形成明确的目录所有权 |
| `src/model/mod.rs` | 声明 model 组内模块,形成明确的目录所有权 |
| `src/render/mod.rs` | 声明 render 组内模块,形成明确的目录所有权 |
| `src/bridge/mod.rs` | 声明 bridge 组内模块,形成明确的目录所有权 |
| [src/runtime/api/worker.rs](../../src/runtime/api/worker.rs) | 从 api.rs 提取 VM worker、增量请求状态、候选/活跃发布及关闭协调,内部可见性限制在父 API 模块 |
| [src/runtime/api/guide.rs](../../src/runtime/api/guide.rs) | 从 api.rs 提取当前 namespace 的在线 agent 使用指南;修正 include_str 示例路径 |
| [src/bridge/ui_bridge/tree.rs](../../src/bridge/ui_bridge/tree.rs) | 从 ui_bridge.rs 提取不可变 UiNode / UiKind 与比较逻辑 |
| [src/bridge/ui_bridge/signatures.rs](../../src/bridge/ui_bridge/signatures.rs) | 提取宿主方法/构造操作的规范签名 |
| [src/bridge/ui_bridge/calls.rs](../../src/bridge/ui_bridge/calls.rs) | 提取 NativeCallable for Function 的 Block 操作分发 |
| [src/bridge/ui_bridge/bootstrap.rs](../../src/bridge/ui_bridge/bootstrap.rs) | 提取 desktop、类型表与宿主 globals 安装 |
## 新增架构文档
| 文件 | 说明 |
| --- | --- |
| `docs/architecture/README.md` | 中文阅读入口与本轮范围 |
| `01-modules.md` | 职责目录、组件和线程部署 |
| `02-object-model.md` | 对象、Mount、强弱引用与版本 |
| `03-runtime.md` | PUT/Console/API、候选发布与任务状态 |
| `04-rendering.md` | 依赖、布局、paint、命中和输入回路 |
| `05-workspace.md` | Page、标签、原生窗口和四个工具页 |
| `06-progress.md` | 已实现、限制、示例和后续建议 |
| `07-decisions.md` | 路径兼容门面与未完全解耦的边界 |
| `file-map.md` | 本逐文件迁移和拆分清单、验收记录 |
| `uml/README.md` | UML 文件导航及本地导出说明 |
| `uml/components.puml` | 组件 UML 源码 |
| `uml/deployment.puml` | 部署 UML 源码 |
| `uml/domain.puml` | 对象类 UML 源码 |
| `uml/publication.puml` | PUT 发布时序 UML 源码 |
| `uml/input.puml` | 输入分发时序 UML 源码 |
| `uml/tasks.puml` | 任务状态 UML 源码 |
| `uml/windows.puml` | Page 可达性/展示状态 UML 源码 |
## 验收记录
- `cargo fmt --check`、`cargo clippy --all-targets --offline -- -D warnings`、`scripts/build-macos-app.sh --offline` 通过。
- 原生启动通过;人工提交 Campus Console 输入成功,七页正常显示。实际点击提交/评分后,仪表盘共享成绩更新为 88.5%。
- 完整 Campus PUT 返回 HTTP 200;故意错误的 PUT 返回 422;随后 GET 返回 HTTP 200,源码与原成功提交逐字节相同。
- 在线指南完整 GET 返回 HTTP 200;新增架构文档、源码导航和项目入口的本地文件链接检查通过。
- 原有 API/宿主测试随模块迁移并通过编译检查;未执行 cargo test、自动 smoke 或 Docker。
- Aster 子模块仍为 `f3e1670`。用户已有的示例变更保留且不提交。
- 初轮仅提供 UML 源码;后续已补齐八图的本地 SVG/PNG 渲染、普通 Markdown 图片引用和实际图像检查,见下节。
## UML 渲染补齐
- `scripts/render-uml.mjs`:新增本地官方 PlantUML 引擎的导出入口,使用 XML DOM、原生 Canvas 字体测量和 Viz 布局;检测错误图,生成不透明白底 SVG 与高分辨率 PNG。
- `scripts/README.md`:增加文档渲染入口;不改变原生打包/检查流程。
- `uml/components.puml`、`deployment.puml`、`domain.puml`、`publication.puml`、`input.puml`、`tasks.puml`、`windows.puml`:修正标签换行,统一字体和画布设置,调整组件图方向并修正部署图中不兼容的注释位置。
- `uml/runtime.puml`:补充文档原有的候选/活跃运行时状态图源码。
- `uml/rendered/{components,deployment,domain,publication,runtime,input,tasks,windows}.{svg,png}`:新增对应八张图的 SVG 和 PNG,共 16 个生成文件。
- `01-modules.md`、`02-object-model.md`、`03-runtime.md`、`04-rendering.md`、`05-workspace.md`:把所有未渲染的 Mermaid 图块替换为普通图片,附 SVG 和源码链接。
- `README.md`、`06-progress.md`、`07-decisions.md`、`uml/README.md` 和本清单:更新查看入口、图册、生成方式与实际验证状态。
八份源码均通过本地导出并检查实际图片;文档图片/本地链接、Node 语法和 Git 空白检查通过。本轮没有修改 Rust 应用代码,因此不重复运行应用构建或 cargo test。
+67
View File
@@ -0,0 +1,67 @@
# UML 图册
下面直接显示已渲染的 PNG,不需要安装 Markdown 插件。打开 SVG 可以放大阅读;`.puml` 保留可编辑源码。画布为不透明白底,避免深色查看器把黑色文字和连线淹没。
## 组件与主要数据流
![组件与主要数据流](rendered/components.png)
[放大 SVG](rendered/components.svg) · [编辑源码](components.puml)
## 进程与线程部署
![进程与线程部署](rendered/deployment.png)
[放大 SVG](rendered/deployment.svg) · [编辑源码](deployment.puml)
## 对象模型与引用关系
![对象模型与引用关系](rendered/domain.png)
[放大 SVG](rendered/domain.svg) · [编辑源码](domain.puml)
## 完整程序执行与发布时序
![完整程序执行与发布时序](rendered/publication.png)
[放大 SVG](rendered/publication.svg) · [编辑源码](publication.puml)
## 候选与活跃运行时状态
![候选与活跃运行时状态](rendered/runtime.png)
[放大 SVG](rendered/runtime.svg) · [编辑源码](runtime.puml)
## 原生输入与事件分发时序
![原生输入与事件分发时序](rendered/input.png)
[放大 SVG](rendered/input.svg) · [编辑源码](input.puml)
## 异步任务状态
![异步任务状态](rendered/tasks.png)
[放大 SVG](rendered/tasks.svg) · [编辑源码](tasks.puml)
## 页面展示与可达性状态
![页面展示与可达性状态](rendered/windows.png)
[放大 SVG](rendered/windows.svg) · [编辑源码](windows.puml)
## 重新生成
从项目根目录运行下面的文档工具。依赖只安装到临时目录,固定版本;不写入 Cargo、应用依赖或全局环境。渲染时不上传图的源码。
```sh
export UML_RENDER_TOOLS="$(mktemp -d /private/tmp/tessera-uml.XXXXXX)"
npm install --prefix "$UML_RENDER_TOOLS" --ignore-scripts --no-audit --no-fund \
@plantuml/core@1.2026.9 @viz-js/viz@3.17.0 \
@napi-rs/canvas@0.1.80 @xmldom/xmldom@0.9.12 sharp@0.34.5
node scripts/render-uml.mjs
```
使用官方 `@plantuml/core` JavaScript 引擎、Viz 布局、XML DOM 和本机 Canvas 字体测量,不需要 Java 或原生 Graphviz。PNG 由同一份 SVG 导出。脚本对渲染错误图做检查,失败则停止;修改源码后应重新生成并查看图片。
字体取自本机,跨机器重建可能有微小的排版差异。源图中的概念状态与省略字段范围以各篇架构说明为准;渲染不会把概念图变成自动提取的完整代码模型。
+32
View File
@@ -0,0 +1,32 @@
@startuml
skinparam backgroundColor #FFFFFF
skinparam defaultFontName Arial
skinparam defaultFontSize 14
skinparam shadowing false
top to bottom direction
title Tessera — implemented components (principal runtime flows)
component "shell\nwindows / tabs / developer tools" as Shell
component "runtime/api\nHTTP + queue" as API
component "runtime/api/worker\nserial VM ownership" as Worker
component "bridge/ui_bridge\ntypes / native calls / refresh" as Bridge
component "model\nobjects / mounts / bindings" as Model
component "render\nlayout / paint / hit / raster" as Render
component "Aster\nfrontend / compiler / core" as Aster
component "runtime/io_tasks\nplain-data completion" as IO
database "NamespaceState\nowned document + frame values" as State
Shell --> API : serialized input / Console
API --> Worker : bounded BuildRequest queue
Worker --> Aster : compile / execute
Worker --> Bridge : install / refresh / dispatch
Bridge <--> Model : managed graph + dependencies
Bridge --> Render : derive frame
Worker --> State : validate epoch + publish
State --> Shell : immutable snapshot
Shell --> Render : compose chrome + rasterize
Worker <--> IO : request / completion
note bottom of Model
Directory groups are not separate crates.
Imports still cross groups; this is not
an exhaustive or acyclic import graph.
end note
@enduml
+29
View File
@@ -0,0 +1,29 @@
@startuml
skinparam backgroundColor #FFFFFF
skinparam defaultFontName Arial
skinparam defaultFontSize 14
skinparam shadowing false
title Tessera — local process and thread deployment
node "User computer" {
artifact "Local agent client" as Agent
node "Tessera desktop process" {
node "GUI main thread\nwinit + softbuffer" as GUI
node "tessera-agent-api\nHTTP receiver" as API
node "tessera-endor-worker\nReplSession / Candidate / Aster heap" as Worker
node "Input sender thread" as Input
node "Lazy bounded I/O pool" as IO
database "Arc<RwLock<NamespaceState>>\nno VM handles in published frames" as State
API --> Worker : bounded queue (8 pending)
Worker --> State : commit document
State --> GUI : native snapshots
GUI --> Input : Input values
Input --> API : loopback HTTP
Worker <--> IO : mailbox / cancellation
}
node "System curl subprocess" as Curl
artifact "OS window + pixel buffer" as Window
Agent --> API : 127.0.0.1:4737
GUI --> Window
IO --> Curl : fetchText transport
}
@enduml
+89
View File
@@ -0,0 +1,89 @@
@startuml
skinparam backgroundColor #FFFFFF
skinparam defaultFontName Arial
skinparam defaultFontSize 14
skinparam shadowing false
title Tessera — managed identity versus published values
hide empty methods
class ReplSession {
id: u64
faulted: bool
}
class Candidate {
vm: Vm
roots: ObjectRef[]
globals: ObjectRef
}
class UiBridge
class Presentation {
desktop: ObjectRef
active: ObjectRef
render_cache: RenderCache
}
class ManagedWindow {
id: u64
pages: ObjectRef[]
closed: bool
}
class Block {
state: ObjectRef
page: bool
}
class Cell
class Data {
kind: Kind
children: Child[]
bindings: ObjectRef[]
}
class Child {
slot: u64
block: ObjectRef
}
class Mount {
block: ObjectRef
page: WeakObjectRef
parent: WeakObjectRef
geometry: MountGeometry
}
class MountTable {
active: Map<u64, WeakObjectRef>
}
class UiNode {
block_id: String
slots: u64[]
kind: UiKind
}
class Frame {
session: u64
layout_version: u64
commands: RenderCommand[]
tabs: Tab[]
}
class RenderDocument {
source: String
ui_root: Arc<UiNode>
windows: Map
}
ReplSession *-- Candidate
ReplSession *-- UiBridge
UiBridge *-- Presentation : shared Session
ManagedWindow --> Block : open Pages retained
Block --> Cell : state
Cell --> Data : ordinary content
Cell --> Block : shared assignment forwarding
Data *-- Child
Child --> Block
Mount --> Block : strong
Mount ..> Mount : weak reverse/sibling links
Presentation *-- MountTable
MountTable ..> Mount : weak index
Presentation ..> UiNode : cached derivation
RenderDocument o-- UiNode
RenderDocument *-- Frame
RenderDocument *-- RenderDocument : secondary windows
note bottom of Block
Page is a managed Block kind/nominal type.
This omits type tables, service dictionaries,
captured roots and many fields: not a full GC graph.
end note
@enduml
+29
View File
@@ -0,0 +1,29 @@
@startuml
skinparam backgroundColor #FFFFFF
skinparam defaultFontName Arial
skinparam defaultFontSize 14
skinparam shadowing false
title Native input — one VM and one event dispatcher
actor User
participant TesseraApp as GUI
participant "events::Client" as Client
participant "API / worker" as Worker
participant ReplSession as VM
participant event_dispatch as Dispatch
participant "refresh / publication" as Refresh
User -> GUI : pointer press / release
GUI -> GUI : published geometry; matching target
GUI -> Client : Input(window, session, layout_version, mount)
Client -> Worker : POST /events
Worker -> Worker : reject stale source/destination identities
Worker -> VM : dispatch_incremental
VM -> Dispatch : target Block + optional Mount
Dispatch -> Dispatch : capture -> target -> bubble
Dispatch -> VM : budgeted handler / onEvent / onClick
VM -> Refresh : update related presentations
Refresh --> GUI : Frame / DocumentUpdated
note over Dispatch
Without a Mount, dispatch visits only the target.
With a Mount, traversal follows that occurrence.
end note
@enduml
+39
View File
@@ -0,0 +1,39 @@
@startuml
skinparam backgroundColor #FFFFFF
skinparam defaultFontName Arial
skinparam defaultFontSize 14
skinparam shadowing false
title Complete PUT — isolated execution and epoch-checked publication
actor Client
participant "api.rs" as API
queue "BuildRequest queue" as Queue
participant "api/worker.rs" as Worker
participant "Aster candidate VM" as VM
participant UiBridge
participant NamespaceState as State
participant TesseraApp as GUI
Client -> API : PUT /v1/namespaces/app.main/code
API -> API : validate / assign accepted submission
API -> Queue : bounded enqueue
Queue -> Worker : receive request
Worker -> VM : parse / compile / execute in fresh candidate
VM -> UiBridge : allocate objects / Pages
loop incremental refresh slices
Worker -> UiBridge : bindings / layout / paint / mounts
UiBridge --> Worker : Pending or native document
end
Worker -> State : verify submission epoch
alt valid and successful
Worker -> State : commit document + window commands
Worker -> Worker : candidate becomes active ReplSession
Worker --> GUI : DocumentUpdated
Worker --> Client : response + committed revision
else superseded / failed
Worker -> Worker : discard candidate; keep valid live owner
Worker --> Client : 409 / 422 / 500 as applicable
end
note over API,Worker
Worker retains the observed request and responds.
GUI does not execute the HTTP request or VM.
end note
@enduml
Binary file not shown.

After

Width:  |  Height:  |  Size: 317 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 264 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 469 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 251 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 376 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 227 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 226 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 169 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.4 KiB

+20
View File
@@ -0,0 +1,20 @@
@startuml
skinparam backgroundColor #FFFFFF
skinparam defaultFontName Arial
skinparam defaultFontSize 14
skinparam shadowing false
title Candidate and active runtime (conceptual states)
[*] --> Candidate : accepted complete PUT
Candidate --> Refreshing : compilation / execution succeeds
Candidate --> Rejected : compilation / execution error
Refreshing --> Refreshing : yield / continue refresh
Refreshing --> Active : valid document + matching submission
Refreshing --> Superseded : newer write / delete
Active --> Active : Console / input / task completion
Active --> Faulted : callback or refresh fault
Active --> Retired : replace / reset / delete / shutdown
Faulted --> Retired : cleanup or replace
Rejected --> [*]
Superseded --> [*]
Retired --> [*]
@enduml
+25
View File
@@ -0,0 +1,25 @@
@startuml
skinparam backgroundColor #FFFFFF
skinparam defaultFontName Arial
skinparam defaultFontSize 14
skinparam shadowing false
title Managed Task — lifecycle states from tasks.rs
[*] --> Pending
Pending --> Running : due / delivery eligible
Pending --> Completed : provider done; no callback
Pending --> Failed : provider error
Pending --> Cancelled : owner invalid / key replacement / cancel
Running --> Completed : successful delivery
Running --> Failed : transport or execution error
Running --> Cancelled : cancel / lifecycle cleanup
Completed --> [*]
Failed --> [*]
Cancelled --> [*]
note right of Pending
Provider I/O may already run while the Task
is Pending. Running does not necessarily
mean the I/O starts at that instant.
Scheduler index is weak; callbacks/scopes
are traced managed edges.
end note
@enduml
+20
View File
@@ -0,0 +1,20 @@
@startuml
skinparam backgroundColor #FFFFFF
skinparam defaultFontName Arial
skinparam defaultFontSize 14
skinparam shadowing false
title Page visibility and reachability (conceptual states)
[*] --> Open : Page registered
Open --> Selected : activate / click tab
Selected --> Open : select another Page
Open --> Closed : close / release registry edge
Selected --> Closed : close active Page
Closed --> Open : still referenced; reopen
Closed --> Collected : no strong managed path; GC
Collected --> [*]
note right of Closed
Closing a tab is not destroying an object.
Cross-window moves update managed registries
only after session/layout/drop validation.
end note
@enduml
+84
View File
@@ -0,0 +1,84 @@
# Endor Campus 多页面示例
源码:[campus-lms.endor](../examples/campus-lms.endor)。这是参考 Instructure
Canvas LMS 信息结构的本地学习环境示例,使用虚构学生、课程与作业数据。
## 运行与页面
在 Tessera 按 F12 打开 Console,点击 `>` 输入位置,粘贴完整源码并按 Enter。
建议在新会话中运行一次;重复执行会创建另一组页面。
源码建立七个真正的 managed Page:仪表盘、程序设计、高等数学、学术英语、
作业中心、成绩总览和实验提交详情。每页进入应用现有的标签栏,可以切换、
关闭,再通过课程卡片或导航重新打开。没有额外模拟一套网页标签栏。
酒红侧栏提供全局导航,仪表盘用三种课程色区分课程,课程主页展示各自的
介绍和学习单元;作业中心汇总课程作业,成绩总览提供课程成绩与实验反馈。
侧栏的「课程」入口回到程序设计示例课,其余课程从仪表盘卡片或成绩行进入。
## 对象与交互
三门课程各有一个 `CampusCourse` 对象。程序设计的 `CampusWork` 对象被
仪表盘、作业中心、成绩页和提交详情共同引用,界面通过 `ui.textOf` 绑定字段。
- 「模拟提交实验」更新提交内容和状态;作业中心同步显示等待评分。
- 「应用示例评分」写入预设的 92 / 100 与反馈,并把课程成绩改为 88.5%、
学习进度改为 4 / 6;课程主页、成绩总览和仪表盘同步更新。
- 「恢复演示数据」恢复未提交、无分数、课程 86.0% 和 3 / 6 的进度。
页面导航通过接收 `Event` 的 `CampusTarget.open` 方法调用零参数 `Page.open()`。
不能把有可选 Window 参数的 `Page.open` 直接当作点击回调,否则 Event 会被
误当作 Window。重新打开页面会保留共享对象中的状态。
## 原生验证
通过原生 Console 输入源码并执行,实际点击检查了:
- 三门课程内容各不相同,卡片和全局导航能切换真实 Page。
- 提交后作业中心显示「已提交 · 等待评分」。
- 评分后详情显示 92 / 100 与反馈,课程主页显示 88.5% 和 4 / 6,
成绩总览与仪表盘也显示 88.5%。
- 关闭高等数学标签,再从仪表盘卡片重新打开成功。
- 恢复数据后,详情和成绩总览恢复未提交、无分数和课程 86.0%。
截图保存在本次会话的 `/private/tmp/endor-campus-demo/`,包括仪表盘、
评分详情、成绩总览与恢复后的仪表盘。首次验证时没有成功的连续录屏;
后续建模视频见下节。
本阶段只增加 Endor 源码与说明,没有修改 Rust 渲染器。验证采用原生运行与
手动点击,以及 `git diff --check`;未运行 cargo test 或自动 smoke 脚本。
## 建模过程视频(2026-10-25)
[观看 MP4](media/endor-campus-modeling.mp4) ·
[中文字幕 SRT](media/endor-campus-modeling.zh.srt)
视频约 72 秒、1920 × 1200,无声,附带中文软字幕与章节。播放器未自动显示
字幕时可以开启中文字幕,或者加载同目录 SRT。
在新 Console 会话中分段执行同一份示例源码:先定义课程和作业模型,再定义
界面组件,创建共享对象图与七个 Page,逐步渲染仪表盘、课程、作业中心、
成绩总览,最后绑定提交与评分事件。末尾实际点击提交和预设评分,展示
作业状态、总评与学习进度在各页之间同步。代码分段粘贴,不是逐字输入。
系统屏幕采集设备虽然可被 FFmpeg 识别,但没有收到画面;因此使用原生
应用控制接口在操作期间连续抓取 Tessera 窗口,再由已有 FFmpeg 编码为 H.264。
共采集 299 帧,采样帧率随操作变化,剪去各采集段之间的等待;输出封装为
15 fps,重复帧不代表原始采样达到了 15 fps。没有使用静态成品截图重演操作。
应用重置后,在首次渲染前保留了上一次页面的显示快照,首次渲染后由新会话
的页面替换。视频包含该过程,并非从应用启动开始的系统录屏。
检查了视频参数、全片解码和抽帧画面;全片解码无错误。录制阶段没有修改
示例程序或 Rust 渲染器。
## 范围
这是多页面交互示例,没有 Canvas 登录、服务器、持久化、真实文件上传或
通用成绩计算。提交文件名为示例字符串,评分和总评是明确的预设状态,
不是根据公式计算的结果。页面使用双向 ScrollBlock;未完成所有小窗口尺寸的
布局验证。它不替代完整的 LMS 产品。
参考的是 Canvas 的课程卡片、全局导航、作业状态和成绩反馈结构:
[Dashboard 官方指南](https://community.instructure.com/en/kb/articles/664620-how-do-i-use-the-dashboard)、
[Grades 官方指南](https://community.instructure.com/en/kb/articles/661305-how-do-i-view-my-grades-in-a-current-course)。
没有登录或查看需要账户的学校数据。
+116
View File
@@ -0,0 +1,116 @@
# Tessera 中文源码注释与阅读索引
本轮只为 Tessera 主项目补充注释,Aster 子模块固定版本与内容均沿用主线。注释按模块职责、类型/函数入口、关键字段、执行阶段和失败/取消路径组织;没有改变接口、算法、常量或资源预算。
## 建议阅读顺序
1. [main](../src/main.rs):创建原生循环、共享文档与执行 worker。
2. [原生应用](../src/shell/app.rs):理解窗口生命周期、可用视口、输入边界和最终 present。
3. [API worker](../src/runtime/api/worker.rs) 与 [运行时](../src/runtime/endor_host.rs):理解候选/活跃 VM、输入串行化、分片刷新和发布。
4. [桥接层](../src/bridge/ui_bridge.rs)、[Block](../src/model/block.rs) 与 [Mount](../src/model/mount.rs):区分共享业务对象、每次出现和展示事务。
5. [快照](../src/model/snapshot.rs)、[源布局](../src/render/source_layout.rs) 和 [源绘制](../src/render/source_paint.rs):理解依赖缓存、只读执行及挂起工作。
6. [二维视口](../src/render/viewport.rs)、[3D](../src/render/scene3d.rs) 和 [面板映射](../src/render/scene3d/panel.rs):理解布局/世界/视图的边界。
7. [任务](../src/runtime/tasks.rs)、[provider](../src/runtime/io_tasks.rs) 和 [事件传播](../src/runtime/event_dispatch.rs):理解异步交付资格与生命周期。
## 阅读时需要保留的边界
- Block/Data 属于共享业务组成;Mount 属于一个展示位置,不能把一次出现的尺寸写回共享对象来代替排版。
- ObjectRef/WeakObjectRef 的含义由真实托管拥有关系决定;派生缓存中的身份索引不能成为隐藏根。
- 窗口线程消费完整发布值;VM、源回调和托管堆操作只在执行 worker 内推进。
- submission 防止旧请求覆盖新输入;session 防止跨 VM 资源误用;layout_version 防止旧几何上的离散操作误触。
- Pending Work 同时拥有续体与上下文;取消必须关闭原 VM 的只读执行并恢复未提交 Mount,不能只丢弃 Rust 值。
- 场景世界不是无限尺寸的排版盒子;有限视口参加布局,摄像机负责投影,命中沿相同链逆变换。
- 现有 CPU 绘制、缓存范围与输入队列限制仍按当前代码执行;说明性注释不代表性能优化已实现。
## Rust 逐文件说明
每行说明该文件本次新增注释解释的职责和目的。生产函数/方法均增加中文入口说明;复杂状态机另外补充阶段和不变量说明。集成测试文件增加整体阅读与检查点说明,测试程序文本和源码范围断言保持原样。
| 文件 | 注释解释的职责与目的 |
| --- | --- |
| [src/bridge/mod.rs](../src/bridge/mod.rs) | 语言桥接模块入口。集中导出 Endor 类型和宿主实现之间的适配层。 |
| [src/bridge/ui_bridge.rs](../src/bridge/ui_bridge.rs) | Endor 与 Tessera 的展示事务协调层:维护每个窗口的 Page、Mount、布局缓存和发布版本。 |
| [src/bridge/ui_bridge/bootstrap.rs](../src/bridge/ui_bridge/bootstrap.rs) | 安装一次 VM 域需要的宿主类型、对象和方法。类型注册表是源代码调用原生能力的入口。 |
| [src/bridge/ui_bridge/calls.rs](../src/bridge/ui_bridge/calls.rs) | 把 Endor 方法调用分派到对应宿主操作。这里处理构造、树修改、绑定、状态与页面能力。 |
| [src/bridge/ui_bridge/developer_pages.rs](../src/bridge/ui_bridge/developer_pages.rs) | 把内置开发工具和起始页接入托管 Page。工厂在所属 VM 中编译和执行,而不是在窗口线程另建业务状态。 |
| [src/bridge/ui_bridge/page_input.rs](../src/bridge/ui_bridge/page_input.rs) | 把页面、2D 视口和 3D 视口的相机输入转换成托管对象更新。 |
| [src/bridge/ui_bridge/signatures.rs](../src/bridge/ui_bridge/signatures.rs) | 声明宿主方法在 Endor 类型系统中的参数和返回契约。 |
| [src/bridge/ui_bridge/tree.rs](../src/bridge/ui_bridge/tree.rs) | 定义从托管对象提取的不可变视觉树。共享业务对象可以有多次展示,树节点与 Mount 出现的身份不是同一概念。 |
| [src/main.rs](../src/main.rs) | 应用组合入口。先创建原生事件循环和共享发布状态,再启动 API/VM worker,最后把窗口事件交给 TesseraApp。 |
| [src/model/binding.rs](../src/model/binding.rs) | 属性绑定:在只读计算中收集依赖,将结果写回绑定目标。 |
| [src/model/block.rs](../src/model/block.rs) | Block 的共享赋值、底层 Data 与视觉属性实现。Block 通过 Cell 间接指向 Data,使别名能观察到同一次替换。 |
| [src/model/document.rs](../src/model/document.rs) | 运行时与窗口线程之间的发布数据契约。NamespaceState 管理提交序号、版本和当前完整文档。 |
| [src/model/mod.rs](../src/model/mod.rs) | 模型层模块入口。包含托管业务对象、每次展示上下文、依赖缓存,以及交给窗口线程的发布值。 |
| [src/model/mount.rs](../src/model/mount.rs) | 每次展示的托管上下文:同一个 Block 出现在两个位置时,有两个独立 Mount。 |
| [src/model/object_list.rs](../src/model/object_list.rs) | 给源协议返回的对象列表提供受控封装。列表内容通过托管引用被追踪,读方法只暴露检查后的条目。 |
| [src/model/presentation.rs](../src/model/presentation.rs) | 一个原生窗口对应一份 Presentation:独立视口、Mount、测量缓存、焦点与依赖记录。 |
| [src/model/protocols.rs](../src/model/protocols.rs) | 安装 Visual、EventTarget、Children 和 Presentable 等能力契约。 |
| [src/model/scene3d.rs](../src/model/scene3d.rs) | 将 Endor 托管场景对象转换成可供渲染线程读取的 3D 数据。 |
| [src/model/snapshot.rs](../src/model/snapshot.rs) | 从可变托管对象图提取不可变 UiNode,并维护反向依赖与父子失效传播。 |
| [src/model/window.rs](../src/model/window.rs) | 托管 Window 的页面所有权、原生命令与关闭生命周期。 |
| [src/render/box_model.rs](../src/render/box_model.rs) | 有限布局盒子的尺寸策略。区分 auto、固定值和 fill,并处理 min/max 对约束与最终尺寸的限制。 |
| [src/render/display_list.rs](../src/render/display_list.rs) | 面向设备像素的绘制指令集合。它承载矩形、文字、裁剪与 3D 表面等原语,不直接操作 VM。 |
| [src/render/geometry.rs](../src/render/geometry.rs) | 共享的二维点和矩形值。命中判断在调用方完成坐标系转换后使用,矩形本身不隐式处理相机。 |
| [src/render/layout.rs](../src/render/layout.rs) | 原生布局求解器:自底向上测量期望尺寸,再自顶向下分配位置和实际尺寸。 |
| [src/render/mod.rs](../src/render/mod.rs) | 渲染模块入口。排版、源视觉协议、相机投影和最终光栅化各自独立,通过不可变帧衔接。 |
| [src/render/native_visual.rs](../src/render/native_visual.rs) | 让原生组件也通过 Endor 的 measure/arrange/paint 协议被调用。 |
| [src/render/page.rs](../src/render/page.rs) | 旧 Page.mode 的兼容空间策略,以及页面级的正逆相机变换。 |
| [src/render/scene.rs](../src/render/scene.rs) | 合成整个原生窗口的显示列表:页面画面、宿主侧栏和开发工具绘制。 |
| [src/render/scene3d.rs](../src/render/scene3d.rs) | 有界 CPU 3D 渲染器。使用相同摄像机与世界变换进行视锥裁剪、深度测试、纹理采样和射线拾取。 |
| [src/render/scene3d/math.rs](../src/render/scene3d/math.rs) | 3D 数学基础:向量、仿射矩阵、摄像机基向量、投影射线和三角形相交。 |
| [src/render/scene3d/panel.rs](../src/render/scene3d/panel.rs) | 连接 3D 平面与普通 UI 的坐标和绘制桥梁。 |
| [src/render/scene3d/spatial.rs](../src/render/scene3d/spatial.rs) | 不可变世界空间 BVH。用网格变换后的包围盒快速筛选视锥与射线候选。 |
| [src/render/scroll.rs](../src/render/scroll.rs) | 逐 Mount 的滚动状态、裁剪和输入目标选择。 |
| [src/render/software_renderer.rs](../src/render/software_renderer.rs) | 把 DisplayList 写入 CPU 像素缓冲。裁剪栈限定矩形、文字和 3D 表面的实际写入区域。 |
| [src/render/source_hit.rs](../src/render/source_hit.rs) | 通过真正的源/原生 hitTest 协议确定指针目标。 |
| [src/render/source_layout.rs](../src/render/source_layout.rs) | 源 measure/arrange 协议的分片布局驱动器。自底向上的测量与自顶向下的安排共享一个只读 VM 调用域。 |
| [src/render/source_paint.rs](../src/render/source_paint.rs) | 执行源 paint 覆盖并解码受检查的 PaintCommand。 |
| [src/render/text.rs](../src/render/text.rs) | 统一字体发现、文字整形、测量与抗锯齿字形绘制。 |
| [src/render/viewport.rs](../src/render/viewport.rs) | 独立 2D 相机与可逆投影。视口尺寸属于布局;平移、缩放属于视图,不改变世界对象的逻辑位置。 |
| [src/render/viewport/spatial.rs](../src/render/viewport/spatial.rs) | 有界屏幕网格,用来减少普通二维命中和相机目标查询的候选。 |
| [src/runtime/api.rs](../src/runtime/api.rs) | 本机 HTTP API 入口:路由请求、限制输入大小、观察活动,并将执行工作送入串行 worker。 |
| [src/runtime/api/guide.rs](../src/runtime/api/guide.rs) | 从当前命名空间生成 /agent 使用指南。返回的示例、地址和版本描述来自运行时上下文;这里生成文档,不执行用户源码。 |
| [src/runtime/api/tests.rs](../src/runtime/api/tests.rs) | API 集成回归。通过实际本地 HTTP 请求检查队列、候选替换、状态码、版本和完整文档发布。 |
| [src/runtime/api/worker.rs](../src/runtime/api/worker.rs) | 唯一串行执行 VM 的 API worker。保留活跃运行时,另建 PUT 候选,并在候选完整成功后切换发布。 |
| [src/runtime/endor_host.rs](../src/runtime/endor_host.rs) | 把 Aster 编译/执行与 Tessera 展示生命周期连接起来。Candidate 拥有 VM 与宿主根,ReplSession 保留实际运行中的全局环境。 |
| [src/runtime/endor_host/tests.rs](../src/runtime/endor_host/tests.rs) | 运行时集成回归与示例验收。测试经真实 Aster 前端、编译器、VM 和展示协议执行,不是手工伪造布局结果。 |
| [src/runtime/endor_script.rs](../src/runtime/endor_script.rs) | 区分完整 Module 与顶层 Script,并保留输入源码位置。 |
| [src/runtime/event_dispatch.rs](../src/runtime/event_dispatch.rs) | 托管事件与订阅的传播实现。Connection 持有回调引用,Event 保存目标、阶段与停止传播状态。 |
| [src/runtime/events.rs](../src/runtime/events.rs) | 原生窗口输入到执行 worker 的纯数据传输。Input 只含窗口/会话/版本/Mount 身份及有限坐标。 |
| [src/runtime/io_tasks.rs](../src/runtime/io_tasks.rs) | 后台文件/网络 provider。线程池只携带纯数据、取消控制与弱 Task 身份,不持有 VM。 |
| [src/runtime/mod.rs](../src/runtime/mod.rs) | 运行时模块入口。VM 生命周期、API、源程序组织、事件与异步任务在这里组合。 |
| [src/runtime/tasks.rs](../src/runtime/tasks.rs) | owner/key 管理的异步任务与协作式源函数调度。弱索引用于查找,回调、等待对象和协程帧是托管图中的真实边。 |
| [src/runtime/vm_sequence.rs](../src/runtime/vm_sequence.rs) | 构造共享 VM 调用序列与同帧循环驱动的字节码。 |
| [src/shell/activity.rs](../src/shell/activity.rs) | 有界 HTTP 活动记录。保存请求/响应的可显示预览供 Network 工具读取,不负责执行请求。 |
| [src/shell/app.rs](../src/shell/app.rs) | winit 原生应用生命周期和窗口事件入口。这里创建窗口、发布逻辑视口、转发输入,并把不可变文档画到原生表面。 |
| [src/shell/clipboard.rs](../src/shell/clipboard.rs) | 把 UTF-8 文本读写适配到当前平台的系统剪贴板命令。 |
| [src/shell/developer_tools.rs](../src/shell/developer_tools.rs) | Console/Sources/Network/Settings 的宿主交互协调与绘制状态。 |
| [src/shell/developer_tools/console.rs](../src/shell/developer_tools/console.rs) | 绘制 Console 输入、结果历史和对应命中区域。 |
| [src/shell/developer_tools/network.rs](../src/shell/developer_tools/network.rs) | 绘制已观察到的 HTTP 活动、请求列表与详情。 |
| [src/shell/developer_tools/painter.rs](../src/shell/developer_tools/painter.rs) | 开发工具画面的绘制辅助:文字行、按钮、分隔线和滚动条。 |
| [src/shell/developer_tools/selection.rs](../src/shell/developer_tools/selection.rs) | 多行文本选择和光标导航。选择端点映射到合法字符边界,避免把 UTF-8 字节中间当成一个字符。 |
| [src/shell/developer_tools/settings.rs](../src/shell/developer_tools/settings.rs) | 绘制宿主设置页面和主题选择区域。 |
| [src/shell/developer_tools/sources.rs](../src/shell/developer_tools/sources.rs) | 绘制 AST、当前源码快照和云文件视图。 |
| [src/shell/mod.rs](../src/shell/mod.rs) | 原生宿主模块入口。窗口、管理控件、系统适配和开发工具状态与用户业务界面分开维护。 |
| [src/shell/native_chrome.rs](../src/shell/native_chrome.rs) | macOS 原生标题栏适配。定位系统窗口按钮并沿用用户的标题栏双击设置。 |
| [src/shell/sidebar.rs](../src/shell/sidebar.rs) | 宿主管理工具和页面列表的唯一侧栏。展开时占据页面左侧空间,折叠后只保留展开按钮区域。 |
| [src/shell/sources.rs](../src/shell/sources.rs) | 云文件浏览的 provider 抽象与工作区状态。默认 provider 未连接,不假装已有外部文件。 |
| [src/shell/system_ui/interaction.rs](../src/shell/system_ui/interaction.rs) | 即时绘制控件的跨帧交互状态:稳定 WidgetId、悬停、按下捕获、键盘焦点和释放激活。 |
| [src/shell/system_ui/mod.rs](../src/shell/system_ui/mod.rs) | 宿主管理控件的共享组件入口。主题、绘制原语和跨帧交互状态分离,用户 Endor 页面不依赖这里的控件树。 |
| [src/shell/system_ui/theme.rs](../src/shell/system_ui/theme.rs) | 宿主控件的颜色与状态调色。根据背景、强调色和交互状态生成可读颜色,不改变业务状态。 |
| [src/shell/system_ui/widgets.rs](../src/shell/system_ui/widgets.rs) | 用统一主题绘制宿主管理控件,并同步注册交互目标。 |
| [src/shell/tabs.rs](../src/shell/tabs.rs) | 发布页面标签的数据结构。保留稳定页面身份、标题、选中状态和开发工具类别;页面的托管所有权由模型层管理。 |
## 其他文件
| 文件 | 本次改动及目的 |
| --- | --- |
| [src/bridge/ui_bridge/start_page.endor](../src/bridge/ui_bridge/start_page.endor) | 解释卡片源测量/背景、页面工厂、纵横布局与滚动组合、共享计数和场景位置,便于从真实 Endor 页面理解宿主边界。 |
| [scripts/build-macos-app.sh](../scripts/build-macos-app.sh) | 说明本地构建前提、锁定依赖、临时文件替换和 bundle 元数据,帮助理解每个打包步骤。 |
| [scripts/render-uml.mjs](../scripts/render-uml.mjs) | 说明独立文档依赖、DOM/Canvas 适配、错误图检查与 SVG/PNG 产物生成,避免混淆运行依赖与文档工具。 |
| [src/README.md](../src/README.md) | 增加本注释索引入口,便于从源码目录开始阅读。 |
| [docs/code-comments.md](code-comments.md) | 本逐文件说明与阅读顺序,覆盖本轮提交的文件及共同边界。 |
## 核对方式
检查差异仅新增独立注释行和注释相关空白,并与主线去除注释后的文本对比;同时运行格式、完整 GUI 回归、Clippy 和包含私有项的 rustdoc。脚本使用语法检查,不执行文档渲染或应用打包。具体检查结果在 PR 中记录。
Binary file not shown.
+83
View File
@@ -0,0 +1,83 @@
1
00:00:00,000 --> 00:00:02,658
01 定义课程和作业对象
2
00:00:02,658 --> 00:00:07,300
02 执行对象定义并建立界面组件
3
00:00:07,300 --> 00:00:11,921
03 实例化课程、共享作业和七个页面
4
00:00:11,921 --> 00:00:14,209
04 执行共享对象图
5
00:00:14,209 --> 00:00:18,392
05 构建仪表盘并渲染
6
00:00:18,392 --> 00:00:22,510
06 仪表盘渲染结果
7
00:00:22,510 --> 00:00:27,198
07 创建三个课程主页
8
00:00:27,198 --> 00:00:30,301
08 渲染课程页面
9
00:00:30,301 --> 00:00:35,238
09 创建作业中心
10
00:00:35,238 --> 00:00:37,881
10 作业中心渲染结果
11
00:00:37,881 --> 00:00:42,805
11 创建成绩总览
12
00:00:42,805 --> 00:00:45,432
12 成绩总览渲染结果
13
00:00:45,432 --> 00:00:50,363
13 绑定提交、评分与恢复事件
14
00:00:50,363 --> 00:00:53,514
14 全部页面完成
15
00:00:53,514 --> 00:00:56,070
15 打开实验并模拟提交
16
00:00:56,070 --> 00:00:57,930
16 提交后切到作业中心查看共享状态
17
00:00:57,930 --> 00:01:00,168
17 作业中心显示已提交
18
00:01:00,168 --> 00:01:02,952
18 应用示例评分
19
00:01:02,952 --> 00:01:06,054
19 成绩总览同步分数与反馈
20
00:01:06,054 --> 00:01:09,211
20 仪表盘同步课程总评
21
00:01:09,211 --> 00:01:12,278
21 课程主页同步进度与成绩
+59
View File
@@ -0,0 +1,59 @@
# Endorphin 页面空间与窗口边界
> 下文的 Page.mode 是前一阶段的兼容接口。当前默认页已迁移到普通 Page、Row/Column、滚动容器和独立 Scene2D / CanvasViewport / Camera2D。新代码请使用 [统一场景架构](scene-architecture.md),不要再把横纵排版或相机作为 Page 的固有模式。
本次按参考图的“左侧栏展开/收起”两种状态调整原生宿主。窗口保留系统关闭、最小化和缩放按钮;宿主管理入口集中在左侧栏。收起后只保留展开按钮及系统三键,页面从窗口左上角铺满,不再保留顶部标签条、左侧空轨或内容卡片边距。
页面内容、卡片、文字和操作按钮由 Endor 源码渲染。默认 [开始页](../src/bridge/ui_bridge/start_page.endor) 是真实的画布 Page,其操作创建另外三种 Page;不会把示例的静态截图当作可操作界面。
## 四种页面模式
| `page.mode` | 布局 | 浏览方式 |
| --- | --- | --- |
| `window`(默认) | 根 Page 等于可用区域,子组件按纵向流组织 | 应用自行安排内部布局或 ScrollBlock |
| `vertical` | 宽度跟随可用区域,高度至少一屏并随子组件增长 | 纵向滚动,偏移限制到内容范围 |
| `horizontal` | 高度跟随可用区域,宽度至少一屏并随子组件增长 | 横向滚动;普通纵向滚轮也可推进横向页面 |
| `canvas` | 直接子组件使用各自的 `x`、`y` 世界坐标 | 双向平移、缩放,视角不限制到内容边界 |
侧栏展开占用 256 个逻辑像素;收起归还全部宽度。`ui.viewport()`、`window.viewport()` 和 GET code 的 viewport headers 均报告实际可用页面区域。窗口变更重排同一个运行时,不重放源码。窗口模式保证根 Page 填满,但不会强迫每个子组件拉伸。
```endor
page = Page()
page.mode = "canvas"
page.title = "我的画布"
card = Button("一个真正的 Endor 组件")
card.x = -120
card.y = 90
page.render(card)
page.panX = -200
page.panY = 0
page.zoom = 1
```
`page.render(root)` 替换内容;`page.append(child)` 继续添加。直接画布子组件的 `x/y` 决定位置,内部 Row/Column 仍使用原来的流式布局;纵向、横向和窗口页面不使用子组件的 `x/y` 排列。共享 Block 可以有多个 Mount,不会为画布复制业务对象。
## 交互与坐标
- 滚轮或触控板平移;嵌套 ScrollBlock 优先处理其可滚动方向。
- 画布支持空格+左键拖动、鼠标中键拖动;已有按钮键盘焦点保留 Space 激活。
- 画布支持捏合、Cmd/Ctrl+滚轮缩放,以指针位置为锚点。
- Cmd/Ctrl+B 展开/收起侧栏;侧栏提供新建、切换和关闭页面及四个开发工具入口。
- Cmd/Ctrl+T 新建,Cmd/Ctrl+W 关闭,Ctrl+Tab / Ctrl+Shift+Tab 切换页面。
`panX/panY` 是可视区域左上角的世界坐标,`zoom` 为 0.1–4。变换是 `screen = (world - pan) * zoom`;绘制使用正变换,原生点击/滚动使用逆变换。VM 中 Mount 始终使用世界坐标,worker 根据同一视角重新检查可见性。Page 自己保存视角,切换后仍保留;有限页面在内容缩短或窗口变大时限制偏移。
画布没有内容边界裁剪,但保留现有运行预算:坐标为有限数且绝对值不超过 1,000,000,维度、对象数和绘制命令数仍有上限。“无限”指可以向内容以外导航,不代表无限内存或数值范围。
原生相机事件 `page-pan/page-zoom` 经过真实 HTTP worker,再由所属 VM 更新 Page;它们使用 `mount=0` 和当前 window/session/layout_version。平移 delta 使用可视区域像素;缩放 delta 为 `[factor,0]`,point 是可视区域内的锚点。普通点击与嵌套滚动的 point 使用世界坐标。过期事件返回 409;不适用于当前模式或参数非法的相机事件在执行前拒绝。
## 实现位置与验证边界
- [page.rs](../src/render/page.rs):模式约束、视角、正逆坐标变换和有限页面偏移限制。
- [sidebar.rs](../src/shell/sidebar.rs):唯一宿主管理栏及折叠后点击遮挡范围。
- [page_input.rs](../src/bridge/ui_bridge/page_input.rs):串行 VM 内的视角变更。
- [API 回归](../src/runtime/api/tests.rs):真实 HTTP 平移、指针锚定缩放、负世界坐标点击、过期/非法事件。
- [宿主回归](../src/runtime/endor_host/tests.rs):四种模式、实时内容增长、共享对象坐标、视角恢复和默认页真实按钮。
本地格式、153 项测试和 all-target Clippy 均通过;release app 已构建并实际启动。运行中平移与缩放事件返回 200,并读回 Page.panX=80、Page.zoom=2,随后恢复初始视角。最初 HTTP worker 漏接相机事件导致 400,现由完整链路回归覆盖。
macOS 当前未授予本次工具模拟输入和窗口截图权限。模拟滚轮未生效,无法据此声称真实鼠标/触控板、捏合或窗口外观验收通过。侧栏指针拖放、跨窗口拖放尚未迁移;原有 `moveTab/moveToWindow/detachToWindow` 与版本校验的 API 保留。没有修改 Aster 或引入新的 GUI/语言依赖。
+63
View File
@@ -0,0 +1,63 @@
# 场景交互性能研究
## 结论
性能问题有可验证的解决路径,但单改 Aster 字典不能让当前世界 UI 达到稳定 60 FPS。本 PR 交付可重复基准和研究记录;去除字符串键比较临时分配的改动仍在独立 Aster 分支,未随本 PR 集成;面板纹理缓存实验因当前示例收益不足而撤回。没有实现 GPU 后端或宣称完成性能目标。
## 方法
在 Apple M4 Pro、macOS 15.6 本机使用 release 构建,固定 1024×800 逻辑视口、1× / 2× 像素比例,分别加载 world-ui 和 scene3d 示例。每组执行 33 次真实 scene-orbit 运行时分发,前 3 次作为预热,统计后 30 次的均值、P50、P95。每次先测分发到文档更新,再测变化后的软件绘制,最后测相同显示列表的缓存绘制。没有运行 Console 编译来代替原生事件。
```sh
cargo test --release --locked scene_interaction_performance -- --ignored --nocapture --test-threads=1
```
这是无窗口的运行时与软件渲染基准,包含回调、快照、布局和运行时收尾,但不包含本地 HTTP、OS 事件排队、窗口呈现或输入到显示延迟。阶段耗时不能简单当作实测 FPS。时间是本机样本,不是跨设备保证;基准默认 ignored,普通回归不以绝对耗时断言通过。
## 对照结果
世界 UI、2× 像素比例,单位 ms:
| 条件 | 更新均值 | 更新 P95 | 变化绘制均值 | 变化绘制 P95 |
| --- | ---: | ---: | ---: | ---: |
| 原始 Aster | 8.456 | 8.843 | 18.704 | 20.742 |
| 借用字符串键比较 | 6.842 | 7.226 | 18.598 | 20.665 |
| 再加面板纹理缓存实验 | 6.823 | 7.053 | 18.410 | 20.482 |
去掉字符串键比较的分配后,本组更新均值减少约 19%,绘制基本不变。面板缓存的绘制收益约 1%,不足以证明值得在本次增加缓存与失效复杂度,因此撤回。
作为对照,普通 scene3d 示例在 2× 下更新约 0.94 ms、变化绘制约 6.15 ms;它的视口尺寸、覆盖像素和 UI 复杂度不同,不能据此把两个示例的全部差值都归给某一层。
## Aster 发现与保留的修改
`EndorDictObject` 用插入有序的数组存储,`dict_position` 逐项调用 `key_equal`。原实现每次比较都会把内联文本或托管 String 转成新的 String;查找名称时会重复分配和复制候选键。
本次只改为借用字符串切片比较。保留线性查找、原 key_equal 分支、对象检查、只读依赖观察、键的插入身份与顺序、写入验证和引用计数流程。新增测试覆盖空文本、普通文本、Unicode、托管 / 内联字符串等价替换、删除和引用释放。
没有把通用字典直接改成 HashMap,也没有绕过 heap.replace_payload 的事务性边验证。前者还需处理托管键相等 / 哈希与顺序语义;后者涉及 GC、失败原子性和只读保护。它们不属于本次已经证明安全的改动。
## 尚未解决的主要成本
1. 世界 UI 的摄像机变化后,当前统计仍为 measured=8、arranged=88;普通 3D 为 measured=0、arranged=14。数据证明相机更新没有彻底绕开排版。
2. 3D 变化帧仍在窗口线程逐像素进行 CPU 绘制。当前世界 UI 的绘制本身已超过 60 Hz 的 16.7 ms 预算,其他 CPU 优化不能消除这个事实。
3. 原生连续输入仍逐项经本地 HTTP 发送,有界队列不等于按显示帧合并;真实排队和呈现延迟需要另外测量。
## 后续实施顺序与条件
1. **相机更新专用路径。** 复用已有 Mount 几何、UI 排版和绘制结果,仅更新视图 / 投影、可见性和命中映射。必须检查源 measure / arrange / paint 的实际读取依赖;源函数若读取相机,应继续正确失效。不能无条件跳过所有布局或绘制。验收:不依赖相机的 UI 在旋转时零测量、零重新排版,依赖相机的源协议回归仍通过。
2. **按帧收集连续输入。** 原生操作直接进入进程内通道,连续手势按捕获会话 / 目标与顺序合并;点击、页面切换和运行时替换保持边界。外部 HTTP API 保留严格版本校验。验收包括缩放锚点、非交换手势顺序、嵌套捕获与过期会话,不能只检查最终数值。
3. **GPU 合成与独立渲染。** 现有不可变网格、变换、相机、深度和 UV 数据可以成为渲染输入;VM 对象留在运行时线程。GPU 应直接向窗口表面呈现,同时合成 2D / 3D 内容,避免每帧 GPU→CPU 回读后再交给 softbuffer。跨线程队列只保留最新可呈现快照;纹理、缓冲与缓存均需资源预算和正确失效。
建议验收目标:固定示例 2× 下相机更新 P95 ≤2 ms、GPU 绘制 P95 ≤8 ms,另外记录真实窗口的帧间隔和输入到呈现延迟。目标尚未达到,也没有用无窗口基准宣称原生 60 FPS。
## 检查说明
Aster 全工作区测试发现 compiler 的 classes 测试中两项解析失败(第三行 expected EOF),以及 core 的 managed_coroutine_hard_budget_accumulates_and_error_releases_frames 指令预算失败。将对象实现恢复为未优化的基线后,这三项失败均能复现,说明不是本次借用字符串比较引入;不把全工作区标为全绿。对象层测试通过,Aster 全工作区 Clippy / 格式通过;GUI 为 186 项通过、1 项默认忽略的基准,GUI Clippy / 格式通过。该基准已经另行在 release 模式实际执行。
本次没有修改用户指向的 builtins.rs 第 176 行(该处是函数对象定义)。实际热路径修改位于 Aster 的 store_builtins.rs。
## PR #6 主线兼容修复
2026-11-12:合入最新 GUI main,保留 main 的 Aster f3e1670,而非旧性能分支 fd247ac。旧引用缺少 GUI 目前使用的精确读取依赖接口,不能为性能实验回退。上文数值是原有实验记录,不代表当前主线已经采用借用键优化。本 PR 的最终差异仅包括本研究记录和默认 ignored 的基准;Aster 优化需单独更新其分支并审阅后再集成。PR 标题中的 WIP 将移除,交付范围为可运行基准,不承诺上述后续性能目标。
本次兼容修复检查:GUI `cargo test --locked` 为 186 passed / 1 ignored;Clippy(全部 target,警告视为错误)、格式和差异空白检查通过。最初沙箱内 9 项 HTTP 测试因不能监听本地端口失败;允许回环网络后全套重跑通过。本次未重跑历史 release 性能采样,也未修改 Aster。
+109
View File
@@ -0,0 +1,109 @@
# UI、场景、视口与摄像机
本次完整实现目标的持续记录。完成布局并不等于完成场景或原生交互验收。
## 边界
- Page 负责页面身份、生命周期和根内容。Row、Column、Overlay 负责有限盒子内的排版。
- Scene2D、Scene3D 管理世界对象。世界不是一个无限宽高的布局盒子。
- CanvasViewport、Viewport3D 是有限的 UI 盒子,可以加入 Row、Column、Overlay,也可以放进世界内的有限 UI 面板。
- Camera2D、透视和正交摄像机是显式对象。视口保存自己的尺寸、裁剪和投影比例;共享场景不隐式共享摄像机。
- 摄像机控制器独立于摄像机数据。移动相机只改变投影、可见性和命中坐标,不应重新排版无关内容。
- 视口覆盖 UI 不随世界移动。世界内 UI 面板拥有有限大小,使用普通布局,再由对应的世界变换呈现。
- 嵌套视口的输入逐级逆变换,尊重裁剪和捕获;同一手势不能同时驱动内外相机。
- 无限导航受数值、可见对象、递归、内存和绘制预算约束;引用环必须在发布部分结果前拒绝。
## 当前实现状态
| 阶段 | 状态 | 证据 / 剩余工作 |
| --- | --- | --- |
| 基线审查 | 完成 | 保留共享 Block / 独立 Mount、源协议和已合并工作区示例 |
| 嵌套布局与盒模型 | 完成 | Row / Column / Overlay、双轴对齐、子项覆盖、外边距、非对称内边距和边框、尺寸策略、裁剪;见下面接口 |
| 独立 2D 场景与视口 | 完成 | 独立场景/摄像机、多视口及嵌套、覆盖 UI、投影/命中、原生输入路由、真实 HTTP 与像素回归;旧 Page.mode 仅保留兼容 |
| 3D 场景、视口和摄像机 | 完成 | 软件深度缓冲、网格/变换/灯光、透视/正交相机、可替换控制器、射线拾取、世界空间 UI 及 2D/3D 嵌套 |
| 可见性与资源防护 | 完成 | 2D 屏幕索引、3D BVH / 视锥剔除、场景缓存、连续原生事件版本更新、字形 LOD 和嵌套资源预算 |
| 原生综合验收 | 可取得检查完成 | release 构建与实际窗口截图,运行实例的按钮 / 旋转 / 缩放事件及过期拒绝均通过;系统不允许模拟鼠标,未冒充硬件验收 |
| 完成交付 | 已提交可评审 PR | [PR #5](https://gitea.entroia.com/Zayden-Jung/endorphin-tessera-gui/pulls/5) 已移除 Draft,Gitea 返回 mergeable=true;等待用户手动合并 |
## 有限盒子的接口
现有 `Row(padding, gap, children...)`、`Column(padding, gap, children...)` 保留,新增 `Overlay(padding, gap, children...)`。Overlay 为构造协议兼容保留 gap 参数,但叠放不使用 gap;子项顺序决定绘制和命中顺序。
- `mainAlign`: `start`、`center`、`end`、`space-between`。Overlay 对应横向对齐,不使用 space-between 分散规则。
- `crossAlign`: `start`、`center`、`end`、`stretch`。Row 对应纵向;Column 对应横向。Overlay 对应纵向。
- `alignSelf`: `auto` 继承所在父容器的 crossAlign,或以上交叉轴选项。属性在对象上,每个 Mount 根据自己的父容器解释。
- `marginTop/Right/Bottom/Left`: 外边距参与父容器的测量、主轴分配和对齐。不折叠外边距,不支持负外边距。
- `paddingTop/Right/Bottom/Left`: 数值覆盖对应边;`auto` 回退到构造参数或容器的 padding 属性。非容器回退为 0。
- `borderTop/Right/Bottom/Left` 和 `borderColor`: 边框占据 border box 内侧,压缩内容空间。原生绘制产生实心直角边框;自定义 paint 可调用基类绘制,也可自行提供完整外观。
- `boxWidth/boxHeight`: `auto`、非负数值或 `fill`。保留 RectBlock / ScrollBlock 原有 width/height 和源子类字段语义,通用盒尺寸使用独立名称。数值表示 border box,不包含外边距。
- `minWidth/minHeight/maxWidth/maxHeight`: 盒尺寸边界,最低值不得超过最高值。父分配小于最低值时,外部有限约束仍然生效。
- 主轴 `fill` 使用零基准分享剩余空间;未显式设置 flex 时权重为 1。最大值饱和后,剩余空间继续分给其他项目。交叉轴 fill 使用父容器提供的有限内容尺寸。没有有限父分配的 fill 报错。
- `stretch` 仅拉伸交叉轴 auto 尺寸,遵守盒尺寸边界;数值固定尺寸保留。显式源 arrange 返回的布局始终优先。
- `overflow`: `visible` 或 `clip`;后者同时裁剪后代绘制和指针命中。需要滚动时使用 ScrollBlock,滚动轴与内层 Row/Column 排版独立。
尺寸、边距和边框必须有限、非负,受现有 1000000 上限限制。根约束、每个 Mount 的偏好尺寸、分配、收敛判定及源协议缓存均保持独立。示例见 [box-layout.endor](../examples/box-layout.endor)。
布局阶段验证:本地 `cargo test --locked` 的 162 项回归全部通过,`cargo clippy --all-targets --locked -- -D warnings`、格式与差异空白检查通过。新增用例执行实际 Endor 脚本,覆盖共享对象在不同父容器中的对齐、实时边距变更、flex 分配、叠放、尺寸边界、文本换行、有限 fill、无界 fill 拒绝、源 arrange 优先、裁剪命中和可运行示例。本阶段尚未重新打包或进行原生指针验收。
## 2D 场景与视口
`Scene2D(children...)` 持有世界内容。直接子项的 x/y 是世界位置;Row/Column/Overlay 仍然只解释自己的有限内容布局。给世界内卡片设置 boxWidth,即可在其内部换行和嵌套排版。
`CanvasViewport(width, height, scene)` 是可参加普通排版的有限盒子,世界范围不参与它的本征尺寸。视口可使用通用盒模型尺寸、边框、内边距和 flex。每个新建视口拥有自己的 `Camera2D()`;显式赋值 `second.camera = first.camera` 才会共享视角。摄像机 x/y 是可视内容左上角的世界位置,zoom 范围 0.01–100;也可以 `Camera2D(x, y, zoom)` 创建。嵌套投影还受合成变换预算限制。
视口的有限内容框裁剪世界绘制和输入,Overlay 中的兄弟 UI 保持固定。场景内可以放另一个 CanvasViewport:布局坐标不变,投影逐层合成,指针逆变换至目标组件坐标。相机改变时复用不变的测量结果。`view.mounts().at(index).fitView()` 使用指定 Mount 的有限尺寸及场景直接子项的有限边界适配摄像机,不把无限世界当作排版边界。
滚轮优先交给命中的可滚动 ScrollView;其余平移交给最内层画布。空格加左键或中键拖动锁定开始时的视口,不因指针跨到另一个视口而切换相机;捏合及 Cmd/Ctrl+滚轮围绕指针缩放。`viewport-pan` / `viewport-zoom` 使用真实 Mount 身份及帧版本,通过 HTTP worker 串行修改所属 VM 的摄像机。非法缩放锚点在进入 VM 前拒绝,过期帧返回 409。
`ScrollView` 是现有 ScrollBlock 的名义子类型别名,滚动轴和其内容 Row/Column 排版独立。默认开始页已使用普通 Page + 独立场景/视口,纵横示例使用 ScrollView 对应的滚动容器组合;不再设置 Page.mode。原有 Page.mode/panX/panY/zoom 暂保留兼容旧脚本,不用于新架构示例。
示例见 [scene-viewports.endor](../examples/scene-viewports.endor)。回归包含两个视口共享同一业务对象、显式共享相机、嵌套变换、真实点击回调、相机修改时测量数为 0、真实 HTTP 链路及软件渲染像素中的缩放/裁剪。它们不能替代原生鼠标和触控板验收。
2D 阶段最终验证:169 项本地回归全部通过,all-target Clippy 拒绝 warnings 通过,编辑器未报告错误。默认页的真实按钮事件也已迁移验证。未将原生窗口验收记为完成。
## 3D 基础接口与当前边界
- `Scene3D(nodes...)` 管理世界对象;`Group3D(nodes...)` 组合变换。`children` 是 ObjectList,可显式替换;共享节点可以出现多次,路径循环会拒绝。
- `Box3D(width,height,depth,color)` 创建网格;`Geometry3D(ObjectList(Vec3(...),...), ObjectList(Triangle3D(a,b,c),...))` 创建不可变顶点/索引缓冲,再用 `Mesh3D(geometry,color)` 实例化。可替换 mesh.geometry;修改原输入 Vec3 不会改写已建立的不可变几何。
- 网格/组有 x/y/z、rotationX/Y/Z(角度)、scaleX/Y/Z;局部缩放、X/Y/Z 旋转、平移依序应用,再继承父组变换。`translate(dx,dy,dz)`、`rotate(dx,dy,dz)` 可在 Endor 中直接调用。
- `DirectionalLight(dx,dy,dz,color,intensity)` 使用传播方向,Scene3D.ambient 为基础照明。当前材质是完全不透明的平面着色。
- `Viewport3D(width,height,scene)` 是普通有限 UI 盒子,可以放入 Row、Column、Overlay 或 Scene2D 中。背景与 3D 内容在独立表面上渲染,再交给现有原生软件合成器;采用实际深度缓冲、六面视锥裁剪,没有用静态图替代三维场景。
- 每个新 Viewport3D 有独立 PerspectiveCamera;可用 `view.camera = OrthographicCamera()` 替换,或显式共享同一个 camera。摄像机字段为 x/y/z、targetX/Y/Z、upX/Y/Z、near/far、透视 fov(角度)、正交 height。宽高比由每次视口投影提供,不写回共享摄像机。`camera.translate(...)` 同时平移位置与观察目标。
- `OrbitController()` 独立于摄像机数据,默认绑定到新视口。左键拖动旋转,中键/空格拖动平移,滚轮/捏合缩放。view.controller 可替换为提供 `update(camera, gesture)` 的 Endor 对象,或设为字符串 `none` 禁用。CameraGesture 提供 kind、dx/dy、factor、width/height、pointX/pointY。透视缩放改变观察距离,正交缩放改变 height。
- `view.mounts().at(index).pick3D(x,y)` 接受投影前页面空间中的指针坐标,返回 RayHit3D 或空值;结果包含实际托管 mesh、世界 point/normal、distance、triangle 和 barycentric。原生指针点击对应视口时,标准 click Event.hit 提供相同结果;点击空白时为空。拾取与绘制共享摄像机和变换,遵守 near/far。
固定 Aster 版本不支持数值算术表达式,不能用 `x = x + dx` 编译控制器。因此示例使用可运行的原生 translate/rotate 操作;自定义控制器可以调用这些方法或直接设置摄像机字段。未修改 Aster 源码或 gitlink。
3D 表面最长边按需降采样至 2048,单表面不超过 4194304 像素;缓存最多 8 个不可变表面、总计 8388608 像素。三角形、顶点、场景节点、灯光、光栅工作和摄像机范围均有检查;超过光栅预算返回错误,不发布截断的半幅结果。降采样保留原始视口宽高比,使绘制与拾取使用相同投影。
示例见 [scene3d.endor](../examples/scene3d.endor)。测试覆盖真正的 Endor 构造/修改、最终渲染像素、深度顺序、透视/正交独立视图、近面裁剪、射线回调、可替换控制器的真实 HTTP 路由以及循环/非法几何拒绝。原生硬件交互尚未验收。
3D 基础阶段检查:176 项本地回归全部通过,all-target Clippy 拒绝 warnings 通过。后续世界空间 UI 与嵌套资源/可见性工作尚未完成,因此整体目标及 PR 仍处于进行中。
## 世界空间 UI 与组合
`Panel3D(worldWidth, worldHeight, content)` 把普通 Endor Block 放进 3D 场景。面板有独立的 uiWidth/uiHeight(默认 512×320,整数 1–2048)和不透明 background;本次 UI 表面不实现透明材质。世界尺寸控制平面几何,UI 尺寸提供有限排版约束,两者互不代替。面板与组/网格一样支持位置、旋转、缩放及 translate/rotate。
内容仍是同一个托管对象树,正常执行 measure/arrange/paint/hitTest;每次出现有自己的 Mount、有限尺寸、滚动状态和纹理。一个组件可以放进多个不同尺寸的面板,不复制其业务状态。3D 摄像机移动不改变 UI 的排版尺寸。UI 绘制指令按面板收集,透视裁剪时保留 UV,并按深度进行透视校正插值;普通网格会正确遮挡面板。
指针先沿视口摄像机发射射线,再沿可见面板的逆世界变换映射到 UI 像素,然后继续通过内部 CanvasViewport 的逆变换。被其他网格挡住的 UI 无法收到指针命中。拖动捕获使用平面的连续逆投影,因此指针移出面板后不会把同一手势交给另一个摄像机。Mount.toView(x,y) 将组件本地坐标转到页面视图坐标;toLocal(x,y) 执行反向转换,无法命中可见面板时返回空值。pick3D 另提供实际 node/mesh 和实例编号。
面板 UI 可以继续嵌入 CanvasViewport 或 Viewport3D,后者也可以再包含 Panel3D;普通 Overlay 的兄弟 UI 仍固定在其 UI 空间。引用环在派生布局前拒绝;世界 UI 最多嵌套 8 层,光栅/纹理像素采用统一总预算。滚动视口与普通画布的世界内容不会撑大外层有限视口或外层滚动范围。
示例见 [world-ui.endor](../examples/world-ui.endor)。世界 UI 阶段的 181 项完整本地回归和 all-target Clippy 均通过;新增回归覆盖真正的像素、托管回调、材质遮挡、多面板独立尺寸、再次嵌入 3D、真实 HTTP 射线/UV 摄像机输入、循环和递归预算。
## 可见性、连续输入与资源
3D 场景快照构建世界 AABB 的 BVH,摄像机变化复用相同的不可变场景和索引。视锥查询剔除不可见网格,射线查询按近到远缩小候选;序列化不携带缓存,反序列化后可重建。几何或变换变化会生成新场景和新索引。
普通 2D 交互和相机目标使用 128px 屏幕网格。每个对象最多进入 256 格,索引总计最多 65536 项;巨大矩形和项目化的 3D 面板 UI 进入精确命中的后备集合。后备集合仍遵循原有裁剪、投影和反向绘制顺序,不因近面投影或索引预算遗漏对象。源 hitTest 仍逐一执行其真实协议,未更改源覆盖行为。
原生输入使用有界 64 项队列。同一个运行时的连续 viewport / scene / scroll 事件在出队时更新到当前帧版本,保留原窗口、会话和捕获 Mount;目标消失、控制器禁用、运行时更换或失败时丢弃。所有窗口共用同一事件客户端和权威文档。离散点击及外部 HTTP 请求仍严格拒绝过时版本,不自动重放业务动作。队列满时仍可拒绝新输入,不保证任意输入速率下无损。
文字先裁剪再遍历可见字形像素;字体超过 512 设备像素时使用有界字形位图采样,避免高倍率缩放产生巨大单字形分配。字形缓存逐字检查 4096 项 / 32 MiB 阈值,整形缓存继续限制字符串数量与源字节数。极端放大时清晰度受字形 LOD 限制。面板派生槽位限制为非负 i64,避免哈希高位造成偶发排版错误;重复标识拒绝发布。
## 原生验证记录
2026-11-11:本地完整回归、格式、all-target Clippy 和 release 应用打包;实际启动 Tessera.app,通过本机 API 加载 world-ui 示例,并取得原生窗口截图,确认立方体、倾斜面板和内部 Canvas 的显示。系统 `CGPreflightScreenCaptureAccess` 为 true,`CGPreflightPostEventAccess` 为 false;集成的原生自动操作工具还因 OpenSSL 配置读取权限启动失败。因此 API / VM 事件与像素测试不宣称为硬件鼠标或触控板验收。最终检查数量及交付提交在 PR 中记录。
最终完整回归为 186 项通过;运行中的原生实例验证世界 UI 按钮将计数从 0 改为 1、scene-orbit 改变摄像机、scene-zoom 改变观察距离、重复旧帧请求返回 HTTP 409,空闲连续采样的版本保持一致。保留应用窗口供用户直接操作。
+52
View File
@@ -0,0 +1,52 @@
# Default-page design
Endor is a working object and UI environment. This page should help someone begin
working, with three existing actions, rather than explain the VM or advertise
future model connections. Layout, painting and callbacks live in Endor source.
## Reference decisions
| User reference | Adopt | Adapt for Endor |
| --- | --- | --- |
| Codex | Clear selected tab and restrained grouped actions | Keep the existing rounded tabs and continuous top/left chrome; omit its tool directory |
| Chrome | A recognizable visual center and immediately usable actions | Use a compact centered start surface; no search field without working search |
| Obsidian | A short vertical list of equal-sized quick actions | Three 360 × 40 logical-pixel action rows with consistent text alignment and spacing |
| VS Code | Quiet branding and aligned action/shortcut information | 28 px wordmark, 14 px supporting text, separate shortcut rows; no oversized slogan |
## Tokens and composition
- Chrome: #E6E9ED; canvas: existing #F7F7F5; action rows have no fill or border.
- Text: #30343B; supporting text: #80858D; action labels use existing native interface text.
- Typeface: existing native interface family with CJK fallback. A desktop tool
should follow the OS text conventions; a decorative web font is inappropriate.
- Type scale: 28 px wordmark, 14 px labels and supporting information.
- Action height: 40 px; no visible container; vertical rhythm: 8 px.
- Group width: 360 px; page centered in content constraints. The app's current
minimum window is 720 × 480, leaving room for the full group and chrome.
- Keep the normal native button focus outline and existing event handling.
```text
Endor
创建页面,或从一个示例开始。
+ 创建页面
↗ 共享对象示例
◇ 界面组合示例
新建标签页 ⌘T / Ctrl+T
关闭标签页 ⌘W / Ctrl+W
```
## Review before implementation
The rejected surface had two competing large titles, prose wider than its actions,
blue buttons of different widths and one long shortcut sentence. Replace those
with one small wordmark, one functional hint, quiet text actions and paired
shortcut rows. The first screenshot review still showed three white bordered
blocks that the user found too prominent; those surfaces were removed, bringing
the action treatment closer to VS Code while retaining Obsidian's short list.
Guidance reviewed: Anthropic's frontend-design SKILL.md (upstream main, retrieved
2026-10-24), using its plan/review/build/critique process. Only a temporary copy
was fetched; no global skill, hooks, browser runtime or frontend dependency was
installed. Native screenshot review and button activation checks follow the build.
+34
View File
@@ -0,0 +1,34 @@
# 学生成绩管理中心测试页
源码:[student-grades.endor](../examples/student-grades.endor)。
在 Tessera 按 F12 打开 Console,点击 `>` 输入位置,粘贴完整源码后按 Enter。
源码创建并渲染一个独立的「学生成绩管理中心」Page,不替换其他页面。
该示例使用 6 位虚构学生的内存对象,展示语文、数学、英语和复核状态。
它验证 Endor 类、原生 Column 子类的测量、自定义绘制、字段绑定、事件和
同一对象在筛选前后的共享状态。关闭应用后数据不会保存。
## 已完成的原生检查
- 通过原生 Console 粘贴完整源码并按 Enter,成功出现成绩页标签和 6 行数据。
- 「查看复核记录」切换为林沐的一行复核记录。
- 「录入复核成绩」执行示例中预设的复核结果:数学 58 → 68、状态改为已复核、待复核 1 → 0。
- 「全部学生」恢复 6 行,林沐的 68 分和已复核状态保留。
- 「恢复示例数据」恢复 58 分、待复核状态和计数 1。
这是交互测试示例,复核按钮应用预设结果,不是通用成绩录入表单;没有
文件存储、通用校验、导入导出、真实学校数据或完整 CRUD 的实现声明。
## 录制结果
尝试了 macOS screencapture 的窗口录像与限定区域录像,均返回 capture error。
随后尝试 QuickTime「新建录屏」,没有成功出现可操作的录制界面;直接打开
系统录屏工具也超时。因此没有成功生成连续录屏,不把截图当作录屏交付。
原生操作关键截图保存在本次会话的 /private/tmp/endor-grades-demo/:
01-endor-input.png、02-rendered.png、03-filtered.png、04-reviewed.png、
05-all-reviewed.png、06-reset.png。
本次仅新增示例和此说明,未修改渲染器。以实际 Console 执行和原生点击
作为验证;未运行 cargo test、自动化 smoke 脚本,也未因纯示例新增而重复构建。
+232
View File
@@ -0,0 +1,232 @@
# Window workspace requirement audit — 2026-10-24
This audit follows the full conversation, including later corrections. Implementation completion and native evidence are different columns. No claim is made that Chrome was personally measured.
| Requirement | Implementation | Evidence / limits |
| --- | --- | --- |
| One top row with native macOS controls | Transparent/full-size native title bar; reserved control space; 40 px tab strip; native AppKit controls repositioned to its y=20 center | Actual Retina macOS windows viewed; native close/minimize/fullscreen controls retained |
| Continuous left/top chrome | One neutral background; 56 px left rail; inset content panel | Actual main and detached windows viewed; no Tools label or rail launchers |
| Compact symmetric round tabs, softer active state | 88–208 px width; 32 px pill with equal 4 px vertical insets; 13 px labels and matching 18 px icon/close slots; no hard active stroke | Native settled UI viewed; hover and selected use the same bounds |
| + and startup default page | One startup request guarded against duplicate resume; + release-inside; Cmd/Ctrl+T | Immediately after restart: pages().count = 1. Two native Cmd+T actions produced three tabs |
| New-tab motion, filled and unfilled | 220 ms cubic ease; insertion grows from the previous trailing edge; full-strip geometry and + interpolate; removed tabs shrink without remaining interactive | Real native new/close/fill operations completed; settled compression/overflow viewed. No frame-by-frame recording or Chrome timing comparison |
| Overflow and scrolling | Separate + reservation; no arrow buttons; logical-pixel wheel/trackpad scrolling and clipped offscreen tabs; invisible drag edge dwell retained | Native overflow reached; + in overflow increased VM count 7 → 8. Dragging out of + kept count at 7 |
| Close/activate/reorder/migrate/detach | Ordinary managed Page methods retained; animated hit bounds and drag anchors use current visual bounds | Native close and drag-out to Endor Window 2 succeeded. API detach/move-back preserved Page 1:135:0. Native cross-window drop, dwell and mixed-DPI were not re-run in this final build |
| Four developer tools separated | Independent Page instances; Console/Sources/Network/Settings modules and separate per-view state | Earlier native top-level Sources/Console activation and read-only copy/paste verified; no nested navigation remains |
| Four tools not default or permanently placed | No Tools menu, rail buttons or new-page tool directory; existing API/shortcut retained | Final default surfaces viewed without tool entries |
| Source reading/selection/copy | Grapheme-boundary selection, no gutter in copy, select-all/copy, Shift navigation, drag edge scrolling | Native single-line drag/copy/paste verified earlier in this change. Final keyboard copy was re-run after the chrome-focus fix: drag-copy matched the complete selected line; four Shift+Right operations copied the expected four characters; select-all copied multiline source without a gutter. Drag edge behavior compiled; exhaustive combinations remain untested |
| Clicking Console output must not jump to prompt/end | Input hit region restricted to actual prompt rows | Native reading/copy path verified earlier; no input hit over transcript-only area |
| Default page reflects Endor | Real Endor Page with creation, shared-object and composition actions; no persistence/model backend claims | Referenced chats read: 01a16819-28c3-7ce0-9423-0ffaa19402ce and 01a1689b-77d8-75a2-ba9e-b2fa3dce654e; actual native start surface viewed |
| Sensible source organization | Runtime/API tests separated; four page view modules; shared painter/selection; native tool Page factory; motion module | All-target Clippy compiled production and test sources. Runtime host reduced from ~7000 to ~1380 lines |
| Protect existing work | examples/README.md and examples/workspace.endor excluded; vendor/Aster untouched | git status checked before staging |
| Verification restrictions | fmt, all-target Clippy -D warnings, release build and manual native/API checks | No cargo test, smoke script, Docker, dependency test install or CI polling |
## Reference boundaries
The user's Chrome/Codex reference images supplied the single-row controls, capsules and continuous left/top chrome. The [Obsidian reading-view reference](https://forum.obsidian.md/t/make-button-to-switch-views-in-tab-title-bar-more-intuitive/89814/6) informed restrained contrast and pane separation.
The actual tools refused access to both Codex and Terminal. The available in-app browser exposes page content, not Chrome's native tab strip. No personal Chrome window/profile was operated. A Chromium source search was supplementary research, not an animation test; fetching the selected source page failed. Therefore the requested isolated Chrome comparison remains unverified.
## Manual request correction
One placement probe used unsupported == syntax and returned a parse error before execution. It was replaced with direct returned object-identity checks. Both the detached-window Page and moved-back Page returned 1:135:0. The failed expression is not counted as passing evidence.
## Remaining verification
Isolated Chrome timing/shape comparison, frame-by-frame animation capture, fresh native cross-window drop/dwell on the final build, mixed-DPI cross-screen interaction and exhaustive keyboard/source-selection combinations remain without new runtime evidence. These are not silently marked passed. The shipped Page lifetime/GC model was preserved; no new persistence or AI backend is claimed.
## Final focus regression fix
Final native retesting found a real regression: title-strip mouse events cleared the active editor focus. Window activation performed before automated key events exposed the same behavior. Chrome mouse presses now preserve content focus; developer pane hit testing ignores points outside the pane; frame publication updates the keyboard route according to the active Page. No source, tab geometry or selection state is logged by the shipped build.
After the fix, direct system clipboard comparisons (without printing clipboard contents) confirmed selected-line equality (28 characters), Shift+Right selection equality (4 characters), and multiline select-all with no line-number gutter. The temporary Sources Page was closed afterwards. All-target Clippy, formatting and release building passed again.
## Local delivery state
Implementation commits: 3220544 (runtime test-source separation), 656522e (managed workspace/chrome implementation), d3165b1 (behavior and requirement audit), followed by the chrome-focus fix commit. A push to origin/main was attempted once and rejected by automatic approval review because explicit authorization for this default-branch remote mutation was required. No alternative push route was attempted. The remote remains unchanged pending the user's approval.
## Functional start-page revision
The previous Rust-painted introduction was removed. `ui_bridge/start_page.endor`
now defines a managed Page subclass with native layout alignment, real buttons,
a shared-state counter and a composed-Blocks example. Its private module globals
do not overwrite user REPL bindings. The same factory is available as `ui.newTab()`;
legacy `ui.developerTools("New tab")` delegates to it. No developer-tool entry is
shown on the start page.
Native startup checks caught unsupported comparison syntax and unimplemented
arithmetic bytecode in initial layout drafts. Those drafts were replaced with
existing Page/Row measurement and native `mainAlign`, without changing Aster.
A subsequent layout check caught unbounded child-height centering; sizing now
belongs to the root Page, which receives the actual content constraints.
These failures were corrected locally, and are not counted as passing checks.
Final native checks for this revision: all three start-page buttons opened their
corresponding managed Pages; the blank-page return action activated its original
home Page; one native counter click changed both views from 0 to 1. Overflow
navigation was visible while these Pages were added. A direct `ui.newTab()` call
increased the live Page count from 4 to 5, confirming one Page per factory call.
The final window was also being operated by the user (reported by the UI tool),
so the pre-existing four tabs are not treated as a clean-start count measurement.
No additional restart was done after that interaction. The earlier isolated
startup count of one remains evidence for the guarded startup path; the new
factory's single-call count was checked separately.
Formatting, all-target offline Clippy with warnings denied, the release macOS
bundle and diff whitespace checks passed. No test suite or smoke script was run.
All earlier requirements were reviewed against the table above; isolated Chrome
motion comparison and the explicitly listed cross-window/DPI verification gaps
remain unverified, rather than being marked complete.
## Chrome contrast correction
The continuous top/left chrome now uses #E6E9ED instead of #F5F5F5,
separating it visibly from the #F7F7F5 content canvas. Selected tabs retain
white fill and dark text; inactive titles use muted text. Geometry and borderless
selection are unchanged. After rebuilding and restarting, the native window
showed one startup tab; a + click added a second tab and the two states were
visually checked. Formatting, all-target offline Clippy and release bundling passed.
## Start-page visual redesign
Reviewed the four user-supplied Codex/Chrome/Obsidian/VS Code references and
Anthropic's frontend-design skill. Reference decisions and tokens are recorded in
`docs/start-page-design.md`. The default page now uses one 28 px wordmark, a short
14 px hint, aligned action rows and separate shortcut rows. A first pass with
white outlined buttons was rejected by the user; the action fill and border were
removed in the final pass. The Endor Button subclass keeps a 360 × 40 hit target
but returns an empty background display list; its label and native focus indicator
still render through the existing tree.
Native screenshot review confirmed the final text-row treatment. Clicking the
shared-object action opened its Page; Tab focused the first action with a visible
outline. Startup displayed one default Page. Formatting, all-target offline Clippy,
release bundling and diff whitespace checks passed. No automated test suite was run.
The design skill was read from a temporary download only; no global skill, hooks
or new application dependency was installed.
## Tab motion, density and macOS alignment correction — 2026-10-25
Reviewed the user-provided 60 fps reference recording by extracting insertion,
full-strip and closing frames. The reference's unfilled strip expands the new tab
from the previous trailing edge and moves + with it; overflow scrolls the strip
and permits a partial tab at the edge. This is analysis of the supplied recording,
not an independently measured live Chrome/Codex session.
The strip now retains geometry for every tab ID, including offscreen tabs. Moving
an existing tab into the viewport no longer treats it as a new zero-width tab.
Geometry retargets from its sampled position during repeated operations; closed
tabs shrink visually and are excluded from hit testing. New selection reveals only
the required portion of the strip rather than centering the selected tab.
The former 160 px minimum is reduced to 88 px, and arrow controls plus their
reserved margins are removed. Horizontal trackpad deltas and vertical mouse-wheel
deltas over the strip both change a clamped floating-point scroll offset. Gesture
scrolling follows input directly, while insertion, closure and automatic reveal
use the 220 ms transition. OS momentum remains ordinary subsequent wheel input.
No touchscreen hardware verification is claimed.
The initial 28 px row was too shallow. The revised 40 px row centers tabs at
y=20 and repositions the retained native AppKit controls onto the same center
line. Pills are 32 px high, with 4 px top/bottom margins and 13 px labels. A 1 × 12 px divider separates adjacent inactive tabs; it is hidden beside
an active or hovered tab. Hover and selection retain the same pill geometry.
Manual native checks covered startup, + and repeated Cmd+T, dense overflow,
vertical wheel movement to either end, hover divider suppression, tab selection
and Cmd+W closure. Native screenshots confirmed alignment, density and absence
of arrow controls. Physical trackpad feel, mixed-DPI cross-window drag and an
exact frame-timing match remain unverified. A capture attempt around an insertion
returned only one usable frame, so it is not presented as animation timing proof.
Formatting, all-target offline Clippy with warnings denied, release app bundling
and whitespace checks passed. Existing geometry test fixtures were updated for
pixel offsets and the denser layout; they were type-checked by Clippy but no
cargo test, automated smoke script or Docker task was run.
### Comfortable row height with native alignment — 2026-10-25
The current Chromium [layout constants](https://github.com/chromium/chromium/blob/main/chrome/browser/ui/layout_constants.cc)
define a 35 px tab (34 + 1 px toolbar overlap) and 6 px strip padding, totaling
41 px. Tessera uses a 40 px row with a symmetric 32 px capsule, retaining its
88–208 px width range, separators, gesture scrolling and insertion motion.
Only the in-app web view is available for agent-owned browser access, so this
is a source/reference-image comparison, not a live measurement of Chrome.
A macOS-only adapter obtains the winit-owned content NSView and positions the
three real standard window buttons at the row's center. It preserves their
native sizes, horizontal positions and actions, and reapplies alignment before
drawing after native layout changes. Fullscreen floating controls stay under
AppKit management. Native bindings were already cached transitively; direct
macOS-only dependencies now declare this use explicitly.
Manual resizing followed by repeated tab creation exposed a renderer panic:
rounding at large absolute x positions could invert a rounded rectangle's
clamp bounds while a tab grew from almost zero width. Rounded hit coverage now
clamps in local coordinates with a radius bounded by half the rectangle size.
Final native checks passed for 18 consecutive Cmd+T insertions, dense overflow,
wheel scrolling, five consecutive Cmd+W closures and native window zoom. The
final process stayed running without stderr errors. Initial native screenshots
showed the traffic lights, tab capsules and + centered at the same y position.
Subsequent computer-control captures can display macOS's capture badge over the
traffic lights. Fullscreen floating controls and mixed-DPI moves were not tested.
Offline all-target Clippy with warnings denied, formatting, release app bundling
and git whitespace checks passed; no cargo test or automated smoke script ran.
### Hover fades with immediate selection — 2026-10-25
Tab bodies, the + button and close-button hover backgrounds now use the same
160 ms cubic ease-out for entering and leaving. Each tab is tracked by its
stable ID; reversing a fade starts from the current sampled intensity. Adjacent
inactive dividers fade with the tab hover instead of disappearing abruptly.
Close-button colors interpolate from the tab's actual current background,
including the selected white surface.
Hover state runs separately from geometry animation. The event loop schedules
frames until either transition finishes, including after the pointer stops or
leaves the window. Selected backgrounds and label colors still read the current
active flag directly, so selection has no color fade or animation delay.
Existing insertion/closure movement and native control alignment are retained.
Native manual checks covered an inactive tab hover, leaving that tab, the +
hover, selecting a different tab and moving back into page content. Settled
screenshots confirmed hover does not select the tab, + has its hover surface,
selection changes to the clicked tab and idle separators return after leaving.
The capture API does not establish frame-accurate 160 ms timing. Offline
all-target Clippy, formatting, release bundling and whitespace checks passed;
no cargo test, automated smoke script or Docker task was run.
### Native toolbar double-click — 2026-10-25
The custom row previously called only winit's native window-drag operation;
a manual double-click in its empty area did not resize the window. The same
empty-area hit test now consults AppKit's current NSEvent clickCount before
starting a drag. On the second press it calls NSWindow.performZoom, preserving
AppKit's standard/user frame toggle and avoiding a hand-built resize animation.
Tabs, close buttons and + remain excluded from this handler.
The adapter reads AppleActionOnDoubleClick without changing system preferences:
Minimize calls performMiniaturize; absent/Maximize calls performZoom; disabled
or unknown values do nothing. Fill also uses the public performZoom action,
whose standard frame fills this application's available screen in the checked
configuration. It does not invoke the private _zoomFill selector used by Chrome.
Consequently Fill is not claimed to reproduce every macOS tiling margin rule.
Native fullscreen uses a different window state and is left to AppKit.
References: Apple's [performZoom](https://developer.apple.com/documentation/appkit/nswindow/performzoom(_:))
and Chromium's [custom draggable-area handling](https://github.com/chromium/chromium/blob/main/components/remote_cocoa/app_shim/native_widget_mac_nswindow.mm).
Manual native verification: an empty-row double-click changed the Retina window
from 2560×1600 to 3024×1888; a second double-click restored 2560×1600. Clicking
+ and double-clicking a tab did not zoom the window. Dragging empty toolbar
space continued to move the window. The user's double-click preference was
absent (default zoom); other preference branches were not changed or manually
tested. Offline all-target Clippy, formatting, release bundling and whitespace
checks passed. No cargo test or automated smoke script was run.
+9 -2
View File
@@ -2,6 +2,10 @@
| File | Purpose |
| --- | --- |
| [world-ui.endor](world-ui.endor) | Interactive Endor UI on a transformed 3D plane, with shared counter state, nested canvas, programmable camera and fixed UI controls. |
| [scene3d.endor](scene3d.endor) | Shared 3D meshes, transforms and light with independent perspective/orthographic cameras, orbit controls and Endor buttons. |
| [scene-viewports.endor](scene-viewports.endor) | One Scene2D in two CanvasViewports with independent Camera2D, a nested viewport, shared state and fixed overlay UI. |
| [box-layout.endor](box-layout.endor) | Nested Row/Column/Overlay, shared text, finite border-box sizing, margins, borders, alignment and clipping. |
| [gc-lifecycle.endor](gc-lifecycle.endor) | A Page/Block/Task/await-frame cycle: hidden retained Blocks keep running, then releasing the last references permits collection despite rendering caches. |
| [scroll-axis.endor](scroll-axis.endor) | One shared TextBlock in vertical and horizontal viewports, live axis changes and independent offsets. |
| [windows.endor](windows.endor) | Two real native windows in one Aster VM, live shared counter state and explicit Page ownership. |
@@ -21,12 +25,15 @@
| [main.endor](main.endor) | The earlier function-entry form, producing the same frame as page.endor. |
| [hello.endor](hello.endor) | Richer function-entry example covering a helper, Row/Column and Spacer. |
| [fonts.endor](fonts.endor) | Mixed Chinese/Latin text and proportional widths, with rectangles following narrow and wide letters. |
| [workspace.endor](workspace.endor) | Larger static workspace dashboard with reusable functions, metrics, progress bars and an activity column. Paste the complete file into Console in Script mode; all displayed data is illustrative. |
Submit a file as the UTF-8 body of a namespace PUT request. No namespace,
scene, render block or imports belong in the source.
The live `/agent` guide embeds page.endor exactly. Remote CI executes the examples through
Aster and checks the resulting coordinates and source ranges after VM cleanup.
The live `/agent` guide embeds page.endor exactly. Local tests execute examples through
Aster and check the resulting coordinates and source ranges after VM cleanup.
For Page window/vertical/horizontal/canvas modes, see [page surfaces](../docs/page-surfaces.md)
and the running start page's four working actions.
The file is client-side sample material; Tessera's API stores source by namespace.
Return to the [project guide](../README.md).
+38
View File
@@ -0,0 +1,38 @@
// Containers compose independently of Page and of any camera.
shared = TextBlock("同一个对象可以有多个 Mount。每个位置分别测量、换行和对齐。", 2)
shared.boxWidth = "fill"
shared.marginBottom = 8
left = Column(16, 12, TextBlock("Row / Column", 2), shared, Button("继续探索"))
left.boxWidth = "fill"
left.minWidth = 180
left.maxWidth = 360
left.borderLeft = 2
left.borderTop = 2
left.borderRight = 2
left.borderBottom = 2
left.borderColor = "#CBD5E1"
left.paddingLeft = 24
left.crossAlign = "center"
right = Column(16, 12, TextBlock("共享内容,独立排版", 2), shared)
right.boxWidth = "fill"
right.maxWidth = 240
right.crossAlign = "end"
content = Row(24, 24, left, right)
content.boxWidth = 760
content.crossAlign = "start"
badge = TextBlock("Endorphin · layout")
badge.marginRight = 12
badge.marginBottom = 12
badge.alignSelf = "end"
surface = Overlay(0, 0, content, badge)
surface.boxWidth = 800
surface.boxHeight = 400
surface.mainAlign = "end"
surface.overflow = "clip"
page = Page()
page.title = "嵌套盒模型"
page.render(surface)
+268
View File
@@ -0,0 +1,268 @@
// Endor Campus — a multi-page learning environment inspired by Canvas LMS.
// Fictional student/course data. Paste the complete source into Console and Enter.
// All seven tabs are ordinary managed Pages. There is no server or Canvas login.
class CampusPanel: Column {
function paint(self: CampusPanel, mount: Mount, geometry: Bounds): DisplayList {
fill = PaintCommand()
fill.kind = "roundedRect"
fill.x = geometry.x
fill.y = geometry.y
fill.width = geometry.width
fill.height = geometry.height
fill.radius = 10
fill.color = "#FFFFFF"
return DisplayList(ObjectList(fill))
}
}
class CampusCell: Column {
width: Number
function measure(self: CampusCell, mount: Mount, constraints: Constraints): MeasureResult {
result = Column.measure(self, mount, constraints)
result.width = self.width
return result
}
}
class CampusSidebar: Column {
function measure(self: CampusSidebar, mount: Mount, constraints: Constraints): MeasureResult {
return MeasureResult(168, 620)
}
function paint(self: CampusSidebar, mount: Mount, geometry: Bounds): DisplayList {
fill = PaintCommand()
fill.kind = "roundedRect"
fill.x = geometry.x
fill.y = geometry.y
fill.width = geometry.width
fill.height = geometry.height
fill.radius = 10
fill.color = "#852B38"
return DisplayList(ObjectList(fill))
}
}
class CampusNav: Button {
background: String
function measure(self: CampusNav, mount: Mount, constraints: Constraints): MeasureResult {
return MeasureResult(144, 40)
}
function paint(self: CampusNav, mount: Mount, geometry: Bounds): DisplayList {
fill = Button.paint(self, mount, geometry).commands.at(0)
fill.color = self.background
fill.radius = 7
return DisplayList(ObjectList(fill))
}
}
class CampusCourse {
title: String
code: String
teacher: String
grade: String
progress: String
}
class CampusWork {
status: String
score: String
feedback: String
submission: String
todo: String
result: String
course: CampusCourse
function submit(self: CampusWork, event: Event): Unit {
self.status = "已提交 · 等待评分"
self.submission = "lab01.endor · 已提交示例内容"
self.todo = "已完成本次实验提交"
self.result = "示例提交成功,可以切到作业中心查看同一条记录。"
}
function assess(self: CampusWork, event: Event): Unit {
self.status = "已评分"
self.score = "92 / 100"
self.feedback = "结构清晰,边界情况处理完整。建议补充函数说明。"
self.submission = "lab01.endor · 已提交示例内容"
self.todo = "本次实验已评分"
self.course.grade = "88.5%"
self.course.progress = "已完成 4 / 6 个学习单元"
self.result = "已应用预设评分;仪表盘、课程主页和成绩总览同步更新。"
}
function reset(self: CampusWork, event: Event): Unit {
self.status = "未提交"
self.score = "— / 100"
self.feedback = "提交后可在此查看教师反馈。"
self.submission = "尚无提交内容"
self.todo = "1 项实验待提交"
self.course.grade = "86.0%"
self.course.progress = "已完成 3 / 6 个学习单元"
self.result = "已恢复实验、课程成绩和学习进度的示例状态。"
}
}
function campusCell(content: Block, width: Number): Block {
return CampusCell(0, 0, content, width)
}
class CampusTarget {
page: Page
// Consume the click Event here; Page.open's optional argument is a Window.
function open(self: CampusTarget, event: Event): Unit { self.page.open() }
}
function campusLink(label: String, target: Page): Button {
button = Button(label)
action = CampusTarget(target)
button.on("click", action.open)
return button
}
function campusNav(label: String, target: Page, background: String): Button {
button = CampusNav(label, background)
button.replace(0, TextBlock(label, 1, "#FFFFFF"))
action = CampusTarget(target)
button.on("click", action.open)
return button
}
function campusNavigation(home: Page, course: Page, assignments: Page, grades: Page, homeTone: String, courseTone: String, workTone: String, gradeTone: String): Block {
return CampusSidebar(12, 10,
TextBlock("Endor", 2, "#FFFFFF"),
TextBlock("Campus", 1, "#E7BAC0"), Spacer(16),
campusNav("仪表盘", home, homeTone),
campusNav("课程", course, courseTone),
campusNav("作业中心", assignments, workTone),
campusNav("成绩总览", grades, gradeTone), Spacer(100),
TextBlock("林沐", 1, "#FFFFFF"),
TextBlock("2026 秋季学期", 1, "#E7BAC0"),
TextBlock("本地演示", 1, "#E7BAC0"))
}
function campusShell(navigation: Block, title: String, subtitle: String, body: Block): Block {
scroll = ScrollBlock(1120, 680,
Row(24, 28, navigation,
Column(0, 16,
TextBlock(title, 2, "#263444"),
TextBlock(subtitle, 1, "#7C8793"),
RectBlock(800, 1, 0, "#E0E5EB"), body)))
scroll.axis = "both"
return scroll
}
function campusCourseCard(course: CampusCourse, page: Page, color: String): Block {
return CampusPanel(0, 0,
RectBlock(248, 44, 8, color),
Column(16, 8,
TextBlock(course.code, 1, "#7C8793"),
TextBlock(course.title, 1, "#263444"),
TextBlock(course.teacher, 1, "#7C8793"),
ui.textOf(course, "grade", 2, color),
campusLink("进入课程", page)))
}
function campusGradeRow(course: CampusCourse, target: Page): Block {
return Column(0, 12,
Row(0, 0,
campusCell(TextBlock(course.title), 240),
campusCell(TextBlock(course.code, 1, "#7C8793"), 140),
campusCell(ui.textOf(course, "grade", 1, "#315E86"), 140),
campusLink("课程详情", target)),
RectBlock(752, 1, 0, "#EDF0F3"))
}
function campusCourseBody(course: CampusCourse, intro: String, moduleOne: String, moduleTwo: String, moduleThree: String, assignments: Page, grades: Page): Block {
return Column(0, 20,
Row(0, 16, campusLink("作业与提交", assignments), campusLink("查看成绩", grades)),
CampusPanel(20, 12,
TextBlock("课程概况", 1, "#263444"),
TextBlock(intro, 1, "#6D7987"),
TextBlock(course.teacher, 1, "#6D7987"),
Row(0, 24, TextBlock("当前成绩", 1, "#7C8793"), ui.textOf(course, "grade", 2, "#315E86")),
ui.textOf(course, "progress", 1, "#6D7987")),
CampusPanel(20, 14,
TextBlock("学习单元", 1, "#263444"),
TextBlock(moduleOne, 1, "#526372"),
RectBlock(752, 1, 0, "#EDF0F3"),
TextBlock(moduleTwo, 1, "#526372"),
RectBlock(752, 1, 0, "#EDF0F3"),
TextBlock(moduleThree, 1, "#526372")))
}
// The shared object graph is created once; each Page projects those same objects.
campusProgramming = CampusCourse("计算机程序设计", "CS 101", "陈老师 · 周二 / 周四", "86.0%", "已完成 3 / 6 个学习单元")
campusMathematics = CampusCourse("高等数学 I", "MATH 101", "周老师 · 周一 / 周三", "91.0%", "已完成 4 / 6 个学习单元")
campusEnglish = CampusCourse("学术英语", "ENG 102", "许老师 · 周五", "89.0%", "已完成 3 / 5 个学习单元")
campusWork = CampusWork("未提交", "— / 100", "提交后可在此查看教师反馈。", "尚无提交内容", "1 项实验待提交", "这是一个本地提交与评分演示。", campusProgramming)
campusDashboard = Page()
campusDashboard.title = "Campus · 仪表盘"
campusProgrammingPage = Page()
campusProgrammingPage.title = "CS 101 · 程序设计"
campusMathPage = Page()
campusMathPage.title = "MATH 101 · 高等数学"
campusEnglishPage = Page()
campusEnglishPage.title = "ENG 102 · 学术英语"
campusAssignments = Page()
campusAssignments.title = "Campus · 作业中心"
campusGrades = Page()
campusGrades.title = "Campus · 成绩总览"
campusWorkPage = Page()
campusWorkPage.title = "实验 01 · 提交详情"
campusHomeNav = campusNavigation(campusDashboard, campusProgrammingPage, campusAssignments, campusGrades, "#A64350", "#852B38", "#852B38", "#852B38")
campusCourseNav = campusNavigation(campusDashboard, campusProgrammingPage, campusAssignments, campusGrades, "#852B38", "#A64350", "#852B38", "#852B38")
campusAssignmentNav = campusNavigation(campusDashboard, campusProgrammingPage, campusAssignments, campusGrades, "#852B38", "#852B38", "#A64350", "#852B38")
campusGradeNav = campusNavigation(campusDashboard, campusProgrammingPage, campusAssignments, campusGrades, "#852B38", "#852B38", "#852B38", "#A64350")
campusDashboard.render(campusShell(campusHomeNav, "仪表盘", "林沐,欢迎回来。这里是你的课程与近期学习安排。",
Column(0, 20,
Row(0, 16,
campusCourseCard(campusProgramming, campusProgrammingPage, "#326A8F"),
campusCourseCard(campusMathematics, campusMathPage, "#547C67"),
campusCourseCard(campusEnglish, campusEnglishPage, "#88647D")),
CampusPanel(20, 12,
TextBlock("近期作业", 1, "#263444"),
Row(0, 24, TextBlock("CS 101 · 实验 01:对象与函数"), ui.textOf(campusWork, "status", 1, "#315E86")),
ui.textOf(campusWork, "todo", 1, "#7C8793"),
campusLink("打开作业详情", campusWorkPage)),
TextBlock("虚构课程与学生数据 · Endor 本地多页面演示", 1, "#8C959F"))))
campusProgrammingPage.render(campusShell(campusCourseNav, "计算机程序设计", "课程 / CS 101 / 主页",
Column(0, 16,
campusCourseBody(campusProgramming, "通过实际编程理解对象、函数与交互。", "01 对象与字段 · 已完成", "02 函数与方法 · 已完成", "03 事件与可视界面 · 进行中", campusAssignments, campusGrades),
campusLink("实验 01:对象与函数", campusWorkPage))))
campusMathPage.render(campusShell(campusCourseNav, "高等数学 I", "课程 / MATH 101 / 主页",
campusCourseBody(campusMathematics, "学习极限、微分与积分的基本方法。", "01 函数与极限 · 已完成", "02 导数及其应用 · 已完成", "03 积分方法 · 进行中", campusAssignments, campusGrades)))
campusEnglishPage.render(campusShell(campusCourseNav, "学术英语", "课程 / ENG 102 / 主页",
campusCourseBody(campusEnglish, "阅读学术文本,练习清晰的论证与表达。", "01 Academic reading · 已完成", "02 Evidence and arguments · 已完成", "03 Research writing · 进行中", campusAssignments, campusGrades)))
campusAssignments.render(campusShell(campusAssignmentNav, "作业中心", "本学期 / 全部课程 / 作业与提交",
Column(0, 20,
CampusPanel(20, 12,
TextBlock("实验 01:对象与函数", 1, "#263444"),
TextBlock("CS 101 · 10 月 30 日 23:59 截止 · 满分 100", 1, "#7C8793"),
Row(0, 24, ui.textOf(campusWork, "status", 1, "#315E86"), ui.textOf(campusWork, "score")),
campusLink("查看提交详情", campusWorkPage)),
CampusPanel(20, 12,
TextBlock("习题 04:微分与应用", 1, "#263444"),
TextBlock("MATH 101 · 已提交 · 90 / 100", 1, "#7C8793")),
CampusPanel(20, 12,
TextBlock("Reading response", 1, "#263444"),
TextBlock("ENG 102 · 已评分 · 88 / 100", 1, "#7C8793")))))
campusGrades.render(campusShell(campusGradeNav, "成绩总览", "2026 秋季学期 / 当前课程成绩",
Column(0, 20,
CampusPanel(20, 16,
Row(0, 0,
campusCell(TextBlock("课程", 1, "#7C8793"), 240),
campusCell(TextBlock("课程编号", 1, "#7C8793"), 140),
campusCell(TextBlock("当前成绩", 1, "#7C8793"), 140)),
campusGradeRow(campusProgramming, campusProgrammingPage),
campusGradeRow(campusMathematics, campusMathPage),
campusGradeRow(campusEnglish, campusEnglishPage)),
CampusPanel(20, 12,
TextBlock("CS 101 · 作业评分与反馈", 1, "#263444"),
Row(0, 24, TextBlock("实验 01:对象与函数"), ui.textOf(campusWork, "score", 1, "#315E86")),
ui.textOf(campusWork, "feedback", 1, "#6D7987"),
campusLink("打开作业与反馈", campusWorkPage)))))
campusSubmitButton = Button("模拟提交实验")
campusSubmitButton.on("click", campusWork.submit)
campusAssessButton = Button("应用示例评分")
campusAssessButton.on("click", campusWork.assess)
campusResetButton = Button("恢复演示数据")
campusResetButton.on("click", campusWork.reset)
campusWorkPage.render(campusShell(campusAssignmentNav, "实验 01:对象与函数", "CS 101 / 作业 / 提交详情",
Column(0, 20,
Row(0, 16, campusLink("返回课程", campusProgrammingPage), campusLink("全部作业", campusAssignments), campusLink("成绩总览", campusGrades)),
CampusPanel(20, 12,
TextBlock("实验要求", 1, "#263444"),
TextBlock("使用 Endor 定义一个对象,并通过方法更新其字段。", 1, "#6D7987"),
TextBlock("为同一个对象建立两个可视展示,验证修改后同时更新。", 1, "#6D7987"),
TextBlock("截止:10 月 30 日 23:59 满分:100", 1, "#7C8793")),
CampusPanel(20, 12,
TextBlock("提交记录", 1, "#263444"),
ui.textOf(campusWork, "submission"),
ui.textOf(campusWork, "status", 1, "#315E86"),
Row(0, 12, campusSubmitButton, campusAssessButton, campusResetButton)),
CampusPanel(20, 12,
Row(0, 24, TextBlock("成绩与反馈"), ui.textOf(campusWork, "score", 2, "#315E86")),
ui.textOf(campusWork, "feedback", 1, "#6D7987")),
ui.textOf(campusWork, "result", 1, "#7C8793"))))
campusDashboard.activate()
+28
View File
@@ -0,0 +1,28 @@
// The scene has world positions; each finite viewport has its own camera.
count = ui.state(0)
increment = Button("共享计数 +1")
increment.onClick(count.increment)
card = Column(20, 12, TextBlock("世界里的 UI", 2), ui.textOf(count, "value", 3), increment)
card.boxWidth = 220
card.x = -60
card.y = 40
card.borderLeft = 2
card.borderColor = "#8CA5B8"
inner = CanvasViewport(200, 100, Scene2D(RectBlock(120, 60, 8, "#D4E6D9")))
inner.x = 260
inner.y = 40
world = Scene2D(card, inner)
left = CanvasViewport(460, 320, world)
left.camera.x = -100
right = CanvasViewport(320, 320, world)
right.camera.x = -80
right.camera.zoom = 0.65
// Set right.camera = left.camera to share a view explicitly.
views = Row(0, 20, left, right)
hud = Column(16, 8, TextBlock("一个世界,多个视角", 2), TextBlock("滚轮平移 · 空格/中键拖动 · 捏合或 Cmd/Ctrl+滚轮缩放"))
hud.alignSelf = "end"
page = Page()
page.title = "场景与视口"
page.render(Overlay(12, 0, views, hud))
+46
View File
@@ -0,0 +1,46 @@
class SceneActions {
view: Viewport3D
cube: Mesh3D
function front(self: SceneActions): Unit {
self.view.camera.x = 0
self.view.camera.y = 0
self.view.camera.z = 6
}
function side(self: SceneActions): Unit {
self.view.camera.x = 6
self.view.camera.y = 2
self.view.camera.z = 0
}
function rotate(self: SceneActions): Unit { self.cube.rotate(0, 15, 0) }
function select(self: SceneActions, event: Event): Unit { event.hit.mesh.color = "#6B9B81" }
}
cube = Box3D(1.6, 1.6, 1.6, "#6687AB")
cube.rotationY = 25
cube.rotationX = 15
small = Box3D(0.7, 0.7, 0.7, "#DBA36E")
small.x = 1.8
small.z = -0.8
group = Group3D(cube, small)
floor = Box3D(6, 0.08, 4, "#D8DEE6")
floor.y = -1.1
light = DirectionalLight(-1, -2, -3, "#FFFFFF", 0.9)
scene = Scene3D(group, floor, light)
scene.ambient = 0.35
perspective = Viewport3D(480, 360, scene)
perspective.camera.z = 6
orthographic = Viewport3D(320, 360, scene)
orthographic.camera = OrthographicCamera()
orthographic.camera.height = 5
orthographic.camera.x = 4
orthographic.camera.y = 2
orthographic.camera.z = 5
actions = SceneActions(perspective, cube)
front = Button("正面")
front.onClick(actions.front)
side = Button("侧面")
side.onClick(actions.side)
rotate = Button("物体旋转 +15°")
rotate.onClick(actions.rotate)
page = Page()
page.title = "场景、视口和摄像机"
page.render(Column(24, 16, TextBlock("同一个 3D 场景,两个摄像机", 2), Row(0, 16, perspective, orthographic), Row(0, 12, front, side, rotate), TextBlock("左键拖动旋转 · 中键或空格拖动平移 · 滚轮缩放\n摄像机和控制器都是可编程对象;2D 控件由 Endor 自己排版。")))
+112
View File
@@ -0,0 +1,112 @@
// Student grades demo. Fictional records; in-memory only.
// Paste the entire file into Tessera Console, then press Enter.
class GradeCell: Column {
width: Number
function measure(self: GradeCell, mount: Mount, constraints: Constraints): MeasureResult {
size = Column.measure(self, mount, constraints)
size.width = self.width
return size
}
}
class GradePanel: Column {
function paint(self: GradePanel, mount: Mount, geometry: Bounds): DisplayList {
fill = PaintCommand()
fill.kind = "roundedRect"
fill.x = geometry.x
fill.y = geometry.y
fill.width = geometry.width
fill.height = geometry.height
fill.radius = 12
fill.color = "#FFFFFF"
return DisplayList(ObjectList(fill))
}
}
class Student {
name: String
number: String
chinese: Number
math: Number
english: Number
status: String
}
function gradeCell(content: Block, width: Number): Block {
return GradeCell(0, 0, content, width)
}
function gradeRow(student: Student): Block {
return Column(0, 12,
Row(0, 0,
gradeCell(TextBlock(student.name), 150),
gradeCell(TextBlock(student.number, 1, "#7A8390"), 120),
gradeCell(ui.textOf(student, "chinese"), 100),
gradeCell(ui.textOf(student, "math"), 100),
gradeCell(ui.textOf(student, "english"), 100),
gradeCell(ui.textOf(student, "status", 1, "#526C83"), 160)),
RectBlock(730, 1, 0, "#EDF0F3"))
}
class GradeCenter {
table: Column
all: Column
attention: Column
student: Student
pending: Number
message: String
function showAll(self: GradeCenter, event: Event): Unit {
self.table.replace(0, self.all)
self.message = "正在查看全部 6 位学生"
}
function showAttention(self: GradeCenter, event: Event): Unit {
self.table.replace(0, self.attention)
self.message = "林沐的数学成绩有一条复核记录"
}
function review(self: GradeCenter, event: Event): Unit {
self.student.math = 68
self.student.status = "已复核"
self.pending = 0
self.message = "已录入复核结果:林沐 · 数学 58 → 68"
}
function reset(self: GradeCenter, event: Event): Unit {
self.student.math = 58
self.student.status = "待复核"
self.pending = 1
self.table.replace(0, self.all)
self.message = "已恢复示例数据"
}
}
studentLin = Student("林沐", "2026001", 86, 58, 91, "待复核")
studentChen = Student("陈知夏", "2026002", 94, 96, 93, "已确认")
studentXu = Student("许星河", "2026003", 82, 88, 85, "已确认")
studentZhou = Student("周予安", "2026004", 91, 89, 95, "已确认")
studentSu = Student("苏映雪", "2026005", 88, 92, 90, "已确认")
studentLu = Student("陆景行", "2026006", 79, 84, 87, "已确认")
allGradeRows = Column(0, 14, gradeRow(studentLin), gradeRow(studentChen), gradeRow(studentXu), gradeRow(studentZhou), gradeRow(studentSu), gradeRow(studentLu))
attentionGradeRows = Column(0, 14, gradeRow(studentLin))
gradeTable = Column(0, 0, allGradeRows)
gradeCenter = GradeCenter(gradeTable, allGradeRows, attentionGradeRows, studentLin, 1, "正在查看全部 6 位学生")
showAllGrades = Button("全部学生")
showAttentionGrades = Button("查看复核记录")
reviewGrade = Button("录入复核成绩")
resetGrades = Button("恢复示例数据")
showAllGrades.on("click", gradeCenter.showAll)
showAttentionGrades.on("click", gradeCenter.showAttention)
reviewGrade.on("click", gradeCenter.review)
resetGrades.on("click", gradeCenter.reset)
gradeHeader = Row(0, 0,
gradeCell(TextBlock("学生", 1, "#7A8390"), 150),
gradeCell(TextBlock("学号", 1, "#7A8390"), 120),
gradeCell(TextBlock("语文", 1, "#7A8390"), 100),
gradeCell(TextBlock("数学", 1, "#7A8390"), 100),
gradeCell(TextBlock("英语", 1, "#7A8390"), 100),
gradeCell(TextBlock("状态", 1, "#7A8390"), 160))
gradeSummary = Row(0, 40,
Column(0, 6, TextBlock("学生人数", 1, "#7A8390"), TextBlock("6", 2)),
Column(0, 6, TextBlock("考试科目", 1, "#7A8390"), TextBlock("3", 2)),
Column(0, 6, TextBlock("待复核", 1, "#7A8390"), ui.textOf(gradeCenter, "pending", 2)))
gradesPage = Page()
gradesPage.title = "学生成绩管理中心"
gradesPage.render(Column(32, 20,
TextBlock("学生成绩管理中心", 2, "#273444"),
TextBlock("高一(3)班 · 2026 秋季阶段测评 · 虚构示例数据", 1, "#7A8390"),
gradeSummary,
Row(0, 10, showAllGrades, showAttentionGrades, reviewGrade, resetGrades),
GradePanel(20, 16, gradeHeader, RectBlock(730, 1, 0, "#E5EAF0"), gradeTable),
ui.textOf(gradeCenter, "message", 1, "#526C83")))
+83
View File
@@ -0,0 +1,83 @@
// Paste the complete file into Console in Script mode, then Run.
// All numbers, progress values and activity entries below are demo data.
function metric(label: Text, value: Text, note: Text, color: Text): View {
return ui.column(0, 6,
ui.text(label, 1, "#637082"),
ui.text(value, 2, "#243047"),
ui.text(note, 1, "#637082"),
ui.rect(160, 4, 2, color)
)
}
function project(name: Text, state: Text, detail: Text, filled: Number, remaining: Number, color: Text): View {
let caption = ui.row(0, 12,
ui.text(name, 1, "#243047"),
ui.text(state, 1, color)
)
let progress = ui.row(0, 0,
ui.rect(filled, 6, 3, color),
ui.rect(remaining, 6, 3, "#E5EAF2")
)
return ui.column(0, 6,
caption,
ui.text(detail, 1, "#637082"),
progress
)
}
function activity(time: Text, title: Text, detail: Text, color: Text): View {
let dot = ui.column(0, 0, ui.spacer(7), ui.rect(6, 6, 3, color))
let stamp = ui.row(0, 8, dot, ui.text(time, 1, "#8490A0"))
return ui.column(0, 4,
stamp,
ui.text(title, 1, "#243047"),
ui.text(detail, 1, "#637082")
)
}
let heading = ui.column(0, 6,
ui.text("ENDOR STUDIO / WORKSPACE", 1, "#5263D6"),
ui.text("项目工作台", 2, "#243047"),
ui.text("把想法组织成对象,把对象组合成界面。", 1, "#637082")
)
let statistics = ui.row(0, 20,
metric("活跃任务", "24", "本周新增 6 项", "#6574E8"),
metric("已完成", "18", "持续推进中", "#299C82"),
metric("页面草稿", "08", "等待下一次灵感", "#D9A34A")
)
let projects = ui.column(0, 14,
ui.text("项目进度", 1, "#243047"),
project("Aster", "进行中", "语言解析 / 编译 / 执行", 240, 60, "#6574E8"),
project("Tessera", "构建中", "桌面界面 / 布局 / 开发工具", 186, 114, "#299C82"),
project("设计文档", "草稿", "Block / Page / 对象模型", 108, 192, "#D9A34A")
)
let timeline = ui.column(0, 14,
ui.text("最近活动", 1, "#243047"),
activity("10:24", "更新字体", "中英文混排预览", "#6574E8"),
activity("09:48", "组织界面", "用函数组合不同区块", "#299C82"),
activity("09:12", "记录想法", "准备下一版页面设计", "#D9A34A")
)
let body = ui.row(0, 20, projects, timeline)
let note = ui.row(0, 12,
ui.rect(4, 46, 2, "#6574E8"),
ui.column(0, 6,
ui.text("下一步:让对象参与交互", 1, "#243047"),
ui.text("当前展示为静态示例,进度条和活动记录均为演示数据。", 1, "#637082")
)
)
let page = ui.page()
page.render(ui.column(24, 20,
heading,
statistics,
ui.rect(520, 1, 0, "#DFE5EE"),
body,
note,
ui.text("DEMO DATA / 函数组合 / 中文字体 / 嵌套布局", 1, "#8490A0")
))
+56
View File
@@ -0,0 +1,56 @@
// A normal Endor UI tree rendered on a transformed plane in the 3D world.
class WorldActions {
view: Viewport3D
panel: Panel3D
canvas: CanvasViewport
function reset(self: WorldActions): Unit {
self.view.camera.x = 0
self.view.camera.y = 0.5
self.view.camera.z = 7
self.view.camera.targetX = 0
self.view.camera.targetY = 0
self.view.camera.targetZ = 0
}
function turn(self: WorldActions): Unit { self.panel.rotate(0, 15, 0) }
function fit(self: WorldActions): Unit { self.canvas.mounts().at(0).fitView() }
}
count = ui.state(0)
increment = Button("点击:世界里的真实按钮")
increment.onClick(count.increment)
card = Column(10, 6, TextBlock("CanvasViewport", 1), RectBlock(180, 26, 6, "#9CB8A8"))
card.boxWidth = 240
card.x = 10
card.y = 4
canvas = CanvasViewport(280, 80, Scene2D(card))
ui_root = Column(8, 8, TextBlock("世界空间 UI", 2), ui.textOf(count, "value", 2), increment, canvas)
ui_root.crossAlign = "stretch"
panel = Panel3D(4, 3, ui_root)
panel.uiWidth = 320
panel.uiHeight = 240
panel.x = -1.2
panel.rotationY = 15
cube = Box3D(1.4, 1.4, 1.4, "#7B9CB7")
cube.x = 2
cube.rotationY = 25
floor = Box3D(10, 0.08, 5, "#D8DEE6")
floor.y = -1.8
scene = Scene3D(panel, cube, floor, DirectionalLight(-1, -2, -3, "#FFFFFF", 0.9))
scene.ambient = 0.35
view = Viewport3D(960, 520, scene)
view.flex = 1
view.camera.y = 0.5
view.camera.z = 7
actions = WorldActions(view, panel, canvas)
reset = Button("重置摄像机")
reset.onClick(actions.reset)
turn = Button("转动 UI 面板")
turn.onClick(actions.turn)
fit = Button("适配面板内的画布")
fit.onClick(actions.fit)
body = Column(24, 16, TextBlock("UI → 3D 世界 → UI → Canvas", 2), view, Row(0, 12, reset, turn, fit), TextBlock("空白处左键拖动旋转 3D · 中键/空格平移 · 滚轮缩放\n面板里的按钮、文本、布局和画布都由同一份 Endor 对象驱动。"))
body.flex = 1
body.crossAlign = "stretch"
page = Page()
page.title = "世界空间 UI"
page.crossAlign = "stretch"
page.render(body)
+14 -9
View File
@@ -9,16 +9,21 @@ when official crates.io is unavailable. Defaults remain the official source.
The local bundle has identifier `com.entroia.tessera` and can be opened from Finder.
It is a development app, without a distribution signature or notarization.
The CI workflow only checks this script's shell syntax on Linux; native bundle
construction and window presentation are verified on macOS.
Check shell syntax with `sh -n scripts/build-macos-app.sh`; native bundle
construction and window presentation are verified locally on macOS.
Return to the [project guide](../README.md).
## Remote verification
## Local verification
[verify-ci.sh](verify-ci.sh) runs only on the Linux ces-control host. It builds the
source-independent [toolchain image](../Dockerfile.ci), mounts the checkout
read-only and retains Cargo downloads/build output in project-specific Docker
volumes. CI_CACHE_SCOPE selects main/manual or a PR cache namespace. It acquires
a host lock and removes its own container on interruption; cached volumes survive.
See [workflow details](../.gitea/workflows/README.md) for invalidation and triggers.
Build and validate with the native Rust toolchain. The project has no CI/CD
workflow or Docker build image. See the [validation commands](../README.md#validation)
for formatting, tests and Clippy; window behavior is checked in the running app.
## UML 文档渲染
`render-uml.mjs` 从 `docs/architecture/uml/*.puml` 在本地生成 SVG 和 PNG,输出到
`docs/architecture/uml/rendered/`。固定工具版本与运行步骤见
[UML 图册](../docs/architecture/uml/README.md#重新生成)。这些 Node 工具独立于应用依赖,
不需要 Java、原生 Graphviz 或远程渲染服务。
+4
View File
@@ -1,18 +1,22 @@
#!/bin/sh
# Native macOS build and app bundle. No Docker, mirror configuration, or tests.
set -eu
# 此入口只能在 macOS 使用;构建授权由调用方确认,脚本不自动执行测试或部署。
if [ "$(uname -s)" != Darwin ]; then
echo "Build this app bundle on macOS." >&2
exit 1
fi
cd "$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)"
# 锁定依赖并生成 release 可执行文件;附加参数原样交给 Cargo。
cargo build --release --locked "$@"
version=$(awk -F '"' '$1 ~ /^version[[:space:]]*=/ { print $2; exit }' Cargo.toml)
test -n "$version"
bundle="$(pwd)/target/release/Tessera.app"
mkdir -p "$bundle/Contents/MacOS"
# 先写临时文件再重命名,避免复制途中将半个二进制留作 bundle 的主程序。
cp target/release/tessera "$bundle/Contents/MacOS/tessera.new"
mv -f "$bundle/Contents/MacOS/tessera.new" "$bundle/Contents/MacOS/tessera"
# 生成最小 macOS bundle 元数据;应用名、入口与高分辨率标志供系统启动/显示使用。
cat > "$bundle/Contents/Info.plist.new" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/env node
// Documentation-only tool. Install pinned packages in a separate temporary directory;
// UML_RENDER_TOOLS points there. No app dependencies or remote rendering service.
import { createRequire } from 'node:module';
import { readFile, readdir, mkdir, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
const tools = process.env.UML_RENDER_TOOLS;
// 工具依赖放在独立目录,避免给应用运行依赖增加文档渲染包。
if (!tools) throw new Error('Set UML_RENDER_TOOLS to the documentation tool directory; see docs/architecture/uml/README.md');
const require = createRequire(path.join(path.resolve(tools), 'package.json'));
const { createCanvas } = require('@napi-rs/canvas');
const { DOMImplementation, XMLSerializer, DOMParser } = require('@xmldom/xmldom');
const sharp = require('sharp');
// PlantUML's official JS engine uses DOM construction and Canvas text metrics.
// Supply a real XML DOM and native Canvas metrics, not approximate text widths.
globalThis.PLANTUML_VIZ = require('@viz-js/viz');
globalThis.window = globalThis;
globalThis.XMLSerializer = XMLSerializer;
globalThis.DOMParser = DOMParser;
const document = new DOMImplementation().createDocument(null, 'root', null);
const element = document.createElement.bind(document);
const elementNS = document.createElementNS.bind(document);
function measurementCanvas() {
// PlantUML 的文本布局需要真实字体宽高,统一用本机 Canvas 测量而非固定字符宽度。
const canvas = createCanvas(1, 1);
const context = canvas.getContext('2d');
const measure = context.measureText.bind(context);
context.measureText = text => {
const metrics = measure(text);
// PlantUML uses this height for line spacing. Font-wide ascent/descent
// keeps adjacent class fields from colliding when glyphs lack descenders.
return {
...metrics,
width: metrics.width,
actualBoundingBoxAscent: metrics.fontBoundingBoxAscent || metrics.actualBoundingBoxAscent,
actualBoundingBoxDescent: metrics.fontBoundingBoxDescent || metrics.actualBoundingBoxDescent,
};
};
return canvas;
}
document.createElement = tag => tag === 'canvas' ? measurementCanvas() : element(tag);
document.createElementNS = (namespace, tag) => {
// 为无浏览器 DOM 补齐样式与 getBBox,满足官方渲染引擎的 SVG 文本布局需求。
const node = elementNS(namespace, tag);
node.style = {};
node.getBBox = () => {
const context = measurementCanvas().getContext('2d');
context.font = `${node.getAttribute('font-size') || 14}px ${node.getAttribute('font-family') || 'Arial'}`;
const metrics = context.measureText(node.textContent || '');
return {
width: metrics.width,
height: metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent,
x: 0,
y: -metrics.actualBoundingBoxAscent,
};
};
return node;
};
document.body = element('body');
document.documentElement.appendChild(document.body);
globalThis.document = document;
const { renderToString } = await import(pathToFileURL(require.resolve('@plantuml/core')));
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const source = path.join(root, 'docs/architecture/uml');
const output = path.join(source, 'rendered');
await mkdir(output, { recursive: true });
for (const filename of (await readdir(source)).filter(name => name.endsWith('.puml')).sort()) {
// 每张图独立渲染并检查错误文本;错误图不能被当作正常产物覆盖已有预览。
const text = await readFile(path.join(source, filename), 'utf8');
const rendered = await new Promise((resolve, reject) => renderToString(text.split('\n'), resolve, reject));
const xml = new DOMParser().parseFromString(rendered, 'image/svg+xml');
const labels = Array.from(xml.getElementsByTagName('text'), node => node.textContent).join('\n');
if (xml.documentElement.tagName !== 'svg' || /syntax error|error line|assumed diagram type|an error has occurr/i.test(labels)) {
throw new Error(`${filename}: renderer returned an error diagram\n${labels}`);
}
// Explicit opaque paper keeps arrows/labels legible in dark Markdown viewers.
const paper = xml.createElementNS('http://www.w3.org/2000/svg', 'rect');
for (const [key, value] of Object.entries({ x: '0', y: '0', width: '100%', height: '100%', fill: '#FFFFFF' })) paper.setAttribute(key, value);
xml.documentElement.insertBefore(paper, xml.documentElement.firstChild);
const svg = new XMLSerializer().serializeToString(xml);
// 同时保存可缩放 SVG 和通用 PNG;写完读取 PNG 元数据确认生成尺寸。
const stem = filename.slice(0, -5);
await writeFile(path.join(output, `${stem}.svg`), svg);
// High-resolution PNG is the universally visible Markdown preview; SVG keeps zoomable text.
const png = sharp(Buffer.from(svg), { density: 192 });
await png.png().toFile(path.join(output, `${stem}.png`));
const metadata = await sharp(path.join(output, `${stem}.png`)).metadata();
console.log(`${filename} -> SVG + PNG (${metadata.width}×${metadata.height})`);
}
-27
View File
@@ -1,27 +0,0 @@
#!/bin/sh
# Run only on the Linux CI host with Docker; never bake source into cache images.
set -eu
scope=${CI_CACHE_SCOPE:-manual}
case "$scope" in *[!a-zA-Z0-9_-]*|'') echo "Invalid cache scope" >&2; exit 1;; esac
root=$(pwd -P)
image=endorphin-tessera-gui-ci:rust-1.91.1
prefix=tessera-ci-rust-1-91-1-$scope
# Serialize access to each target directory, including manually started checks.
exec 9>"/tmp/$prefix.lock"
flock 9
sh -n scripts/build-macos-app.sh
# Empty context: only the toolchain and OS dependencies become image layers.
docker build -t "$image" - < Dockerfile.ci
name="$prefix-${GITHUB_RUN_ID:-$$}"
cleanup() { docker rm -f "$name" >/dev/null 2>&1 || true; }
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
docker run --name "$name" --rm --init \
--mount "type=bind,src=$root,dst=/build,readonly" \
--mount "type=volume,src=$prefix-target,dst=/cargo-target" \
--mount "type=volume,src=$prefix-registry,dst=/usr/local/cargo/registry" \
--mount "type=volume,src=$prefix-git,dst=/usr/local/cargo/git" \
"$image" &
run_pid=$!
wait "$run_pid"
+89 -252
View File
@@ -1,254 +1,91 @@
# Tessera source
# Tessera 源码导航
| Module | Responsibility |
本体代码已补充中文模块、类型、函数与关键流程注释;建议按[注释阅读索引和逐文件说明](../docs/code-comments.md)从启动、运行时发布和视觉协议依次阅读。
整体设计和当前进展从 [架构导览](../docs/architecture/README.md) 开始;本轮每个文件的迁移对应见 [逐文件清单](../docs/architecture/file-map.md)。
`main.rs` 只负责组合启动,并保留 crate 私有模块路径别名。五组目录仍在同一个 binary crate 中,不是严格单向分层。
| 目录 | 责任 |
| --- | --- |
| 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, 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, compiled source/call-graph effect query and rebinding coverage, 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/field/override checks with deferred typed public/native constructor signatures and split option/field preflight plus shared native arity intervals plus resolved types/unions/effects on methods, tab registry, stable-slot insertion, source-dispatched tab reorder/drop and callback registration checks, Page lifecycle/navigation, Event returns/effect bounds, intrinsic handler recognition and immutable frame extraction |
| binding.rs | Target-owned managed property bindings, weak Subscription tokens, zero-argument callback preflight, 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, typed method attribute validity and protocol function payload-version dependencies, reverse parent links and cached immutable visual derivation |
| mount.rs | Typed per-occurrence methods and nominal Bounds results, managed contexts, weak reverse links, ordered mount/unmount hooks, geometry and focus queries |
| events.rs | Bounded native input transport with kind-specific tab-drop/desktop-position metadata to the owning VM |
| event_dispatch.rs | Typed Event factory and managed Event/Subscription methods, weak Subscription tokens, Block-owned connections and occurrence-specific capture/target/bubble through a budgeted VM driver |
| protocols.rs | Register typed Visual/EventTarget/Children (including insert)/Presentable managed trait requirements, using canonical signatures and explicit native type declarations |
| presentation.rs | Per-window layout, Mount/focus/tab state and read dependencies; VM changes fan out before any view consumes work |
| io_tasks.rs | Lazy bounded file-provider pool, plain-data mailbox and cancellation leases without managed roots |
| tasks.rs | Typed Task/ui.after/ui.readText/ui.fetchText/result/error methods, 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, drag gaps/anchors/insertion markers and opaque published Page identities |
| window.rs | Typed native Window queries/effects, 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 and EXTENDED_ARG-aware same-frame repetition for layout, event and lifecycle work |
| source_layout.rs | Read-only source layout, repeated constraint/geometry solving with cycle detection, per-Mount measurement caches with subcall dependencies and actual scroll-viewport cross-axis constraints, viewport constraints, typed/slot validation, concrete intrinsic recognition and occurrence geometry |
| source_hit.rs | Read-only source/native pointer target selectors, reverse paint order, strict Bool results and matching press/release targets |
| source_paint.rs | Read-only source paint dispatch with concrete intrinsic recognition, shared VM budget, paired text-wrap bounds and checked command conversion and versioned object dependencies |
| native_visual.rs | Managed native visual protocol queries with resolved type/read-only signatures, occurrence validation, concrete implementation/operation identity, arranged-viewport child constraints, value conversion and bounded results |
| object_list.rs | Typed factory envelopes, read-only indexed access and traced results shared by Mount queries and visual protocol results |
| layout.rs | Shared native geometry/paint functions, iterative measurement/arrangement, stable occurrence IDs, measurement cache, solve-pass counters, geometry budgets and width-sensitive native text measurement |
| document.rs | Published source/AST/UI snapshot, revisions, invalidation, frame validation, single-line fault banner (full cause retained in Frame), validated optional text-wrap bounds and display commands |
| 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, 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, bounded wrapped text and color representation |
| geometry.rs | Native points and rectangles |
| software_renderer.rs | Software rasterization, per-text bounds and nested rectangular clipping for independently scrolling panes |
| text.rs | Shared system font discovery, shaping, real measurements, antialiased glyphs and bounded caches keyed by wrap width |
| README.md | Module map |
Aster is an independent source submodule pinned to the published managed type/native-call implementation. Language parsing, AST definitions,
compilation, bytecode and VM execution come from its libraries. Tessera implements
only host UI behavior and layout. No CLI, HTTP server or Docker process is needed
to execute Endor in the application.
A complete-PUT candidate owns the desktop and UI service roots, with dynamic
Block allocation through scoped NativeContext. Block -> Cell -> data and all
child/history/forwarding references are managed VM edges. Native functions declare
their captured owner edges. The bridge holds only weak diagnostic references to
allocated Blocks; the tab registry owns open Pages. Closing a tab releases that
edge, without destroying a still-referenced Page. Console retains the actual VM;
a successful complete PUT also retains its candidate as the active program, accessible from Console and native input. Failed PUT preserves the previous heap. Cleanup releases
globals/service roots, collects cycles and requires an empty VM. Window frames
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, 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/declared-field annotation checks, constructor side-effect prevention, native callback signature/pre-registration validation, shared field forwarding/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
advances, multiline height, fractional scaling, CJK fallback, grapheme-safe fitting,
antialiasing and transparency. A process-wide mutex keeps font discovery, shaping
and glyph caches shared between the worker's layout and window redraw. The
256-string/512-KiB source cache and 4096-glyph/32-MiB image cache are discarded
when their budgets are exceeded. See the [project guide](../README.md) for public behavior.
The expression endpoint deliberately uses Aster's Expression entry in a fresh VM;
it has no host UI, no history replay and no published document. API observation
notifies the window for accepted and completed requests, including failures. The
worker still owns source compilation and snapshot publication. Console sends real
loopback HTTP requests on a separate client thread and reports transport failures
through the native event loop. CloudSourceProvider is an optional host-side adapter,
not a cloud service. A future network adapter should deliver cached/asynchronous
results to the workspace rather than block the native event loop during I/O.
The [System UI library](system_ui/README.md) owns management control appearance and
interaction. It imports no Endor runtime or guest UI bridge; developer tools supply
typed actions and keep all execution/source behavior outside the widget layer.
Console sessions use `endor_host::ReplSession` on the same worker thread. Real VM
globals, live Blocks and `_` survive between inputs. Parse/compile precede execution;
only a successful input commits a pending mount or publishes changes to an existing mount.
Runtime-failed input can retain earlier completed bindings, but cannot publish its
pending render. Session budgets cover cumulative source/AST and live Block counts.
page.unmount releases current content; unreachable object cycles are reclaimed between inputs.
Explicit reset drops the VM. Successful PUT replaces it with the fresh program; failed PUT restores the displayed program’s event epoch. Code DELETE invalidates the context. Source snapshots carry annotated AST ranges for the
actual Console transcript; source history is never rerun to reconstruct memory.
The Aster pin includes independent Assignment syntax and generic opt-in assign_from support.
Live reference tests cover alias updates, nested mounts, cycle rejection, detached branch release and unmount/remount.
Stopped runtimes have a separate host-only secondary-window teardown path. It detaches
Mounts and releases window/Page roots without executing source lifecycle callbacks,
and does not resume the failed VM. Preserved old-generation pictures can be closed
without borrowing a new Console VM's same-number resource. Secondary viewport inputs
are filtered by their published runtime generation. Native window/surface failures
are returned to the host diagnostics rather than panicking the event loop; main
window initialization errors propagate to process exit. The stopped-window and
cross-generation regression sources are compiled, not locally executed.
Native visual scalar parameters live in the Block's managed property storage.
Snapshot extraction validates and reads those fields, and records exact property
invalidation keys. Payload kind values remain constructor defaults; drawing uses
the property projection. Binding refresh traverses the weak visual registry and
deduplicates forwarded content, including hidden objects. It records object-level
read versions and borrowed output values for equality without adding GC roots;
cache updates do not mutate the connection's business version. Target content
traces the compute function. Subscription tokens are weak and also support bindings.
All binding work settles before published frames; compute failure stops the VM.
The host registers Trait definitions through Aster's checked nominal capability
API. Source subclasses validate inherited method arity before class publication.
Presentable dispatch uses a generated validated bytecode continuation inside the
current call budget, passes the current managed Window, and validates a real
Block result before opening it. Native base visual methods and runtime result
checks remain the rendering boundary. Matching present names without an explicit
implementation keep the summary fallback and do not execute guest methods.
ScrollBlock keeps viewport dimensions in the managed Block properties and keeps
scroll offsets on Mounts. Layout measures content without a finite viewport bound;
a post-layout projection clamps offsets, translates descendants and intersects
ancestor clips before committing Mount geometry. It rebuilds native commands and
per-command clips; source painting preserves the same clip table. Input, focus
outlines and public hit queries consume this projection. Wheel transport carries
finite signed deltas, validates the frame/window/session, and invokes the actual
Mount.scrollBy method without changing guest focus. Mount requests mark a
per-window projection refresh; snapshots/caches never own business objects.
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.
NativeCallable implementations publish positional metadata, including internal layout/paint/hit/event continuations. The VM validates it before entering Rust. Event delivery uses the same source/native/bound arity query; binding and Task registration reject incompatible or unknown metadata before changing ownership. Native parameter/return types and effects remain checked by existing host boundaries rather than this count-only metadata.
Native TextBlock measurement and painting now share width-sensitive shaping. Column/Button cross-axis constraints feed both the native fast path and source base calls; direct base measurement also uses its supplied viewport. RenderCommand text has optional wrap_bounds, converted to a clipped WrappedText primitive. Source PaintCommand uses paired wrapWidth/wrapHeight and legacy text remains unwrapped when both are absent. Source-arranged dimensions now participate in repeated constraint solving; general flex allocation, resumable work and axis-specific ScrollBlock wrapping remain future work.
Layout convergence uses exact finite snapshots of constraints/sizes/bounds and source-selected limits. The same immutable driver loops within one shared VM budget, clears all provisional measurement geometry between passes and rejects nonconsecutive repeated states. Aster ReadAccess distinguishes annotation validation from normal reads; the bridge skips only validation-only Mount reads after independently validating the live Mount/owner context. Actual Mount reads remain volatile; all other recorded dependencies are retained.
ScrollBlock.axis is stored in its managed properties and projected into the visual snapshot. Axis-aware child constraints use constructor/clamped size for initial measurement and actual occurrence bounds after arrangement. Scroll projection clamps disabled offsets/limits; the same geometry feeds paint and input.
Container mainAlign projects from managed properties into UiNode and its shallow equality. Native arrangement receives the actual allocated Size, computes positive remaining main-axis space and keeps child sizes unchanged.
Block.flex is a nonnegative managed weight, default 0. In native containers, fixed children retain measured main-axis sizes; positive weights share the remaining allocated space after padding/gaps with zero basis. This does not request extra parent size. Actual allocated child bounds feed back into measurement before publication. Source arrangement overrides remain authoritative. The additional flexBasis, flexMin, flexMax and flexShrink attributes control bounded allocation and opt-in shrinking along the parent main axis; see the policy below.
Trees with positive flex weights use the settling driver even when all layout methods are native. This remeasures wrapping and ancestor geometry before publishing. Fast-path eligibility checks actual intrinsic implementations, rather than comparing against a mutable Block method table.
Flex main-axis policy: flexBasis is "auto" by default (zero basis when flex > 0, otherwise the first measured size of this occurrence in the current solve); a number supplies an explicit basis. flexMin defaults to 0, flexMax to 1000000, and flexShrink to 0. All numbers are finite/nonnegative and at most 1000000; flexMin must not exceed flexMax. The parent clamps bases to min/max, distributes positive space by flex, and redistributes space left after a maximum is reached. Deficits shrink by flexShrink times the original basis, freezing at minima. A fixed child can opt into shrink without growth. Unresolvable minimum overflow is preserved, and remaining positive space follows mainAlign. The policy applies to width in a Row and height in Column-like containers; these are not independent width/height bounds. Source arrange overrides remain authoritative. Preferred sizes are derived per occurrence and reset for each new solve, never shared through Block state. See examples/flex-constraints.endor. Layout continuation remains unfinished.
When an occurrence's cross-axis constraint changes during settling, its preferred main-axis size is invalidated and remeasured. Any obsolete native flex allocation on that axis is removed for the replacement measurement, so narrowing a nested Column can increase wrapped text height. Source arrange allocations remain explicit. Preferred-size presence and values participate in convergence/cycle detection.
The source layout driver now uses Aster's resumable read-only call API with a soft quantum of 256 instructions. Pauses retain the same VM frames, operand/local roots, return contracts and read tracking; total instruction/frame limits still apply across slices. ui.stats().layoutSlices counts slices in the most recent solve (native fast path: 1). The worker currently resumes Pending immediately after yielding its OS time slice. Parking the solve across worker turns, scheduling other work and handling newer inputs before completion are not implemented yet. Native callbacks are not preempted. Only the completed settled frame is published.
source_layout::start now returns either Complete(Draft) or Pending(Work). The host-owned Work retains the unpublished frame, derived runtime/cache snapshots, convergence plan and prepare root without borrowing caller frame/cache variables. Work::resume consumes the saved job and advances the same VM continuation; Work::cancel closes that continuation and releases the prepare root without merging a draft. A second start is rejected while any read-only execution is active. Every pending Work must be resumed or explicitly cancelled with its owning VM; dropping it is not cancellation. Synchronous ReplSession operations drain the same saved refresh state. Mount preparation/lifecycle cancellation and parking jobs in the execution worker remain unfinished.
UiBridge::begin_layout_frame/resume_layout_frame now expose PendingLayout around the source job. This bridge-level continuation also owns its target window, page snapshot, tab projection, viewport restoration and retained lifecycle hook root. Only the Complete branch projects scroll/focus, captures dependency versions, merges derived caches, commits Mount geometry and runs deferred hooks. Resume restores the saved window context, and failure releases hook roots. ReplSession uses this protocol through its saved refresh state. Viewport refresh supports cross-worker-turn scheduling and prepared-Mount rollback; callers must not drop a pending bridge layout as a substitute for cancellation.
ReplSession now owns a resumable RefreshWork containing window traversal, pending bridge layout, unpublished per-window documents and the cumulative refresh work budget. poll_refresh advances one refresh stage or VM quantum; only a complete stable pass replaces the session's full document map. Synchronous callers drain the same state machine. Failure stops the domain, releases any pending bridge work and preserves the externally published picture. refreshYields counts cooperative refresh returns, not wall-clock time. Only still-pending Mount preparation is rolled back; completed callbacks remain committed.
Viewport refresh now advances through ReplSession's saved refresh state on worker idle turns. A turn advances one traversal stage or a 256-instruction layout quantum; a pending job shortens the next worker wait to 1 ms. Tasks/window commands and document publication wait for complete refresh. ui.stats().refreshYields reports cooperative idle returns. Mutating requests wait across worker turns for the existing job, so they cannot run inside its read-only scope. Mutating requests are serialized; newer viewport targets coalesce by cancelling unpublished layout. Initial source execution remains atomic; its layout can park across worker turns. Explicit REPL/event refresh can park across worker turns. Idle tasks deliver at most one callback per turn and park subsequent layout; callbacks and individual native nodes remain atomic. Large intrinsic trees use the sliced driver; small intrinsic trees keep the fast path.
Runtime mutation entry points reject direct calls while refresh work is pending, before executing source or changing metadata; task polling defers. The API worker drains the saved refresh before accepting those mutations, keeping the runtime usable. Incremental refresh keeps the prior complete document map until a stable pass, including across window traversal boundaries where no VM read-only frame is currently active.
Mount preparation now has an explicit checkpoint that roots the previous dictionary, Mount payloads and metadata values. It can restore geometry/relations/registry after cancelling an unpublished layout, or release its roots after completion. Task cancellation moves from speculative preparation to immediately before the actual onUnmount callback, so cancelling preparation does not destroy the old occurrence's tasks.
Pending bridge layouts now retain a Mount checkpoint. cancel_layout_frame closes the VM continuation, restores the old Mount payloads/links/dictionary and marks the presentation dirty for a new solve; discarded lifecycle hooks do not run. Successful finalization releases checkpoint roots after callbacks. This restores speculative Mount preparation, not arbitrary application writes or already completed lifecycle callbacks.
New viewport targets now coalesce pending refresh work. The runtime cancels only an unfinished bridge layout, restores its Mount checkpoint, preserves completed per-window drafts/callback effects and restarts traversal with the latest viewport map. refreshRestarts counts target replacements; layoutCancels counts replacements that actually closed a pending VM layout. Unchanged targets resume the same job. A new external target resets its convergence budget; internal settling does not. Ordinary source/event mutations still serialize behind refresh rather than roll back application effects.
Cancellation checkpoints own explicit VM roots until restored or released. Initial presentations may have no mount dictionary; cancellation restores that absence too. Saved metadata values retain object-valued attributes. A pending refresh can restart while keeping already completed window drafts; no onMount/onUnmount callback is replayed merely because the viewport target changed. Mount-owned tasks are cancelled immediately before an actual onUnmount callback, never during abandoned preparation.
source_layout uses the same resumable node driver for trees over 64 occurrences even when measure/arrange are intrinsic. Small intrinsic trees retain LayoutRuntime::frame. The larger path keeps LayoutRuntime measurement caches and yields between node calls; structural extraction, bytecode preparation, a single node, settling and paint remain atomic.
Worker idle polls use ReplSession::poll_tasks_incremental with the current viewport map. Scheduler::poll accepts a checked 1..=64 work limit, counting both delivery and ineligible-task cancellation; idle uses one, synchronous compatibility uses 64. Once delivery begins layout, further tasks and window-command projection wait until the saved refresh completes. The viewport stamp allows cancellation of task-induced pending layout without repeating callback effects.
REPL and event mutations now have incremental refresh entry points. They execute source/callbacks once, retain scalar response metadata, then park layout with the current viewport target. While pending, mutation, command extraction and garbage collection wait; layout can be retargeted by a newer native size. Synchronous helpers remain for host regression coverage. Discarding a ReplSession explicitly cancels any still-pending bridge layout before the Candidate releases service/global roots. This does not preempt source/callback execution, structural preparation or paint.
The API worker now owns a pending HTTP request plus its scalar result while REPL/event layout is parked. It advances the layout with current native viewport targets and responds only after the stable full-window publication and command extraction. Later mutation requests remain queued; GET /code can observe the last complete publication. A newer accepted PUT invalidates queued inputs but lets the already-running owner settle before candidate construction, so failed replacement can preserve its consistent heap. DELETE revokes that owner and prevents late publication. This queue ordering does not roll back already-executed source effects.
Complete-source candidates now separate one-time compilation/source execution from initial layout. load_incremental owns the isolated VM while its first layout is pending; the current live VM stays separate. Cancellation uses the same Mount checkpoint/continuation cleanup as later refresh. Synchronous load helpers remain for host regression coverage. This does not slice parsing, compilation, mutating source execution, structural preparation or final command projection.
The API keeps the old runtime alongside a pending PUT candidate. Newer submissions cancel only the obsolete candidate; failures restore the published runtime's submission owner. Background epoch checks distinguish accepted replacements from DELETE revocation, so queued/superseded candidates do not destroy the previous live heap. Candidate resumption reads only the primary shell viewport, avoiding reuse of an old secondary window's dimensions for a new VM's resource with the same numeric ID. Success publishes the complete candidate document and commands together, then replaces the old runtime.
Source paint now uses a resumable read-only VM call with the same 256-instruction quantum and a cumulative 1,000,000-instruction budget. The pending job owns the unpublished frame, visual snapshot, decoded command buffer and prepare root. The refresh worker resumes paint before advancing to another window and publishes only the full stable window set. New viewport targets cancel unfinished paint, discard partial commands and force that window to refresh. Already completed layout/Mount geometry and lifecycle callbacks remain committed; cancelling paint does not replay or undo them. Failure/discard explicitly closes the read-only continuation and releases its roots. paintSlices reports the most recently completed paint solve (1 when the solve completes within its first quantum); paintCancels counts viewport replacements that closed pending paint. Layout checkpoint rollback remains limited to unfinished layout preparation. Native callback bodies, driver preparation, command decoding/projection and rasterization remain atomic.
Layout and paint drivers now prepare one occurrence at a time. Their fixed-size outer bytecode repeats on the same VM frame; a short-lived helper retains only the current call, its bounds/arguments and collector. The helper is released before the next occurrence. Layout keeps bottom-up measure, top-down arrange and the same settling loop. Paint advances even intrinsic method classification through VM quanta. The weak occurrence list and native scratch/output data remain proportional to the actual tree, but preparation no longer allocates managed callables/Bounds for the whole tree before the first slice. All helpers share the original read-only scope and cumulative instruction/frame limits. Weak-list copying, structural extraction, settling and final projection remain bounded atomic native work.
Presentation dependency diagnostics record a counter and the last invalidated object kind/identity and version transition. ui.stats exposes dependencyInvalidations and lastInvalidDependency without retaining the dependency or rendering its data. windowDependencyDiagnostics includes nonempty reasons from every window, prefixed by window identity. Snapshot replacement also records its last invalidating object/property or change-journal overflow, so cache invalidation can be distinguished from source layout/paint dependencies. These help distinguish expected input invalidation from repeated background refresh.
ui.readText(owner,key,path[,callback]) returns an owner-scoped Task and reads a regular UTF-8 file off the VM thread. Paths use native filesystem syntax; absolute paths are recommended. The optional callback takes zero arguments and must return Unit; it runs only on successful read and can use task.result(). Without a callback, poll status then read result from code. result() is available while a success callback is running or after completion (timers return Unit); error() returns an empty String or the provider/callback error. A provider failure marks the task failed and skips its callback without stopping the VM; a source callback failure still stops the shared domain. Owner/key replacement, explicit cancellation, close/reset/VM discard and GC drop the provider lease, remove queued completion and reject late delivery. In-progress OS reads may finish, but cannot deliver after cancellation. Only the owning VM worker updates managed results and rechecks owner/key identity. No VM handles enter provider threads beyond opaque weak identities.
The lazy shared pool has four threads and a 64-job queue. Each runtime permits 16 outstanding I/O requests (one temporary replacement reservation), and each read is capped at 1 MiB by metadata plus actual streaming length; non-regular files, non-UTF-8 data and over-limit content fail rather than truncate. These limits do not constitute a full filesystem sandbox. The provider returns text in the same managed Task, not a second application-state store. Task await is supported through ui.spawn; see the await contract below. See examples/async-file.endor; from REPL call reader.read("/absolute/path.txt") to update its actual TextBlock, even when that object is hidden but retained.
ui.fetchText(owner,key,url[,callback]) performs an asynchronous HTTP(S) GET using the same Task, owner/key replacement and success-only callback protocol as readText. Example: fetcher.fetch("http://127.0.0.1:4737/agent") after loading examples/async-network.endor. The example retains the complete result in fetcher.response and displays completion status; it does not put arbitrary network content into a TextBlock, whose own 16 KiB limit is independent of the provider limit. Only 2xx responses produce a UTF-8 result; HTTP failures, invalid UTF-8, oversize bodies and transport errors set status() to failed with error(). It verifies HTTPS certificates, follows at most five HTTP(S) redirects, has a 10-second connect and 30-second total transfer timeout (starting when a worker takes the request), and bounds decoded text to 1 MiB without truncation. URLs are limited to 8192 bytes and must not contain credentials or control characters. This GET API does not accept request bodies, custom headers or authentication.
The current transport uses a separate system curl process per request (/usr/bin/curl on Unix, curl.exe on Windows); missing or incompatible curl fails the Task. User curlrc and URL globbing are disabled; URL data is passed through escaped stdin configuration rather than command arguments. TLS and normal system proxy behavior remain enabled. Cancellation kills an active HTTP process immediately and the provider worker reaps it; the VM thread never waits for the process. All file and HTTP requests share the per-runtime 16-task limit and global four-worker/64-job queue. In-progress file reads remain cooperatively cancelled at delivery. Network access is not a security sandbox, and this is a text GET provider rather than a general HTTP client. Task await is supported through ui.spawn; see below.
ui.spawn(owner,key,function) creates an owner-scoped cooperative Task for a zero-argument function; its returned value is retained as the Task result. Each owning VM poll resumes at most a 256-instruction quantum per selected Task, rotates runnable tasks fairly, and retains source frames in an Aster-managed coroutine edge. Calls and writes may interleave between quanta; prior writes are not rolled back on cancellation or error. Pending/running Task replacement, owner closure, GC and reset release parked frames through the same managed graph. Native calls remain atomic and all quanta share the 128-frame/100000-instruction callback limit; a native entry may run during preparation. result() is unavailable until spawn completes. A source error still stops the shared runtime. See examples/cooperative-tasks.endor. Endor await expressions now suspend these calls on a Task without replaying the operand. See the await contract below.
Inside a function run by ui.spawn, `value = await task` waits for any timer/file/network/spawn Task and resumes at the same expression with its retained result. A source function may return a Number, String, managed Object or Unit; normal source annotations still apply. Task.result() and await share the result. `ui.sleep(owner,key,milliseconds)` creates a callback-free timer Task returning Unit. Plain calls/REPL can await an already completed Task; a pending await requires a coroutine and fails explicitly rather than blocking. There is no new async function declaration: ui.spawn explicitly schedules an ordinary Endor function. See examples/await-file.endor.
A waiting coroutine retains its evaluated operand and frames as managed edges; waiting performs no VM execution or active 1ms spin. Source side effects and IO initiation before await are not replayed. When the dependency completes, the owning VM worker resumes the waiter through the existing fair quantum scheduler. Cancelling/replacing/closing the waiter releases its frames and operand; it does not automatically cancel an independently owned or shared dependency. Dependency cancellation propagates cancellation to its waiters without running the remainder. An unhandled dependency failure becomes a source await error (with the original provider message), fails the waiter and follows the existing shared-runtime fault rule; provider failure alone still only fails its own Task. Self-await and cyclic Task waits fail explicitly. Read-only layout/paint cannot await. Waiting state is reported as running, while active() remains true; result() is unavailable until completion. These APIs do not introduce try/finally or change the existing exception model.
While a native tab drag is held over an overflow arrow area, the strip waits 350ms then reveals one hidden tab every 120ms, including in a compatible destination window. The preview scroll does not activate Pages or change business state. Drawing, hit testing and insertion gaps share the same transient visible range; release uses its full-order insertion index. Leaving the strip stops the timer; release, Escape, a new press or runtime generation change restores the normal active-tab-centered strip. A resize or changing tab count clamps the range. Native drag/mixed-DPI behavior still requires platform validation; application-exit cleanup is described below.
CI regression fixtures use the published frame's session identity for input,
current Endor statement boundaries/type names and the retained runtime's actual
layout/paint pipeline. Failed first Console rendering discards unpublished Page
registrations through host-only cleanup, preventing the next successful query
from silently opening a previously failed pending render. Earlier ordinary
bindings remain live; explicit page.render can subsequently publish the Page.
Application exit now uses a private VM-worker control channel, independent of HTTP queue capacity. Main native close and a managed primary Window.close request asynchronous cleanup; duplicate requests coalesce and mutation requests are rejected with 503 while exiting. An unpublished candidate/input refresh is cancelled without replay. The current VM cancels all Task entries, closes managed windows, detaches occurrences child-before-parent per window, and invokes normal onUnmount hooks once. It does not run layout/paint during shutdown. All windows are closed before hooks run; new windows and tasks are forbidden. A stopped/faulted VM detaches without source hooks; reset/discarded pictures cannot revive an old VM. A hook error aborts remaining source hooks, releases prepared hook roots, drops the VM and reports failure before native exit. Completed shutdown is acknowledged to the GUI, which then ends the event loop. An OS exit bypassing CloseRequested uses a five-second bounded final fallback; non-cooperative native calls remain atomic and force-kill/crash cannot guarantee notifications. Native stderr records the window/mount/task-entry counts and whether source hooks were enabled, or the cleanup error. See examples/exit-lifecycle.endor. Cross-platform exit/drag validation remains broader follow-up work.
Foreground REPL/events now retain a BeforeInput request while an existing idle layout/paint refresh advances one stage/quantum per worker turn. They execute their source only after that refresh settles, so mutations never enter its read-only scope. New task callbacks are not delivered ahead of this accepted input. Shutdown can cancel the waiting request with 503, and superseded submissions still return 409. Reset cancels/discards the old VM instead of synchronously draining its unpublished refresh. Source parsing/compilation and ordinary synchronous source/native calls remain atomic boundaries; this change removes the worker's synchronous pre-input refresh drain.
Source layout/paint now validate name-level read observations from Aster: each globals/builtins lookup records its text key and observed presence/value, while dictionary kind checks remain separate. Updating the REPL result `_` or another unread global no longer invalidates these frames solely because the whole globals dictionary version changed. Reading `_` still observes its value; adding a previously missing global correctly invalidates a builtin fallback. Ordinary native dictionary iteration/content reads retain whole-object version dependencies. Measurement cache hits replay their recorded observations into the outer solve; they do not drop dependencies merely because source execution was skipped. Cache observations contain borrowed handles (including object-valued names), add no GC roots, and never write comparison snapshots back into language objects. Invalid-name diagnostics report only identity/key, not captured values. General Block binding and other legacy readers keep their existing conservative object dependencies. See examples/global-dependencies.endor.
Source layout/paint and measurement caches exclude every presentation's private desktop identity, including the primary desktop captured by shared native visual methods. Per-window bookkeeping must not invalidate another window's source output. This exclusion does not cover managed Window objects, viewport input records, type definitions or business objects; their observed changes remain dependencies.
The gc-lifecycle example and endor_host regression combine a mounted Page/Block cycle, source measure/paint dependencies and an owner-scoped coroutine suspended on sleep. Closing the tab preserves a referenced Block's workflow; releasing the external Page/Task holders lets normal collection reclaim the cycle before the wait completes. Regression assertions check both the same-program object baseline and weak identities.
The API worker logs the submission identity once when a newly accepted input enters BeforeInput waiting. It omits source and runtime values, and resume quanta do not repeat it. This distinguishes cancellation of an accepted pre-input wait from cancellation of an unpublished candidate or a request still in the transport queue.
Property binding caches now consume synchronous precise ReadSet dependencies, replay validation through ObjectStore and exclude the same private presentation desktops as source layout/paint. Cached output equality still repairs a direct overwrite even when its compute dependencies are unchanged. ui.stats().bindingEvaluations counts computations in completed binding refreshes for this VM, including initial/hidden bindings, so unrelated REPL inputs can be checked without adding effects to read-only source compute functions.
| `shell/` | 原生工作区、窗口输入、标签、开发工具和独立宿主管理控件 |
| `runtime/` | 本机 API、串行 VM 执行、事件和异步任务 |
| `model/` | 托管对象、绑定、Mount、窗口语义、依赖与发布值 |
| `render/` | 几何、布局、source/native 视觉协议、绘制、命中、字体和软件渲染 |
| `bridge/` | Endor 类型/方法与宿主能力及展示刷新之间的连接 |
## shell
| 模块 | 职责 |
| --- | --- |
| [activity](shell/activity.rs) | 有界 HTTP 活动记录与允许的头部预览 |
| [app](shell/app.rs) | GUI 事件循环、窗口/viewport、输入与 chrome 调度 |
| [clipboard](shell/clipboard.rs) | 原生 UTF-8 剪贴板适配 |
| [developer_tools](shell/developer_tools.rs) | 四个工具 Page 的状态、焦点与管理交互协调 |
| [native_chrome](shell/native_chrome.rs) | macOS 原生按钮对齐和工具栏双击系统动作 |
| [sources](shell/sources.rs) | 默认断开的云文件 provider 接口及工作区 |
| [system_ui](shell/system_ui/mod.rs) | 独立宿主管理控件、交互和主题 |
| [tabs](shell/tabs.rs) | 页面注册表的不可变 ID、标题和当前选择投影 |
| [sidebar](shell/sidebar.rs) | 页面/开发工具入口、收起状态与最小宿主控制区 |
## runtime
| 模块 | 职责 |
| --- | --- |
| [api](runtime/api.rs) | HTTP 请求路由、队列、请求观察和响应;worker/指南拆为子模块 |
| [endor_host](runtime/endor_host.rs) | 候选/活跃 VM、编译执行、增量刷新、清理和诊断 |
| [endor_script](runtime/endor_script.rs) | 组织 Aster Script/Module 输入及原始源码范围 |
| [events](runtime/events.rs) | 原生输入的有界 loopback 传输 |
| [event_dispatch](runtime/event_dispatch.rs) | 托管事件、订阅和 capture/target/bubble 分发 |
| [io_tasks](runtime/io_tasks.rs) | 有界文件/HTTP provider、纯数据完成消息和取消 |
| [tasks](runtime/tasks.rs) | 托管 Task、owner/key 取消和协作任务调度 |
| [vm_sequence](runtime/vm_sequence.rs) | 共享 VM 调用序列及同帧迭代驱动 |
## model
| 模块 | 职责 |
| --- | --- |
| [binding](model/binding.rs) | 属性依赖、只读计算与托管绑定 |
| [block](model/block.rs) | Block/Cell/Data 语义、稳定子 slot 和共享赋值 |
| [document](model/document.rs) | NamespaceState、RenderDocument、Frame、发布校验与原生命令 |
| [mount](model/mount.rs) | 每次展示出现的托管上下文、生命周期及弱索引 |
| [object_list](model/object_list.rs) | 托管结果集合的类型封装与只读访问 |
| [presentation](model/presentation.rs) | 逐窗口布局、Mount、缓存、读依赖和失效状态 |
| [protocols](model/protocols.rs) | Visual/EventTarget/Children/Presentable 能力契约安装 |
| [snapshot](model/snapshot.rs) | 变化依赖和不可变视觉提取缓存 |
| [window](model/window.rs) | 托管 Window、Page registry、命令及生命周期 |
## render
| 模块 | 职责 |
| --- | --- |
| [display_list](render/display_list.rs) | 原生绘制原语和颜色 |
| [geometry](render/geometry.rs) | 点和矩形值 |
| [layout](render/layout.rs) | 原生测量、排列、出现几何及预算 |
| [native_visual](render/native_visual.rs) | 托管原生视觉协议、值转换和签名检查 |
| [scene](render/scene.rs) | 页面视角、可见裁剪、侧栏和开发工具画面合成 |
| [page](render/page.rs) | 四种页面空间、约束、平移缩放及正逆坐标变换 |
| [scroll](render/scroll.rs) | 逐 Mount 偏移、嵌套滚动和剪裁投影 |
| [software_renderer](render/software_renderer.rs) | 软件光栅化、抗锯齿覆盖和嵌套剪裁 |
| [source_hit](render/source_hit.rs) | 源/原生命中协议与匹配目标 |
| [source_layout](render/source_layout.rs) | 源 measure/arrange、约束、挂起工作和测量缓存 |
| [source_paint](render/source_paint.rs) | 源 paint 调用、受限命令转换和依赖 |
| [text](render/text.rs) | 系统字体、shaping、字形和测量缓存 |
## bridge
| 模块 | 职责 |
| --- | --- |
| [ui_bridge](bridge/ui_bridge.rs) | Endor 宿主类型、窗口展示会话、布局/绘制发布协调 |
## 主要入口和运行约束
- HTTP 路由:`runtime/api.rs`;worker:`runtime/api/worker.rs`;在线指南:`runtime/api/guide.rs`。
- Bridge 安装:`bridge/ui_bridge/bootstrap.rs`;Block 调用:`calls.rs`;签名:`signatures.rs`;不可变树:`tree.rs`。
- 默认页:`bridge/ui_bridge/start_page.endor`;Console/Sources/Network/Settings:`shell/developer_tools/`。
- 页面模式与宿主边界见 [页面空间说明](../docs/page-surfaces.md);相机输入:`bridge/ui_bridge/page_input.rs`。
- 现有 API 和宿主测试:`runtime/api/tests.rs`、`runtime/endor_host/tests.rs`;其他模块中也保留原单元测试。
VM 和托管根只由执行 worker 操作。原生窗口收到已发布值,不收到 ObjectRef。完整 PUT 成功才接替活跃程序;Console 保留实际 VM;失败和清理语义见架构文档。
当前开发与验证在本机使用原生 Rust 工具链完成:格式、现有测试、Clippy、原生构建和人工运行检查。CI/CD 工作流与 Docker 检查入口已移除;具体命令见 [项目验证说明](../README.md#validation)。历史验收记录只代表当时实际执行的检查。
-2277
View File
File diff suppressed because it is too large Load Diff
+4
View File
@@ -0,0 +1,4 @@
//! 语言桥接模块入口。集中导出 Endor 类型和宿主实现之间的适配层。
//!
// Module ownership follows the directory; crate-root aliases keep internal call sites stable.
pub(crate) mod ui_bridge;
File diff suppressed because it is too large Load Diff
+450
View File
@@ -0,0 +1,450 @@
//! 安装一次 VM 域需要的宿主类型、对象和方法。类型注册表是源代码调用原生能力的入口。
//! 先建立类型与桌面基础设施,再绑定构造器、视觉协议和开发工具工厂;返回的根负责保持这些对象存活。
//!
//! Allocate and connect the managed desktop, type tables and host globals.
use super::*;
/// 把本模块的类型、方法或能力注册到所属运行时上下文。
pub fn install(vm: &mut Vm, roots: &mut Vec<ObjectRef>) -> Result<UiBridge> {
let desktop = vm.new_object()?;
roots.push(desktop);
vm.set_attr(desktop, "viewport", Value::Nil)?;
let tabs = vm.new_dict()?;
roots.push(tabs);
vm.set_attr(desktop, "tabs", Value::Object(tabs))?;
let ui = vm.new_object()?;
roots.push(ui);
let session = Arc::new(Mutex::new(Session {
nodes: Vec::new(),
presentations: std::collections::BTreeMap::from([(
crate::window::MAIN_WINDOW,
crate::presentation::Presentation::new(desktop, tabs),
)]),
current: crate::window::MAIN_WINDOW,
master: desktop,
next_window: crate::window::MAIN_WINDOW,
next_mount: 0,
retired_commands: Vec::new(),
refresh_yields: 0,
refresh_restarts: 0,
layout_cancels: 0,
paint_cancels: 0,
paint_slices: 0,
binding_evaluations: 0,
exiting: false,
}));
let mut public_functions = Vec::new();
let mut factories = Vec::new();
for (name, operation) in [
("implement", Operation::Implement),
("implements", Operation::Implements),
("supports", Operation::Supports),
("isInstance", Operation::IsInstance),
("isSubtype", Operation::IsSubtype),
("open", Operation::OpenValue),
("text", Operation::Text),
("rect", Operation::Rect),
("spacer", Operation::Spacer),
("row", Operation::Row),
("column", Operation::Column),
("overlay", Operation::Overlay),
("scene2D", Operation::Scene2D),
("canvasViewport", Operation::CanvasViewport),
("camera2D", Operation::Camera2D),
("button", Operation::Button),
("page", Operation::Page),
("present", Operation::Present),
("state", Operation::State),
("textOf", Operation::TextOf),
("stats", Operation::Stats),
("viewport", Operation::Viewport),
("window", Operation::Window),
] {
let function = vm.allocate(ContextNativeFunction::new(
name,
Function {
signature: None,
operation,
owner: None,
session: session.clone(),
requested_type: None,
},
vec![desktop],
))?;
roots.push(function);
vm.set_attr(ui, name, Value::Object(function))?;
public_functions.push((name, function, operation));
}
let root_types = vm.bootstrap_types()?;
roots.extend([root_types.object, root_types.type_type]);
vm.set_attr(ui, "Object", Value::Object(root_types.object))?;
vm.set_attr(ui, "Type", Value::Object(root_types.type_type))?;
let mut definitions = vec![
("Object", root_types.object),
("Type", root_types.type_type),
];
for (name, base_name, constructor_name) in [
("Trait", "Object", None),
("Function", "Object", None),
("Block", "Object", None),
("ContainerBlock", "Block", None),
("TextBlock", "Block", Some("text")),
("RectBlock", "Block", Some("rect")),
("Spacer", "Block", Some("spacer")),
("ScrollBlock", "ContainerBlock", Some("scroll")),
("ScrollView", "ScrollBlock", Some("scroll")),
("Row", "ContainerBlock", Some("row")),
("Column", "ContainerBlock", Some("column")),
("Overlay", "ContainerBlock", Some("overlay")),
("Scene2D", "ContainerBlock", Some("scene2D")),
("CanvasViewport", "ContainerBlock", Some("canvasViewport")),
("Camera2D", "Object", Some("camera2D")),
("Vec3", "Object", Some("vec3")),
("Triangle3D", "Object", Some("triangle3D")),
("Geometry3D", "Object", Some("geometry3D")),
("Mesh3D", "Object", Some("mesh3D")),
("Box3D", "Mesh3D", Some("box3D")),
("Group3D", "Object", Some("group3D")),
("Scene3D", "Object", Some("scene3D")),
("DirectionalLight", "Object", Some("directionalLight")),
("PerspectiveCamera", "Object", Some("perspectiveCamera")),
("OrthographicCamera", "Object", Some("orthographicCamera")),
("OrbitController", "Object", Some("orbitController")),
("Viewport3D", "Block", Some("viewport3D")),
("Panel3D", "Object", Some("panel3D")),
("RayHit3D", "Object", None),
("Button", "ContainerBlock", Some("button")),
("Page", "ContainerBlock", Some("page")),
("Window", "Object", Some("window-create")),
("Mount", "Object", None),
("Event", "Object", Some("event")),
("Subscription", "Object", None),
("Task", "Object", None),
("ObjectList", "Object", Some("object-list")),
] {
let base = object(Some(&vm.get_attr(ui, base_name)?))?;
let constructor = match constructor_name {
Some("object-list") => {
let factory = vm.allocate(ContextNativeFunction::new(
"object-list",
crate::object_list::Constructor {
desktop,
signature: None,
},
vec![desktop],
))?;
roots.push(factory);
let function_type = object(Some(&vm.get_attr(ui, "Function")?))?;
vm.attach_type(factory, function_type)?;
TypeConstructor::NativeTyped(factory)
}
Some("event") => {
let factory = vm.allocate(ContextNativeFunction::new(
"event",
crate::event_dispatch::Constructor { signature: None },
vec![],
))?;
roots.push(factory);
let function_type = object(Some(&vm.get_attr(ui, "Function")?))?;
vm.attach_type(factory, function_type)?;
TypeConstructor::NativeTyped(factory)
}
Some(constructor_name) => {
let operation = match constructor_name {
"text" => Operation::Text,
"rect" => Operation::Rect,
"spacer" => Operation::Spacer,
"scroll" => Operation::Scroll,
"row" => Operation::Row,
"column" => Operation::Column,
"overlay" => Operation::Overlay,
"scene2D" => Operation::Scene2D,
"canvasViewport" => Operation::CanvasViewport,
"camera2D" => Operation::Camera2D,
"viewport3D" => Operation::Viewport3D,
"button" => Operation::Button,
"page" => Operation::Page,
"window-create" => Operation::NewWindow,
name => crate::scene3d_model::Constructor::from_function(name)
.map(Operation::SceneObject)
.ok_or(invalid("unknown native type allocator"))?,
};
let factory = vm.allocate(ContextNativeFunction::new(
constructor_name,
NativeFactory {
signature: None,
options: None,
operation,
session: session.clone(),
},
vec![desktop],
))?;
roots.push(factory);
let function_type = object(Some(&vm.get_attr(ui, "Function")?))?;
vm.attach_type(factory, function_type)?;
TypeConstructor::NativeTyped(factory)
}
None => TypeConstructor::Abstract,
};
if let (Some(tag), TypeConstructor::NativeTyped(factory)) = (constructor_name, constructor)
{
factories.push((tag, factory));
}
let definition = vm.new_type(name, base, constructor)?;
roots.push(definition);
vm.set_attr(ui, name, Value::Object(definition))?;
definitions.push((name, definition));
}
for (name, fields) in [
(
"Constraints",
vec!["minWidth", "minHeight", "maxWidth", "maxHeight"],
),
("MeasureResult", vec!["width", "height"]),
("Bounds", vec!["x", "y", "width", "height"]),
("Point", vec!["x", "y"]),
("Arrangement", vec!["children"]),
("DisplayList", vec!["commands"]),
("PaintCommand", vec![]),
("CameraGesture", vec![]),
] {
let fields = fields
.into_iter()
.map(|name| endor_core::ClassField {
name: name.into(),
type_name: if matches!(name, "children" | "commands") {
"Object"
} else {
"Number"
}
.into(),
})
.collect();
let definition = vm.new_class(
name,
root_types.object,
fields,
std::collections::BTreeMap::new(),
)?;
roots.push(definition);
vm.set_attr(ui, name, Value::Object(definition))?;
definitions.push((name, definition));
}
// The desktop owns the registry through ordinary traced attributes. The
// Rust session only borrows handles and adds no hidden lifetime roots.
let types = vm.new_dict()?;
roots.push(types);
for (name, definition) in definitions {
vm.dict_set(types, Value::Text(name.into()), Value::Object(definition))?;
}
vm.set_attr(desktop, "types", Value::Object(types))?;
vm.attach_type(desktop, root_types.object)?;
vm.attach_type(ui, root_types.object)?;
let function_type = object(Some(&vm.get_attr(ui, "Function")?))?;
vm.set_function_type(function_type)?;
vm.set_source_type_checks(true)?;
for (name, function, operation) in public_functions {
vm.replace_payload(
function,
ContextNativeFunction::new(
name,
Function {
signature: Some(operation_signature(vm.object_store(), desktop, operation)?),
operation,
owner: None,
session: session.clone(),
requested_type: None,
},
vec![desktop],
),
)?;
}
for (name, function) in factories {
let operation = match name {
"text" => Some(Operation::Text),
"rect" => Some(Operation::Rect),
"spacer" => Some(Operation::Spacer),
"scroll" => Some(Operation::Scroll),
"row" => Some(Operation::Row),
"column" => Some(Operation::Column),
"overlay" => Some(Operation::Overlay),
"scene2D" => Some(Operation::Scene2D),
"canvasViewport" => Some(Operation::CanvasViewport),
"camera2D" => Some(Operation::Camera2D),
"viewport3D" => Some(Operation::Viewport3D),
"button" => Some(Operation::Button),
"page" => Some(Operation::Page),
"window-create" => Some(Operation::NewWindow),
"event" | "object-list" => None,
name => Some(
crate::scene3d_model::Constructor::from_function(name)
.map(Operation::SceneObject)
.ok_or(invalid("unknown deferred factory"))?,
),
};
if let Some(operation) = operation {
let options = operation_signature(vm.object_store(), desktop, operation)?;
let envelope = CallSignature {
arity: endor_core::CallArity::range(options.arity.required + 1, usize::MAX),
parameters: vec![AnnotationType::Type.into()],
variadic: Some(AnnotationType::Any.into()),
returns: options.returns.clone(),
effect: options.effect,
};
let mut captures = vec![desktop];
captures.extend(options.references());
vm.replace_payload(
function,
ContextNativeFunction::new(
name,
NativeFactory {
signature: Some(envelope),
options: Some(options),
operation,
session: session.clone(),
},
captures,
),
)?;
} else {
let kind = if name == "event" {
"Event"
} else {
"ObjectList"
};
let signature = CallSignature {
arity: endor_core::CallArity::range(
if name == "event" { 2 } else { 1 },
usize::MAX,
),
parameters: if name == "event" {
vec![AnnotationType::Type.into(), AnnotationType::String.into()]
} else {
vec![AnnotationType::Type.into()]
},
variadic: Some(AnnotationType::Any.into()),
returns: AnnotationType::Nominal(desktop_type(vm.object_store(), kind, desktop)?)
.into(),
effect: CallEffect::ReadOnly,
};
if name == "event" {
vm.replace_payload(
function,
ContextNativeFunction::new(
name,
crate::event_dispatch::Constructor {
signature: Some(signature),
},
vec![],
),
)?;
} else {
vm.replace_payload(
function,
ContextNativeFunction::new(
name,
crate::object_list::Constructor {
desktop,
signature: Some(signature),
},
vec![desktop],
),
)?;
}
}
}
for name in [
"open",
"text",
"rect",
"spacer",
"row",
"column",
"button",
"page",
"present",
"state",
"textOf",
"stats",
"viewport",
"window",
"isInstance",
"isSubtype",
"implement",
"implements",
"supports",
] {
let function = object(Some(&vm.get_attr(ui, name)?))?;
vm.attach_type(function, function_type)?;
}
for (type_name, name, operation) in [
("Block", "bind", Operation::Bind),
("OrbitController", "update", Operation::CameraControl),
("Mesh3D", "translate", Operation::Translate3D),
("Group3D", "translate", Operation::Translate3D),
("Panel3D", "translate", Operation::Translate3D),
("PerspectiveCamera", "translate", Operation::Translate3D),
("OrthographicCamera", "translate", Operation::Translate3D),
("Mesh3D", "rotate", Operation::Rotate3D),
("Group3D", "rotate", Operation::Rotate3D),
("Panel3D", "rotate", Operation::Rotate3D),
("Block", "mounts", Operation::Mounts),
("Block", "invalidate", Operation::Invalidate),
("Block", "onClick", Operation::OnClick),
("Block", "on", Operation::On),
("Block", "dispatch", Operation::Dispatch),
("Block", "onEvent", Operation::OnEvent),
("Block", "onMount", Operation::OnMount),
("Block", "onUnmount", Operation::OnUnmount),
("Block", "click", Operation::Click),
("TextBlock", "setText", Operation::SetText),
("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),
("Page", "open", Operation::Open),
("Page", "window", Operation::PageWindow),
("Page", "close", Operation::Close),
("Page", "activate", Operation::Activate),
("Page", "navigate", Operation::Navigate),
("Page", "back", Operation::Back),
("Page", "forward", Operation::Forward),
] {
let expected = object(Some(&vm.get_attr(ui, type_name)?))?;
let method = vm.allocate(ContextNativeFunction::new(
name,
TypeMethod {
signature: method_signature(vm.object_store(), desktop, expected, operation)?,
operation,
expected,
session: session.clone(),
},
vec![expected, desktop],
))?;
roots.push(method);
vm.attach_type(method, function_type)?;
vm.define_method(expected, name, method)?;
}
crate::window::install(vm, roots, desktop, tabs)?;
let block_type = object(Some(&vm.get_attr(ui, "Block")?))?;
crate::native_visual::install(vm, roots, desktop, block_type, function_type)?;
let event_type = object(Some(&vm.get_attr(ui, "Event")?))?;
let token_type = object(Some(&vm.get_attr(ui, "Subscription")?))?;
crate::event_dispatch::install(vm, roots, event_type, token_type, function_type)?;
crate::protocols::install(vm, roots, desktop, ui)?;
let tasks = crate::tasks::install(vm, roots, ui, desktop)?;
developer_pages::install(vm, ui, &session)?;
let bridge = UiBridge { ui, session, tasks };
developer_pages::install_start_page(vm, &bridge)?;
Ok(bridge)
}
+889
View File
@@ -0,0 +1,889 @@
//! 把 Endor 方法调用分派到对应宿主操作。这里处理构造、树修改、绑定、状态与页面能力。
//! 先检查参数和只读阶段限制,再修改托管状态;对象引用的生命周期仍交给 NativeContext 和 Aster 管理。
//!
//! Native Block operations executed on the owning VM worker.
use super::*;
impl NativeCallable for Function {
/// 给出参数与返回值的托管类型契约;实际操作在 invoke 中执行。
fn signature(&self) -> Option<CallSignature> {
self.signature.clone()
}
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
fn arity(&self) -> Option<endor_core::CallArity> {
Some(self.operation.arity())
}
/// VM 调入本宿主能力的入口;按所属操作解码参数并返回托管值或后续调用。
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
use Operation::*;
let arity = self.operation.arity();
let (minimum, maximum) = (arity.required, arity.maximum);
if !(minimum..=maximum).contains(&args.len()) {
return Err(invalid("incorrect UI method argument count"));
}
if matches!(self.operation, Camera2D) {
let camera = new_camera2d(cx, &self.session, self.requested_type, args)?;
return Ok(NativeResult::Return(Value::Object(camera)));
}
if let SceneObject(kind) = self.operation {
let desktop = self
.session
.lock()
.map_err(|_| invalid("UI session poisoned"))?
.desktop;
let definition =
self.requested_type
.unwrap_or(desktop_type(cx.store(), kind.name(), desktop)?);
let object = crate::scene3d_model::allocate(cx, desktop, definition, kind, args)?;
return Ok(NativeResult::Return(Value::Object(object)));
}
if matches!(self.operation, CameraControl) {
crate::scene3d_model::control(
cx,
self.owner
.ok_or(invalid("controller requires a receiver"))?,
object(args.first())?,
object(args.get(1))?,
)?;
return Ok(NativeResult::Return(Value::Nil));
}
if matches!(self.operation, Translate3D | Rotate3D) {
crate::scene3d_model::transform(
cx,
self.owner
.ok_or(invalid("3D transform requires a receiver"))?,
args,
matches!(self.operation, Rotate3D),
)?;
return Ok(NativeResult::Return(Value::Nil));
}
if matches!(self.operation, Implement | Implements | Supports) {
let capability = object(args.get(1))?;
let value = match self.operation {
Implement => {
cx.implement_trait(object(args.first())?, capability)?;
Value::Nil
}
Implements => Value::Bool(
cx.store()
.implements_trait(object(args.first())?, capability)?,
),
Supports => {
// Validate the contract even for immediate scalar values.
cx.store()
.payload::<endor_core::EndorTraitObject>(capability, "Trait")?;
Value::Bool(match args[0] {
Value::Object(value) => cx.store().supports(value, capability)?,
_ => false,
})
}
_ => unreachable!(),
};
return Ok(NativeResult::Return(value));
}
if matches!(self.operation, IsInstance | IsSubtype) {
let candidate = object(args.first())?;
let expected = object(args.get(1))?;
let value = if matches!(self.operation, IsInstance) {
cx.store().is_instance(candidate, expected)?
} else {
cx.store().is_subtype(candidate, expected)?
};
return Ok(NativeResult::Return(Value::Bool(value)));
}
if matches!(self.operation, Invalidate) {
if cx.store().is_read_only() {
return Err(invalid(
"invalidation is forbidden during read-only rendering",
));
}
let reason = args
.first()
.map(|value| text(Some(value)))
.transpose()?
.unwrap_or_else(|| "layout".into());
if !matches!(reason.as_str(), "paint" | "layout" | "content") {
return Err(invalid(
"invalidation reason must be paint, layout or content",
));
}
let owner = self.owner.ok_or(invalid("invalidation requires a Block"))?;
let (data, _) = block::resolve(cx.store(), owner)?;
let mut session = self
.session
.lock()
.map_err(|_| invalid("UI session poisoned"))?;
let mut affected = std::collections::HashSet::new();
for weak in &session.nodes {
if let Some(block) = cx.upgrade(*weak)?
&& block::resolve(cx.store(), block)?.0 == data
{
affected.insert(block);
}
}
for presentation in session.presentations.values_mut() {
presentation.invalidate(cx, &affected, &reason)?;
}
return Ok(NativeResult::Return(Value::Nil));
}
if matches!(self.operation, Mounts) {
let owner = self.owner.ok_or(invalid("mount query requires a Block"))?;
let session = self
.session
.lock()
.map_err(|_| invalid("UI session poisoned"))?;
let mut positions = Vec::new();
for (window, presentation) in &session.presentations {
for (id, weak) in &presentation.mounts.active {
if let Some(object) = cx.upgrade(*weak)?
&& cx
.store()
.payload::<crate::mount::Mount>(object, "Mount")?
.block
== owner
{
positions.push((*window, *id, object));
}
}
}
positions.sort_unstable_by_key(|(window, id, _)| (*window, *id));
let set = crate::mount::collection(
cx,
positions.into_iter().map(|(_, _, object)| object).collect(),
session.desktop,
)?;
return Ok(NativeResult::Return(Value::Object(set)));
}
if matches!(self.operation, NewWindow) {
let mut state = self
.session
.lock()
.map_err(|_| invalid("UI session poisoned"))?;
let definition = self
.requested_type
.ok_or(invalid("Window constructor requires a type"))?;
let window = create_window(cx, &mut state, definition)?;
return Ok(NativeResult::Return(Value::Object(window)));
}
if matches!(self.operation, CloseWindow) {
let window = self
.owner
.ok_or(invalid("window close requires a receiver"))?;
let id = cx
.store()
.payload::<crate::window::ManagedWindow>(window, "Window")?
.id;
crate::window::close(cx, window)?;
let mut state = self
.session
.lock()
.map_err(|_| invalid("UI session poisoned"))?;
if let Some(view) = state.presentations.get_mut(&id) {
cx.set_attr(view.desktop, "pending", Value::Nil)?;
view.pending = Some(None);
view.force_frame = true;
view.closing = true;
}
return Ok(NativeResult::Return(Value::Nil));
}
if matches!(self.operation, Window) {
let desktop = self
.session
.lock()
.map_err(|_| invalid("UI session poisoned"))?
.desktop;
return Ok(NativeResult::Return(
cx.store().get_attr(desktop, "window")?,
));
}
if matches!(self.operation, Viewport) {
let desktop = self
.session
.lock()
.map_err(|_| invalid("UI session poisoned"))?
.desktop;
let Value::Object(input) = cx.store().get_attr(desktop, "viewport")? else {
return Err(invalid("window viewport is unavailable"));
};
let width = cx.store().get_attr(input, "width")?;
let height = cx.store().get_attr(input, "height")?;
return Ok(NativeResult::Return(Value::Object(
crate::native_visual::record(
cx,
desktop,
"MeasureResult",
vec![("width", width), ("height", height)],
)?,
)));
}
if matches!(self.operation, Stats) {
if cx.store().is_read_only() {
return Err(invalid(
"runtime statistics are unavailable during read-only rendering",
));
}
let session = self
.session
.lock()
.map_err(|_| invalid("UI session poisoned"))?;
let mut blocks = 0_i64;
let mut pages = 0_i64;
for weak in &session.nodes {
if let Some(object) = cx.upgrade(*weak)? {
blocks += 1;
if cx.store().payload::<block::Block>(object, "Block")?.page {
pages += 1;
}
}
}
let objects = cx.store().object_count() as i64;
let tabs = cx.store().dict_items(session.tabs)?.len() as i64;
let stats = cx.new_object()?;
for (name, value) in [
("objects", objects),
("blocks", blocks),
("pages", pages),
("tabs", tabs),
("mounts", session.mounts.active.len() as i64),
("snapshotVisited", session.snapshot_visited as i64),
("snapshotReused", session.snapshot_reused as i64),
("measured", session.layout.measured as i64),
("sourceMeasureHits", session.measure_cache.hits as i64),
("sourceMeasureMisses", session.measure_cache.misses as i64),
("arranged", session.layout.arranged as i64),
("layoutPasses", session.layout.settle_passes as i64),
("layoutSlices", session.layout.slices as i64),
("refreshYields", session.refresh_yields as i64),
("refreshRestarts", session.refresh_restarts as i64),
("layoutCancels", session.layout_cancels as i64),
("paintCancels", session.paint_cancels as i64),
("paintSlices", session.paint_slices as i64),
("bindingEvaluations", session.binding_evaluations as i64),
(
"dependencyInvalidations",
session.dependency_invalidations as i64,
),
] {
cx.set_attr(stats, name, Value::Number(value.into()))?;
}
cx.set_attr(
stats,
"lastInvalidDependency",
Value::Text(session.last_invalid_dependency.clone()),
)?;
cx.set_attr(
stats,
"windowDependencyDiagnostics",
Value::Text(
session
.presentations
.iter()
.filter(|(_, view)| !view.last_invalid_dependency.is_empty())
.map(|(id, view)| format!("{id}: {}", view.last_invalid_dependency))
.collect::<Vec<_>>()
.join("; "),
),
)?;
return Ok(NativeResult::Return(Value::Object(stats)));
}
if matches!(self.operation, State) {
let state = cx.new_object()?;
attach_named_type(cx, state, "Object", &self.session)?;
cx.set_attr(state, "value", args[0].clone())?;
bind(cx, state, "set", StateSet, &self.session)?;
bind(cx, state, "increment", Increment, &self.session)?;
return Ok(NativeResult::Return(Value::Object(state)));
}
if matches!(self.operation, StateSet | Increment) {
let owner = self.owner.ok_or(invalid("state method has no owner"))?;
let value = if matches!(self.operation, StateSet) {
args[0].clone()
} else {
let Value::Number(value) = cx.store().get_attr(owner, "value")? else {
return Err(invalid("increment requires an integer state"));
};
let next = value
.as_i64()
.and_then(|n| n.checked_add(1))
.ok_or(invalid("integer state increment exceeds its range"))?;
Value::Number(next.into())
};
cx.set_attr(owner, "value", value)?;
return Ok(NativeResult::Return(Value::Nil));
}
if matches!(self.operation, TextOf) {
let source = object(args.first())?;
let field = text(args.get(1))?;
cx.store().get_attr(source, &field)?;
let size = args
.get(2)
.map(|v| integer(Some(v)))
.transpose()?
.unwrap_or(1);
if !(1..=8).contains(&size) {
return Err(invalid("text size must be 1 through 8"));
}
let mut data = Data::new(
Kind::Text {
value: String::new(),
size: size as u32,
color: color(args.get(3), "#242422")?,
},
vec![],
0.0,
0.0,
);
data.text_binding = Some((source, field));
return Ok(NativeResult::Return(Value::Object(new_block(
cx,
data,
&self.session,
)?)));
}
let constructor = match self.operation {
Scroll => Some(Data::new(
Kind::Scroll {
width: dimension(args.first())?,
height: dimension(args.get(1))?,
},
vec![object(args.get(2))?],
0.0,
0.0,
)),
Text => Some(Data::new(
Kind::Text {
value: text(args.first())?,
size: args
.get(1)
.map(|v| integer(Some(v)))
.transpose()?
.unwrap_or(1)
.try_into()
.map_err(|_| invalid("text size exceeds limits"))?,
color: color(args.get(2), "#242422")?,
},
vec![],
0.0,
0.0,
)),
Rect => Some(Data::new(
Kind::Rect {
width: dimension(args.first())?,
height: dimension(args.get(1))?,
radius: args
.get(2)
.map(|v| dimension(Some(v)))
.transpose()?
.unwrap_or(0.0),
color: color(args.get(3), "#DCE8FF")?,
},
vec![],
0.0,
0.0,
)),
Spacer => Some(Data::new(
Kind::Spacer(dimension(args.first())?),
vec![],
0.0,
0.0,
)),
Row | Column | Overlay => Some(Data::new(
if matches!(self.operation, Row) {
Kind::Row
} else if matches!(self.operation, Overlay) {
Kind::Overlay
} else {
Kind::Column
},
args[2..]
.iter()
.map(|v| object(Some(v)))
.collect::<Result<_, _>>()?,
dimension(args.first())?,
dimension(args.get(1))?,
)),
Page => Some(Data::new(Kind::Page, vec![], 0.0, 0.0)),
Scene2D => Some(Data::new(
Kind::Scene2D,
args.iter()
.map(|value| object(Some(value)))
.collect::<Result<_, _>>()?,
0.0,
0.0,
)),
CanvasViewport => {
let mut data = Data::new(
Kind::CanvasViewport {
width: dimension(args.first())?,
height: dimension(args.get(1))?,
},
vec![object(args.get(2))?],
0.0,
0.0,
);
data.camera = Some(new_camera2d(cx, &self.session, None, &[])?);
Some(data)
}
Viewport3D => {
let desktop = self
.session
.lock()
.map_err(|_| invalid("UI session poisoned"))?
.desktop;
let definition = desktop_type(cx.store(), "PerspectiveCamera", desktop)?;
let camera = crate::scene3d_model::allocate(
cx,
desktop,
definition,
crate::scene3d_model::Constructor::Perspective,
&[],
)?;
let mut data = Data::new(
Kind::Viewport3D {
width: dimension(args.first())?,
height: dimension(args.get(1))?,
},
vec![],
0.,
0.,
);
data.camera = Some(camera);
data.scene3d = Some(object(args.get(2))?);
let definition = desktop_type(cx.store(), "OrbitController", desktop)?;
data.controller = Some(crate::scene3d_model::allocate(
cx,
desktop,
definition,
crate::scene3d_model::Constructor::Orbit,
&[],
)?);
Some(data)
}
Button => {
let label = new_block(
cx,
Data::new(
Kind::Text {
value: text(args.first())?,
size: 1,
color: "#243047".into(),
},
vec![],
0.0,
0.0,
),
&self.session,
)?;
Some(Data::new(Kind::Button, vec![label], 10.0, 0.0))
}
_ => None,
};
if let Some(data) = constructor {
if let Kind::Text { size, value, .. } = &data.kind
&& (!(1..=8).contains(size) || value.len() > 16_384)
{
return Err(invalid("text exceeds size limits"));
}
return Ok(NativeResult::Return(Value::Object(new_typed_block(
cx,
data,
&self.session,
self.requested_type,
)?)));
}
if matches!(self.operation, OpenValue | Present)
&& let Value::Object(value) = args[0]
{
let (desktop, current) = {
let state = self
.session
.lock()
.map_err(|_| invalid("UI session poisoned"))?;
(state.master, state.desktop)
};
let capability = desktop_type(cx.store(), "Presentable", desktop)?;
if !cx
.store()
.object(value)?
.payload()
.as_any()
.is::<block::Block>()
&& cx.store().supports(value, capability)?
{
let definition = cx
.store()
.type_of(value)?
.ok_or(invalid("untyped Presentable"))?;
let function = cx
.store()
.lookup_method(definition, "present")?
.ok_or(invalid("missing present method"))?;
let window = object(Some(&cx.store().get_attr(current, "window")?))?;
let complete = cx.allocate(ContextNativeFunction::new(
"validate presentation",
PresentResult {
open: matches!(self.operation, OpenValue),
session: self.session.clone(),
},
vec![desktop],
))?;
let instructions = [
endor_core::Instruction::new(endor_core::Opcode::LoadConst, 0),
endor_core::Instruction::simple(endor_core::Opcode::PushNull),
endor_core::Instruction::new(endor_core::Opcode::LoadConst, 1),
endor_core::Instruction::simple(endor_core::Opcode::PushNull),
endor_core::Instruction::new(endor_core::Opcode::LoadConst, 2),
endor_core::Instruction::new(endor_core::Opcode::LoadConst, 3),
endor_core::Instruction::new(endor_core::Opcode::Call, 2),
endor_core::Instruction::new(endor_core::Opcode::Call, 1),
endor_core::Instruction::simple(endor_core::Opcode::ReturnValue),
];
let code = endor_core::EndorCode::from_instructions(
&instructions,
vec![
Value::Object(complete),
Value::Object(function),
Value::Object(value),
Value::Object(window),
],
endor_core::CodeLayout::default(),
)?
.with_location("Presentable.present", "<tessera>", 1);
let code = cx.allocate(endor_core::EndorCodeObject::new(code))?;
let globals = cx.new_dict()?;
let driver = cx.new_function("Presentable.present", code, globals)?;
attach_desktop_type(cx, driver, "Function", desktop)?;
return Ok(NativeResult::Invoke {
function: driver,
arguments: vec![],
});
}
}
if matches!(self.operation, OpenValue) {
let root = present_value(cx, &args[0], &self.session)?;
let page = if cx.store().payload::<block::Block>(root, "Block")?.page {
root
} else {
new_block(
cx,
Data::new(Kind::Page, vec![root], 0.0, 0.0),
&self.session,
)?
};
show(cx, page, &self.session)?;
return Ok(NativeResult::Return(Value::Object(page)));
}
if matches!(self.operation, Present) {
return Ok(NativeResult::Return(Value::Object(present_value(
cx,
&args[0],
&self.session,
)?)));
}
let owner = self.owner.ok_or(invalid("method has no owner"))?;
if matches!(self.operation, Bind) {
let field = text(args.first())?;
let compute = object(args.get(1))?;
return Ok(NativeResult::Return(Value::Object(
crate::binding::connect(
cx,
owner,
&field,
compute,
self.session
.lock()
.map_err(|_| invalid("UI session poisoned"))?
.master,
)?,
)));
}
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;
match self.operation {
SetText => match &mut data.kind {
Kind::Text { value, .. } => {
let next = text(args.first())?;
if next.len() > 16_384 {
return Err(invalid("text exceeds 16 KiB"));
}
*value = next;
data.text_binding = None;
cx.set_attr(owner, "text", args[0].clone())?;
}
_ => return Err(invalid("setText requires a text Block")),
},
SetColor => match &mut data.kind {
Kind::Text { color: value, .. } | Kind::Rect { color: value, .. } => {
*value = color(args.first(), "#242422")?;
cx.set_attr(owner, "color", Value::Text(value.clone()))?;
}
_ => return Err(invalid("this Block has no color")),
},
Append | Insert | Remove | Replace | Move => {
if !data.is_container() {
return Err(invalid("expected a container Block"));
}
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)
.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())?;
let index = data
.children
.iter()
.position(|v| v.slot == slot)
.ok_or(invalid("child slot does not exist"))?;
match self.operation {
Remove => {
data.children.remove(index);
}
Replace => {
let child = object(args.get(1))?;
block::validate(cx.store(), child, Some(data_ref))?;
data.children[index].block = child;
}
Move => {
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"));
}
let child = data.children.remove(index);
data.children.insert(to, child);
}
_ => unreachable!(),
}
}
}
Children => {
let result = cx.new_dict()?;
for child in data.children {
cx.dict_set(
result,
Value::Text(child.slot.to_string()),
Value::Object(child.block),
)?;
}
return Ok(NativeResult::Return(Value::Object(result)));
}
Render | Navigate => {
if !matches!(data.kind, Kind::Page) {
return Err(invalid("expected a Page"));
}
let root = object(args.first())?;
block::validate(cx.store(), root, Some(data_ref))?;
if matches!(self.operation, Navigate) {
if data.history.is_empty() {
if let Some(old) = data.children.first() {
data.history.push(old.block);
}
} else {
data.history.truncate(data.history_index + 1);
}
data.history.push(root);
data.history_index = data.history.len() - 1;
}
data.children = vec![Child {
slot: 0,
block: root,
}];
data.next_slot = data.next_slot.max(1);
show(cx, owner, &self.session)?;
}
Back | Forward => {
if data.history.is_empty() {
return Ok(NativeResult::Return(Value::Nil));
}
let next = if matches!(self.operation, Back) {
data.history_index.saturating_sub(1)
} else {
(data.history_index + 1).min(data.history.len() - 1)
};
data.history_index = next;
data.children = vec![Child {
slot: 0,
block: data.history[next],
}];
show(cx, owner, &self.session)?;
}
Detach => {
let window = {
let mut state = self
.session
.lock()
.map_err(|_| invalid("UI session poisoned"))?;
let definition = desktop_type(cx.store(), "Window", state.master)?;
create_window(cx, &mut state, definition)?
};
show_in(cx, owner, &self.session, Some(window))?;
return Ok(NativeResult::Return(Value::Object(window)));
}
PageWindow => {
let state = self
.session
.lock()
.map_err(|_| invalid("UI session poisoned"))?;
let value = if let Some(id) = page_window(cx.store(), &state, owner)? {
cx.store()
.get_attr(state.presentations[&id].desktop, "window")?
} else {
Value::Nil
};
return Ok(NativeResult::Return(value));
}
Open | Activate | MoveWindow => {
if matches!(self.operation, MoveWindow)
&& matches!(args.first(), None | Some(Value::Nil))
{
return Err(invalid("Page.moveToWindow requires a Window"));
}
let target = match args.first() {
None | Some(Value::Nil) => None,
Some(value) => Some(object(Some(value))?),
};
show_in(cx, owner, &self.session, target)?;
return Ok(NativeResult::Return(Value::Object(owner)));
}
Unmount => {
data.children.clear();
}
Close => {
crate::tasks::cancel_owner(cx, owner)?;
let mut state = self
.session
.lock()
.map_err(|_| invalid("UI session poisoned"))?;
if let Some(id) = page_window(cx.store(), &state, owner)? {
// Closing the tab ends its presentation even if source
// reopens it before the next layout can detach the Mounts.
let page = cx.store().downgrade(owner)?;
for weak in state.presentations[&id].mounts.ordered() {
if let Some(mount) = cx.upgrade(weak)?
&& cx
.store()
.payload::<crate::mount::Mount>(mount, "Mount")?
.page
== Some(page)
{
crate::tasks::cancel_owner(cx, mount)?;
}
}
remove_page(
cx,
state
.presentations
.get_mut(&id)
.ok_or(invalid("missing window"))?,
owner,
)?;
}
return Ok(NativeResult::Return(Value::Nil));
}
OnClick => {
let handler = object(args.first())?;
crate::event_dispatch::validate_handler(cx.store(), handler)?;
data.click = Some(handler);
result = Value::Object(owner);
}
On => {
let kind = text(args.first())?;
if kind.is_empty() || kind.len() > 128 {
return Err(invalid("invalid event kind"));
}
let handler = object(args.get(1))?;
crate::event_dispatch::validate_handler(cx.store(), handler)?;
let capture = match args.get(2) {
None | Some(Value::Bool(false)) => false,
Some(Value::Bool(true)) => true,
Some(Value::Text(phase)) if phase == "capture" => true,
Some(Value::Text(phase)) if phase == "bubble" => false,
_ => return Err(invalid("phase must be capture or bubble")),
};
let mut active = Vec::new();
for token in &data.subscriptions {
if cx
.store()
.payload::<crate::event_dispatch::Connection>(*token, "Connection")?
.handler
.is_some()
{
active.push(*token);
}
}
if active.len() >= MAX_UI_NODES {
return Err(invalid("too many event subscriptions"));
}
let connection = cx.allocate(crate::event_dispatch::Connection {
kind,
handler: Some(handler),
capture,
})?;
let token = cx.allocate(crate::event_dispatch::Subscription {
connection: cx.store().downgrade(connection)?,
})?;
attach_named_type(cx, token, "Subscription", &self.session)?;
active.push(connection);
data.subscriptions = active;
result = Value::Object(token);
}
OnEvent | OnMount | OnUnmount => return Ok(NativeResult::Return(Value::Nil)),
Click | Dispatch => {
let desktop = self
.session
.lock()
.map_err(|_| invalid("UI session poisoned"))?
.desktop;
let (event, mount) = if matches!(self.operation, Click) {
let definition = desktop_type(cx.store(), "Event", desktop)?;
(
crate::event_dispatch::new_event(cx, definition, "click")?,
args.first(),
)
} else {
(object(args.first())?, args.get(1))
};
let mount = mount.map(|value| object(Some(value))).transpose()?;
return crate::event_dispatch::dispatch(cx, owner, event, mount, desktop);
}
_ => return Err(invalid("unsupported Block operation")),
}
cx.replace_payload(data_ref, data)?;
Ok(NativeResult::Return(result))
}
}
+128
View File
@@ -0,0 +1,128 @@
//! 把内置开发工具和起始页接入托管 Page。工厂在所属 VM 中编译和执行,而不是在窗口线程另建业务状态。
//!
//! Developer workspaces are managed Pages, using the same roots and placement API.
use super::*;
#[derive(Debug)]
/// 工具打开能力,保存所属会话和 ui 对象;调用时校验工具名,再在该 VM 中展示页面。
struct OpenTool {
session: Shared,
ui: ObjectRef,
}
impl NativeCallable for OpenTool {
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
fn arity(&self) -> Option<endor_core::CallArity> {
Some(endor_core::CallArity::exact(1))
}
/// VM 调入本宿主能力的入口;按所属操作解码参数并返回托管值或后续调用。
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
let [Value::Text(name)] = args else {
return Err(invalid("developerTools requires a tool name"));
};
if !["Console", "Sources", "Network", "Settings", "New tab"].contains(&name.as_str()) {
return Err(invalid("unknown developer tool"));
}
if name == "New tab" {
let factory = object(Some(&cx.store().get_attr(self.ui, "newTab")?))?;
return Ok(NativeResult::Invoke {
function: factory,
arguments: vec![],
});
}
let nodes = self
.session
.lock()
.map_err(|_| invalid("UI session poisoned"))?
.nodes
.clone();
for weak in nodes {
if let Some(page) = cx.upgrade(weak)?
&& cx.store().get_attr(page, "_tesseraTool").ok() == Some(Value::Text(name.clone()))
{
show(cx, page, &self.session)?;
let window = {
let state = self
.session
.lock()
.map_err(|_| invalid("UI session poisoned"))?;
let id = page_window(cx.store(), &state, page)?
.ok_or(invalid("tool is not open"))?;
object(Some(
&cx.store()
.get_attr(state.presentations[&id].desktop, "window")?,
))?
};
crate::window::enqueue(cx, window, crate::window::Action::Focus)?;
return Ok(NativeResult::Return(Value::Object(page)));
}
}
let page = new_typed_block(
cx,
Data::new(Kind::Page, vec![], 0.0, 0.0),
&self.session,
None,
)?;
cx.set_attr(page, "title", Value::Text(name.clone()))?;
cx.set_attr(page, "_tesseraTool", Value::Text(name.clone()))?;
show(cx, page, &self.session)?;
Ok(NativeResult::Return(Value::Object(page)))
}
}
/// 把本模块的类型、方法或能力注册到所属运行时上下文。
pub(super) fn install(vm: &mut Vm, ui: ObjectRef, session: &Shared) -> Result<()> {
let function = vm.allocate(ContextNativeFunction::new(
"developerTools",
OpenTool {
session: session.clone(),
ui,
},
vec![ui],
))?;
vm.set_attr(ui, "developerTools", Value::Object(function))?;
vm.release(function)?;
Ok(())
}
/// Compile the bundled Endor page once per VM, in a private module namespace.
/// Its functions/classes and callbacks remain ordinary managed VM objects.
/// 编译并安装 VM 私有的起始页工厂,供新页面动作重复调用。
pub(super) fn install_start_page(vm: &mut Vm, bridge: &UiBridge) -> Result<()> {
let source = frontend::EndorReader::from_text(
"tessera:start-page.endor",
include_str!("start_page.endor"),
);
let ast = frontend::parse_source_ast(&source, frontend::ParseMode::Module)?;
let compiled = compiler::compile_ast(
&ast,
&source,
&compiler::CompileOptions {
globals: std::iter::once("ui")
.chain(TYPE_NAMES.iter().copied())
.map(str::to_owned)
.collect(),
},
)
.map_err(|error| source.annotate(error))?;
let globals = vm.new_dict()?;
let result = (|| -> Result<()> {
bridge.install_globals(vm, globals)?;
let code = compiled.load(vm)?;
let value = vm.execute_with_limits(
code,
globals,
endor_core::ExecutionLimits {
max_frames: 128,
max_instructions: 100_000,
},
);
vm.release(code)?;
vm.release_value(value?)?;
let factory = vm
.dict_get(globals, &Value::Text("newTab".into()))?
.ok_or_else(|| anyhow::anyhow!("start page module requires newTab"))?;
vm.set_attr(bridge.ui, "newTab", factory)?;
Ok(())
})();
vm.release(globals)?;
result
}
+267
View File
@@ -0,0 +1,267 @@
//! 把页面、2D 视口和 3D 视口的相机输入转换成托管对象更新。
//! 输入携带具体出现的 Mount;嵌套世界 UI 先做逆投影,避免把屏幕位移直接当成场景坐标。
//!
//! Camera mutations run on the owning VM worker, just like other page input.
use super::*;
impl UiBridge {
/// 解码指定 3D 视口的旋转/平移/缩放输入,再调用其托管相机控制器。
pub(super) fn dispatch_scene_view(
&self,
vm: &mut Vm,
input: &crate::events::Input,
) -> Result<()> {
let (weak, desktop) = {
let state = self
.session
.lock()
.map_err(|_| anyhow::anyhow!("UI session poisoned"))?;
anyhow::ensure!(
state.published_version == input.layout_version,
"obsolete 3D camera view"
);
(
*state
.mounts
.active
.get(&input.mount)
.ok_or_else(|| anyhow::anyhow!("3D viewport unavailable"))?,
state.desktop,
)
};
let mount = vm
.upgrade(weak)?
.ok_or_else(|| anyhow::anyhow!("3D viewport Mount expired"))?;
let result = (|| {
let occurrence = vm.payload::<crate::mount::Mount>(mount, "Mount")?.clone();
anyhow::ensure!(
occurrence.mounted
&& occurrence.version == input.layout_version
&& occurrence.geometry.scene3d_viewport,
"obsolete 3D viewport"
);
let (_, data) = block::resolve(vm.object_store(), occurrence.block)?;
let data = block::visual_data(vm.object_store(), data)?;
let camera = data
.camera
.ok_or_else(|| anyhow::anyhow!("missing 3D camera"))?;
let controller = data
.controller
.ok_or_else(|| anyhow::anyhow!("3D controller disabled"))?;
let node = block::snapshot(vm.object_store(), occurrence.block)?;
let inset = crate::layout::insets(&node);
let geometry = &occurrence.geometry;
let outer = geometry.view.unwrap_or_default();
let delta = input
.delta
.ok_or_else(|| anyhow::anyhow!("3D camera delta required"))?;
let local_delta = if input.kind == "scene-zoom" {
[0., 0.]
} else {
let Some(delta) = geometry.logical_delta(input.point, delta) else {
return Ok(());
};
delta
};
let point = input
.point
.and_then(|p| geometry.view_point(crate::geometry::Point::new(p[0], p[1]), false))
.map(|p| outer.inverse(p))
.unwrap_or(crate::geometry::Point::new(
geometry.x + inset.left,
geometry.y + inset.top,
));
let gesture = vm.new_object()?;
let result = (|| {
vm.attach_type(
gesture,
desktop_type(vm.object_store(), "CameraGesture", desktop)?,
)?;
vm.set_attr(gesture, "kind", Value::Text(input.kind.clone()))?;
for (name, value) in [
("dx", local_delta[0]),
("dy", local_delta[1]),
("factor", delta[0]),
("width", (geometry.width - inset.horizontal()).max(0.)),
("height", (geometry.height - inset.vertical()).max(0.)),
("pointX", point.x - geometry.x - inset.left),
("pointY", point.y - geometry.y - inset.top),
] {
vm.set_attr(gesture, name, crate::native_visual::value(value))?;
}
let function = vm.bind_attr(controller, "update")?;
let result = match function {
Value::Object(function) => vm.call_with_limits(
function,
&[Value::Object(camera), Value::Object(gesture)],
endor_core::ExecutionLimits {
max_frames: 128,
max_instructions: 1_000_000,
},
),
_ => Err(invalid("controller.update is not callable")),
};
vm.release_value(function)?;
vm.release_value(result?)?;
Ok(())
})();
vm.release(gesture)?;
result
})();
vm.release(mount)?;
result
}
/// 把具体 CanvasViewport 的位移或缩放锚点映射到其显式 Camera2D。
pub(super) fn dispatch_viewport_view(
&self,
vm: &mut Vm,
input: &crate::events::Input,
) -> Result<()> {
let weak = {
let state = self
.session
.lock()
.map_err(|_| anyhow::anyhow!("UI session poisoned"))?;
anyhow::ensure!(
state.published_version == input.layout_version,
"obsolete viewport view"
);
*state
.mounts
.active
.get(&input.mount)
.ok_or_else(|| anyhow::anyhow!("viewport is no longer active"))?
};
let mount = vm
.upgrade(weak)?
.ok_or_else(|| anyhow::anyhow!("viewport Mount expired"))?;
let result = (|| {
let occurrence = vm.payload::<crate::mount::Mount>(mount, "Mount")?;
anyhow::ensure!(
occurrence.mounted
&& occurrence.version == input.layout_version
&& occurrence.geometry.canvas_viewport,
"obsolete viewport occurrence"
);
let geometry = occurrence.geometry.clone();
let block = occurrence.block;
let (_, data) = block::resolve(vm.object_store(), block)?;
let data = block::visual_data(vm.object_store(), data)?;
let camera = data
.camera
.ok_or_else(|| anyhow::anyhow!("viewport has no camera"))?;
let old = crate::viewport::camera(vm.object_store(), camera)?;
let delta = input
.delta
.ok_or_else(|| anyhow::anyhow!("viewport input has no delta"))?;
let (mut x, mut y, mut zoom) = (old.x, old.y, old.zoom);
if input.kind == "viewport-zoom" {
let pointer = input
.point
.ok_or_else(|| anyhow::anyhow!("zoom requires anchor"))?;
let pointer = crate::geometry::Point::new(pointer[0], pointer[1]);
anyhow::ensure!(
geometry.contains(pointer),
"zoom anchor is outside viewport"
);
let pointer = geometry
.logical_point(pointer)
.ok_or_else(|| anyhow::anyhow!("zoom anchor cannot be projected"))?;
let node = block::snapshot(vm.object_store(), block)?;
let inset = crate::layout::insets(&node);
let local = [
pointer.x - geometry.x - inset.left,
pointer.y - geometry.y - inset.top,
];
anyhow::ensure!(
local[0] >= 0.0
&& local[1] >= 0.0
&& local[0] < geometry.width - inset.horizontal()
&& local[1] < geometry.height - inset.vertical(),
"zoom anchor is outside content viewport"
);
zoom = (old.zoom * delta[0]).clamp(0.01, 100.0);
x += local[0] / old.zoom - local[0] / zoom;
y += local[1] / old.zoom - local[1] / zoom;
} else {
let Some(delta) = geometry.logical_delta(input.point, delta) else {
return Ok(());
};
x += delta[0] / zoom;
y += delta[1] / zoom;
}
x = x.clamp(-MAX_DIMENSION as f32, MAX_DIMENSION as f32);
y = y.clamp(-MAX_DIMENSION as f32, MAX_DIMENSION as f32);
vm.set_attr(camera, "x", crate::native_visual::value(x))?;
vm.set_attr(camera, "y", crate::native_visual::value(y))?;
vm.set_attr(camera, "zoom", crate::native_visual::value(zoom))?;
Ok(())
})();
vm.release(mount)?;
result
}
/// 处理旧 Page 模式的兼容相机事件;独立视口使用各自的输入路径。
pub(super) fn dispatch_page_view(
&self,
vm: &mut Vm,
input: &crate::events::Input,
) -> Result<()> {
let (page, mut surface, viewport) = {
let state = self
.session
.lock()
.map_err(|_| anyhow::anyhow!("UI session poisoned"))?;
anyhow::ensure!(
state.published_version == input.layout_version,
"obsolete page view"
);
(
state
.active
.ok_or_else(|| anyhow::anyhow!("no active Page"))?,
state.surface.clone(),
state.layout.viewport,
)
};
let delta = input
.delta
.ok_or_else(|| anyhow::anyhow!("page view requires delta"))?;
if input.kind == "page-zoom" {
anyhow::ensure!(
surface.mode == crate::page::Mode::Canvas,
"zoom requires canvas mode"
);
let pointer = input
.point
.ok_or_else(|| anyhow::anyhow!("zoom requires anchor"))?;
let pointer = crate::geometry::Point::new(pointer[0], pointer[1]);
anyhow::ensure!(
pointer.x >= 0.0
&& pointer.y >= 0.0
&& viewport.is_none_or(|v| pointer.x < v.width && pointer.y < v.height),
"zoom anchor is outside viewport"
);
let world = surface.to_world(pointer);
surface.zoom = (surface.zoom * delta[0]).clamp(0.1, 4.0);
surface.pan = crate::geometry::Point::new(
world.x - pointer.x / surface.zoom,
world.y - pointer.y / surface.zoom,
);
} else {
surface.pan.x += delta[0] / surface.zoom;
surface.pan.y += delta[1] / surface.zoom;
}
if let Some(viewport) = viewport {
surface.clamp(viewport);
}
let limit = MAX_DIMENSION as f32;
surface.pan.x = surface.pan.x.clamp(-limit, limit);
surface.pan.y = surface.pan.y.clamp(-limit, limit);
vm.set_attr(page, "panX", crate::native_visual::value(surface.pan.x))?;
vm.set_attr(page, "panY", crate::native_visual::value(surface.pan.y))?;
vm.set_attr(page, "zoom", crate::native_visual::value(surface.zoom))?;
Ok(())
}
}
+220
View File
@@ -0,0 +1,220 @@
//! 声明宿主方法在 Endor 类型系统中的参数和返回契约。
//! 签名用于构造/调用检查,应与 calls 和各 NativeCallable 实现保持一致;这里不执行实际业务操作。
//!
//! Canonical contracts for native Block methods and constructors.
use super::*;
/// 根据宿主方法类别提供 Endor 方法的签名,供类型与调用检查使用。
pub(super) fn method_signature(
store: &endor_core::ObjectStore,
desktop: ObjectRef,
receiver: ObjectRef,
operation: Operation,
) -> Result<CallSignature, VmError> {
use AnnotationType::{Any, Function, Nominal, Number, String as TextType, Unit};
use Operation::*;
let nominal = |name| desktop_type(store, name, desktop).map(Nominal);
let (arguments, returns, effect) = match operation {
Translate3D | Rotate3D => (vec![Number, Number, Number], Unit, CallEffect::Mutating),
CameraControl => (
vec![nominal("Object")?, nominal("CameraGesture")?],
Unit,
CallEffect::Mutating,
),
Bind => (
vec![TextType, Function],
nominal("Subscription")?,
CallEffect::Mutating,
),
Mounts => (vec![], nominal("ObjectList")?, CallEffect::ReadOnly),
Children => (vec![], Any, CallEffect::ReadOnly),
Invalidate => (vec![TextType], Unit, CallEffect::Mutating),
SetText | SetColor => (vec![TextType], Unit, CallEffect::Mutating),
Append => (vec![nominal("Block")?], Number, CallEffect::Mutating),
Insert => (
vec![Number, nominal("Block")?],
Number,
CallEffect::Mutating,
),
Remove => (vec![Number], Unit, CallEffect::Mutating),
Replace => (vec![Number, nominal("Block")?], Unit, CallEffect::Mutating),
Move => (vec![Number, Number], Unit, CallEffect::Mutating),
Render | Navigate => (vec![nominal("Block")?], Unit, CallEffect::Mutating),
OnClick => (vec![Function], Nominal(receiver), CallEffect::Mutating),
OnEvent => (vec![nominal("Event")?], Unit, CallEffect::External),
OnMount | OnUnmount => (vec![nominal("Mount")?], Unit, CallEffect::External),
Click => (
vec![nominal("Mount")?],
nominal("Event")?,
CallEffect::External,
),
Dispatch => (
vec![nominal("Event")?, nominal("Mount")?],
nominal("Event")?,
CallEffect::External,
),
MoveWindow => (
vec![nominal("Window")?],
Nominal(receiver),
CallEffect::Mutating,
),
MoveTab => (vec![Number], Nominal(receiver), CallEffect::Mutating),
Activate => (vec![], Nominal(receiver), CallEffect::Mutating),
Detach => (vec![], nominal("Window")?, CallEffect::Mutating),
Unmount | Close | CloseWindow | Back | Forward => (vec![], Unit, CallEffect::Mutating),
Open => (vec![Any], Nominal(receiver), CallEffect::Mutating),
PageWindow => (vec![], Any, CallEffect::ReadOnly),
On => (
vec![TextType, Function, Any],
nominal("Subscription")?,
CallEffect::Mutating,
),
_ => return Err(invalid("unsupported native method signature")),
};
let arity = operation.arity();
let mut parameters = vec![Nominal(receiver)];
parameters.extend(arguments);
let mut signature = CallSignature {
arity: endor_core::CallArity::range(arity.required + 1, arity.maximum + 1),
parameters: parameters.into_iter().map(CallType::from).collect(),
variadic: None,
returns: returns.into(),
effect,
};
match operation {
Open => signature.parameters[1] = CallType::nullable(nominal("Window")?),
PageWindow => signature.returns = CallType::nullable(nominal("Window")?),
On => signature.parameters[3] = CallType::Union(vec![AnnotationType::Bool, TextType]),
_ => {}
}
Ok(signature)
}
/// 将具体宿主 Operation 映射到参数/返回类型契约。
pub(super) fn operation_signature(
store: &endor_core::ObjectStore,
desktop: ObjectRef,
operation: Operation,
) -> Result<CallSignature, VmError> {
use AnnotationType::{Any, Bool, Number, String as TextType, Trait, Type, Unit};
use Operation::*;
let nominal = |name| desktop_type(store, name, desktop).map(AnnotationType::Nominal);
let (parameters, variadic, returns, effect) = match operation {
IsInstance => (vec![Any, Type], None, Bool, CallEffect::ReadOnly),
IsSubtype => (vec![Type, Type], None, Bool, CallEffect::ReadOnly),
Implement => (vec![Type, Trait], None, Unit, CallEffect::Mutating),
Implements => (vec![Type, Trait], None, Bool, CallEffect::ReadOnly),
Supports => (vec![Any, Trait], None, Bool, CallEffect::ReadOnly),
OpenValue => (vec![Any], None, nominal("Page")?, CallEffect::Mutating),
Present => (vec![Any], None, nominal("Block")?, CallEffect::Delegated),
State => (vec![Any], None, Any, CallEffect::ReadOnly),
StateSet => (vec![Any], None, Unit, CallEffect::Mutating),
Increment => (vec![], None, Unit, CallEffect::Mutating),
Stats => (vec![], None, Any, CallEffect::External),
Viewport => (
vec![],
None,
nominal("MeasureResult")?,
CallEffect::ReadOnly,
),
Window => (vec![], None, nominal("Window")?, CallEffect::ReadOnly),
NewWindow => (vec![], None, nominal("Window")?, CallEffect::Mutating),
TextOf => (
vec![Any, TextType, Number, TextType],
None,
nominal("TextBlock")?,
CallEffect::ReadOnly,
),
Text => (
vec![TextType, Number, TextType],
None,
nominal("TextBlock")?,
CallEffect::ReadOnly,
),
Rect => (
vec![Number, Number, Number, TextType],
None,
nominal("RectBlock")?,
CallEffect::ReadOnly,
),
Spacer => (vec![Number], None, nominal("Spacer")?, CallEffect::ReadOnly),
Scroll => (
vec![Number, Number, nominal("Block")?],
None,
nominal("ScrollBlock")?,
CallEffect::ReadOnly,
),
Row | Column | Overlay => (
vec![Number, Number],
Some(nominal("Block")?),
nominal(if matches!(operation, Row) {
"Row"
} else if matches!(operation, Overlay) {
"Overlay"
} else {
"Column"
})?,
CallEffect::ReadOnly,
),
Button => (
vec![TextType],
None,
nominal("Button")?,
CallEffect::ReadOnly,
),
Page => (vec![], None, nominal("Page")?, CallEffect::ReadOnly),
Viewport3D => (
vec![Number, Number, nominal("Scene3D")?],
None,
nominal("Viewport3D")?,
CallEffect::ReadOnly,
),
SceneObject(kind) => {
let parameters = kind
.parameters()
.iter()
.map(|name| match *name {
"Number" => Ok(Number),
"String" => Ok(TextType),
name => nominal(name),
})
.collect::<Result<Vec<_>, VmError>>()?;
(
parameters,
if kind.variadic() {
Some(nominal("Object")?)
} else {
None
},
nominal(kind.name())?,
CallEffect::ReadOnly,
)
}
Scene2D => (
vec![],
Some(nominal("Block")?),
nominal("Scene2D")?,
CallEffect::ReadOnly,
),
CanvasViewport => (
vec![Number, Number, nominal("Scene2D")?],
None,
nominal("CanvasViewport")?,
CallEffect::ReadOnly,
),
Camera2D => (
vec![Number, Number, Number],
None,
nominal("Camera2D")?,
CallEffect::ReadOnly,
),
_ => return Err(invalid("unsupported UI function signature")),
};
Ok(CallSignature {
arity: operation.arity(),
parameters: parameters.into_iter().map(CallType::from).collect(),
variadic: variadic.map(CallType::from),
returns: returns.into(),
effect,
})
}
+129
View File
@@ -0,0 +1,129 @@
// The page, cards and actions belong to Endor. The host only owns its sidebar.
// 默认页由真实 Endor 对象组成:宿主负责窗口和侧栏,卡片布局、绘制和按钮回调在源代码中定义。
// Note 复用 Column 的内容测量,但固定卡片宽度;paint 只提供背景,孩子仍沿正常树绘制。
class Note: Column {
tint: String
function measure(self: Note, mount: Mount, constraints: Constraints): MeasureResult {
measured = Column.measure(self, mount, constraints)
return MeasureResult(224, measured.height)
}
function paint(self: Note, mount: Mount, geometry: Bounds): DisplayList {
fill = PaintCommand()
fill.kind = "roundedRect"
fill.x = geometry.x
fill.y = geometry.y
fill.width = geometry.width
fill.height = geometry.height
fill.radius = 14
fill.color = self.tint
return DisplayList(ObjectList(fill))
}
}
class QuietButton: Button {
// 返回空绘制列表保留 Button 的交互能力,同时让这个入口只显示孩子文字。
function paint(self: QuietButton, mount: Mount, geometry: Bounds): DisplayList {
return DisplayList(ObjectList())
}
}
class StartActions {
// 保存起始页面身份,子页面中的返回按钮激活同一 Page,而不是复制一份页面。
home: Page
// 窗口页面是普通有限 Column;可用区域来自宿主发布的逻辑视口。
function blank(self: StartActions, event: Event): Unit {
page = Page()
page.title = "窗口页面"
back = Button("返回画布")
back.onClick(self.home.activate)
page.render(Column(56, 20, TextBlock("恰好一个窗口", 3), TextBlock("页面跟随可用区域调整。内容和工具栏由 Endor 自己组织。"), back))
}
// 延伸方向属于容器与滚动组合:Column 安排内容,有限 ScrollBlock 控制可见范围。
function vertical(self: StartActions, event: Event): Unit {
page = Page()
page.title = "纵向页面"
content = Column(48, 28, Column(0, 12, TextBlock("向下,继续生长", 3), TextBlock("纵向滚动和 Column 排版可以独立组合。")))
content.append(Note(24, 16, TextBlock("01 / 收集想法", 2), RectBlock(176, 130, 10, "#E2EADB"), TextBlock("从一个小小的念头开始。"), "#F0F3E9"))
content.append(Note(24, 16, TextBlock("02 / 连接片段", 2), RectBlock(176, 130, 10, "#E6DBEF"), TextBlock("内容保留在同一条连续的页面里。"), "#F4EEF7"))
content.append(Note(24, 16, TextBlock("03 / 慢慢展开", 2), RectBlock(176, 130, 10, "#EDDCC5"), TextBlock("追加一个子组件,内容自然延伸。"), "#FAF2E7"))
content.append(Note(24, 16, TextBlock("04 / 留一点空白", 2), TextBlock("不必把所有想法都放在第一屏。"), "#EDF1F6"))
view = ScrollBlock(1024, 800, content)
view.axis = "vertical"
view.flex = 1
page.crossAlign = "stretch"
page.render(view)
}
// Row 内可继续放 Column 卡片;横向滚动不要求改变 Page 的身份或生命周期。
function horizontal(self: StartActions, event: Event): Unit {
page = Page()
page.title = "横向页面"
content = Row(48, 32, Note(24, 16, TextBlock("从左,走向右", 2), RectBlock(176, 180, 10, "#DDE8F1"), TextBlock("Row 内仍然可以包含 Column。"), "#EDF3F8"))
content.append(Note(24, 16, TextBlock("收集", 2), RectBlock(176, 210, 10, "#D7E5DA"), TextBlock("一张卡片,一个想法。"), "#EFF4EC"))
content.append(Note(24, 16, TextBlock("整理", 2), RectBlock(176, 170, 10, "#E5D9EB"), TextBlock("横向滚动,保留思考的顺序。"), "#F4EFF7"))
content.append(Note(24, 16, TextBlock("继续", 2), RectBlock(176, 230, 10, "#EFDFC7"), TextBlock("Shift + 滚轮浏览更多内容。"), "#FAF3E8"))
content.append(Note(24, 16, TextBlock("不止一屏", 2), TextBlock("右侧仍有空间。"), "#EEF1F5"))
view = ScrollBlock(1024, 800, content)
view.axis = "horizontal"
view.flex = 1
page.crossAlign = "stretch"
page.render(view)
}
// 重新调用工厂得到独立页面与相机,已有画布继续保留自己的视角。
function canvas(self: StartActions, event: Event): Unit {
page = newTab()
}
// 两个文字绑定观察同一个状态对象,示范共享业务状态与多个展示位置的区别。
function counter(self: StartActions, event: Event): Unit {
count = ui.state(0)
add = Button("增加计数")
add.onClick(count.increment)
page = Page()
page.title = "共享对象"
page.render(Column(48, 24, TextBlock("一个对象,两个视图", 2), Row(0, 32, ui.textOf(count, "value", 3), ui.textOf(count, "value", 3)), add))
}
}
// 页面工厂:先建立业务对象/动作,再建立世界组成,最后用一个有限视口显示它。
function newTab(): Page {
page = Page()
page.title = "自由画布"
actions = StartActions(page)
fixed = Button("窗口页面")
vertical = Button("纵向延伸")
horizontal = Button("横向延伸")
canvas = Button("新的画布")
shared = QuietButton("试试:一个对象,两个视图 ↗")
fixed.on("click", actions.blank)
vertical.on("click", actions.vertical)
horizontal.on("click", actions.horizontal)
canvas.on("click", actions.canvas)
shared.on("click", actions.counter)
hero = Column(0, 16, TextBlock("给想法,一点空间。", 3, "#303941"), TextBlock("页面可以是一扇窗口,也可以一直延伸。", 1, "#7D858C"), Spacer(8), Row(0, 10, fixed, vertical), Row(0, 10, horizontal, canvas), shared)
// x/y 属于 Scene2D 子组件的世界位置;卡片内部依旧由普通 Row/Column 排版。
hero.x = 316
hero.y = 254
world = Scene2D(hero)
left = Note(24, 14, TextBlock("随手记下", 2), RectBlock(176, 100, 10, "#D5E4DA"), TextBlock("想法不必排成一条直线。"), "#EDF3E9")
left.x = 36
left.y = 92
world.append(left)
top = Note(24, 14, TextBlock("四种页面,同一个世界"), TextBlock("窗口 · 纵向 · 横向 · 自由画布", 1, "#7D858C"), "#EFF1F7")
top.x = 466
top.y = 58
world.append(top)
right = Note(24, 14, RectBlock(176, 138, 12, "#DDDAEA"), TextBlock("把片段放在一起", 2), TextBlock("布局属于组件,视角属于摄像机。"), "#F1EDF5")
right.x = 826
right.y = 190
world.append(right)
bottom = Note(24, 14, TextBlock("不止眼前这一屏", 2), TextBlock("触控板或滚轮平移\n空格拖动 / 鼠标中键拖动\n双指捏合 / ⌘ Ctrl + 滚轮缩放"), "#F7F0E5")
bottom.x = 104
bottom.y = 524
world.append(bottom)
end = Note(24, 14, TextBlock("继续向外探索", 2), RectBlock(176, 100, 10, "#CEDFE7"), TextBlock("画布上的对象仍是普通 Endor 组件。"), "#EAF1F5")
end.x = 716
end.y = 614
world.append(end)
// 视口参加有限布局并占用剩余空间;移动它的 Camera2D 不改写卡片世界位置。
view = CanvasViewport(1024, 800, world)
view.flex = 1
page.crossAlign = "stretch"
page.render(view)
return page
}
+275
View File
@@ -0,0 +1,275 @@
//! 定义从托管对象提取的不可变视觉树。共享业务对象可以有多次展示,树节点与 Mount 出现的身份不是同一概念。
//! 节点保存排版、绘制和协议投影信息;浅比较用于决定是否复用已有快照。
//!
//! Owned immutable visual derivation; no managed VM handles.
use std::sync::Arc;
#[derive(Debug, Clone, PartialEq)]
/// 不可变视觉节点。block_id 关联业务身份,slots 保留子项出现的稳定组成;kind 和盒模型字段用于派生排版与绘制。
pub struct UiNode {
// 只有页面根带兼容 Page 相机;其余字段是普通有限盒子的布局策略。
pub surface: Option<crate::page::Surface>,
pub flex: f32,
pub flex_policy: crate::layout::FlexPolicy,
pub main_align: crate::layout::MainAlign,
pub cross_align: crate::layout::CrossAlign,
pub align_self: Option<crate::layout::CrossAlign>,
pub margin: crate::layout::Insets,
pub sizing: crate::box_model::Sizing,
pub padding_edges: [Option<f32>; 4],
pub border: crate::layout::Insets,
pub border_color: String,
pub clip_children: bool,
// 这些字符串只是派生身份/协议版本键,不是可以操作托管堆的 ObjectRef。
pub block_id: String,
pub protocol_key: String,
// slot 保持组成身份;数组次序确定当前绘制/布局顺序,二者不是同一概念。
pub slots: Vec<u64>,
pub interactive: bool,
pub kind: UiKind,
}
impl UiNode {
/// 按节点种类返回其视觉子项;叶节点使用空切片,避免为遍历另建组成。
pub fn children(&self) -> &[Arc<UiNode>] {
match &self.kind {
UiKind::Column { children, .. }
| UiKind::Overlay { children, .. }
| UiKind::Canvas { children, .. }
| UiKind::Scene2D { children, .. }
| UiKind::CanvasViewport { children, .. }
| UiKind::Viewport3D { children, .. }
| UiKind::Row { children, .. }
| UiKind::Button { children, .. }
| UiKind::Scroll { children, .. } => children,
_ => &[],
}
}
/// 判断是否需要对子项执行弹性主轴分配。
pub fn has_flex(&self) -> bool {
self.flex > 0.0
|| self.flex_policy != crate::layout::FlexPolicy::default()
|| self.sizing.width == crate::box_model::Dimension::Fill
|| self.sizing.height == crate::box_model::Dimension::Fill
}
/// 判断当前节点是否会为子项指定实际分配范围,供源布局选择安排路径。
pub fn allocates_children(&self) -> bool {
self.children().iter().any(|child| {
child.has_flex()
|| child.align_self.unwrap_or(self.cross_align)
== crate::layout::CrossAlign::Stretch
})
}
/// 比较节点自身配置和直接子项身份,决定能否复用旧 Arc;不是深拷贝业务图。
pub fn shallow_eq(&self, other: &Self) -> bool {
if self.surface != other.surface
|| self.flex_policy != other.flex_policy
|| self.flex != other.flex
|| self.main_align != other.main_align
|| self.cross_align != other.cross_align
|| self.align_self != other.align_self
|| self.margin != other.margin
|| self.sizing != other.sizing
|| self.padding_edges != other.padding_edges
|| self.border != other.border
|| self.border_color != other.border_color
|| self.clip_children != other.clip_children
|| self.block_id != other.block_id
|| self.protocol_key != other.protocol_key
|| self.slots != other.slots
|| self.interactive != other.interactive
{
return false;
}
let same_children = || {
self.children().len() == other.children().len()
&& self
.children()
.iter()
.zip(other.children())
.all(|(a, b)| Arc::ptr_eq(a, b))
};
match (&self.kind, &other.kind) {
(
UiKind::Viewport3D {
width: a,
height: b,
view: c,
controls: g,
panels: i,
..
},
UiKind::Viewport3D {
width: d,
height: e,
view: f,
controls: h,
panels: j,
..
},
) => a == d && b == e && c == f && g == h && i == j && same_children(),
(
UiKind::CanvasViewport {
width: a,
height: b,
camera: c,
..
},
UiKind::CanvasViewport {
width: d,
height: e,
camera: f,
..
},
) => a == d && b == e && c == f && same_children(),
(UiKind::Scene2D { positions: a, .. }, UiKind::Scene2D { positions: b, .. }) => {
a == b && same_children()
}
(UiKind::Overlay { padding: a, .. }, UiKind::Overlay { padding: b, .. }) => {
a == b && same_children()
}
(UiKind::Canvas { positions: a, .. }, UiKind::Canvas { positions: b, .. }) => {
a == b && same_children()
}
(
UiKind::Text {
value: a,
size: sa,
color: ca,
},
UiKind::Text {
value: b,
size: sb,
color: cb,
},
) => a == b && sa == sb && ca == cb,
(
UiKind::Rect {
width: a,
height: b,
radius: c,
color: d,
},
UiKind::Rect {
width: e,
height: f,
radius: g,
color: h,
},
) => (a, b, c, d) == (e, f, g, h),
(UiKind::Spacer(a), UiKind::Spacer(b)) => a == b,
(
UiKind::Scroll {
axis: aa,
width: a,
height: b,
padding: pa,
gap: ga,
children: _,
},
UiKind::Scroll {
axis: ab,
width: c,
height: d,
padding: pb,
gap: gb,
children: _,
},
) => aa == ab && a == c && b == d && pa == pb && ga == gb && same_children(),
(
UiKind::Column {
padding: a, gap: b, ..
},
UiKind::Column {
padding: c, gap: d, ..
},
)
| (
UiKind::Row {
padding: a, gap: b, ..
},
UiKind::Row {
padding: c, gap: d, ..
},
)
| (
UiKind::Button {
padding: a, gap: b, ..
},
UiKind::Button {
padding: c, gap: d, ..
},
) => a == c && b == d && same_children(),
_ => false,
}
}
}
#[derive(Debug, Clone, PartialEq)]
/// 视觉内容的原生分类。叶节点保存绘制数据,容器保存子树,场景视口另外保存相机与世界投影。
pub enum UiKind {
Viewport3D {
width: f32,
height: f32,
view: Arc<crate::scene3d::View>,
controls: bool,
panels: Vec<crate::layout::Size>,
children: Vec<Arc<UiNode>>,
},
Scene2D {
positions: Vec<[f32; 2]>,
children: Vec<Arc<UiNode>>,
},
CanvasViewport {
width: f32,
height: f32,
camera: crate::viewport::CameraView,
children: Vec<Arc<UiNode>>,
},
Overlay {
padding: f32,
children: Vec<Arc<UiNode>>,
},
Canvas {
positions: Vec<[f32; 2]>,
children: Vec<Arc<UiNode>>,
},
Button {
padding: f32,
gap: f32,
children: Vec<Arc<UiNode>>,
},
Text {
value: String,
size: u32,
color: String,
},
Rect {
width: f32,
height: f32,
radius: f32,
color: String,
},
Column {
padding: f32,
gap: f32,
children: Vec<Arc<UiNode>>,
},
Row {
padding: f32,
gap: f32,
children: Vec<Arc<UiNode>>,
},
Spacer(f32),
Scroll {
axis: crate::scroll::Axis,
width: f32,
height: f32,
padding: f32,
gap: f32,
children: Vec<Arc<UiNode>>,
},
}
File diff suppressed because it is too large Load Diff
-98
View File
@@ -1,98 +0,0 @@
use crate::geometry::{Point, Rect};
use crate::text::TextStyle;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Color {
pub red: u8,
pub green: u8,
pub blue: u8,
pub alpha: u8,
}
impl Color {
pub const fn rgb(red: u8, green: u8, blue: u8) -> Self {
Self {
red,
green,
blue,
alpha: 255,
}
}
pub const fn rgba(red: u8, green: u8, blue: u8, alpha: u8) -> Self {
Self {
red,
green,
blue,
alpha,
}
}
}
#[derive(Clone, Debug)]
pub enum DrawCommand {
Clear(Color),
PushClip(Rect),
PopClip,
FillRoundedRect {
rect: Rect,
radius: f32,
color: Color,
},
StrokeRoundedRect {
rect: Rect,
radius: f32,
width: f32,
color: Color,
},
WrappedText {
rect: Rect,
value: String,
style: TextStyle,
color: Color,
},
Text {
origin: Point,
value: String,
style: TextStyle,
color: Color,
},
}
#[derive(Clone, Debug, Default)]
pub struct DisplayList {
commands: Vec<DrawCommand>,
}
impl DisplayList {
pub fn push(&mut self, command: DrawCommand) {
self.commands.push(command);
}
pub fn translate(&mut self, delta: Point) {
for command in &mut self.commands {
match command {
DrawCommand::WrappedText { rect, .. }
| 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
}
pub fn extend(&mut self, other: DisplayList) {
self.commands.extend(other.commands);
}
}
-7018
View File
File diff suppressed because it is too large Load Diff
-194
View File
@@ -1,194 +0,0 @@
//! Native input transport. Frame/mount identities and optional logical pointer positions cross to the VM worker.
use serde::{Deserialize, Serialize};
use std::{
io::{Read, Write},
net::TcpStream,
sync::mpsc::{SyncSender, sync_channel},
thread,
time::Duration,
};
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 {
#[serde(default = "default_window")]
pub window: u64,
pub session: u64,
pub layout_version: u64,
pub mount: u64,
pub kind: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub point: Option<[f32; 2]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub press_point: Option<[f32; 2]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub delta: Option<[f32; 2]>,
#[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 {
crate::window::MAIN_WINDOW
}
impl Input {
pub fn validate(&self) -> Result<(), &'static str> {
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))
if point
.iter()
.all(|v| v.is_finite() && (0.0..=1_000_000.0).contains(v))
&& delta
.iter()
.all(|v| v.is_finite() && v.abs() <= 1_000_000.0) =>
{
Ok(())
}
_ => Err("scroll requires point and finite delta, with no press_point"),
};
}
if self.delta.is_some() {
return Err("delta is only accepted for scroll input");
}
match (self.point, self.press_point) {
(None, None) => Ok(()),
(Some(point), Some(press))
if self.kind == "click"
&& point
.into_iter()
.chain(press)
.all(|value| value.is_finite() && (0.0..=1_000_000.0).contains(&value)) =>
{
Ok(())
}
_ => Err("pointer click requires finite press/release coordinates"),
}
}
}
pub struct Client(SyncSender<Input>);
impl Client {
pub fn new(proxy: EventLoopProxy<crate::app::AppEvent>) -> anyhow::Result<Self> {
let (sender, receiver) = sync_channel::<Input>(8);
thread::Builder::new()
.name("tessera-native-events".into())
.spawn(move || {
for input in receiver {
if let Err(error) = send(&input) {
let _ = proxy.send_event(crate::app::AppEvent::RuntimeFailed {
message: error.to_string(),
});
}
}
})?;
Ok(Self(sender))
}
pub fn send(&self, input: Input) -> bool {
self.0.try_send(input).is_ok()
}
}
fn send(input: &Input) -> anyhow::Result<()> {
let body = serde_json::to_string(input)?;
let mut stream =
TcpStream::connect_timeout(&crate::api::API_ADDRESS.parse()?, Duration::from_secs(2))?;
stream.set_read_timeout(Some(Duration::from_secs(10)))?;
stream.set_write_timeout(Some(Duration::from_secs(2)))?;
write!(
stream,
"POST /v1/namespaces/app.main/events HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
body.len(),
body
)?;
let mut response = String::new();
stream.take(32768).read_to_string(&mut response)?;
let status = response.split_whitespace().nth(1).unwrap_or("");
// An old frame's event is deliberately discarded, with no automatic retry.
if status == "409" {
return Ok(());
}
if status != "200" {
let body = response
.split_once("\r\n\r\n")
.map(|(_, body)| body)
.unwrap_or(&response);
anyhow::bail!(
"Native event failed: {}",
body.chars().take(1024).collect::<String>()
);
}
Ok(())
}
#[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 =
serde_json::from_str(r#"{"session":1,"layout_version":2,"mount":3,"kind":"focus"}"#)
.unwrap();
assert_eq!(input.window, crate::window::MAIN_WINDOW);
assert!(input.validate().is_ok());
input.window = 0;
assert!(input.validate().is_err());
}
}
-639
View File
@@ -1,639 +0,0 @@
//! Iterative measure/arrange/paint over derived visual data. Every occurrence
//! has its own geometry; measurement caches never become semantic object state.
use crate::{
document::{Frame, MountGeometry, RenderCommand},
text::{self, TextStyle},
ui_bridge::{MAX_DIMENSION, UiKind, UiNode},
};
use anyhow::{Context as _, Result, bail};
use std::collections::{HashMap, HashSet};
const MAX_LAYOUT_VISITS: usize = 10_000;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum MainAlign {
#[default]
Start,
Center,
End,
SpaceBetween,
}
impl MainAlign {
pub fn name(self) -> &'static str {
match self {
Self::Start => "start",
Self::Center => "center",
Self::End => "end",
Self::SpaceBetween => "space-between",
}
}
pub fn parse(value: &str) -> Result<Self, endor_core::VmError> {
match value {
"start" => Ok(Self::Start),
"center" => Ok(Self::Center),
"end" => Ok(Self::End),
"space-between" => Ok(Self::SpaceBetween),
_ => Err(endor_core::VmError::InvalidArgument(
"mainAlign expects start, center, end or space-between",
)),
}
}
}
/// Main-axis constraints interpreted independently by each parent occurrence.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FlexPolicy {
pub basis: Option<f32>,
pub min: f32,
pub max: f32,
pub shrink: f32,
}
impl Default for FlexPolicy {
fn default() -> Self {
Self {
basis: None,
min: 0.0,
max: MAX_DIMENSION as f32,
shrink: 0.0,
}
}
}
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct Size {
pub width: f32,
pub height: f32,
}
#[derive(Debug, Clone, PartialEq)]
enum Shape {
Text(String, u32, f32),
Rect(f32, f32),
Container(bool, f32, f32, Vec<Size>),
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
struct Key {
parent: Option<u64>,
slot: u64,
block: String,
}
#[derive(Debug, Clone, Default)]
pub struct LayoutRuntime {
sizes: HashMap<String, (Shape, Size)>,
ids: HashMap<Key, u64>,
next_id: u64,
pub version: u64,
pub measured: usize,
pub arranged: usize,
pub settle_passes: usize,
pub slices: usize,
pub viewport: Option<Size>,
}
struct Item<'a> {
node: &'a UiNode,
parent: Option<usize>,
children: Vec<usize>,
id: u64,
constraints: [f32; 4],
}
fn bounded(value: f32) -> Result<f32> {
if !value.is_finite() || !(0.0..=MAX_DIMENSION as f32).contains(&value) {
bail!("UI layout exceeds the 1000000 coordinate/size limit");
}
Ok(value)
}
pub fn root_constraints(viewport: Option<Size>) -> [f32; 4] {
let size = viewport.unwrap_or(Size {
width: MAX_DIMENSION as f32,
height: MAX_DIMENSION as f32,
});
[0.0, 0.0, size.width, size.height]
}
pub fn child_constraints(node: &UiNode, parent: [f32; 4]) -> [f32; 4] {
if let UiKind::Scroll { width, height, .. } = node.kind {
return arranged_child_constraints(
node,
parent,
constrained(Size { width, height }, parent),
);
}
match container(node) {
Some((true, padding, _)) => [
0.0,
0.0,
MAX_DIMENSION as f32,
(parent[3] - padding * 2.0).max(0.0),
],
Some((false, padding, _)) => [
0.0,
0.0,
(parent[2] - padding * 2.0).max(0.0),
MAX_DIMENSION as f32,
],
None => parent,
}
}
/// Scroll cross-axis constraints come from this occurrence's actual viewport,
/// including a source parent's allocation rather than only constructor size.
pub fn arranged_child_constraints(node: &UiNode, available: [f32; 4], bounds: Size) -> [f32; 4] {
if let UiKind::Scroll { padding, axis, .. } = node.kind {
return [
0.0,
0.0,
if axis.horizontal() {
MAX_DIMENSION as f32
} else {
(bounds.width - padding * 2.0).max(0.0)
},
if axis.vertical() {
MAX_DIMENSION as f32
} else {
(bounds.height - padding * 2.0).max(0.0)
},
];
}
child_constraints(node, available)
}
pub fn constrained(size: Size, constraints: [f32; 4]) -> Size {
Size {
width: size.width.clamp(constraints[0], constraints[2]),
height: size.height.clamp(constraints[1], constraints[3]),
}
}
fn container(node: &UiNode) -> Option<(bool, f32, f32)> {
match &node.kind {
UiKind::Row { padding, gap, .. } => Some((true, *padding, *gap)),
UiKind::Scroll { padding, gap, .. } => Some((false, *padding, *gap)),
UiKind::Column { padding, gap, .. } | UiKind::Button { padding, gap, .. } => {
Some((false, *padding, *gap))
}
_ => None,
}
}
pub fn main_axis(node: &UiNode) -> Option<usize> {
container(node).map(|(row, _, _)| usize::from(!row))
}
fn measure_shape(shape: &Shape) -> Result<Size> {
let size = match shape {
Shape::Text(value, size, width) => {
let style = TextStyle::ui(*size);
let intrinsic = text::measure(value, style);
let wrapped = text::measure_wrapped(value, style, *width);
Size {
width: intrinsic.width.min(*width),
height: wrapped.height,
}
}
Shape::Rect(width, height) => Size {
width: *width,
height: *height,
},
Shape::Container(row, padding, gap, children) => {
let along = children
.iter()
.map(|s| if *row { s.width } else { s.height })
.sum::<f32>()
+ padding * 2.0
+ gap * children.len().saturating_sub(1) as f32;
let cross = children
.iter()
.map(|s| if *row { s.height } else { s.width })
.fold(0.0_f32, f32::max)
+ padding * 2.0;
if *row {
Size {
width: along,
height: cross,
}
} else {
Size {
width: cross,
height: along,
}
}
}
};
bounded(size.width)?;
bounded(size.height)?;
Ok(size)
}
fn shape(node: &UiNode, children: Vec<Size>, constraints: [f32; 4]) -> Result<Shape> {
Ok(match &node.kind {
UiKind::Text { value, size, .. } => Shape::Text(value.clone(), *size, constraints[2]),
UiKind::Rect { width, height, .. } => Shape::Rect(*width, *height),
UiKind::Spacer(size) => Shape::Rect(*size, *size),
UiKind::Scroll { width, height, .. } => Shape::Rect(*width, *height),
_ => {
let (row, padding, gap) = container(node).context("unknown native visual protocol")?;
Shape::Container(row, padding, gap, children)
}
})
}
pub fn measure_native(node: &UiNode, children: Vec<Size>, constraints: [f32; 4]) -> Result<Size> {
measure_shape(&shape(node, children, constraints)?)
}
/// Private derived scratch space for one occurrence during layout. Contains no
/// managed references; source code cannot mutate it through heap attributes.
#[derive(Debug, Default)]
pub struct Context {
pub node: Option<std::sync::Arc<UiNode>>,
pub children: Vec<Size>,
pub preferred: Vec<Size>,
pub bounds: Option<[f32; 4]>,
}
pub fn paint_native(node: &UiNode, x: f32, y: f32, size: Size) -> Option<RenderCommand> {
let size_for_text = size;
match &node.kind {
UiKind::Text { value, size, color } => Some(RenderCommand::Text {
x,
y,
value: value.clone(),
size: *size,
color: color.clone(),
wrap_bounds: Some([size_for_text.width, size_for_text.height]),
}),
UiKind::Rect { radius, color, .. } => Some(RenderCommand::RoundedRect {
x,
y,
width: size.width,
height: size.height,
radius: *radius,
color: color.clone(),
}),
UiKind::Button { .. } => Some(RenderCommand::RoundedRect {
x,
y,
width: size.width,
height: size.height,
radius: 7.0,
color: "#E3EAF7".into(),
}),
_ => None,
}
}
/// Allocate main-axis space with bounded growth and basis-weighted shrinking.
/// Preferred sizes come from this occurrence's first measurement in the solve;
/// remeasurement must not turn a prior allocation into a new intrinsic basis.
pub fn flex_sizes(node: &UiNode, bounds: Size, children: &[Size], preferred: &[Size]) -> Vec<Size> {
let Some((row, padding, gap)) = container(node) else {
return children.to_vec();
};
let nodes = node.children();
if !nodes.iter().any(|child| child.has_flex()) {
return children.to_vec();
}
let space = ((if row { bounds.width } else { bounds.height }) as f64
- padding as f64 * 2.0
- gap as f64 * children.len().saturating_sub(1) as f64)
.max(0.0);
let bases: Vec<f64> = nodes
.iter()
.zip(preferred)
.map(|(child, size)| {
child.flex_policy.basis.unwrap_or_else(|| {
if child.flex > 0.0 {
0.0
} else if row {
size.width
} else {
size.height
}
}) as f64
})
.collect();
let mut sizes: Vec<f64> = nodes
.iter()
.zip(&bases)
.map(|(child, basis)| {
basis.clamp(child.flex_policy.min as f64, child.flex_policy.max as f64)
})
.collect();
let free = space - sizes.iter().sum::<f64>();
let growing = free > 0.0;
let weights: Vec<f64> = nodes
.iter()
.zip(&bases)
.map(|(child, basis)| {
if growing {
child.flex as f64
} else {
child.flex_policy.shrink as f64 * basis
}
})
.collect();
let limits: Vec<f64> = nodes
.iter()
.map(|child| {
if growing {
child.flex_policy.max as f64
} else {
child.flex_policy.min as f64
}
})
.collect();
let mut active: Vec<usize> = (0..nodes.len())
.filter(|&i| {
weights[i] > 0.0
&& if growing {
sizes[i] < limits[i]
} else {
sizes[i] > limits[i]
}
})
.collect();
let mut remaining = free.abs();
while remaining > 0.0 && !active.is_empty() {
let total = active.iter().map(|&i| weights[i]).sum::<f64>();
let mut spent = 0.0;
let mut saturated = false;
for &i in &active {
let capacity = (limits[i] - sizes[i]).abs();
let amount = (remaining * weights[i] / total).min(capacity);
sizes[i] += if growing { amount } else { -amount };
spent += amount;
saturated |= amount >= capacity;
}
remaining = (remaining - spent).max(0.0);
// Without saturation this round distributed all available space. Do not
// spin on floating point residue; a saturated round freezes a child.
if !saturated {
break;
}
active.retain(|&i| {
if growing {
sizes[i] < limits[i]
} else {
sizes[i] > limits[i]
}
});
}
let mut output = children.to_vec();
for (size, along) in output.iter_mut().zip(sizes) {
if row {
size.width = along as f32;
} else {
size.height = along as f32;
}
}
output
}
pub fn arrange_native(
node: &UiNode,
x: f32,
y: f32,
bounds: Size,
children: &[Size],
) -> Result<Vec<(f32, f32)>> {
let Some((row, padding, gap)) = container(node) else {
return Ok(vec![]);
};
let occupied = children
.iter()
.map(|child| if row { child.width } else { child.height })
.sum::<f32>()
+ gap * children.len().saturating_sub(1) as f32;
let available = if row { bounds.width } else { bounds.height };
let spare = (available - padding * 2.0 - occupied).max(0.0);
let offset = match node.main_align {
MainAlign::Center => spare / 2.0,
MainAlign::End => spare,
_ => 0.0,
};
let distributed_gap = if node.main_align == MainAlign::SpaceBetween && children.len() > 1 {
spare / (children.len() - 1) as f32
} else {
0.0
};
let mut cursor = padding + offset;
let mut points = Vec::with_capacity(children.len());
for child in children {
let point = if row {
(x + cursor, y + padding)
} else {
(x + padding, y + cursor)
};
bounded(point.0)?;
bounded(point.1)?;
bounded(point.0 + child.width)?;
bounded(point.1 + child.height)?;
points.push(point);
cursor += if row { child.width } else { child.height };
cursor += gap + distributed_gap;
}
Ok(points)
}
impl LayoutRuntime {
pub fn invalidate(&mut self, block: &str) {
self.sizes.remove(block);
}
pub fn reserve_identity_floor(&mut self, floor: u64) {
self.next_id = self.next_id.max(floor);
}
pub fn identity_high_watermark(&self) -> u64 {
self.next_id
}
pub fn clear_occurrences(&mut self) {
self.ids.clear();
}
pub fn frame(&mut self, root: &UiNode) -> Result<Frame> {
// Stage all cache/identity changes; a rejected frame leaves the last
// valid occurrence registry intact and never publishes partial geometry.
let mut next = self.clone();
let frame = next.build(root, false)?;
*self = next;
Ok(frame)
}
/// Allocate stable occurrence identities without measuring or publishing geometry.
pub fn structure(&mut self, root: &UiNode) -> Result<Frame> {
let mut next = self.clone();
let frame = next.build(root, true)?;
*self = next;
Ok(frame)
}
pub fn measure_node(
&mut self,
node: &UiNode,
children: Vec<Size>,
constraints: [f32; 4],
) -> Result<Size> {
let shape = shape(node, children, constraints)?;
if let Some((_, size)) = self
.sizes
.get(&node.block_id)
.filter(|(old, _)| *old == shape)
{
return Ok(*size);
}
self.measured += 1;
let size = measure_shape(&shape)?;
self.sizes.insert(node.block_id.clone(), (shape, size));
Ok(size)
}
fn build(&mut self, root: &UiNode, structural: bool) -> Result<Frame> {
self.measured = 0;
self.arranged = 0;
self.settle_passes = usize::from(!structural);
self.slices = usize::from(!structural);
let mut items = Vec::<Item<'_>>::new();
let mut work = vec![(root, None::<usize>, 0, root_constraints(self.viewport))];
let mut used = HashSet::new();
while let Some((node, parent, slot, constraints)) = work.pop() {
if items.len() >= MAX_LAYOUT_VISITS {
bail!("expanded UI layout exceeds 10000 nodes");
}
if node.slots.len() != node.children().len() {
bail!("invalid child slot table");
}
let key = Key {
parent: parent.map(|i| items[i].id),
slot,
block: node.block_id.clone(),
};
let id = if let Some(id) = self.ids.get(&key) {
*id
} else {
self.next_id = self
.next_id
.checked_add(1)
.context("Mount identity exhausted")?;
self.ids.insert(key.clone(), self.next_id);
self.next_id
};
if !used.insert(key) {
bail!("duplicate child slot in one presentation");
}
let index = items.len();
if let Some(parent) = parent {
items[parent].children.push(index);
}
items.push(Item {
node,
parent,
children: vec![],
id,
constraints,
});
for (child, slot) in node.children().iter().zip(&node.slots).rev() {
work.push((
child.as_ref(),
Some(index),
*slot,
child_constraints(node, constraints),
));
}
}
let mut sizes = vec![Size::default(); items.len()];
if !structural {
for (index, item) in items.iter().enumerate().rev() {
sizes[index] = constrained(
self.measure_node(
item.node,
item.children.iter().map(|i| sizes[*i]).collect(),
item.constraints,
)?,
item.constraints,
);
}
}
let mut points = vec![(0.0_f32, 0.0_f32); items.len()];
let mut mounts = Vec::with_capacity(items.len());
let mut commands = Vec::new();
let mut siblings = vec![None; items.len()];
for item in &items {
for pair in item.children.windows(2) {
siblings[pair[0]] = Some(items[pair[1]].id);
}
}
for (index, item) in items.iter().enumerate() {
self.arranged += usize::from(!structural);
let (x, y) = points[index];
let size = sizes[index];
bounded(x)?;
bounded(y)?;
bounded(x + size.width)?;
bounded(y + size.height)?;
mounts.push(MountGeometry {
id: item.id,
clip: None,
scroll: None,
block_id: item.node.block_id.clone(),
parent: item.parent.map(|i| items[i].id),
first_child: item.children.first().map(|i| items[*i].id),
next_sibling: siblings[index],
x,
y,
width: size.width,
height: size.height,
interactive: item.node.interactive,
});
if !structural && let Some(command) = paint_native(item.node, x, y, size) {
commands.push(command);
}
if structural {
continue;
}
let child_sizes: Vec<_> = item.children.iter().map(|child| sizes[*child]).collect();
let child_sizes = flex_sizes(item.node, size, &child_sizes, &child_sizes);
for (child, allocated) in item.children.iter().zip(&child_sizes) {
sizes[*child] = *allocated;
}
for (child, point) in
item.children
.iter()
.zip(arrange_native(item.node, x, y, size, &child_sizes)?)
{
points[*child] = point;
}
}
self.ids.retain(|key, _| used.contains(key));
let blocks: HashSet<_> = items
.iter()
.map(|item| item.node.block_id.as_str())
.collect();
self.sizes
.retain(|block, _| blocks.contains(block.as_str()));
self.version = self
.version
.checked_add(1)
.context("layout version exhausted")?;
Ok(Frame {
commands,
mounts,
layout_version: self.version,
..Frame::default()
})
}
}
pub fn frame(root: &UiNode) -> Result<Frame> {
LayoutRuntime::default().frame(root)
}
pub fn frame_with_viewport(root: &UiNode, viewport: Size) -> Result<Frame> {
LayoutRuntime {
viewport: Some(viewport),
..Default::default()
}
.frame(root)
}
+32 -36
View File
@@ -1,39 +1,31 @@
mod activity;
mod api;
mod app;
mod binding;
mod block;
mod clipboard;
mod developer_tools;
mod display_list;
mod document;
mod endor_host;
mod endor_script;
mod event_dispatch;
mod events;
mod geometry;
mod io_tasks;
mod layout;
mod mount;
mod native_visual;
mod object_list;
mod presentation;
mod protocols;
mod scene;
mod scroll;
mod snapshot;
mod software_renderer;
mod source_hit;
mod source_layout;
mod source_paint;
mod sources;
mod system_ui;
mod tabs;
mod tasks;
mod text;
mod ui_bridge;
mod vm_sequence;
mod window;
//! 应用组合入口。先创建原生事件循环和共享发布状态,再启动 API/VM worker,最后把窗口事件交给 TesseraApp。
//! VM 操作由运行时线程串行处理;窗口线程只消费发布文档与纯数据通知。crate 私有别名用于保持模块内部引用路径稳定。
//!
//! Application composition root. Directory modules own implementation; these
//! crate-private aliases keep existing internal paths stable during reorganization.
mod bridge;
mod model;
mod render;
mod runtime;
mod shell;
pub(crate) use bridge::ui_bridge;
pub(crate) use model::scene3d as scene3d_model;
pub(crate) use model::{
binding, block, document, mount, object_list, presentation, protocols, snapshot, window,
};
pub(crate) use render::{
box_model, display_list, geometry, layout, native_visual, page, scene, scene3d, scroll,
software_renderer, source_hit, source_layout, source_paint, text, viewport,
};
pub(crate) use runtime::{
api, endor_host, endor_script, event_dispatch, events, io_tasks, tasks, vm_sequence,
};
#[cfg(target_os = "macos")]
pub(crate) use shell::native_chrome;
pub(crate) use shell::{
activity, app, clipboard, developer_tools, sidebar, sources, system_ui, tabs,
};
use std::sync::{Arc, RwLock};
@@ -42,12 +34,16 @@ use app::{AppEvent, TesseraApp};
use document::NamespaceState;
use winit::event_loop::{ControlFlow, EventLoop};
/// 按顺序建立事件循环、共享文档、API/VM worker 和应用窗口;事件循环结束后返回原生退出清理结果。
fn main() -> Result<()> {
// 原生窗口由事件循环所属线程驱动;Wait 让空闲时休眠,而不是持续重绘。
let event_loop = EventLoop::<AppEvent>::with_user_event().build()?;
event_loop.set_control_flow(ControlFlow::Wait);
// 共享最近完整发布的文档。后台 worker 拥有 VM,GUI 不借用其托管堆。
let namespace = Arc::new(RwLock::new(NamespaceState::default()));
let (activity, control) = api::start(namespace.clone(), event_loop.create_proxy())?;
let mut app = TesseraApp::new(namespace, activity, event_loop.create_proxy(), control)?;
// run_app 接管线程直至退出;退出后仍需检查清理过程中记录的错误。
event_loop.run_app(&mut app)?;
app.exit_result()
}
+11
View File
@@ -1,3 +1,6 @@
//! 属性绑定:在只读计算中收集依赖,将结果写回绑定目标。
//! 缓存记录读取版本而不是复制业务模型;依赖变化才重新计算。托管连接对象追踪其拥有的引用。
//!
//! Target-owned managed bindings. Dependency versions are borrowed identities;
//! the host's weak Block registry never roots an otherwise unreachable graph.
use std::{
@@ -13,27 +16,33 @@ use crate::{block, event_dispatch::Subscription, ui_bridge::attach_desktop_type}
/// The output value is borrowed for equality only, including object handles.
/// It never owns a reference or dereferences a possibly reclaimed cached object.
#[derive(Debug, Clone)]
/// 上次绑定计算的读取观察,用于判断是否需要重新执行源计算。
struct Cached {
reads: Vec<endor_core::ReadDependency>,
output: Value,
}
#[derive(Debug, Clone)]
/// 托管属性连接,强持有计算/目标所需引用,并保留只读计算的版本缓存。
pub struct Binding {
field: String,
pub compute: Option<ObjectRef>,
reads: Arc<Mutex<Option<Cached>>>,
}
impl ObjectPayload for Binding {
/// 声明此 payload 的赋值遵循引用身份语义,避免把内部宿主状态当作可复制值。
fn reference_assignment_only(&self) -> bool {
true
}
/// 提供受检查的 Any 下转型入口,让宿主按具体 payload 类型读取数据。
fn as_any(&self) -> &dyn std::any::Any {
self
}
/// 返回运行时诊断/类型检查使用的稳定 payload 名称。
fn kind_name(&self) -> &'static str {
"tessera-binding"
}
/// 枚举本对象真正拥有的托管强引用,供 Aster 引用追踪和循环回收使用。
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
if let Some(compute) = self.compute {
visit(compute);
@@ -41,6 +50,7 @@ impl ObjectPayload for Binding {
}
}
/// 检查绑定目标与可调用计算,建立托管连接及其引用关系。
pub fn connect(
cx: &mut NativeContext<'_>,
target: ObjectRef,
@@ -114,6 +124,7 @@ pub fn connect(
Ok(token)
}
/// 在只读调用中重算失效绑定,采集新的读取版本,再将成功结果应用到目标属性。
pub fn refresh(
vm: &mut Vm,
nodes: &[WeakObjectRef],
+364 -1
View File
@@ -1,3 +1,7 @@
//! Block 的共享赋值、底层 Data 与视觉属性实现。Block 通过 Cell 间接指向 Data,使别名能观察到同一次替换。
//! Data 保存子组件 slot、布局配置、绑定和订阅。属性读写需要沿有效的类型/存储路径解析,不能把快照当成可变业务对象。
//! 提取视觉数据时将托管属性覆盖到原生描述;校验负责拒绝循环、非法尺寸和不符合类型的组成。
//!
//! Live visual objects. All semantic references are owned by Aster's heap;
//! native Arcs are reserved for immutable rendering snapshots.
use std::sync::Arc;
@@ -7,12 +11,14 @@ use endor_core::{NativeContext, ObjectPayload, ObjectRef, ObjectStore, Value, Vm
use crate::ui_bridge::UiNode;
#[derive(Debug, Clone)]
/// 稳定组成 slot 与子 Block 的配对;slot 不依赖孩子当前的屏幕位置。
pub struct Child {
pub slot: u64,
pub block: ObjectRef,
}
#[derive(Debug, Clone)]
/// 原生组件分类,只描述业务组件种类;每种展示几何由布局和 Mount 另行生成。
pub enum Kind {
Text {
value: String,
@@ -32,6 +38,16 @@ pub enum Kind {
},
Row,
Column,
Overlay,
Scene2D,
Viewport3D {
width: f32,
height: f32,
},
CanvasViewport {
width: f32,
height: f32,
},
Button,
Page,
}
@@ -39,6 +55,7 @@ pub enum Kind {
/// The VM owns the Block -> Cell -> Data relationship. Shared assignment
/// changes the Cell to point at another Block, retaining the original identity.
#[derive(Debug, Clone)]
/// 对共享 Cell 的稳定包装。赋值可让所有别名一起改指向,而每次出现的 Mount 仍独立。
pub struct Block {
pub state: ObjectRef,
pub page: bool,
@@ -46,9 +63,11 @@ pub struct Block {
}
impl ObjectPayload for Block {
/// 声明此 payload 的赋值遵循引用身份语义,避免把内部宿主状态当作可复制值。
fn reference_assignment_only(&self) -> bool {
true
}
/// 沿 Block 的共享 Cell 定位属性存储,使别名替换后读取到同一份新 Data。
fn attribute_target(&self, store: &ObjectStore) -> Result<Option<ObjectRef>, VmError> {
let Value::Object(value) = store.cell_get(self.state)? else {
return Err(VmError::InvalidArgument("Block state is not an object"));
@@ -66,6 +85,7 @@ impl ObjectPayload for Block {
}
}
/// 从 Block 当前 Data 解析其类型转发目标,使共享替换后的类型查询仍一致。
fn type_target(&self, store: &ObjectStore) -> Result<Option<ObjectRef>, VmError> {
let Value::Object(value) = store.cell_get(self.state)? else {
return Err(VmError::InvalidArgument("Block state is not an object"));
@@ -78,21 +98,26 @@ impl ObjectPayload for Block {
}
}
/// 提供受检查的 Any 下转型入口,让宿主按具体 payload 类型读取数据。
fn as_any(&self) -> &dyn std::any::Any {
self
}
/// 返回运行时诊断/类型检查使用的稳定 payload 名称。
fn kind_name(&self) -> &'static str {
"tessera-block"
}
/// 声明此 payload 是否允许使用托管属性存储,具体字段仍由类型与调用检查约束。
fn allows_attributes(&self) -> bool {
true
}
/// 枚举本对象真正拥有的托管强引用,供 Aster 引用追踪和循环回收使用。
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
visit(self.state);
if let Some(tasks) = self.tasks {
visit(tasks);
}
}
/// 向 VM 暴露共享赋值单元;替换的是指向关系,不是逐项复制组件业务字段。
fn assignment_cell(
&self,
source: ObjectRef,
@@ -112,6 +137,7 @@ impl ObjectPayload for Block {
}
#[derive(Debug, Clone)]
/// 组件当前业务描述与组成。与一次求出的屏幕几何分开保存,替换或属性变化会触发派生快照失效。
pub struct Data {
pub kind: Kind,
pub children: Vec<Child>,
@@ -120,7 +146,20 @@ pub struct Data {
pub flex: f32,
pub flex_policy: crate::layout::FlexPolicy,
pub main_align: crate::layout::MainAlign,
pub cross_align: crate::layout::CrossAlign,
pub align_self: Option<crate::layout::CrossAlign>,
pub margin: crate::layout::Insets,
pub sizing: crate::box_model::Sizing,
pub padding_edges: [Option<f32>; 4],
pub border: crate::layout::Insets,
pub border_color: String,
pub clip_children: bool,
pub camera: Option<ObjectRef>,
pub scene3d: Option<ObjectRef>,
pub controller: Option<ObjectRef>,
pub scroll_axis: crate::scroll::Axis,
pub position: [f32; 2],
pub surface: crate::page::Surface,
pub next_slot: u64,
pub history: Vec<ObjectRef>,
pub history_index: usize,
@@ -132,6 +171,7 @@ pub struct Data {
}
impl Data {
/// 构造本类型并初始化其状态;资源建立和默认字段以函数体为准。
pub fn new(kind: Kind, children: Vec<ObjectRef>, padding: f32, gap: f32) -> Self {
let next_slot = children.len() as u64;
Self {
@@ -149,7 +189,20 @@ impl Data {
flex: 0.0,
flex_policy: crate::layout::FlexPolicy::default(),
main_align: crate::layout::MainAlign::Start,
cross_align: crate::layout::CrossAlign::Start,
align_self: None,
margin: crate::layout::Insets::default(),
sizing: crate::box_model::Sizing::default(),
padding_edges: [None; 4],
border: crate::layout::Insets::default(),
border_color: "#D8DCE2".into(),
clip_children: false,
camera: None,
scene3d: None,
controller: None,
scroll_axis: crate::scroll::Axis::Both,
position: [0.0, 0.0],
surface: crate::page::Surface::new(crate::page::Mode::Window),
next_slot,
history: vec![],
history_index: 0,
@@ -160,25 +213,46 @@ impl Data {
properties: None,
}
}
/// 检查原生组件种类是否承载子组成,供树修改和布局选择使用。
pub fn is_container(&self) -> bool {
matches!(
self.kind,
Kind::Row | Kind::Column | Kind::Button | Kind::Page | Kind::Scroll { .. }
Kind::Row
| Kind::Column
| Kind::Overlay
| Kind::Scene2D
| Kind::CanvasViewport { .. }
| Kind::Button
| Kind::Page
| Kind::Scroll { .. }
)
}
}
impl ObjectPayload for Data {
/// 声明此 payload 的赋值遵循引用身份语义,避免把内部宿主状态当作可复制值。
fn reference_assignment_only(&self) -> bool {
true
}
/// 提供受检查的 Any 下转型入口,让宿主按具体 payload 类型读取数据。
fn as_any(&self) -> &dyn std::any::Any {
self
}
/// 返回运行时诊断/类型检查使用的稳定 payload 名称。
fn kind_name(&self) -> &'static str {
"tessera-block-data"
}
/// 枚举本对象真正拥有的托管强引用,供 Aster 引用追踪和循环回收使用。
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
if let Some(scene) = self.scene3d {
visit(scene);
}
if let Some(controller) = self.controller {
visit(controller);
}
if let Some(camera) = self.camera {
visit(camera);
}
if let Some(properties) = self.properties {
visit(properties);
}
@@ -203,6 +277,7 @@ impl ObjectPayload for Data {
}
}
/// 分配 Data、共享 Cell 和 Block 包装,并让托管图拥有必要引用。
pub fn allocate(cx: &mut NativeContext<'_>, mut data: Data) -> Result<ObjectRef, VmError> {
let page = matches!(data.kind, Kind::Page);
for child in &data.children {
@@ -224,11 +299,13 @@ pub fn allocate(cx: &mut NativeContext<'_>, mut data: Data) -> Result<ObjectRef,
/// Borrowed final data; forwarding is part of the managed graph, never an Arc
/// ownership graph hidden from the VM's cycle collector.
/// 解析一个 Block 当前指向的 Data,返回底层身份和借用描述。
pub fn resolve(store: &ObjectStore, block: ObjectRef) -> Result<(ObjectRef, &Data), VmError> {
let (reference, data, _) = resolve_tracked(store, block)?;
Ok((reference, data))
}
/// 解析 Block 的完整引用路径,并返回快照失效所需的依赖身份。
pub fn resolve_tracked(
store: &ObjectStore,
block: ObjectRef,
@@ -259,11 +336,13 @@ pub fn resolve_tracked(
/// Validate the entire finite expansion before establishing a new composition
/// edge. The node count is an explicit rejected resource quota, not truncated UI.
/// 检查当前输入或发布值的不变量,调用方据校验结果决定是否继续。
pub fn validate(
store: &ObjectStore,
root: ObjectRef,
forbidden_state: Option<ObjectRef>,
) -> Result<(), VmError> {
// 显式进入/退出栈模拟深度优先遍历;退出时移除祖先链标记,允许共享子树。
enum Step {
Enter(ObjectRef),
Exit(ObjectRef),
@@ -309,17 +388,22 @@ pub fn validate(
Ok(())
}
/// 将当前托管或可变状态提取为后续阶段使用的派生表示。
pub fn snapshot(store: &ObjectStore, root: ObjectRef) -> Result<Arc<UiNode>, VmError> {
crate::snapshot::RenderCache::default().snapshot(store, root)
}
/// Native visual parameters are ordinary managed attributes too. Composition,
/// histories and connections remain structural payload edges.
/// 列出本类型可投影到托管属性的原生字段及默认值。
pub fn native_properties(data: &Data) -> Vec<(&'static str, Value)> {
/// 在源 Value 与所需数值表示之间转换,并沿用本调用的有限值/范围检查。
fn number(value: f32) -> Value {
Value::Number((value as f64).into())
}
let mut fields = vec![
("x", number(data.position[0])),
("y", number(data.position[1])),
("flex", number(data.flex)),
(
"flexBasis",
@@ -330,8 +414,73 @@ pub fn native_properties(data: &Data) -> Vec<(&'static str, Value)> {
("flexMin", number(data.flex_policy.min)),
("flexMax", number(data.flex_policy.max)),
("flexShrink", number(data.flex_policy.shrink)),
("marginTop", number(data.margin.top)),
("marginRight", number(data.margin.right)),
("marginBottom", number(data.margin.bottom)),
("marginLeft", number(data.margin.left)),
("boxWidth", data.sizing.width.value()),
("boxHeight", data.sizing.height.value()),
("minWidth", number(data.sizing.min_width)),
("minHeight", number(data.sizing.min_height)),
("maxWidth", number(data.sizing.max_width)),
("maxHeight", number(data.sizing.max_height)),
("borderTop", number(data.border.top)),
("borderRight", number(data.border.right)),
("borderBottom", number(data.border.bottom)),
("borderLeft", number(data.border.left)),
("borderColor", Value::Text(data.border_color.clone())),
(
"overflow",
Value::Text(
if data.clip_children {
"clip"
} else {
"visible"
}
.into(),
),
),
(
"alignSelf",
Value::Text(
data.align_self
.map_or("auto", crate::layout::CrossAlign::name)
.into(),
),
),
];
for (name, edge) in ["paddingTop", "paddingRight", "paddingBottom", "paddingLeft"]
.into_iter()
.zip(data.padding_edges)
{
fields.push((
name,
edge.map_or_else(|| Value::Text("auto".into()), number),
));
}
match &data.kind {
Kind::Viewport3D { width, height } => fields.extend([
("width", number(*width)),
("height", number(*height)),
("scene", data.scene3d.map_or(Value::Nil, Value::Object)),
(
"controller",
data.controller
.map_or_else(|| Value::Text("none".into()), Value::Object),
),
("camera", data.camera.map_or(Value::Nil, Value::Object)),
]),
Kind::CanvasViewport { width, height } => fields.extend([
("width", number(*width)),
("height", number(*height)),
("camera", data.camera.map_or(Value::Nil, Value::Object)),
]),
Kind::Page => fields.extend([
("mode", Value::Text(data.surface.mode.name().into())),
("panX", number(data.surface.pan.x)),
("panY", number(data.surface.pan.y)),
("zoom", number(data.surface.zoom)),
]),
Kind::Text { value, size, color } => fields.extend([
("text", Value::Text(value.clone())),
("size", Value::Number((*size as i64).into())),
@@ -361,11 +510,13 @@ pub fn native_properties(data: &Data) -> Vec<(&'static str, Value)> {
("padding", number(data.padding)),
("gap", number(data.gap)),
("mainAlign", Value::Text(data.main_align.name().into())),
("crossAlign", Value::Text(data.cross_align.name().into())),
]);
}
fields
}
/// 复制原生描述并用当前托管属性覆盖它;结果只用于展示,不反向修改业务对象。
pub fn visual_data(store: &ObjectStore, data: &Data) -> Result<Data, VmError> {
let mut data = data.clone();
let properties = data
@@ -378,9 +529,53 @@ pub fn visual_data(store: &ObjectStore, data: &Data) -> Result<Data, VmError> {
if data.flex_policy.min > data.flex_policy.max {
return Err(VmError::InvalidArgument("flexMin exceeds flexMax"));
}
if data.sizing.min_width > data.sizing.max_width
|| data.sizing.min_height > data.sizing.max_height
{
return Err(VmError::InvalidArgument("box minimum exceeds maximum"));
}
if matches!(data.kind, Kind::CanvasViewport { .. }) {
crate::viewport::camera(
store,
data.camera.ok_or(VmError::InvalidArgument(
"CanvasViewport requires a Camera2D",
))?,
)?;
if data.children.len() != 1
|| !matches!(
resolve(store, data.children[0].block)?.1.kind,
Kind::Scene2D
)
{
return Err(VmError::InvalidArgument(
"CanvasViewport requires exactly one Scene2D",
));
}
}
if matches!(data.kind, Kind::Viewport3D { .. })
&& let Some(controller) = data.controller
{
let definition = store.type_of(controller)?.ok_or(VmError::InvalidArgument(
"3D controller requires a nominal update method",
))?;
let method = store
.lookup_method(definition, "update")?
.ok_or(VmError::InvalidArgument(
"3D controller must define update(camera, gesture)",
))?;
if store
.call_arity(method)?
.is_none_or(|arity| !arity.accepts(3))
{
return Err(VmError::InvalidArgument(
"3D controller update expects camera and CameraGesture",
));
}
}
Ok(data)
}
/// 按属性名检查和解码源值,再更新对应视觉字段;非法尺寸、枚举或颜色被拒绝。
pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Result<(), VmError> {
let bad = || VmError::InvalidArgument("invalid native visual property");
let number = || -> Result<f32, VmError> {
@@ -393,7 +588,151 @@ pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Resu
}
Ok(n)
};
if matches!(name, "x" | "y" | "panX" | "panY" | "zoom") {
let n = crate::scroll::coordinate(value)?;
match name {
"x" => data.position[0] = n,
"y" => data.position[1] = n,
"panX" if matches!(data.kind, Kind::Page) => data.surface.pan.x = n,
"panY" if matches!(data.kind, Kind::Page) => data.surface.pan.y = n,
"zoom" if matches!(data.kind, Kind::Page) => {
if !(0.1..=4.0).contains(&n) {
return Err(invalid_zoom());
}
data.surface.zoom = n;
}
_ => {}
}
return Ok(());
}
if matches!(data.kind, Kind::Page) && name == "mode" {
let Value::Text(name) = value else {
return Err(bad());
};
data.surface.mode = crate::page::Mode::parse(name)?;
return Ok(());
}
match name {
"controller" if matches!(data.kind, Kind::Viewport3D { .. }) => {
data.controller = match value {
Value::Object(controller) => Some(*controller),
Value::Text(text) if text == "none" => None,
_ => return Err(bad()),
};
return Ok(());
}
"camera"
if matches!(
data.kind,
Kind::CanvasViewport { .. } | Kind::Viewport3D { .. }
) =>
{
let Value::Object(camera) = value else {
return Err(bad());
};
data.camera = Some(*camera);
return Ok(());
}
"scene" if matches!(data.kind, Kind::Viewport3D { .. }) => {
let Value::Object(scene) = value else {
return Err(bad());
};
data.scene3d = Some(*scene);
return Ok(());
}
"paddingTop" | "paddingRight" | "paddingBottom" | "paddingLeft" => {
let index = match name {
"paddingTop" => 0,
"paddingRight" => 1,
"paddingBottom" => 2,
_ => 3,
};
data.padding_edges[index] = if matches!(value, Value::Text(text) if text == "auto") {
None
} else {
Some(number()?)
};
return Ok(());
}
"borderTop" => {
data.border.top = number()?;
return Ok(());
}
"borderRight" => {
data.border.right = number()?;
return Ok(());
}
"borderBottom" => {
data.border.bottom = number()?;
return Ok(());
}
"borderLeft" => {
data.border.left = number()?;
return Ok(());
}
"borderColor" => {
let Value::Text(color) = value else {
return Err(bad());
};
crate::document::parse_color(color).map_err(|_| bad())?;
data.border_color.clone_from(color);
return Ok(());
}
"overflow" => {
let Value::Text(overflow) = value else {
return Err(bad());
};
data.clip_children = match overflow.as_str() {
"clip" => true,
"visible" => false,
_ => {
return Err(VmError::InvalidArgument(
"overflow expects visible or clip; use ScrollBlock for scrolling",
));
}
};
return Ok(());
}
"boxWidth" => {
data.sizing.width = crate::box_model::Dimension::parse(value)?;
return Ok(());
}
"boxHeight" => {
data.sizing.height = crate::box_model::Dimension::parse(value)?;
return Ok(());
}
"minWidth" => {
data.sizing.min_width = number()?;
return Ok(());
}
"minHeight" => {
data.sizing.min_height = number()?;
return Ok(());
}
"maxWidth" => {
data.sizing.max_width = number()?;
return Ok(());
}
"maxHeight" => {
data.sizing.max_height = number()?;
return Ok(());
}
"marginTop" => {
data.margin.top = number()?;
return Ok(());
}
"marginRight" => {
data.margin.right = number()?;
return Ok(());
}
"marginBottom" => {
data.margin.bottom = number()?;
return Ok(());
}
"marginLeft" => {
data.margin.left = number()?;
return Ok(());
}
"flexBasis" => {
data.flex_policy.basis = if matches!(value, Value::Nil)
|| matches!(value, Value::Text(text) if text == "auto")
@@ -423,6 +762,21 @@ pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Resu
return Ok(());
}
let container = data.is_container();
if name == "alignSelf" || (container && name == "crossAlign") {
let Value::Text(value) = value else {
return Err(bad());
};
if name == "alignSelf" {
data.align_self = if value == "auto" {
None
} else {
Some(crate::layout::CrossAlign::parse(value)?)
};
} else {
data.cross_align = crate::layout::CrossAlign::parse(value)?;
}
return Ok(());
}
if container && name == "mainAlign" {
let Value::Text(value) = value else {
return Err(bad());
@@ -431,6 +785,10 @@ pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Resu
return Ok(());
}
match (&mut data.kind, name) {
(Kind::Viewport3D { width, .. }, "width") => *width = number()?,
(Kind::Viewport3D { height, .. }, "height") => *height = number()?,
(Kind::CanvasViewport { width, .. }, "width") => *width = number()?,
(Kind::CanvasViewport { height, .. }, "height") => *height = number()?,
(Kind::Text { value: text, .. }, "text") => {
let Value::Text(value) = value else {
return Err(bad());
@@ -472,3 +830,8 @@ pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Resu
}
Ok(())
}
/// 统一返回非法页面缩放错误,确保属性写入与输入路径使用相同限制。
fn invalid_zoom() -> VmError {
VmError::InvalidArgument("Page.zoom expects a number from 0.1 to 4")
}
+194 -10
View File
@@ -1,3 +1,7 @@
//! 运行时与窗口线程之间的发布数据契约。NamespaceState 管理提交序号、版本和当前完整文档。
//! RenderDocument/Frame 包含绘制命令、Mount 几何、页面标签和相机投影。发布前统一检查数量、坐标、颜色及索引一致性。
//! 屏幕命中、逻辑坐标和世界 UI 的射线映射必须与绘制采用同一变换;这里的 ID 是数据身份,不是窗口线程可操作的托管引用。
//!
use std::collections::HashSet;
use std::sync::Arc;
@@ -13,18 +17,23 @@ use crate::{
pub const DEFAULT_NAMESPACE: &str = "app.main";
#[derive(Clone, Debug)]
/// HTTP/GUI 共享的最近完整发布状态;submission 决定结果归属,revision 表示实际发布次数。
pub struct NamespaceState {
pub name: String,
pub revision: u64,
// 较新完整 PUT/DELETE 会改变提交身份;旧输入即使晚完成也不得覆盖新结果。
pub submission: u64,
pub document: RenderDocument,
// viewport 是主窗口逻辑页面区域;window_viewports 同时记录仍存活的副窗口。
pub viewport: Option<crate::layout::Size>,
pub window_viewports: std::collections::BTreeMap<u64, crate::layout::Size>,
// 原生命令与运行时世代一起发布,防止窗口 ID 在跨 VM 时被误用。
pub runtime_session: u64,
pub window_commands: Vec<crate::window::Envelope>,
}
impl Default for NamespaceState {
/// 建立类型约定的初始值,供尚未发布或尚未交互的状态使用。
fn default() -> Self {
Self {
name: DEFAULT_NAMESPACE.to_owned(),
@@ -40,6 +49,7 @@ impl Default for NamespaceState {
}
impl NamespaceState {
/// 仅接收当前 session 的纯数据窗口命令,并按种类合并同资源的重复请求。
pub fn publish_window_commands(&mut self, session: u64, commands: Vec<crate::window::Command>) {
if self.runtime_session != session {
self.window_commands.clear();
@@ -63,13 +73,16 @@ impl NamespaceState {
.sort_by_key(|command| command.command.sequence);
}
/// 计算下一个完整源码提交身份;计数溢出时返回错误而不是复用旧身份。
pub fn next_submission(&self) -> Result<u64> {
self.submission
.checked_add(1)
.context("submission counter exhausted")
}
/// 仅当提交身份仍是最新时替换完整文档并递增版本;已被取代的结果不发布。
pub fn commit(&mut self, submission: u64, document: RenderDocument) -> Result<Option<u64>> {
// 先核对归属,再计算新版本;失败或过时的结果不会替换已显示文档。
if submission != self.submission {
return Ok(None);
}
@@ -82,6 +95,7 @@ impl NamespaceState {
Ok(Some(revision))
}
/// 清空本对象维护的当前内容或缓存,后续状态由调用方重新建立。
pub fn clear(&mut self) -> Result<u64> {
let submission = self.next_submission()?;
let revision = self
@@ -98,6 +112,7 @@ impl NamespaceState {
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
/// 可以离开 VM 线程的完整展示值,包含源码投影、根帧和其他窗口的文档。
pub struct RenderDocument {
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
pub windows: std::collections::BTreeMap<u64, RenderDocument>,
@@ -112,7 +127,20 @@ pub struct RenderDocument {
}
impl RenderDocument {
/// 检查当前输入或发布值的不变量,调用方据校验结果决定是否继续。
pub fn validate(&self) -> Result<()> {
let surface = &self.frame.surface;
if !surface.zoom.is_finite()
|| !(0.1..=4.0).contains(&surface.zoom)
|| ![surface.pan.x, surface.pan.y]
.iter()
.all(|v| v.is_finite() && v.abs() <= 1_000_000.0)
|| ![surface.extent.width, surface.extent.height]
.iter()
.all(|v| v.is_finite() && (0.0..=1_000_000.0).contains(v))
{
bail!("invalid page camera or extent");
}
if self.windows.len() > 15 {
bail!("too many window projections");
}
@@ -144,6 +172,16 @@ impl RenderDocument {
for clip in self.frame.command_clips.iter().flatten() {
validate_rect(clip[0], clip[1], clip[2], clip[3], 0.0)?;
}
if !self.frame.command_views.is_empty()
&& self.frame.command_views.len() != self.frame.commands.len()
{
bail!("invalid command view table");
}
for view in self.frame.command_views.iter().flatten() {
if !view.valid() {
bail!("invalid command view transform");
}
}
for command in &self.frame.commands {
command.validate()?;
}
@@ -163,6 +201,9 @@ impl RenderDocument {
}
let mut mount_ids = HashSet::new();
for mount in &self.frame.mounts {
if mount.view.is_some_and(|view| !view.valid()) {
bail!("invalid Mount view transform");
}
if mount.id == 0 || mount.block_id.is_empty() || !mount_ids.insert(mount.id) {
bail!("invalid or duplicate mount identity");
}
@@ -170,6 +211,9 @@ impl RenderDocument {
if let Some(clip) = mount.clip {
validate_rect(clip[0], clip[1], clip[2], clip[3], 0.0)?;
}
if let Some(clip) = mount.viewport_clip {
validate_rect(clip[0], clip[1], clip[2], clip[3], 0.0)?;
}
if let Some(scroll) = mount.scroll
&& (!scroll.iter().all(|n| {
n.is_finite() && (0.0..=crate::ui_bridge::MAX_DIMENSION as f32).contains(n)
@@ -206,6 +250,7 @@ impl RenderDocument {
Ok(())
}
/// 校验文档后把逻辑绘制命令转换成给定设备比例的显示列表,应用变换与裁剪。
pub fn display_list(&self, scale: f32) -> Result<DisplayList> {
let frame = &self.frame;
let mut list = DisplayList::default();
@@ -217,7 +262,17 @@ impl RenderDocument {
clip[0], clip[1], clip[2], clip[3], scale,
)));
}
list.push(command.to_draw_command(scale)?);
let view = frame
.command_views
.get(index)
.copied()
.flatten()
.unwrap_or_default();
list.push(
command
.to_draw_command(scale * view.zoom)?
.translated(Point::new(view.x * scale, view.y * scale)),
);
if clip.is_some() {
list.push(DrawCommand::PopClip);
}
@@ -225,6 +280,7 @@ impl RenderDocument {
if let Some(focus) = frame
.focus
.and_then(|id| frame.mounts.iter().find(|m| m.id == id))
.filter(|mount| mount.panel.is_none())
{
if let Some(c) = focus.clip {
list.push(DrawCommand::PushClip(scaled_rect(
@@ -233,10 +289,18 @@ impl RenderDocument {
}
list.push(
RenderCommand::StrokeRoundedRect {
x: focus.x,
y: focus.y,
width: focus.width,
height: focus.height,
x: focus
.view
.unwrap_or_default()
.rect(Rect::new(focus.x, focus.y, focus.width, focus.height))
.x,
y: focus
.view
.unwrap_or_default()
.rect(Rect::new(focus.x, focus.y, focus.width, focus.height))
.y,
width: focus.width * focus.view.unwrap_or_default().zoom,
height: focus.height * focus.view.unwrap_or_default().zoom,
radius: 7.0,
stroke_width: 2.0,
color: "#4F6FDB".into(),
@@ -274,12 +338,14 @@ impl RenderDocument {
Ok(list)
}
/// 从源码投影根按 ID 查找节点,供 Sources 查看与定位使用。
pub fn node(&self, id: &str) -> Option<&CodeNode> {
self.root.as_ref()?.find(id)
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
/// Sources 使用的源码层次节点;ID、名称、种类和行列范围都属于代码投影而不是运行时对象句柄。
pub struct CodeNode {
pub id: String,
pub name: String,
@@ -293,6 +359,7 @@ pub struct CodeNode {
}
impl CodeNode {
/// 检查当前输入或发布值的不变量,调用方据校验结果决定是否继续。
fn validate<'a>(&'a self, depth: usize, ids: &mut HashSet<&'a str>) -> Result<()> {
if depth > 64 {
bail!("architecture tree exceeds 64 levels");
@@ -312,6 +379,7 @@ impl CodeNode {
Ok(())
}
/// 按请求的代码节点身份或路径查找对应的源码投影。
fn find(&self, id: &str) -> Option<&CodeNode> {
if self.id == id {
return Some(self);
@@ -321,7 +389,13 @@ impl CodeNode {
}
#[derive(Clone, Debug, Serialize, Deserialize)]
/// 一个窗口的一次完整视觉发布:有序命令及其裁剪/变换、出现几何、焦点和版本。平行索引表必须和命令数量一致。
pub struct Frame {
// 命中索引是可重建的本地优化,不作为序列化协议的一部分保存。
#[serde(skip)]
pub hit_index: Arc<crate::viewport::spatial::Index>,
#[serde(default)]
pub surface: crate::page::Surface,
#[serde(default = "default_window")]
pub window: u64,
#[serde(default = "default_background")]
@@ -331,6 +405,10 @@ pub struct Frame {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub command_clips: Vec<Option<[f32; 4]>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub command_views: Vec<Option<crate::viewport::Transform>>,
#[serde(skip)]
pub command_mounts: Vec<u64>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub mounts: Vec<MountGeometry>,
#[serde(default)]
pub layout_version: u64,
@@ -345,12 +423,17 @@ pub struct Frame {
}
impl Default for Frame {
/// 建立类型约定的初始值,供尚未发布或尚未交互的状态使用。
fn default() -> Self {
Self {
hit_index: Arc::default(),
surface: crate::page::Surface::default(),
window: crate::window::MAIN_WINDOW,
background: default_background(),
commands: Vec::new(),
command_clips: Vec::new(),
command_views: Vec::new(),
command_mounts: Vec::new(),
mounts: Vec::new(),
layout_version: 0,
session: 0,
@@ -363,7 +446,20 @@ impl Default for Frame {
/// A position in a published frame. Identifiers are opaque data, never VM handles.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
/// 某次出现的几何与投影元数据。逻辑矩形不被相机直接改写,view/panel 保存通往视图空间的映射。
pub struct MountGeometry {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub panel: Option<Arc<crate::scene3d::panel::Mapping>>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub canvas_viewport: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub scene3d_viewport: bool,
#[serde(default)]
pub camera_controls: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub viewport_clip: Option<[f32; 4]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub view: Option<crate::viewport::Transform>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub clip: Option<[f32; 4]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -381,8 +477,39 @@ pub struct MountGeometry {
}
impl MountGeometry {
/// 先沿世界 UI 面板逆投影指针,按需要执行可见性和裁剪检查。
pub fn view_point(&self, point: Point, clipped: bool) -> Option<Point> {
self.panel
.as_ref()
.map_or(Some(point), |panel| panel.texture_point(point, clipped))
}
/// 把页面指针转换为该出现的布局坐标,供 hitTest 和局部事件处理使用。
pub fn logical_point(&self, point: Point) -> Option<Point> {
let point = self.view_point(point, true)?;
Some(self.view.unwrap_or_default().inverse(point))
}
/// 把视图位移换算成目标出现的局部位移,处理缩放与世界 UI 投影差异。
pub fn logical_delta(&self, point: Option<[f32; 2]>, delta: [f32; 2]) -> Option<[f32; 2]> {
let zoom = self.view.unwrap_or_default().zoom;
if self.panel.is_none() {
return Some([delta[0] / zoom, delta[1] / zoom]);
}
let point = point?;
let current = self.view_point(Point::new(point[0], point[1]), false)?;
let previous =
self.view_point(Point::new(point[0] + delta[0], point[1] + delta[1]), false)?;
Some([
((previous.x - current.x) / zoom).clamp(-1_000_000., 1_000_000.),
((previous.y - current.y) / zoom).clamp(-1_000_000., 1_000_000.),
])
}
/// 判断给定点是否位于目标范围;需要相机转换的类型会先转换再判断。
pub fn contains(&self, point: Point) -> bool {
Rect::new(self.x, self.y, self.width, self.height).contains(point)
let Some(point) = self.view_point(point, true) else {
return false;
};
let local = self.view.map_or(point, |view| view.inverse(point));
Rect::new(self.x, self.y, self.width, self.height).contains(local)
&& self.clip.is_none_or(|c| {
c[2] > 0.0 && c[3] > 0.0 && Rect::new(c[0], c[1], c[2], c[3]).contains(point)
})
@@ -390,28 +517,56 @@ impl MountGeometry {
}
impl Frame {
/// 从顶层绘制顺序向后查找可控制的视口,命中与裁剪均成立才接收相机手势。
pub fn camera_at(&self, point: Point) -> Option<&MountGeometry> {
self.hit_index
.candidates(point, self.mounts.len())
.into_iter()
.map(|index| &self.mounts[index])
.find(|mount| {
(mount.canvas_viewport || mount.scene3d_viewport && mount.camera_controls)
&& mount.contains(point)
&& mount.viewport_clip.is_some_and(|clip| {
mount.view_point(point, true).is_some_and(|point| {
Rect::new(clip[0], clip[1], clip[2], clip[3]).contains(point)
})
})
})
}
/// 在无故障帧中按逆绘制顺序选中可交互的出现,空间索引只缩小候选。
pub fn hit_test(&self, point: Point) -> Option<&MountGeometry> {
if self.fault.is_some() {
return None;
}
self.mounts
.iter()
.rev()
self.hit_index
.candidates(point, self.mounts.len())
.into_iter()
.map(|index| &self.mounts[index])
.find(|mount| mount.interactive && mount.contains(point))
}
}
/// 返回默认主窗口身份,供省略窗口字段的兼容输入使用。
fn default_window() -> u64 {
crate::window::MAIN_WINDOW
}
/// 提供空帧或未指定背景时的默认页面底色。
fn default_background() -> String {
"#F7F7F5".to_owned()
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
/// 可校验、可序列化的逻辑绘制命令;转换到设备像素在 display_list 阶段完成。
pub enum RenderCommand {
Scene3D {
x: f32,
y: f32,
width: f32,
height: f32,
view: Arc<crate::scene3d::View>,
},
RoundedRect {
x: f32,
y: f32,
@@ -445,8 +600,21 @@ pub enum RenderCommand {
}
impl RenderCommand {
/// 检查当前输入或发布值的不变量,调用方据校验结果决定是否继续。
pub(crate) fn validate(&self) -> Result<()> {
match self {
Self::Scene3D {
x,
y,
width,
height,
view,
} => {
validate_rect(*x, *y, *width, *height, 0.0)?;
if !view.valid() {
bail!("invalid 3D view");
}
}
Self::RoundedRect {
x,
y,
@@ -505,8 +673,19 @@ impl RenderCommand {
Ok(())
}
/// 把一条已验证的发布命令变成原生绘制原语,缩放几何和文字样式。
fn to_draw_command(&self, scale: f32) -> Result<DrawCommand> {
Ok(match self {
Self::Scene3D {
x,
y,
width,
height,
view,
} => DrawCommand::Scene3D {
rect: scaled_rect(*x, *y, *width, *height, scale),
view: view.clone(),
},
Self::RoundedRect {
x,
y,
@@ -558,14 +737,17 @@ impl RenderCommand {
}
}
/// 提供未指定描边宽度时的兼容默认值。
fn default_stroke_width() -> f32 {
1.0
}
/// 提供未指定字号时的协议默认值。
fn default_text_size() -> u32 {
1
}
/// 统一检查有限矩形坐标、尺寸与可选圆角,阻止异常值进入光栅循环。
fn validate_rect(x: f32, y: f32, width: f32, height: f32, radius: f32) -> Result<()> {
if !x.is_finite() || !y.is_finite() || !width.is_finite() || !height.is_finite() {
bail!("rectangle values must be finite");
@@ -576,10 +758,12 @@ fn validate_rect(x: f32, y: f32, width: f32, height: f32, radius: f32) -> Result
Ok(())
}
/// 将逻辑矩形转换为设备比例下的矩形,保持位置与尺寸同比缩放。
fn scaled_rect(x: f32, y: f32, width: f32, height: f32, scale: f32) -> Rect {
Rect::new(x * scale, y * scale, width * scale, height * scale)
}
/// 解析支持的十六进制 RGB/RGBA 文本,拒绝错误长度或非法字符。
pub fn parse_color(value: &str) -> Result<Color> {
let hex = value
.strip_prefix('#')
+13
View File
@@ -0,0 +1,13 @@
//! 模型层模块入口。包含托管业务对象、每次展示上下文、依赖缓存,以及交给窗口线程的发布值。
//!
// Module ownership follows the directory; crate-root aliases keep internal call sites stable.
pub(crate) mod binding;
pub(crate) mod block;
pub(crate) mod document;
pub(crate) mod mount;
pub(crate) mod object_list;
pub(crate) mod presentation;
pub(crate) mod protocols;
pub(crate) mod scene3d;
pub(crate) mod snapshot;
pub(crate) mod window;
+132 -4
View File
@@ -1,3 +1,7 @@
//! 每次展示的托管上下文:同一个 Block 出现在两个位置时,有两个独立 Mount。
//! Mount 保存父子关系、出现几何和布局期间的查询上下文;MountTable 用弱索引定位对象,不靠索引强行保活业务树。
//! 同步会安排 onMount/onUnmount。布局取消时使用 Checkpoint 恢复未发布状态,避免半完成的出现关系影响下一次刷新。
//!
//! Managed presentation contexts. The active desktop owns the mount dictionary;
//! reverse links and the host registry are weak, so shared content cannot retain a Page.
use crate::document::{Frame, MountGeometry};
@@ -11,16 +15,20 @@ use std::{
};
#[derive(Debug, Clone)]
/// 一个组件在一个展示位置上的上下文。强持有 Block,反向页面/父子链接使用弱身份,避免共享组件把已关闭页面保活。
pub struct Mount {
// 组件是强引用;页面、父节点和兄弟链接是弱引用,防止反向链接形成保活环。
pub block: ObjectRef,
pub page: Option<WeakObjectRef>,
pub parent: Option<WeakObjectRef>,
pub first_child: Option<WeakObjectRef>,
pub next_sibling: Option<WeakObjectRef>,
// 已发布几何与每次出现的滚动位置分开保存,同一 Block 的多个位置互不覆盖。
pub geometry: MountGeometry,
pub scroll_offset: [f32; 2],
pub version: u64,
pub mounted: bool,
// Mount 可以拥有任务;退役后任务交付还要检查 owner 是否仍有效。
pub tasks: Option<ObjectRef>,
// Private derived scratch, installed before the read-only layout call and
// cleared by geometry commit. It contains no managed references or roots.
@@ -28,18 +36,23 @@ pub struct Mount {
}
impl ObjectPayload for Mount {
/// 声明此 payload 的赋值遵循引用身份语义,避免把内部宿主状态当作可复制值。
fn reference_assignment_only(&self) -> bool {
true
}
/// 提供受检查的 Any 下转型入口,让宿主按具体 payload 类型读取数据。
fn as_any(&self) -> &dyn std::any::Any {
self
}
/// 返回运行时诊断/类型检查使用的稳定 payload 名称。
fn kind_name(&self) -> &'static str {
"tessera-mount"
}
/// 声明此 payload 是否允许使用托管属性存储,具体字段仍由类型与调用检查约束。
fn allows_attributes(&self) -> bool {
true
}
/// 枚举本对象真正拥有的托管强引用,供 Aster 引用追踪和循环回收使用。
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
visit(self.block);
if let Some(tasks) = self.tasks {
@@ -49,12 +62,17 @@ impl ObjectPayload for Mount {
}
#[derive(Debug, Clone, Copy)]
/// 该原生能力的查询/操作分类,方法包装用它选择具体实现。
enum Query {
Bounds,
ScrollTo,
ScrollBy,
ScrollPosition,
ScrollIntoView,
FitView,
Pick3D,
ToView,
ToLocal,
Parent,
FirstChild,
NextSibling,
@@ -64,6 +82,7 @@ enum Query {
}
#[derive(Debug)]
/// 保存 owner、签名或操作枚举的原生方法适配器,统一由 VM 调用。
struct Method {
signature: endor_core::CallSignature,
owner: ObjectRef,
@@ -72,14 +91,21 @@ struct Method {
}
impl NativeCallable for Method {
/// 给出参数与返回值的托管类型契约;实际操作在 invoke 中执行。
fn signature(&self) -> Option<endor_core::CallSignature> {
Some(self.signature.clone())
}
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
fn arity(&self) -> Option<endor_core::CallArity> {
Some(endor_core::CallArity::exact(
if matches!(
self.query,
Query::HitTest | Query::ScrollTo | Query::ScrollBy
Query::HitTest
| Query::Pick3D
| Query::ToView
| Query::ToLocal
| Query::ScrollTo
| Query::ScrollBy
) {
2
} else {
@@ -88,6 +114,7 @@ impl NativeCallable for Method {
))
}
/// VM 调入本宿主能力的入口;按所属操作解码参数并返回托管值或后续调用。
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
let mount = cx.store().payload::<Mount>(self.owner, "Mount")?.clone();
if !mount.mounted
@@ -99,6 +126,10 @@ impl NativeCallable for Method {
| Query::ScrollTo
| Query::ScrollBy
| Query::ScrollIntoView
| Query::FitView
| Query::Pick3D
| Query::ToView
| Query::ToLocal
| Query::ScrollPosition
)
{
@@ -106,7 +137,12 @@ impl NativeCallable for Method {
}
let arity = if matches!(
self.query,
Query::HitTest | Query::ScrollTo | Query::ScrollBy
Query::HitTest
| Query::Pick3D
| Query::ToView
| Query::ToLocal
| Query::ScrollTo
| Query::ScrollBy
) {
2
} else {
@@ -116,6 +152,50 @@ impl NativeCallable for Method {
return Err(VmError::InvalidArgument("incorrect Mount method arity"));
}
let value = match self.query {
Query::ToView | Query::ToLocal => {
if mount.layout.is_some() {
return Err(VmError::InvalidArgument(
"coordinate conversion requires committed geometry",
));
}
let point = crate::geometry::Point::new(
crate::scroll::coordinate(&args[0])?,
crate::scroll::coordinate(&args[1])?,
);
let point =
if matches!(self.query, Query::ToView) {
let point = mount.geometry.view.unwrap_or_default().point(
crate::geometry::Point::new(
point.x + mount.geometry.x,
point.y + mount.geometry.y,
),
);
mount
.geometry
.panel
.as_ref()
.map_or(Some(point), |panel| panel.project_point(point))
} else {
mount.geometry.logical_point(point).map(|point| {
crate::geometry::Point::new(
point.x - mount.geometry.x,
point.y - mount.geometry.y,
)
})
};
if let Some(point) = point {
let result = cx.new_object()?;
let desktop = cx.upgrade(self.desktop)?.ok_or(VmError::InvalidArgument(
"coordinate conversion desktop expired",
))?;
crate::ui_bridge::attach_desktop_type(cx, result, "Point", desktop)?;
cx.set_attr(result, "x", crate::native_visual::value(point.x))?;
cx.set_attr(result, "y", crate::native_visual::value(point.y))?;
Value::Object(result)
} else {
Value::Nil
}
}
Query::ScrollTo | Query::ScrollBy => {
crate::scroll::set(
cx,
@@ -133,6 +213,24 @@ impl NativeCallable for Method {
crate::scroll::into_view(cx, self.owner, self.desktop)?;
Value::Nil
}
Query::FitView => {
crate::viewport::fit(cx, &mount)?;
Value::Nil
}
Query::Pick3D => {
let desktop = cx
.upgrade(self.desktop)?
.ok_or(VmError::InvalidArgument("viewport desktop expired"))?;
crate::scene3d_model::pick(
cx,
desktop,
&mount,
crate::geometry::Point::new(
crate::scroll::coordinate(&args[0])?,
crate::scroll::coordinate(&args[1])?,
),
)?
}
Query::ScrollPosition => {
let p = mount
.geometry
@@ -244,6 +342,7 @@ impl NativeCallable for Method {
}
}
/// 声明 Mount 查询方法的源类型契约,区分几何、层次与坐标操作。
fn mount_signature(
store: &endor_core::ObjectStore,
desktop: ObjectRef,
@@ -258,18 +357,28 @@ fn mount_signature(
}
Query::Page => CallType::nullable(nominal("Page")?),
Query::HitTest => T::Bool.into(),
Query::Pick3D => CallType::nullable(nominal("RayHit3D")?),
Query::ToView | Query::ToLocal => CallType::nullable(nominal("Point")?),
Query::ScrollPosition => T::Any.into(),
_ => T::Unit.into(),
};
let effect = if matches!(
query,
Query::ScrollTo | Query::ScrollBy | Query::ScrollIntoView | Query::Focus
Query::ScrollTo | Query::ScrollBy | Query::ScrollIntoView | Query::FitView | Query::Focus
) {
CallEffect::Mutating
} else {
CallEffect::ReadOnly
};
let parameters = if matches!(query, Query::HitTest | Query::ScrollTo | Query::ScrollBy) {
let parameters = if matches!(
query,
Query::HitTest
| Query::Pick3D
| Query::ToView
| Query::ToLocal
| Query::ScrollTo
| Query::ScrollBy
) {
vec![T::Number, T::Number]
} else {
vec![]
@@ -280,12 +389,14 @@ fn mount_signature(
}
#[derive(Debug, Default, Clone)]
/// 活动出现的弱索引。真实托管拥有关系在 desktop 的挂载字典中,索引不能充当隐藏 GC 根。
pub struct MountTable {
pub active: HashMap<u64, WeakObjectRef>,
order: Vec<u64>,
}
#[derive(Debug)]
/// 同步出现关系时的共享临时工作状态,保存本轮重用、建立和退役安排。
struct Sync {
desktop: ObjectRef,
page: Option<ObjectRef>,
@@ -298,6 +409,7 @@ struct Sync {
}
#[derive(Debug)]
/// 将一个生命周期回调及参数接入同一 VM 调用序列。
struct LifecycleCall {
function: ObjectRef,
block: ObjectRef,
@@ -305,10 +417,12 @@ struct LifecycleCall {
unmount: bool,
}
impl NativeCallable for LifecycleCall {
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
fn arity(&self) -> Option<endor_core::CallArity> {
Some(endor_core::CallArity::exact(0))
}
/// VM 调入本宿主能力的入口;按所属操作解码参数并返回托管值或后续调用。
fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> {
if self.unmount {
crate::tasks::cancel_owner(cx, self.mount)?;
@@ -320,6 +434,7 @@ impl NativeCallable for LifecycleCall {
}
}
/// 构造生命周期调用所需的托管函数与参数,使回调遵循同一 VM 的引用和执行约束。
fn lifecycle_call(
cx: &mut NativeContext<'_>,
mount: ObjectRef,
@@ -347,10 +462,12 @@ fn lifecycle_call(
}
impl NativeCallable for Sync {
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
fn arity(&self) -> Option<endor_core::CallArity> {
Some(endor_core::CallArity::exact(0))
}
/// VM 调入本宿主能力的入口;按所属操作解码参数并返回托管值或后续调用。
fn invoke(&self, cx: &mut NativeContext<'_>, _args: &[Value]) -> Result<NativeResult, VmError> {
let mut blocks = HashMap::new();
for weak in &self.nodes {
@@ -405,6 +522,10 @@ impl NativeCallable for Sync {
("scrollBy", Query::ScrollBy),
("scrollPosition", Query::ScrollPosition),
("scrollIntoView", Query::ScrollIntoView),
("fitView", Query::FitView),
("pick3D", Query::Pick3D),
("toView", Query::ToView),
("toLocal", Query::ToLocal),
("parent", Query::Parent),
("firstChild", Query::FirstChild),
("nextSibling", Query::NextSibling),
@@ -536,6 +657,7 @@ impl NativeCallable for Sync {
/// Explicitly owned roots protect the old presentation while preparation
/// temporarily replaces its desktop dictionary and Mount payloads.
/// 布局准备前的挂载快照与临时保留,用于取消恢复;成功提交后必须释放其保留引用。
pub struct Checkpoint {
table: MountTable,
dictionary: Option<ObjectRef>,
@@ -544,6 +666,7 @@ pub struct Checkpoint {
}
impl Checkpoint {
/// 释放检查点为回滚临时保留的托管根,成功提交后不再需要这些引用。
pub fn release(self, vm: &mut Vm) -> Result<(), VmError> {
let mut result = Ok(());
for root in self.roots.into_iter().rev() {
@@ -554,6 +677,7 @@ impl Checkpoint {
result
}
/// 恢复检查点中尚未发布的出现关系与布局上下文,并释放临时保留。
pub fn restore(
self,
vm: &mut Vm,
@@ -613,6 +737,7 @@ impl Checkpoint {
}
impl MountTable {
/// 保留布局准备前的 Mount 状态,供失败或取消路径恢复。
pub fn checkpoint(&self, vm: &mut Vm, desktop: ObjectRef) -> Result<Checkpoint, VmError> {
let dictionary = match vm.get_attr(desktop, "mounts") {
Ok(Value::Object(dictionary)) => Some(dictionary),
@@ -668,6 +793,7 @@ impl MountTable {
/// A faulted domain cannot run user onUnmount callbacks. Still detach every
/// context and release its owning dictionary through the normal heap barrier.
/// 退役当前出现表,撤销挂载关系并准备不再展示的生命周期状态。
pub fn retire(&mut self, vm: &mut Vm, desktop: ObjectRef) -> Result<(), VmError> {
for weak in self.ordered().into_iter().rev() {
if let Some(object) = vm.upgrade(weak)? {
@@ -694,6 +820,7 @@ impl MountTable {
Ok(())
}
/// 按原始展示顺序返回弱 Mount 身份,供事件和协议驱动器保持稳定顺序。
pub fn ordered(&self) -> Vec<WeakObjectRef> {
self.order
.iter()
@@ -701,6 +828,7 @@ impl MountTable {
.collect()
}
/// 根据新结构复用或建立每次出现的 Mount,连接父子关系并准备生命周期调用。
pub fn synchronize(
&mut self,
vm: &mut Vm,
@@ -1,23 +1,32 @@
//! 给源协议返回的对象列表提供受控封装。列表内容通过托管引用被追踪,读方法只暴露检查后的条目。
//! 用于儿童组成、布局结果和几何输入等需要保留对象身份的场景;不是窗口线程共享的可变容器。
//!
//! Managed indexed host results; values and the at method are traced edges.
use endor_core::{
ContextNativeFunction, NativeCallable, NativeContext, NativeResult, ObjectPayload, ObjectRef,
Value, VmError,
};
#[derive(Debug)]
/// 托管对象序列,trace 负责拥有其中的对象引用;源代码通过受检查方法读取。
struct ObjectList(Vec<ObjectRef>);
impl ObjectPayload for ObjectList {
/// 声明此 payload 的赋值遵循引用身份语义,避免把内部宿主状态当作可复制值。
fn reference_assignment_only(&self) -> bool {
true
}
/// 提供受检查的 Any 下转型入口,让宿主按具体 payload 类型读取数据。
fn as_any(&self) -> &dyn std::any::Any {
self
}
/// 返回运行时诊断/类型检查使用的稳定 payload 名称。
fn kind_name(&self) -> &'static str {
"tessera-object-list"
}
/// 声明此 payload 是否允许使用托管属性存储,具体字段仍由类型与调用检查约束。
fn allows_attributes(&self) -> bool {
true
}
/// 枚举本对象真正拥有的托管强引用,供 Aster 引用追踪和循环回收使用。
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
for mount in &self.0 {
visit(*mount);
@@ -26,8 +35,10 @@ impl ObjectPayload for ObjectList {
}
#[derive(Debug)]
/// 绑定到某个列表对象的下标访问适配器。
struct At(ObjectRef);
impl NativeCallable for At {
/// 给出参数与返回值的托管类型契约;实际操作在 invoke 中执行。
fn signature(&self) -> Option<endor_core::CallSignature> {
Some(endor_core::CallSignature::exact(
vec![endor_core::AnnotationType::Number],
@@ -35,10 +46,12 @@ impl NativeCallable for At {
endor_core::CallEffect::ReadOnly,
))
}
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
fn arity(&self) -> Option<endor_core::CallArity> {
Some(endor_core::CallArity::exact(1))
}
/// VM 调入本宿主能力的入口;按所属操作解码参数并返回托管值或后续调用。
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
let [Value::Number(index)] = args else {
return Err(VmError::InvalidArgument("object list at expects an index"));
@@ -57,6 +70,7 @@ impl NativeCallable for At {
}
}
/// 将已有对象引用包装为新的 ObjectList,并安装默认名义类型及下标查询方法。
pub fn collection(
cx: &mut NativeContext<'_>,
mounts: Vec<ObjectRef>,
@@ -65,6 +79,7 @@ pub fn collection(
build(cx, mounts, desktop, None)
}
/// 根据当前输入构造本模块的派生结果,具体的验证与资源边界见函数内步骤。
fn build(
cx: &mut NativeContext<'_>,
mounts: Vec<ObjectRef>,
@@ -96,23 +111,28 @@ fn build(
Ok(set)
}
/// 借用受检查列表的条目;返回值的有效期仍依赖原托管对象存活。
pub fn items(store: &endor_core::ObjectStore, list: ObjectRef) -> Result<&[ObjectRef], VmError> {
Ok(&store.payload::<ObjectList>(list, "ObjectList")?.0)
}
#[derive(Debug)]
/// ObjectList 原生类型的可调用构造器,负责检查传入子对象。
pub struct Constructor {
pub signature: Option<endor_core::CallSignature>,
pub desktop: ObjectRef,
}
impl NativeCallable for Constructor {
/// 给出参数与返回值的托管类型契约;实际操作在 invoke 中执行。
fn signature(&self) -> Option<endor_core::CallSignature> {
self.signature.clone()
}
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
fn arity(&self) -> Option<endor_core::CallArity> {
Some(endor_core::CallArity::range(1, usize::MAX))
}
/// VM 调入本宿主能力的入口;按所属操作解码参数并返回托管值或后续调用。
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
let [Value::Object(definition), values @ ..] = args else {
return Err(VmError::InvalidArgument("ObjectList type argument"));
@@ -1,3 +1,6 @@
//! 一个原生窗口对应一份 Presentation:独立视口、Mount、测量缓存、焦点与依赖记录。
//! 多个窗口仍使用同一个 VM 和共享业务对象。读取版本失效时只标记相关展示需要刷新,不能因此复制一份业务状态。
//!
//! Per-window rendering state. Business objects and code remain in one VM.
//! Registries and caches borrow checked identities; the managed desktop owns
//! presentation roots through its pending/mount dictionaries.
@@ -6,6 +9,7 @@ use endor_core::{ChangeBatch, NativeContext, ObjectRef, Vm, VmError, WeakObjectR
use std::sync::Arc;
#[derive(Debug)]
/// 一个窗口独立的展示状态:活动页面、待提交请求、Mount、布局与源读取缓存;共享 VM 的业务状态不放在这里复制。
pub(crate) struct Presentation {
pub desktop: ObjectRef,
pub closing: bool,
@@ -16,6 +20,7 @@ pub(crate) struct Presentation {
pub tab_ids: Vec<(WeakObjectRef, u64)>,
pub next_tab: u64,
pub last_tabs: Vec<crate::tabs::Tab>,
pub surface: crate::page::Surface,
pub render_cache: crate::snapshot::RenderCache,
pub layout: crate::layout::LayoutRuntime,
pub mounts: crate::mount::MountTable,
@@ -33,6 +38,7 @@ pub(crate) struct Presentation {
}
impl Presentation {
/// 比较布局/绘制读取版本和名称依赖,标记需要刷新并通知快照缓存。
pub fn observe_changes(&mut self, vm: &Vm, changes: &ChangeBatch) {
if let Some((phase, object, version)) = self
.layout_reads
@@ -81,6 +87,7 @@ impl Presentation {
});
}
/// 按尺寸、内容或绘制失效原因清理对应缓存,避免把所有变化都当成相同重建。
pub fn invalidate(
&mut self,
cx: &mut NativeContext<'_>,
@@ -111,6 +118,7 @@ impl Presentation {
Ok(())
}
/// 构造本类型并初始化其状态;资源建立和默认字段以函数体为准。
pub fn new(desktop: ObjectRef, tabs: ObjectRef) -> Self {
Self {
desktop,
@@ -122,6 +130,7 @@ impl Presentation {
tab_ids: Vec::new(),
next_tab: 0,
last_tabs: Vec::new(),
surface: crate::page::Surface::default(),
render_cache: crate::snapshot::RenderCache::default(),
layout: crate::layout::LayoutRuntime::default(),
mounts: crate::mount::MountTable::default(),
@@ -140,6 +149,7 @@ impl Presentation {
}
}
/// 把读取记录拆成对象版本和精确名称依赖,便于按实际观察内容判断失效。
pub(crate) fn split_reads(
reads: Vec<endor_core::ReadDependency>,
) -> (
@@ -177,9 +187,18 @@ mod tests {
height: 160.0,
});
let root = UiNode {
surface: None,
flex: 0.0,
flex_policy: crate::layout::FlexPolicy::default(),
main_align: crate::layout::MainAlign::Start,
cross_align: crate::layout::CrossAlign::Start,
align_self: None,
margin: crate::layout::Insets::default(),
sizing: crate::box_model::Sizing::default(),
padding_edges: [None; 4],
border: crate::layout::Insets::default(),
border_color: "#D8DCE2".into(),
clip_children: false,
block_id: "shared".into(),
protocol_key: "rect".into(),
slots: Vec::new(),
@@ -1,9 +1,13 @@
//! 安装 Visual、EventTarget、Children 和 Presentable 等能力契约。
//! 契约描述对象能响应什么源方法;具体测量、绘制、事件执行仍在各自协议驱动器中完成。
//!
//! Host capability definitions over Aster's explicit managed trait relations.
use endor_core::{
AnnotationType, CallArity, CallEffect, CallSignature, ObjectRef, TypedMethodRequirement, Value,
Vm, VmError,
};
/// 把本模块的类型、方法或能力注册到所属运行时上下文。
pub fn install(
vm: &mut Vm,
roots: &mut Vec<ObjectRef>,
+927
View File
@@ -0,0 +1,927 @@
//! 将 Endor 托管场景对象转换成可供渲染线程读取的 3D 数据。
//! 构造器和字段仍属于 VM;快照复制必要的数值、不可变网格和依赖,渲染器不读取托管堆。
//! 场景遍历组合局部变换、检查环和资源限制,并为 Panel3D 提取独立 UI 根。控制器更新相机;拾取结果再映射回托管节点。
//!
//! Traced 3D objects and checked immutable snapshots. No managed handle enters
//! the renderer; cameras and node transforms remain editable Endor attributes.
use crate::{
object_list,
scene3d::{
self,
math::{Camera, Matrix, Projection, Vec3},
},
};
use endor_core::{NativeContext, ObjectPayload, ObjectRef, ObjectStore, Value, VmError};
use std::{collections::HashSet, sync::Arc};
#[derive(Debug, Clone, Copy)]
/// 源 3D 类型的构造元数据入口,统一管理名称、参数、数量和可变子项。
pub enum Constructor {
Vec3,
Triangle,
Geometry,
Mesh,
Box,
Group,
Scene,
Light,
Perspective,
Orthographic,
Orbit,
Panel,
}
impl Constructor {
/// 返回内部枚举或对象对应的稳定源名称。
pub fn name(self) -> &'static str {
match self {
Self::Vec3 => "Vec3",
Self::Triangle => "Triangle3D",
Self::Geometry => "Geometry3D",
Self::Mesh => "Mesh3D",
Self::Box => "Box3D",
Self::Group => "Group3D",
Self::Scene => "Scene3D",
Self::Light => "DirectionalLight",
Self::Perspective => "PerspectiveCamera",
Self::Orthographic => "OrthographicCamera",
Self::Orbit => "OrbitController",
Self::Panel => "Panel3D",
}
}
/// 取得本构造器对应的源工厂函数名称。
pub fn function(self) -> &'static str {
match self {
Self::Vec3 => "vec3",
Self::Triangle => "triangle3D",
Self::Geometry => "geometry3D",
Self::Mesh => "mesh3D",
Self::Box => "box3D",
Self::Group => "group3D",
Self::Scene => "scene3D",
Self::Light => "directionalLight",
Self::Perspective => "perspectiveCamera",
Self::Orthographic => "orthographicCamera",
Self::Orbit => "orbitController",
Self::Panel => "panel3D",
}
}
/// 反查源构造器名称对应的原生 3D 种类,不认识的名称返回空值。
pub fn from_function(name: &str) -> Option<Self> {
[
Self::Vec3,
Self::Triangle,
Self::Geometry,
Self::Mesh,
Self::Box,
Self::Group,
Self::Scene,
Self::Light,
Self::Perspective,
Self::Orthographic,
Self::Orbit,
Self::Panel,
]
.into_iter()
.find(|kind| kind.function() == name)
}
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
pub fn arity(self) -> (usize, usize) {
match self {
Self::Vec3 | Self::Triangle => (3, 3),
Self::Geometry | Self::Mesh => (2, 2),
Self::Box => (4, 4),
Self::Group | Self::Scene => (0, 4096),
Self::Light => (5, 5),
Self::Panel => (3, 3),
_ => (0, 0),
}
}
/// 列出本构造器的参数类型名称,供签名安装与源调用检查使用。
pub fn parameters(self) -> &'static [&'static str] {
match self {
Self::Vec3 | Self::Triangle => &["Number", "Number", "Number"],
Self::Geometry => &["ObjectList", "ObjectList"],
Self::Mesh => &["Geometry3D", "String"],
Self::Box => &["Number", "Number", "Number", "String"],
Self::Light => &["Number", "Number", "Number", "String", "Number"],
Self::Panel => &["Number", "Number", "Block"],
_ => &[],
}
}
/// 标记构造器是否接收数量可变的子对象。
pub fn variadic(self) -> bool {
matches!(self, Self::Group | Self::Scene)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// 托管 3D 节点的名义种类,防止仅有同名字段的任意对象冒充场景节点。
pub enum NodeKind {
Vector,
Triangle,
Mesh,
Group,
Scene,
Light,
Perspective,
Orthographic,
Orbit,
Panel,
}
#[derive(Debug)]
/// 允许普通属性的 3D 标记 payload;数值字段仍由托管属性系统拥有。
pub struct Node(pub NodeKind);
impl ObjectPayload for Node {
/// 提供受检查的 Any 下转型入口,让宿主按具体 payload 类型读取数据。
fn as_any(&self) -> &dyn std::any::Any {
self
}
/// 返回运行时诊断/类型检查使用的稳定 payload 名称。
fn kind_name(&self) -> &'static str {
"scene-3d-object"
}
/// 声明此 payload 的赋值遵循引用身份语义,避免把内部宿主状态当作可复制值。
fn reference_assignment_only(&self) -> bool {
true
}
/// 声明此 payload 是否允许使用托管属性存储,具体字段仍由类型与调用检查约束。
fn allows_attributes(&self) -> bool {
true
}
}
#[derive(Debug)]
/// 托管不可变网格包装,顶点和三角形数值已经复制为原生 Arc 数据。
pub struct Geometry(pub Arc<scene3d::Geometry>);
impl ObjectPayload for Geometry {
/// 提供受检查的 Any 下转型入口,让宿主按具体 payload 类型读取数据。
fn as_any(&self) -> &dyn std::any::Any {
self
}
/// 返回运行时诊断/类型检查使用的稳定 payload 名称。
fn kind_name(&self) -> &'static str {
"geometry-3d"
}
/// 声明此 payload 的赋值遵循引用身份语义,避免把内部宿主状态当作可复制值。
fn reference_assignment_only(&self) -> bool {
true
}
/// 声明此 payload 是否允许使用托管属性存储,具体字段仍由类型与调用检查约束。
fn allows_attributes(&self) -> bool {
true
}
}
/// 统一构造本模块的参数错误,让调用方停止处理无效输入。
fn invalid(message: &'static str) -> VmError {
VmError::InvalidArgument(message)
}
/// 把源 Value 转换为受检查的托管对象引用,拒绝非对象输入。
fn object_ref(value: &Value) -> Result<ObjectRef, VmError> {
if let Value::Object(object) = value {
Ok(*object)
} else {
Err(invalid("3D field requires an object"))
}
}
/// 在源 Value 与所需数值表示之间转换,并沿用本调用的有限值/范围检查。
fn number(value: &Value) -> Result<f32, VmError> {
crate::scroll::coordinate(value)
}
/// 把当前源值或文本选择解码成此调用需要的文本表示。
fn text(value: &Value) -> Result<String, VmError> {
if let Value::Text(text) = value {
Ok(text.clone())
} else {
Err(invalid("3D field requires text"))
}
}
/// 把经过转换的数值写回指定托管字段,仍通过 VM/NativeContext 的检查入口。
fn set_number(
cx: &mut NativeContext<'_>,
object: ObjectRef,
name: &str,
value: f32,
) -> Result<(), VmError> {
cx.set_attr(object, name, crate::native_visual::value(value))
}
/// 解析颜色值并检查其满足当前原生绘制约定。
fn color(value: &str) -> Result<[f32; 3], VmError> {
let color = crate::document::parse_color(value).map_err(|_| invalid("invalid 3D color"))?;
if color.alpha != 255 {
return Err(invalid("3D opaque material color requires full alpha"));
}
Ok([
color.red as f32 / 255.,
color.green as f32 / 255.,
color.blue as f32 / 255.,
])
}
/// 按构造器建立对应托管 3D 类型,检查几何输入并安装默认属性。
pub fn allocate(
cx: &mut NativeContext<'_>,
desktop: ObjectRef,
definition: ObjectRef,
constructor: Constructor,
args: &[Value],
) -> Result<ObjectRef, VmError> {
let kind = match constructor {
Constructor::Vec3 => NodeKind::Vector,
Constructor::Triangle => NodeKind::Triangle,
Constructor::Mesh | Constructor::Box => NodeKind::Mesh,
Constructor::Group => NodeKind::Group,
Constructor::Scene => NodeKind::Scene,
Constructor::Light => NodeKind::Light,
Constructor::Perspective => NodeKind::Perspective,
Constructor::Orthographic => NodeKind::Orthographic,
Constructor::Orbit => NodeKind::Orbit,
Constructor::Panel => NodeKind::Panel,
Constructor::Geometry => {
let vertices = object_list::items(cx.store(), object_ref(&args[0])?)?
.iter()
.map(|&item| {
let p = cx.store();
if p.payload::<Node>(item, "Vec3")?.0 != NodeKind::Vector {
return Err(invalid("geometry vertices require Vec3"));
}
Ok(Vec3::new(
number(&p.get_attr(item, "x")?)?,
number(&p.get_attr(item, "y")?)?,
number(&p.get_attr(item, "z")?)?,
))
})
.collect::<Result<Vec<_>, VmError>>()?;
let triangles = object_list::items(cx.store(), object_ref(&args[1])?)?
.iter()
.map(|&item| {
if cx.store().payload::<Node>(item, "Triangle3D")?.0 != NodeKind::Triangle {
return Err(invalid("geometry indices require Triangle3D"));
}
let mut triangle = [0; 3];
for (index, name) in ["a", "b", "c"].into_iter().enumerate() {
let value = number(&cx.store().get_attr(item, name)?)?;
if value < 0. || value.fract() != 0. {
return Err(invalid("triangle indices must be nonnegative integers"));
}
triangle[index] = value as u32;
}
Ok(triangle)
})
.collect::<Result<Vec<_>, VmError>>()?;
let geometry = scene3d::Geometry {
vertices,
triangles,
uv: vec![],
};
if !geometry.valid() {
return Err(invalid(
"invalid Geometry3D buffers or geometry budget exceeded",
));
}
let object = cx.allocate(Geometry(Arc::new(geometry)))?;
cx.attach_type(object, definition)?;
return Ok(object);
}
};
let instance = cx.allocate(Node(kind))?;
cx.attach_type(instance, definition)?;
match kind {
NodeKind::Vector | NodeKind::Triangle => {
for (name, value) in (if kind == NodeKind::Vector {
["x", "y", "z"]
} else {
["a", "b", "c"]
})
.into_iter()
.zip(args)
{
set_number(cx, instance, name, number(value)?)?;
}
}
NodeKind::Mesh => {
let (geometry, material) = if matches!(constructor, Constructor::Box) {
let (w, h, d) = (number(&args[0])?, number(&args[1])?, number(&args[2])?);
if w < 0. || h < 0. || d < 0. {
return Err(invalid("Box3D dimensions must be nonnegative"));
}
let geometry =
cx.allocate(Geometry(Arc::new(scene3d::Geometry::cuboid(w, h, d))))?;
crate::ui_bridge::attach_desktop_type(cx, geometry, "Geometry3D", desktop)?;
(geometry, text(&args[3])?)
} else {
(object_ref(&args[0])?, text(&args[1])?)
};
cx.store().payload::<Geometry>(geometry, "Geometry3D")?;
color(&material)?;
cx.set_attr(instance, "geometry", Value::Object(geometry))?;
cx.set_attr(instance, "color", Value::Text(material))?;
}
NodeKind::Group | NodeKind::Scene => {
let children = args.iter().map(object_ref).collect::<Result<Vec<_>, _>>()?;
for child in &children {
if !matches!(
cx.store().payload::<Node>(*child, "3D node")?.0,
NodeKind::Mesh | NodeKind::Group | NodeKind::Light | NodeKind::Panel
) {
return Err(invalid(
"Scene3D/Group3D children require meshes, groups or lights",
));
}
}
let children = object_list::collection(cx, children, desktop)?;
cx.set_attr(instance, "children", Value::Object(children))?;
if kind == NodeKind::Scene {
set_number(cx, instance, "ambient", 0.25)?;
cx.set_attr(instance, "background", Value::Text("#F1F3F6".into()))?;
}
}
NodeKind::Light => {
for (name, value) in ["directionX", "directionY", "directionZ"]
.into_iter()
.zip(args)
{
set_number(cx, instance, name, number(value)?)?;
}
color(&text(&args[3])?)?;
cx.set_attr(instance, "color", args[3].clone())?;
set_number(cx, instance, "intensity", number(&args[4])?)?;
}
NodeKind::Panel => {
let content = object_ref(&args[2])?;
crate::block::validate(cx.store(), content, None)?;
set_number(cx, instance, "width", number(&args[0])?)?;
set_number(cx, instance, "height", number(&args[1])?)?;
set_number(cx, instance, "uiWidth", 512.)?;
set_number(cx, instance, "uiHeight", 320.)?;
cx.set_attr(instance, "content", Value::Object(content))?;
cx.set_attr(instance, "background", Value::Text("#FFFFFF".into()))?;
}
NodeKind::Perspective | NodeKind::Orthographic => {
for (name, value) in [
("x", 0.),
("y", 0.),
("z", 5.),
("targetX", 0.),
("targetY", 0.),
("targetZ", 0.),
("upX", 0.),
("upY", 1.),
("upZ", 0.),
("near", 0.1),
("far", 1000.),
("fov", 50.),
("height", 5.),
] {
set_number(cx, instance, name, value)?;
}
}
NodeKind::Orbit => {
set_number(cx, instance, "rotationSpeed", 0.005)?;
set_number(cx, instance, "panSpeed", 1.)?;
}
}
if matches!(kind, NodeKind::Mesh | NodeKind::Group | NodeKind::Panel) {
for (name, value) in [
("x", 0.),
("y", 0.),
("z", 0.),
("rotationX", 0.),
("rotationY", 0.),
("rotationZ", 0.),
("scaleX", 1.),
("scaleY", 1.),
("scaleZ", 1.),
] {
set_number(cx, instance, name, value)?;
}
}
Ok(instance)
}
/// 快照字段读取器,同时记录实际观察到的对象/属性依赖。
struct Reader<'a> {
store: &'a ObjectStore,
reads: HashSet<(ObjectRef, String)>,
}
impl Reader<'_> {
/// 读取字段并登记依赖,使后续字段变更能够使 3D 快照失效。
fn value(&mut self, object: ObjectRef, name: &str) -> Result<Value, VmError> {
self.reads.insert((object, name.into()));
self.store.get_attr(object, name)
}
/// 在源 Value 与所需数值表示之间转换,并沿用本调用的有限值/范围检查。
fn number(&mut self, object: ObjectRef, name: &str) -> Result<f32, VmError> {
number(&self.value(object, name)?)
}
/// 连续读取三个数值字段,组成位置、旋转或缩放向量。
fn vector(&mut self, object: ObjectRef, names: [&str; 3]) -> Result<Vec3, VmError> {
Ok(Vec3::new(
self.number(object, names[0])?,
self.number(object, names[1])?,
self.number(object, names[2])?,
))
}
/// 读取并校验透视或正交摄像机字段,生成不持有 VM 引用的投影描述。
fn camera(&mut self, object: ObjectRef) -> Result<Camera, VmError> {
let projection = match self.store.payload::<Node>(object, "3D camera")?.0 {
NodeKind::Perspective => Projection::Perspective {
fov: self.number(object, "fov")?,
},
NodeKind::Orthographic => Projection::Orthographic {
height: self.number(object, "height")?,
},
_ => {
return Err(invalid(
"Viewport3D requires a PerspectiveCamera or OrthographicCamera",
));
}
};
let camera = Camera {
position: self.vector(object, ["x", "y", "z"])?,
target: self.vector(object, ["targetX", "targetY", "targetZ"])?,
up: self.vector(object, ["upX", "upY", "upZ"])?,
near: self.number(object, "near")?,
far: self.number(object, "far")?,
projection,
};
if !camera.valid() {
return Err(invalid("invalid 3D camera basis or projection range"));
}
Ok(camera)
}
}
/// 从场景中提取的有限 UI 根,携带稳定面板 key 和逻辑排版尺寸。
pub struct PanelMount {
pub key: u64,
pub content: ObjectRef,
pub size: crate::layout::Size,
}
pub type Snapshot = (
Arc<scene3d::View>,
Vec<(ObjectRef, String)>,
Vec<PanelMount>,
);
/// 将当前托管或可变状态提取为后续阶段使用的派生表示。
pub fn snapshot(
store: &ObjectStore,
scene: ObjectRef,
camera: ObjectRef,
) -> Result<Snapshot, VmError> {
snapshot_reusing(store, scene, camera, None)
}
/// 遍历场景并记录字段依赖;如果世界数据未变则复用不可变场景和 BVH,只替换摄像机视图。
pub fn snapshot_reusing(
store: &ObjectStore,
scene: ObjectRef,
camera: ObjectRef,
reuse: Option<Arc<scene3d::Scene>>,
) -> Result<Snapshot, VmError> {
if store.payload::<Node>(scene, "Scene3D")?.0 != NodeKind::Scene {
return Err(invalid("Viewport3D requires a Scene3D"));
}
let mut reader = Reader {
store,
reads: HashSet::new(),
};
let camera = reader.camera(camera)?;
let ambient = reader.number(scene, "ambient")?;
if !(0.0..=1.0).contains(&ambient) {
return Err(invalid("Scene3D.ambient expects 0 through 1"));
}
let background = color(&text(&reader.value(scene, "background")?)?)?;
let mut output = scene3d::Scene {
meshes: Vec::new(),
lights: Vec::new(),
ambient,
background,
acceleration: Arc::default(),
};
let mut work = vec![(scene, Matrix::default(), false, 0u64)];
let mut panels = Vec::new();
let mut path = HashSet::new();
let mut visits = 0;
let mut triangles = 0;
let mut vertices = 0;
while let Some((object, parent, finish, key)) = work.pop() {
if finish {
path.remove(&object);
continue;
}
visits += 1;
if visits > 4096 {
return Err(VmError::ExecutionLimit("3D scene occurrences"));
}
if !path.insert(object) {
return Err(invalid("cyclic 3D scene graph"));
}
work.push((object, parent, true, key));
let kind = store.payload::<Node>(object, "3D node")?.0;
let world = if matches!(kind, NodeKind::Mesh | NodeKind::Group | NodeKind::Panel) {
parent.compose(Matrix::trs(
reader.vector(object, ["x", "y", "z"])?,
reader.vector(object, ["rotationX", "rotationY", "rotationZ"])?,
reader.vector(object, ["scaleX", "scaleY", "scaleZ"])?,
))
} else {
parent
};
match kind {
NodeKind::Scene | NodeKind::Group => {
let list = object_ref(&reader.value(object, "children")?)?;
for (index, child) in object_list::items(store, list)?.iter().enumerate().rev() {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
key.hash(&mut hasher);
index.hash(&mut hasher);
child.hash(&mut hasher);
work.push((*child, world, false, hasher.finish()));
}
}
NodeKind::Mesh => {
let geometry = object_ref(&reader.value(object, "geometry")?)?;
let geometry = store.payload::<Geometry>(geometry, "Geometry3D")?.0.clone();
triangles += geometry.triangles.len();
vertices += geometry.vertices.len();
if vertices > 262_144 {
return Err(VmError::ExecutionLimit("3D scene vertices"));
}
if triangles > scene3d::MAX_TRIANGLES {
return Err(VmError::ExecutionLimit("3D scene triangles"));
}
let material = color(&text(&reader.value(object, "color")?)?)?;
output.meshes.push(scene3d::Mesh {
identity: object.to_string(),
geometry,
world,
color: material,
panel: None,
});
}
NodeKind::Panel => {
// Arrangement slots cross Endor's signed integer API. A raw
// u64 hash can turn negative when native Bounds are created.
let key = key & i64::MAX as u64;
if panels.iter().any(|panel: &PanelMount| panel.key == key) {
return Err(invalid("colliding 3D UI occurrence identities"));
}
if panels.len() >= 64 {
return Err(VmError::ExecutionLimit("3D UI panels"));
}
let width = reader.number(object, "width")?;
let height = reader.number(object, "height")?;
let ui_width = reader.number(object, "uiWidth")?;
let ui_height = reader.number(object, "uiHeight")?;
if width <= 0.
|| height <= 0.
|| ![ui_width, ui_height]
.iter()
.all(|size| (1.0..=2048.0).contains(size) && size.fract() == 0.)
{
return Err(invalid(
"Panel3D requires positive world dimensions and integer UI dimensions from 1 through 2048",
));
}
let content = object_ref(&reader.value(object, "content")?)?;
crate::block::resolve(store, content)?;
let background = color(&text(&reader.value(object, "background")?)?)?;
let geometry = Arc::new(scene3d::Geometry {
vertices: vec![
Vec3::new(-width / 2., height / 2., 0.),
Vec3::new(width / 2., height / 2., 0.),
Vec3::new(width / 2., -height / 2., 0.),
Vec3::new(-width / 2., -height / 2., 0.),
],
triangles: vec![[0, 1, 2], [0, 2, 3]],
uv: vec![[0., 0.], [1., 0.], [1., 1.], [0., 1.]],
});
output.meshes.push(scene3d::Mesh {
identity: object.to_string(),
geometry,
world,
color: [1., 1., 1.],
panel: Some(scene3d::Panel {
key,
width: ui_width as u32,
height: ui_height as u32,
background,
surface: None,
}),
});
panels.push(PanelMount {
key,
content,
size: crate::layout::Size {
width: ui_width,
height: ui_height,
},
});
}
NodeKind::Light => {
if output.lights.len() >= 32 {
return Err(VmError::ExecutionLimit("3D scene lights"));
}
let direction =
reader.vector(object, ["directionX", "directionY", "directionZ"])?;
let direction = (world.point(direction) - world.point(Vec3::default()))
.normalized()
.ok_or(invalid("light direction cannot be zero"))?;
let color = color(&text(&reader.value(object, "color")?)?)?;
let intensity = reader.number(object, "intensity")?;
if !(0.0..=32.0).contains(&intensity) {
return Err(invalid("light intensity expects 0 through 32"));
}
output.lights.push(scene3d::Light {
direction,
color,
intensity,
});
}
_ => return Err(invalid("invalid node in 3D scene graph")),
}
}
let scene = if let Some(scene) = reuse.filter(|scene| **scene == output) {
scene
} else {
output.acceleration = Arc::new(scene3d::spatial::Index::build(&output.meshes));
Arc::new(output)
};
let view = Arc::new(scene3d::View { scene, camera });
if !view.valid() {
return Err(invalid("invalid 3D scene snapshot"));
}
Ok((view, reader.reads.into_iter().collect(), panels))
}
/// 把视口中的指针射线结果转换成 RayHit3D,关联实际托管网格和交点数据。
pub fn pick(
cx: &mut NativeContext<'_>,
desktop: ObjectRef,
mount: &crate::mount::Mount,
point: crate::geometry::Point,
) -> Result<Value, VmError> {
if mount.layout.is_some() {
return Err(invalid("pick3D requires a committed viewport"));
}
let (_, data) = crate::block::resolve(cx.store(), mount.block)?;
let data = crate::block::visual_data(cx.store(), data)?;
if !matches!(data.kind, crate::block::Kind::Viewport3D { .. }) {
return Err(invalid("pick3D requires a Viewport3D"));
}
if !mount.geometry.contains(point) {
return Ok(Value::Nil);
}
let node = crate::block::snapshot(cx.store(), mount.block)?;
let inset = crate::layout::insets(&node);
let Some(point) = mount.geometry.logical_point(point) else {
return Ok(Value::Nil);
};
let (width, height) = (
(mount.geometry.width - inset.horizontal()).max(0.),
(mount.geometry.height - inset.vertical()).max(0.),
);
if width <= 0. || height <= 0. {
return Ok(Value::Nil);
}
let (view, reads, _) = snapshot(
cx.store(),
data.scene3d.ok_or(invalid("missing Scene3D"))?,
data.camera.ok_or(invalid("missing 3D camera"))?,
)?;
let hit = view.pick(
(point.x - mount.geometry.x - inset.left) / width,
(point.y - mount.geometry.y - inset.top) / height,
width / height,
);
let Some(hit) = hit else {
return Ok(Value::Nil);
};
let mesh = reads
.iter()
.find_map(|(object, _)| (object.to_string() == hit.identity).then_some(*object))
.ok_or(invalid("picked mesh is unavailable"))?;
let result = cx.new_object()?;
crate::ui_bridge::attach_desktop_type(cx, result, "RayHit3D", desktop)?;
cx.set_attr(result, "mesh", Value::Object(mesh))?;
cx.set_attr(result, "node", Value::Object(mesh))?;
cx.set_attr(
result,
"instance",
Value::Number((hit.instance as i64).into()),
)?;
cx.set_attr(
result,
"distance",
crate::native_visual::value(hit.distance),
)?;
cx.set_attr(
result,
"triangle",
Value::Number((hit.triangle as i64).into()),
)?;
for (name, vector) in [
("point", hit.point),
("normal", hit.normal),
(
"barycentric",
Vec3::new(hit.barycentric[0], hit.barycentric[1], hit.barycentric[2]),
),
] {
let definition = crate::ui_bridge::desktop_type(cx.store(), "Vec3", desktop)?;
let vector = allocate(
cx,
desktop,
definition,
Constructor::Vec3,
&[
crate::native_visual::value(vector.x),
crate::native_visual::value(vector.y),
crate::native_visual::value(vector.z),
],
)?;
cx.set_attr(result, name, Value::Object(vector))?;
}
Ok(Value::Object(result))
}
#[derive(Debug)]
/// 指针拾取的中间结果,保留交点与所属实例信息供 Event/RayHit3D 使用。
pub struct PointerPick {
pub mount: ObjectRef,
pub desktop: ObjectRef,
pub point: crate::geometry::Point,
}
/// The default controller is replaceable; camera data has no dependency on it.
/// 为指定出现解码相机手势并调用控制器;嵌套面板输入先转换到所属视口坐标。
pub fn control(
cx: &mut NativeContext<'_>,
controller: ObjectRef,
camera_ref: ObjectRef,
gesture: ObjectRef,
) -> Result<(), VmError> {
if cx.store().payload::<Node>(controller, "OrbitController")?.0 != NodeKind::Orbit {
return Err(invalid("invalid orbit controller"));
}
let mut reader = Reader {
store: cx.store(),
reads: HashSet::new(),
};
let camera = reader.camera(camera_ref)?;
let dx = reader.number(gesture, "dx")?;
let dy = reader.number(gesture, "dy")?;
let kind = text(&reader.value(gesture, "kind")?)?;
let offset = camera.position - camera.target;
let radius = offset.length();
let mut position = camera.position;
let mut target = camera.target;
match kind.as_str() {
"scene-orbit" => {
let speed = reader.number(controller, "rotationSpeed")?;
if !(0.0..=1.0).contains(&speed) {
return Err(invalid("rotationSpeed expects 0 through 1"));
}
let up = camera
.up
.normalized()
.ok_or(invalid("camera up cannot be zero"))?;
let vertical = (offset.dot(up) / radius).clamp(-1., 1.);
let horizontal = (offset - up * offset.dot(up))
.normalized()
.ok_or(invalid("orbit at pole requires a different up vector"))?;
let (sine, cosine) = (dx * speed).sin_cos();
let horizontal = horizontal * cosine + up.cross(horizontal) * sine;
let pitch = (vertical.asin() + dy * speed).clamp(
-std::f32::consts::FRAC_PI_2 + 0.01,
std::f32::consts::FRAC_PI_2 - 0.01,
);
position = target + horizontal * (radius * pitch.cos()) + up * (radius * pitch.sin());
}
"scene-pan" => {
let speed = reader.number(controller, "panSpeed")?;
if !(0.0..=100.0).contains(&speed) {
return Err(invalid("panSpeed expects 0 through 100"));
}
let height = reader.number(gesture, "height")?.max(1.);
let units = match camera.projection {
Projection::Perspective { fov } => {
2. * radius * (fov.to_radians() / 2.).tan() / height
}
Projection::Orthographic { height: extent } => extent / height,
};
let basis = camera.basis().ok_or(invalid("invalid camera basis"))?;
let delta = basis.right * (dx * units * speed) + basis.up * (-dy * units * speed);
position = position + delta;
target = target + delta;
}
"scene-zoom" => {
let factor = reader.number(gesture, "factor")?;
if !(0.1..=10.0).contains(&factor) {
return Err(invalid("zoom factor expects 0.1 through 10"));
}
if let Projection::Orthographic { height } = camera.projection {
set_number(
cx,
camera_ref,
"height",
(height / factor).clamp(0.001, 1_000_000.),
)?;
} else {
let next =
(radius / factor).clamp(camera.near * 2., camera.far.max(camera.near * 2.));
position = target + offset * (next / radius);
}
}
_ => return Err(invalid("unsupported 3D camera gesture")),
}
if !position.valid() || !target.valid() {
return Err(invalid("camera movement exceeds world budget"));
}
for (name, value) in [
("x", position.x),
("y", position.y),
("z", position.z),
("targetX", target.x),
("targetY", target.y),
("targetZ", target.z),
] {
set_number(cx, camera_ref, name, value)?;
}
Ok(())
}
/// 执行托管 3D 节点的原生平移/旋转操作,供尚不支持普通数值算术表达式的源程序调用。
pub fn transform(
cx: &mut NativeContext<'_>,
owner: ObjectRef,
args: &[Value],
rotate: bool,
) -> Result<(), VmError> {
let kind = cx.store().payload::<Node>(owner, "3D transform target")?.0;
let camera = matches!(kind, NodeKind::Perspective | NodeKind::Orthographic);
if !matches!(
kind,
NodeKind::Mesh
| NodeKind::Group
| NodeKind::Panel
| NodeKind::Perspective
| NodeKind::Orthographic
) || rotate && camera
{
return Err(invalid("unsupported 3D transform target"));
}
let names = if rotate {
["rotationX", "rotationY", "rotationZ"]
} else {
["x", "y", "z"]
};
let mut updates = Vec::new();
for (index, name) in names.into_iter().enumerate() {
let delta = number(&args[index])?;
let value = number(&cx.store().get_attr(owner, name)?)? + delta;
if !value.is_finite() || !rotate && value.abs() > 1_000_000. {
return Err(invalid("3D transform exceeds world budget"));
}
updates.push((
name,
if rotate {
value.rem_euclid(360.)
} else {
value
},
));
if camera {
let name = ["targetX", "targetY", "targetZ"][index];
let value = number(&cx.store().get_attr(owner, name)?)? + delta;
if value.abs() > 1_000_000. {
return Err(invalid("camera target exceeds world budget"));
}
updates.push((name, value));
}
}
for (name, value) in updates {
set_number(cx, owner, name, value)?;
}
Ok(())
}
impl endor_core::NativeCallable for PointerPick {
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
fn arity(&self) -> Option<endor_core::CallArity> {
Some(endor_core::CallArity::exact(0))
}
/// VM 调入本宿主能力的入口;按所属操作解码参数并返回托管值或后续调用。
fn invoke(
&self,
cx: &mut NativeContext<'_>,
_: &[Value],
) -> Result<endor_core::NativeResult, VmError> {
let mount = cx
.store()
.payload::<crate::mount::Mount>(self.mount, "Mount")?
.clone();
let hit = pick(cx, self.desktop, &mount, self.point)?;
let definition = crate::ui_bridge::desktop_type(cx.store(), "Event", self.desktop)?;
let event = crate::event_dispatch::new_event(cx, definition, "click")?;
cx.set_attr(event, "hit", hit)?;
crate::event_dispatch::dispatch(cx, mount.block, event, Some(self.mount), self.desktop)
}
}
+122 -2
View File
@@ -1,3 +1,7 @@
//! 从可变托管对象图提取不可变 UiNode,并维护反向依赖与父子失效传播。
//! 缓存只借用可检查的对象身份,不增加托管根。对象释放后必须清理缓存索引;快照仍可持有独立的原生数值数据。
//! 干净子树直接复用 Arc;脏节点重新检查属性、方法、绑定和子项,循环与展开数量在发布前拒绝。
//!
//! Object-to-visual dependencies. Cached results never own VM references.
use crate::{
block::{self, Kind},
@@ -10,6 +14,7 @@ use std::{
};
#[derive(Debug)]
/// 某个业务组件的视觉快照,以及使它失效的读取依赖和子项身份。
struct Cached {
node: Arc<UiNode>,
dependencies: Vec<Dependency>,
@@ -17,13 +22,16 @@ struct Cached {
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// 反向依赖键:区分整个对象内容和精确属性名称,减少无关字段变化引起的失效。
struct Dependency {
object: ObjectRef,
property: Option<String>,
}
#[derive(Debug, Default)]
/// 视觉快照缓存与反向依赖图。对象身份是借用索引,原生 Arc 数据不拥有 VM 根。
pub struct RenderCache {
scenes3d: HashMap<ObjectRef, Arc<crate::scene3d::Scene>>,
entries: HashMap<ObjectRef, Cached>,
dependents: HashMap<Dependency, HashSet<ObjectRef>>,
parents: HashMap<ObjectRef, HashSet<ObjectRef>>,
@@ -34,6 +42,7 @@ pub struct RenderCache {
}
impl RenderCache {
/// 把 VM 变化映射到读取过这些属性/对象的视觉节点,再沿父链向上传播脏标记。
pub fn invalidate(&mut self, batch: ChangeBatch) {
let mut queue = VecDeque::new();
if batch.rescan_required {
@@ -57,6 +66,7 @@ impl RenderCache {
self.invalidate_objects(queue);
}
/// 迭代传播显式失效,使用集合避免共享父链重复遍历或循环入队。
pub fn invalidate_objects(&mut self, objects: impl IntoIterator<Item = ObjectRef>) {
let mut queue: VecDeque<_> = objects.into_iter().collect();
while let Some(block) = queue.pop_front() {
@@ -68,6 +78,7 @@ impl RenderCache {
}
}
/// 撤销旧缓存的反向读取边和父子边,为重新登记该节点做准备。
fn remove(&mut self, block: ObjectRef) -> Option<Cached> {
let old = self.entries.remove(&block)?;
for source in &old.dependencies {
@@ -89,7 +100,10 @@ impl RenderCache {
Some(old)
}
/// 删除托管堆中已不存在的身份,缓存本身不负责保持业务对象存活。
pub fn prune(&mut self, store: &ObjectStore) {
self.scenes3d
.retain(|object, _| store.object(*object).is_ok());
let dead: Vec<_> = self
.entries
.keys()
@@ -102,6 +116,7 @@ impl RenderCache {
}
}
/// 按显式栈遍历托管组成;复用干净子树,重建脏节点,并在完成前检查循环和资源上限。
pub fn snapshot(
&mut self,
store: &ObjectStore,
@@ -113,6 +128,7 @@ impl RenderCache {
let mut path = HashSet::new();
let mut values = Vec::<Arc<UiNode>>::new();
while let Some((block, finish)) = work.pop() {
// 入栈时先尝试复用;退出标记表示孩子已形成快照,可以组装父节点。
if !finish {
if !self.dirty.contains(&block)
&& let Some(cached) = self.entries.get(&block)
@@ -128,7 +144,7 @@ impl RenderCache {
}
store.check_typed_instance_storage(block)?;
let (data_ref, raw_data, raw_dependencies) = block::resolve_tracked(store, block)?;
let data = block::visual_data(store, raw_data)?;
let mut data = block::visual_data(store, raw_data)?;
let mut dependencies: Vec<_> = raw_dependencies
.into_iter()
.map(|object| Dependency {
@@ -154,6 +170,48 @@ impl RenderCache {
});
}
}
if matches!(data.kind, Kind::CanvasViewport { .. })
&& let Some(camera) = data.camera
{
for name in ["x", "y", "zoom"] {
dependencies.push(Dependency {
object: camera,
property: Some(name.into()),
});
}
}
let mut panel_sizes = Vec::new();
let view3d = if matches!(data.kind, Kind::Viewport3D { .. }) {
let scene = data
.scene3d
.ok_or(VmError::InvalidArgument("missing Scene3D"))?;
let (view, reads, panels) = crate::scene3d_model::snapshot_reusing(
store,
scene,
data.camera
.ok_or(VmError::InvalidArgument("missing 3D camera"))?,
self.scenes3d.get(&scene).cloned(),
)?;
self.scenes3d.insert(scene, view.scene.clone());
dependencies.extend(reads.into_iter().map(|(object, name)| Dependency {
object,
property: Some(name),
}));
data.children = panels
.into_iter()
.map(|panel| {
panel_sizes.push(panel.size);
crate::block::Child {
slot: panel.key,
block: panel.content,
}
})
.collect();
Some(view)
} else {
None
};
// path 只追踪当前祖先链,因此允许同一业务组件在不同分支多次出现。
if !finish {
if !path.insert(data_ref) {
return Err(VmError::InvalidArgument("cyclic Block composition"));
@@ -259,11 +317,60 @@ impl RenderCache {
children,
},
Kind::Spacer(size) => UiKind::Spacer(*size),
Kind::Viewport3D { width, height } => UiKind::Viewport3D {
width: *width,
height: *height,
view: view3d.ok_or(VmError::InvalidArgument("missing 3D view"))?,
controls: data.controller.is_some(),
panels: panel_sizes,
children,
},
Kind::CanvasViewport { width, height } => UiKind::CanvasViewport {
width: *width,
height: *height,
camera: crate::viewport::camera(
store,
data.camera
.ok_or(VmError::InvalidArgument("missing camera"))?,
)?,
children,
},
Kind::Scene2D => UiKind::Scene2D {
positions: data
.children
.iter()
.map(|child| {
let (_, child) = block::resolve(store, child.block)?;
Ok(block::visual_data(store, child)?.position)
})
.collect::<Result<Vec<_>, VmError>>()?,
children,
},
Kind::Overlay => UiKind::Overlay {
padding: data.padding,
children,
},
Kind::Row => UiKind::Row {
padding: data.padding,
gap: data.gap,
children,
},
Kind::Page if data.surface.mode == crate::page::Mode::Canvas => UiKind::Canvas {
positions: data
.children
.iter()
.map(|child| {
let (_, data) = block::resolve(store, child.block)?;
Ok(block::visual_data(store, data)?.position)
})
.collect::<Result<Vec<_>, VmError>>()?,
children,
},
Kind::Page if data.surface.mode == crate::page::Mode::Horizontal => UiKind::Row {
padding: data.padding,
gap: data.gap,
children,
},
Kind::Column | Kind::Page => UiKind::Column {
padding: data.padding,
gap: data.gap,
@@ -276,13 +383,26 @@ impl RenderCache {
},
};
let next = UiNode {
surface: matches!(data.kind, Kind::Page).then(|| {
let mut surface = data.surface.clone();
surface.page = block.to_string();
surface
}),
flex: data.flex,
flex_policy: data.flex_policy,
main_align: data.main_align,
cross_align: data.cross_align,
align_self: data.align_self,
margin: data.margin,
sizing: data.sizing,
padding_edges: data.padding_edges,
border: data.border,
border_color: data.border_color.clone(),
clip_children: data.clip_children,
block_id: block.to_string(),
protocol_key,
slots: data.children.iter().map(|c| c.slot).collect(),
interactive: matches!(&data.kind, Kind::Button)
interactive: matches!(&data.kind, Kind::Button | Kind::Viewport3D { .. })
|| data.click.is_some()
|| click_connection
|| custom_event,
+33
View File
@@ -1,3 +1,7 @@
//! 托管 Window 的页面所有权、原生命令与关闭生命周期。
//! 源码 resize/focus/setTitle 先产生纯数据命令;只有所属输入成功发布后,GUI 线程才应用它们。
//! 窗口 ID 和运行时 session 共同限定资源归属;切换 VM 或关闭窗口时不能让旧命令作用到新资源。
//!
//! Managed window resources and versioned, coalesced native projections.
//! The VM owns Page roots; only scalar commands cross to the GUI thread.
use crate::{native_visual, object_list, ui_bridge::desktop_type};
@@ -10,6 +14,7 @@ use std::sync::{Arc, Mutex};
pub const MAIN_WINDOW: u64 = 1;
pub const MAX_WINDOW_DIMENSION: f64 = 4096.0;
#[derive(Debug, Clone, PartialEq)]
/// 可投影到原生窗口的动作类别,如尺寸、标题、焦点与关闭。
pub enum Action {
Resize { width: f64, height: f64 },
SetTitle(String),
@@ -18,23 +23,27 @@ pub enum Action {
Close,
}
#[derive(Debug, Clone, PartialEq)]
/// 成功发布后由 GUI 执行的一条原生窗口请求,含资源身份和动作顺序。
pub struct Command {
pub window: u64,
pub sequence: u64,
pub action: Action,
}
impl Command {
/// 判断两条命令是否针对同一资源的同类动作,用于替换尚未执行的旧请求。
pub fn same_kind(&self, other: &Self) -> bool {
self.window == other.window
&& std::mem::discriminant(&self.action) == std::mem::discriminant(&other.action)
}
}
#[derive(Debug, Clone)]
/// 附带运行时 session 的命令,阻止旧域请求在新 VM 上生效。
pub struct Envelope {
pub session: u64,
pub command: Command,
}
#[derive(Debug, Clone)]
/// 托管窗口资源状态与页面拥有关系;本对象存在不等于 OS 窗口已创建。
pub struct ManagedWindow {
pub id: u64,
pub desktop: ObjectRef,
@@ -48,18 +57,23 @@ pub struct ManagedWindow {
outbox: Arc<Mutex<Vec<Command>>>,
}
impl ObjectPayload for ManagedWindow {
/// 提供受检查的 Any 下转型入口,让宿主按具体 payload 类型读取数据。
fn as_any(&self) -> &dyn std::any::Any {
self
}
/// 返回运行时诊断/类型检查使用的稳定 payload 名称。
fn kind_name(&self) -> &'static str {
"tessera-window"
}
/// 声明此 payload 是否允许使用托管属性存储,具体字段仍由类型与调用检查约束。
fn allows_attributes(&self) -> bool {
true
}
/// 声明此 payload 的赋值遵循引用身份语义,避免把内部宿主状态当作可复制值。
fn reference_assignment_only(&self) -> bool {
true
}
/// 枚举本对象真正拥有的托管强引用,供 Aster 引用追踪和循环回收使用。
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
visit(self.desktop);
if let Some(tasks) = self.tasks {
@@ -71,9 +85,11 @@ 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"));
@@ -84,6 +100,7 @@ fn screen_coordinate(value: &Value) -> Result<i32, VmError> {
.and_then(|number| i32::try_from(number).ok())
.ok_or(invalid("screen position exceeds limits"))
}
/// 从源 Value 取得窗口操作需要的数值,保留错误类型诊断。
fn scalar(value: &Value) -> Result<f64, VmError> {
let Value::Number(value) = value else {
return Err(invalid("window size requires numbers"));
@@ -98,6 +115,7 @@ fn scalar(value: &Value) -> Result<f64, VmError> {
Ok(number)
}
#[derive(Debug, Clone, Copy)]
/// 当前宿主 API 的操作分类,分派代码负责参数校验与状态更新。
enum Operation {
Id,
Viewport,
@@ -108,15 +126,18 @@ enum Operation {
Focus,
}
#[derive(Debug)]
/// 保存 owner、签名或操作枚举的原生方法适配器,统一由 VM 调用。
struct Method {
signature: endor_core::CallSignature,
operation: Operation,
desktop: ObjectRef,
}
impl NativeCallable for Method {
/// 给出参数与返回值的托管类型契约;实际操作在 invoke 中执行。
fn signature(&self) -> Option<endor_core::CallSignature> {
Some(self.signature.clone())
}
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
fn arity(&self) -> Option<endor_core::CallArity> {
Some(endor_core::CallArity::exact(match self.operation {
Operation::Resize | Operation::MoveTo => 3,
@@ -125,6 +146,7 @@ impl NativeCallable for Method {
}))
}
/// VM 调入本宿主能力的入口;按所属操作解码参数并返回托管值或后续调用。
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
let Some(Value::Object(owner)) = args.first() else {
return Err(invalid("Window method requires a Window"));
@@ -196,6 +218,7 @@ impl NativeCallable for Method {
Ok(NativeResult::Return(result))
}
}
/// 把合法窗口操作追加到所属窗口的待发布命令,不能直接在 VM 线程操作 OS。
pub fn enqueue(
cx: &mut NativeContext<'_>,
owner: ObjectRef,
@@ -225,6 +248,7 @@ pub fn enqueue(
Ok(())
}
/// 将页面登记到其窗口,维护托管所有权与页面顺序。
pub fn register_page(
cx: &mut NativeContext<'_>,
window: ObjectRef,
@@ -253,6 +277,7 @@ pub fn register_page(
}
Ok(())
}
/// 从窗口的页面集合撤销指定页面,保持后续展示索引一致。
pub fn unregister_page(
cx: &mut NativeContext<'_>,
window: ObjectRef,
@@ -276,6 +301,7 @@ pub fn unregister_page(
Ok(())
}
/// Discard an unpublished Page registration without invoking guest callbacks.
/// 宿主收尾路径撤销页面登记,用于已经由外层决定的关闭/退役流程。
pub fn unregister_page_host(
vm: &mut Vm,
window: ObjectRef,
@@ -290,6 +316,7 @@ pub fn unregister_page_host(
Ok(())
}
/// 在窗口之间移动页面的所有权和登记顺序,保留同一业务页面身份。
pub fn move_page(
cx: &mut NativeContext<'_>,
window: ObjectRef,
@@ -323,9 +350,11 @@ pub fn move_page(
}
Ok(())
}
/// 借用一个有效托管窗口的已登记页面集合。
pub fn pages(store: &ObjectStore, window: ObjectRef) -> Result<&[ObjectRef], VmError> {
Ok(&store.payload::<ManagedWindow>(window, "Window")?.pages)
}
/// 取走当前窗口累积的命令,后续由成功发布结果携带到 GUI。
pub fn take_commands(vm: &Vm, window: ObjectRef) -> Result<Vec<Command>, VmError> {
let data = vm.payload::<ManagedWindow>(window, "Window")?;
let mut queue = data
@@ -336,6 +365,7 @@ pub fn take_commands(vm: &Vm, window: ObjectRef) -> Result<Vec<Command>, VmError
commands.sort_by_key(|command| command.sequence);
Ok(commands)
}
/// 把本模块的类型、方法或能力注册到所属运行时上下文。
pub fn install(
vm: &mut Vm,
roots: &mut Vec<ObjectRef>,
@@ -413,6 +443,7 @@ pub fn install(
/// Create a managed native-window resource. The GUI creates the OS resource only
/// after the owning candidate/input publishes its immutable projection.
/// 建立托管窗口、desktop 与页面容器;原生窗口通过命令发布后出现。
pub fn create(
cx: &mut NativeContext<'_>,
master: ObjectRef,
@@ -449,6 +480,7 @@ pub fn create(
Ok((window, desktop, tabs))
}
/// 发起窗口关闭和相应生命周期清理,拒绝重复或不再有效的操作。
pub fn close(cx: &mut NativeContext<'_>, window: ObjectRef) -> Result<(), VmError> {
if cx.store().is_read_only() {
return Err(invalid(
@@ -477,6 +509,7 @@ pub fn close(cx: &mut NativeContext<'_>, window: ObjectRef) -> Result<(), VmErro
}
/// Host teardown for a stopped VM: no binding, dispatch or source execution.
/// 撤销已失效窗口的托管资源关系,不重新执行源关闭请求。
pub fn retire(vm: &mut Vm, window: ObjectRef) -> Result<(), VmError> {
let mut data = vm.payload::<ManagedWindow>(window, "Window")?.clone();
vm.dict_clear(data.tabs)?;
+135
View File
@@ -0,0 +1,135 @@
//! 有限布局盒子的尺寸策略。区分 auto、固定值和 fill,并处理 min/max 对约束与最终尺寸的限制。
//! margin、border、padding 的空间分配由布局层结合本模块完成;场景世界范围不被当成无限布局盒子。
//!
//! Native border-box sizing. An unbounded axis cannot resolve `fill`.
use crate::{layout::Size, ui_bridge::MAX_DIMENSION};
use anyhow::Result;
use endor_core::{Value, VmError};
#[derive(Debug, Clone, Copy, Default, PartialEq)]
/// 一个布局轴的尺寸策略:随内容、固定值或占用有限可用空间。
pub enum Dimension {
#[default]
Auto,
Fixed(f32),
Fill,
}
impl Dimension {
/// 把内部尺寸策略投影为相应的源属性表示。
pub fn value(self) -> Value {
match self {
Self::Auto => Value::Text("auto".into()),
Self::Fill => Value::Text("fill".into()),
Self::Fixed(value) => Value::Number((value as f64).into()),
}
}
/// 把外部源码或属性表示转换为内部枚举/结构,并反馈不支持的输入。
pub fn parse(value: &Value) -> Result<Self, VmError> {
match value {
Value::Text(text) if text == "auto" => Ok(Self::Auto),
Value::Text(text) if text == "fill" => Ok(Self::Fill),
Value::Number(_) => Ok(Self::Fixed(crate::scroll::coordinate(value).and_then(
|n| {
if n >= 0.0 {
Ok(n)
} else {
Err(VmError::InvalidArgument(
"box dimensions must be nonnegative",
))
}
},
)?)),
_ => Err(VmError::InvalidArgument(
"box dimension expects auto, fill or a nonnegative number",
)),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
/// border-box 尺寸策略与双轴上下限,实际求解仍要结合父级约束。
pub struct Sizing {
pub width: Dimension,
pub height: Dimension,
pub min_width: f32,
pub min_height: f32,
pub max_width: f32,
pub max_height: f32,
}
impl Default for Sizing {
/// 建立类型约定的初始值,供尚未发布或尚未交互的状态使用。
fn default() -> Self {
Self {
width: Dimension::Auto,
height: Dimension::Auto,
min_width: 0.0,
min_height: 0.0,
max_width: MAX_DIMENSION as f32,
max_height: MAX_DIMENSION as f32,
}
}
}
impl Sizing {
/// Constrain descendants using the actual finite box before wrapping text.
/// 根据固定/auto/fill 与 min/max 规则细化父级提供的可用约束。
pub fn available(self, mut constraints: [f32; 4]) -> [f32; 4] {
constraints[2] = constraints[2].min(self.max_width);
constraints[3] = constraints[3].min(self.max_height);
if let Dimension::Fixed(width) = self.width {
constraints[2] = constraints[2].min(width.max(self.min_width));
}
if let Dimension::Fixed(height) = self.height {
constraints[3] = constraints[3].min(height.max(self.min_height));
}
constraints[0] = constraints[0].min(constraints[2]);
constraints[1] = constraints[1].min(constraints[3]);
constraints
}
/// 结合内容期望尺寸、轴策略和父级约束求最终盒子尺寸;无界轴不能解析 fill。
pub fn resolve(self, intrinsic: Size, constraints: [f32; 4]) -> Result<Size> {
/// 针对单个尺寸轴应用约束与边界规则,供双轴尺寸求解复用。
fn axis(
policy: Dimension,
intrinsic: f32,
min: f32,
max: f32,
available: f32,
) -> Result<f32> {
let value = match policy {
Dimension::Auto => intrinsic,
Dimension::Fixed(value) => value,
Dimension::Fill => {
if available >= MAX_DIMENSION as f32 {
return Err(VmError::InvalidArgument(
"fill requires a finite parent allocation on this axis",
)
.into());
}
available
}
};
Ok(value.clamp(min, max).min(available))
}
Ok(Size {
width: axis(
self.width,
intrinsic.width,
self.min_width,
self.max_width,
constraints[2],
)?,
height: axis(
self.height,
intrinsic.height,
self.min_height,
self.max_height,
constraints[3],
)?,
})
}
}
+177
View File
@@ -0,0 +1,177 @@
//! 面向设备像素的绘制指令集合。它承载矩形、文字、裁剪与 3D 表面等原语,不直接操作 VM。
//! 平移和缩放统一作用于命令几何;文字样式和裁剪也要使用一致的设备比例。
//!
use crate::geometry::{Point, Rect};
use crate::text::TextStyle;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
/// 设备绘制使用的 RGBA 字节通道,区别于源代码的颜色文本。
pub struct Color {
pub red: u8,
pub green: u8,
pub blue: u8,
pub alpha: u8,
}
impl Color {
/// 从 RGB 通道构造不透明颜色值。
pub const fn rgb(red: u8, green: u8, blue: u8) -> Self {
Self {
red,
green,
blue,
alpha: 255,
}
}
/// 从 RGBA 通道构造带透明度的颜色值。
pub const fn rgba(red: u8, green: u8, blue: u8, alpha: u8) -> Self {
Self {
red,
green,
blue,
alpha,
}
}
}
#[derive(Clone, Debug)]
/// 原生画布最终顺序执行的绘制原语,已经使用对应设备比例。
pub enum DrawCommand {
Scene3D {
rect: Rect,
view: std::sync::Arc<crate::scene3d::View>,
},
Clear(Color),
PushClip(Rect),
PopClip,
FillRoundedRect {
rect: Rect,
radius: f32,
color: Color,
},
StrokeRoundedRect {
rect: Rect,
radius: f32,
width: f32,
color: Color,
},
WrappedText {
rect: Rect,
value: String,
style: TextStyle,
color: Color,
},
Text {
origin: Point,
value: String,
style: TextStyle,
color: Color,
},
}
impl DrawCommand {
/// 返回平移后的绘制命令,并同步移动命令中的相关几何。
pub fn translated(mut self, delta: Point) -> Self {
match &mut self {
Self::WrappedText { rect, .. }
| Self::Scene3D { rect, .. }
| Self::PushClip(rect)
| Self::FillRoundedRect { rect, .. }
| Self::StrokeRoundedRect { rect, .. } => {
rect.x += delta.x;
rect.y += delta.y;
}
Self::Text { origin, .. } => {
origin.x += delta.x;
origin.y += delta.y;
}
_ => {}
}
self
}
}
#[derive(Clone, Debug, Default)]
/// 有序绘制原语容器;命令顺序同时约束叠放和裁剪栈行为。
pub struct DisplayList {
commands: Vec<DrawCommand>,
}
impl DisplayList {
/// 按设备比例缩放命令,文字、边框和矩形不能分别使用不一致比例。
pub fn scale(&mut self, scale: f32) {
for command in &mut self.commands {
let rect = match command {
DrawCommand::WrappedText { rect, style, .. } => {
*style = style.scaled(scale);
Some(rect)
}
DrawCommand::PushClip(rect) => Some(rect),
DrawCommand::Scene3D { rect, .. } => Some(rect),
DrawCommand::FillRoundedRect { rect, radius, .. } => {
*radius *= scale;
Some(rect)
}
DrawCommand::StrokeRoundedRect {
rect,
radius,
width,
..
} => {
*radius *= scale;
*width *= scale;
Some(rect)
}
DrawCommand::Text { origin, style, .. } => {
origin.x *= scale;
origin.y *= scale;
*style = style.scaled(scale);
None
}
_ => None,
};
if let Some(rect) = rect {
rect.x *= scale;
rect.y *= scale;
rect.width *= scale;
rect.height *= scale;
}
}
}
/// 按绘制顺序追加一条原语,后加入的内容在合成顺序中位于后面。
pub fn push(&mut self, command: DrawCommand) {
self.commands.push(command);
}
/// 平移当前显示列表中的命令,供整块页面或管理面板放入窗口坐标。
pub fn translate(&mut self, delta: Point) {
for command in &mut self.commands {
match command {
DrawCommand::WrappedText { rect, .. }
| DrawCommand::Scene3D { rect, .. }
| 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
}
/// 按原顺序合并另一组绘制命令,不在这里重排层次。
pub fn extend(&mut self, other: DisplayList) {
self.commands.extend(other.commands);
}
}
+8 -1
View File
@@ -1,16 +1,21 @@
#[derive(Clone, Copy, Debug, Default, PartialEq)]
//! 共享的二维点和矩形值。命中判断在调用方完成坐标系转换后使用,矩形本身不隐式处理相机。
//!
#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
/// 二维坐标值;具体处于逻辑、局部还是设备空间由调用上下文决定。
pub struct Point {
pub x: f32,
pub y: f32,
}
impl Point {
/// 构造本类型并初始化其状态;资源建立和默认字段以函数体为准。
pub const fn new(x: f32, y: f32) -> Self {
Self { x, y }
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
/// 轴对齐矩形,保存原点和宽高,用于布局、裁剪与命中。
pub struct Rect {
pub x: f32,
pub y: f32,
@@ -19,6 +24,7 @@ pub struct Rect {
}
impl Rect {
/// 构造本类型并初始化其状态;资源建立和默认字段以函数体为准。
pub const fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
Self {
x,
@@ -28,6 +34,7 @@ impl Rect {
}
}
/// 判断给定点是否位于目标范围;需要相机转换的类型会先转换再判断。
pub fn contains(self, point: Point) -> bool {
point.x >= self.x
&& point.x <= self.x + self.width
+1160
View File
File diff suppressed because it is too large Load Diff
+18
View File
@@ -0,0 +1,18 @@
//! 渲染模块入口。排版、源视觉协议、相机投影和最终光栅化各自独立,通过不可变帧衔接。
//!
// Module ownership follows the directory; crate-root aliases keep internal call sites stable.
pub(crate) mod box_model;
pub(crate) mod display_list;
pub(crate) mod geometry;
pub(crate) mod layout;
pub(crate) mod native_visual;
pub(crate) mod page;
pub(crate) mod scene;
pub(crate) mod scene3d;
pub(crate) mod scroll;
pub(crate) mod software_renderer;
pub(crate) mod source_hit;
pub(crate) mod source_layout;
pub(crate) mod source_paint;
pub(crate) mod text;
pub(crate) mod viewport;
@@ -1,3 +1,6 @@
//! 让原生组件也通过 Endor 的 measure/arrange/paint 协议被调用。
//! 将 Constraints、Size、Bounds 与 PaintCommand 在托管值和 Rust 值之间转换;原生方法与源覆盖方法共用调用契约。
//!
//! Native visual protocol entry points. Values are ordinary managed Endor
//! objects; geometry is scoped to a live occurrence, never stored on a Block.
use crate::{
@@ -12,9 +15,11 @@ use endor_core::{
NativeContext, NativeResult, ObjectRef, ObjectStore, Value, Vm, VmError,
};
/// 统一构造本模块的参数错误,让调用方停止处理无效输入。
fn invalid(message: &'static str) -> VmError {
VmError::InvalidArgument(message)
}
/// 从源值中提取并检查托管对象身份,错误类型沿 VM 错误返回。
fn object(value: &Value) -> Result<ObjectRef, VmError> {
if let Value::Object(object) = value {
Ok(*object)
@@ -22,6 +27,7 @@ fn object(value: &Value) -> Result<ObjectRef, VmError> {
Err(invalid("visual protocol requires objects"))
}
}
/// 在源 Value 与所需数值表示之间转换,并沿用本调用的有限值/范围检查。
pub(crate) fn number(
cx: &NativeContext<'_>,
object: ObjectRef,
@@ -40,9 +46,11 @@ pub(crate) fn number(
}
Ok(value)
}
/// 将原生布局计算结果封装为协议需要的托管 Value。
pub(crate) fn value(value: f32) -> Value {
Value::Number((value as f64).into())
}
/// 新建指定名义类型的托管记录,并逐项设置字段,作为视觉协议的结果返回。
pub(crate) fn record(
cx: &mut NativeContext<'_>,
desktop: ObjectRef,
@@ -56,6 +64,7 @@ pub(crate) fn record(
}
Ok(object)
}
/// 在约束提供的视口内执行原生布局,从根出现提取宽高,再按协议约束限制结果。
fn size(node: &crate::ui_bridge::UiNode, constraints: [f32; 4]) -> Result<Size, VmError> {
let frame = layout::frame_with_viewport(
node,
@@ -75,6 +84,7 @@ fn size(node: &crate::ui_bridge::UiNode, constraints: [f32; 4]) -> Result<Size,
})
}
#[derive(Debug, Clone, Copy)]
/// 该原生能力的查询/操作分类,方法包装用它选择具体实现。
enum Query {
Measure,
Arrange,
@@ -82,12 +92,14 @@ enum Query {
HitTest,
}
#[derive(Debug)]
/// 保存 owner、签名或操作枚举的原生方法适配器,统一由 VM 调用。
struct Method {
query: Query,
desktop: ObjectRef,
signature: CallSignature,
}
/// Only this actual implementation can use the matching intrinsic fast path.
/// 判断方法是否为匹配协议的宿主原生实现,决定能否安全使用快速路径。
pub(crate) fn is_intrinsic(
store: &ObjectStore,
function: ObjectRef,
@@ -122,13 +134,16 @@ pub(crate) fn is_intrinsic(
}
impl NativeCallable for Method {
/// 给出参数与返回值的托管类型契约;实际操作在 invoke 中执行。
fn signature(&self) -> Option<CallSignature> {
Some(self.signature.clone())
}
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
fn arity(&self) -> Option<endor_core::CallArity> {
Some(endor_core::CallArity::exact(3))
}
/// VM 调入本宿主能力的入口;按所属操作解码参数并返回托管值或后续调用。
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
let [owner, context, input] = args else {
return Err(invalid("visual method expects a Mount and an input value"));
@@ -202,8 +217,8 @@ impl NativeCallable for Method {
)?)
}
Query::Arrange => {
let x = number(cx, input, "x", false)?;
let y = number(cx, input, "y", false)?;
let x = number(cx, input, "x", true)?;
let y = number(cx, input, "y", true)?;
let width = number(cx, input, "width", false)?;
let height = number(cx, input, "height", false)?;
if x + width > MAX_DIMENSION as f32 || y + height > MAX_DIMENSION as f32 {
@@ -214,13 +229,20 @@ impl NativeCallable for Method {
} else {
node.children()
.iter()
.map(|child| {
.enumerate()
.map(|(child_index, child)| {
size(
child,
layout::arranged_child_constraints(
layout::occurrence_constraints(
&node,
[0.0, 0.0, width, height],
child,
layout::arranged_child_constraints(
&node,
[0.0, 0.0, width, height],
Size { width, height },
),
Size { width, height },
child_index,
),
)
})
@@ -268,8 +290,25 @@ impl NativeCallable for Method {
return Err(invalid("visual bounds exceed limits"));
}
let mut commands = Vec::new();
if let Some(command) = layout::paint_native(&node, x, y, Size { width, height }) {
for command in layout::paint_commands(&node, x, y, Size { width, height }) {
let fields = match command {
RenderCommand::Scene3D {
x,
y,
width,
height,
view,
} => {
let snapshot = cx.allocate(crate::scene3d::PaintView(view))?;
vec![
("kind", Value::Text("scene3d".into())),
("x", value(x)),
("y", value(y)),
("width", value(width)),
("height", value(height)),
("scene", Value::Object(snapshot)),
]
}
RenderCommand::Text {
x,
y,
@@ -328,15 +367,18 @@ impl NativeCallable for Method {
}
#[derive(Debug)]
/// Point 的矩形/圆形命中辅助方法,保存结果类型和具体几何判定种类。
struct PointMethod {
expected: ObjectRef,
circle: bool,
signature: CallSignature,
}
impl NativeCallable for PointMethod {
/// 给出参数与返回值的托管类型契约;实际操作在 invoke 中执行。
fn signature(&self) -> Option<CallSignature> {
Some(self.signature.clone())
}
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
fn arity(&self) -> Option<endor_core::CallArity> {
Some(endor_core::CallArity::exact(if self.circle {
4
@@ -345,6 +387,7 @@ impl NativeCallable for PointMethod {
}))
}
/// VM 调入本宿主能力的入口;按所属操作解码参数并返回托管值或后续调用。
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
let Some(Value::Object(point)) = args.first() else {
return Err(invalid("Point method requires a Point"));
@@ -395,6 +438,7 @@ impl NativeCallable for PointMethod {
}
}
/// 把本模块的类型、方法或能力注册到所属运行时上下文。
pub fn install(
vm: &mut Vm,
roots: &mut Vec<ObjectRef>,
+205
View File
@@ -0,0 +1,205 @@
//! 旧 Page.mode 的兼容空间策略,以及页面级的正逆相机变换。
//! 新组合应优先使用普通布局、ScrollView 和独立场景视口;保留这里是为了兼容已有 window/vertical/horizontal/canvas 页面。
//!
//! Page space is independent of the native window. The camera is applied once
//! for painting and inverted once for input; layout and Mounts stay in world units.
use crate::{geometry::Point, layout::Size};
use endor_core::VmError;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
/// 旧 Page 的有限或自由空间模式,新场景视口不依赖它表达布局方向。
pub enum Mode {
#[default]
Window,
Vertical,
Horizontal,
Canvas,
}
impl Mode {
/// 返回内部枚举或对象对应的稳定源名称。
pub fn name(self) -> &'static str {
match self {
Self::Window => "window",
Self::Vertical => "vertical",
Self::Horizontal => "horizontal",
Self::Canvas => "canvas",
}
}
/// 把外部源码或属性表示转换为内部枚举/结构,并反馈不支持的输入。
pub fn parse(name: &str) -> Result<Self, VmError> {
match name {
"window" => Ok(Self::Window),
"vertical" => Ok(Self::Vertical),
"horizontal" => Ok(Self::Horizontal),
"canvas" => Ok(Self::Canvas),
_ => Err(VmError::InvalidArgument(
"Page.mode expects window, vertical, horizontal or canvas",
)),
}
}
/// 为旧页面模式生成有限轴和可延伸轴的根约束。
pub fn constraints(self, viewport: Option<Size>) -> [f32; 4] {
let Some(size) = viewport else {
return crate::layout::root_constraints(None);
};
let limit = crate::ui_bridge::MAX_DIMENSION as f32;
match self {
Self::Window => [size.width, size.height, size.width, size.height],
Self::Vertical => [size.width, size.height, size.width, limit],
Self::Horizontal => [size.width, size.height, limit, size.height],
Self::Canvas => [0.0, 0.0, limit, limit],
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
/// 页面级兼容相机状态和有限内容范围,支持绘制与命中正逆变换。
pub struct Surface {
pub mode: Mode,
pub page: String,
pub pan: Point,
#[serde(default = "unit")]
pub zoom: f32,
pub extent: Size,
}
/// 生成页面相机计算所需的单位比例或边界默认值。
fn unit() -> f32 {
1.0
}
impl Default for Surface {
/// 建立类型约定的初始值,供尚未发布或尚未交互的状态使用。
fn default() -> Self {
Self {
mode: Mode::Window,
page: String::new(),
pan: Point::default(),
zoom: 1.0,
extent: Size::default(),
}
}
}
impl Surface {
/// 构造本类型并初始化其状态;资源建立和默认字段以函数体为准。
pub fn new(mode: Mode) -> Self {
Self {
mode,
zoom: 1.0,
..Self::default()
}
}
/// 把页面视图坐标反算为旧 Page 相机下的世界坐标。
pub fn to_world(&self, point: Point) -> Point {
Point::new(
point.x / self.zoom + self.pan.x,
point.y / self.zoom + self.pan.y,
)
}
/// 把旧页面世界坐标变换到可见视图坐标。
pub fn to_view(&self, point: Point) -> Point {
Point::new(
(point.x - self.pan.x) * self.zoom,
(point.y - self.pan.y) * self.zoom,
)
}
/// 判断给定点是否位于目标范围;需要相机转换的类型会先转换再判断。
pub fn contains(&self, point: [f32; 2], viewport: Option<Size>) -> bool {
let point = self.to_view(Point::new(point[0], point[1]));
point.x >= 0.0
&& point.y >= 0.0
&& viewport.is_none_or(|size| point.x < size.width && point.y < size.height)
}
/// 只对有限页面按实际内容范围钳制偏移;自由画布不按内容边缘停止导航。
pub fn clamp(&mut self, viewport: Size) {
match self.mode {
Mode::Window => {
self.pan = Point::default();
self.zoom = 1.0;
}
Mode::Vertical => {
self.zoom = 1.0;
self.pan.x = 0.0;
self.pan.y = self
.pan
.y
.clamp(0.0, (self.extent.height - viewport.height).max(0.0));
}
Mode::Horizontal => {
self.zoom = 1.0;
self.pan.y = 0.0;
self.pan.x = self
.pan
.x
.clamp(0.0, (self.extent.width - viewport.width).max(0.0));
}
Mode::Canvas => {}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn camera_inverse_and_cursor_anchored_zoom_preserve_world_position() {
let mut view = Surface::new(Mode::Canvas);
view.pan = Point::new(-240.0, 120.0);
view.zoom = 0.75;
let pointer = Point::new(300.0, 180.0);
let world = view.to_world(pointer);
assert_eq!(view.to_view(world), pointer);
view.zoom = 2.0;
view.pan = Point::new(
world.x - pointer.x / view.zoom,
world.y - pointer.y / view.zoom,
);
assert_eq!(view.to_view(world), pointer);
assert!(view.contains(
[world.x, world.y],
Some(Size {
width: 500.0,
height: 400.0
})
));
assert!(!view.contains(
[-1000.0, -1000.0],
Some(Size {
width: 500.0,
height: 400.0
})
));
}
#[test]
fn finite_pages_clamp_after_content_shrinks() {
let mut view = Surface::new(Mode::Vertical);
view.pan = Point::new(25.0, 900.0);
view.extent = Size {
width: 400.0,
height: 800.0,
};
view.clamp(Size {
width: 400.0,
height: 600.0,
});
assert_eq!(view.pan, Point::new(0.0, 200.0));
view.extent.height = 100.0;
view.clamp(Size {
width: 400.0,
height: 600.0,
});
assert_eq!(view.pan.y, 0.0);
}
}
+96
View File
@@ -0,0 +1,96 @@
//! 合成整个原生窗口的显示列表:页面画面、宿主侧栏和开发工具绘制。
//! 窗口逻辑尺寸与设备像素比例在这里衔接。页面内容先应用其视角并裁剪,宿主控件的区域和命中布局另外返回。
//!
use crate::{
activity::Activity,
developer_tools::{self, DeveloperToolsLayout, Workspace as DeveloperToolsState},
display_list::{DisplayList, DrawCommand},
document::RenderDocument,
geometry::{Point, Rect},
};
#[derive(Clone, Debug, Default)]
/// 宿主管理区域的几何布局,供窗口事件分辨页面与工具命中。
pub struct SceneLayout {
pub developer_tools: DeveloperToolsLayout,
}
/// 组合页面、开发工具和侧栏的设备像素显示列表,同时返回供命中使用的宿主布局。
pub fn build_scene(
width: u32,
height: u32,
scale: f32,
document: &RenderDocument,
developer_tools_state: &mut DeveloperToolsState,
activity: &Activity,
sidebar: &mut crate::sidebar::State,
) -> DisplayScene {
let tool = document
.frame
.tabs
.iter()
.find(|tab| tab.active)
.and_then(|tab| tab.developer_tool.as_deref());
developer_tools_state.select(tool);
developer_tools_state.document_updated(document);
let left = sidebar.left();
let surface = &document.frame.surface;
let content = Rect::new(
left * scale,
0.0,
(width as f32 - left * scale).max(0.0),
height as f32,
);
let zoom = if tool.is_some() { 1.0 } else { surface.zoom };
let mut page = document.display_list(scale * zoom).unwrap_or_else(|_| {
RenderDocument::default()
.display_list(scale)
.expect("default document is valid")
});
page.translate(Point::new(
(left - surface.pan.x * zoom) * scale,
-surface.pan.y * zoom * scale,
));
let mut display_list = DisplayList::default();
display_list.push(DrawCommand::Clear(
crate::document::parse_color(&document.frame.background)
.unwrap_or(crate::system_ui::theme::BG),
));
display_list.push(DrawCommand::PushClip(content));
for command in page.commands() {
if !matches!(command, DrawCommand::Clear(_)) {
display_list.push(command.clone());
}
}
display_list.push(DrawCommand::PopClip);
let (mut developer_list, mut developer_layout) = developer_tools::build(
width.saturating_sub((left * scale) as u32),
height,
scale,
document,
developer_tools_state,
activity,
);
developer_list.translate(Point::new(left * scale, 0.0));
developer_layout.translate(left, 0.0);
display_list.extend(developer_list);
let mut chrome = sidebar.draw(
&document.frame.tabs,
height as f32 / scale,
developer_tools_state.accent,
);
chrome.scale(scale);
display_list.extend(chrome);
DisplayScene {
display_list,
layout: SceneLayout {
developer_tools: developer_layout,
},
}
}
/// 整窗合成结果:显示列表与同帧管理交互几何一起返回。
pub struct DisplayScene {
pub display_list: DisplayList,
pub layout: SceneLayout,
}

Some files were not shown because too many files have changed in this diff Show More