Compare commits
140 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e0eff7755f | |||
| 303c823eb0 | |||
| f787ff25e0 | |||
| 1fb6dc3b8f | |||
| 714d257058 | |||
| 21439d4c4d | |||
| 18376793b0 | |||
| 48fcb96f42 | |||
| 050f777e33 | |||
| 7b769b1477 | |||
| 846c99a991 | |||
| 38ddb80b7c | |||
| e54264f23b | |||
| 3a4a91d5b6 | |||
| 8881650d4f | |||
| cd092a9fed | |||
| 952fc2eff2 | |||
| 3cb44b96eb | |||
| d3165b1224 | |||
| 656522edfe | |||
| 3220544777 | |||
| 193c5bca89 | |||
| fa6dfa7062 | |||
| 1cf07a75f7 | |||
| 918cdbfa27 | |||
| e2802efe0a | |||
| ea81150390 | |||
| a5a55699cf | |||
| 1975d36cb1 | |||
| 514eeb8648 | |||
| ae3a2d6163 | |||
| 9bb61befd8 | |||
| a508842b09 | |||
| 1808c87394 | |||
| 839a3f248b | |||
| 13bb9e84aa | |||
| 6a8a643371 | |||
| 0c63cd3102 | |||
| ac1ae782c7 | |||
| a55178abb6 | |||
| 435f95187b | |||
| 1e7925ca65 | |||
| 0ad4555922 | |||
| 864e57ce1f | |||
| 7f77a4aa72 | |||
| d86b84800a | |||
| c9eb498932 | |||
| 5256ac1318 | |||
| 750484477b | |||
| 7bb59fe06f | |||
| e0a7d8169c | |||
| 485c35c641 | |||
| eb48ec3396 | |||
| 053b0f5fba | |||
| c418a425f3 | |||
| b725cf488d | |||
| 05b727a4a5 | |||
| 047e008729 | |||
| 05403e6996 | |||
| fc0634e79f | |||
| ae89dfad1e | |||
| 618bffdada | |||
| 65f5092f0f | |||
| acaef9ae29 | |||
| 180a08ea63 | |||
| d521568d73 | |||
| 799fe9f3c7 | |||
| 470454caa6 | |||
| 7289df036f | |||
| dfc69b4777 | |||
| ef44d7cb18 | |||
| 184b067945 | |||
| bd5c91ba99 | |||
| 5a1cf9d702 | |||
| 8a13cd027a | |||
| cd35121b59 | |||
| 4df99cb2aa | |||
| d452b95e57 | |||
| ed301b2eb4 | |||
| cd07c958c1 | |||
| 8f7255f4cf | |||
| 6c4be694f7 | |||
| ba26e74bea | |||
| 3a636a8a79 | |||
| 175421ece3 | |||
| 020b914658 | |||
| 09c3902d84 | |||
| 33f94da927 | |||
| 1fda07ebc5 | |||
| 78fb66277d | |||
| 0c1cc12b6b | |||
| 1885693f7c | |||
| 2b20976658 | |||
| 8d0dbbce29 | |||
| 666fd2d973 | |||
| b2fe392ddb | |||
| ab40e424e0 | |||
| 8b698cb39f | |||
| 579b6f8bec | |||
| d9fd3f2f65 | |||
| 543c909d53 | |||
| 1eb3b87050 | |||
| 7b5d3940fd | |||
| 25275b515c | |||
| 50422f801a | |||
| 7cd7ec2c11 | |||
| 6d6a9b7a34 | |||
| 3a7b755532 | |||
| 6e69c5e5ce | |||
| 7acc5783a5 | |||
| 8d980745ea | |||
| dff49770fa | |||
| e3e46068eb | |||
| f8173168fd | |||
| 96319b13a3 | |||
| 76e293d3b8 | |||
| 3ea4bac48c | |||
| 1b5fe1069f | |||
| 7b11e32eb6 | |||
| d19fab55b9 | |||
| 6a88447524 | |||
| dc61f5e33c | |||
| d2f167e71f | |||
| 8886bdbd2d | |||
| 6c42e5dde4 | |||
| 0d5e4b318d | |||
| 757fa22d9b | |||
| 9d3f766275 | |||
| 098fe45129 | |||
| 53e8d7b287 | |||
| 1d4b1d3c86 | |||
| d641f62116 | |||
| 5f202e8347 | |||
| f0fae1792f | |||
| 1f64de48b9 | |||
| 47ab2aa3a6 | |||
| 8cb2bf8607 | |||
| 3e1cce78f8 | |||
| c5a226f291 | |||
| 30c5fd5774 |
@@ -0,0 +1,3 @@
|
||||
[submodule "vendor/aster"]
|
||||
path = vendor/aster
|
||||
url = ssh://git@gitea.entroia.com:22222/Zayden-Jung/endorphin-aster-vm.git
|
||||
@@ -211,6 +211,14 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "compiler"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"core",
|
||||
"frontend",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "concurrent-queue"
|
||||
version = "2.5.0"
|
||||
@@ -220,6 +228,13 @@ dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"objects",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation"
|
||||
version = "0.9.4"
|
||||
@@ -260,6 +275,39 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core_maths"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30"
|
||||
dependencies = [
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cosmic-text"
|
||||
version = "0.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "be17b688510d934ce13f48a2beba700e11583e281e0fda99c22bb256a14eda73"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"fontdb",
|
||||
"harfrust",
|
||||
"linebender_resource_handle",
|
||||
"log",
|
||||
"rangemap",
|
||||
"rustc-hash",
|
||||
"self_cell",
|
||||
"skrifa 0.40.0",
|
||||
"smol_str 0.3.6",
|
||||
"swash",
|
||||
"sys-locale",
|
||||
"unicode-bidi",
|
||||
"unicode-linebreak",
|
||||
"unicode-script",
|
||||
"unicode-segmentation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-utils"
|
||||
version = "0.8.23"
|
||||
@@ -393,10 +441,45 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"
|
||||
|
||||
[[package]]
|
||||
name = "font8x8"
|
||||
version = "0.3.1"
|
||||
name = "font-types"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "875488b8711a968268c7cf5d139578713097ca4635a76044e8fe8eedf831d07e"
|
||||
checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "font-types"
|
||||
version = "0.12.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fontconfig-parser"
|
||||
version = "0.5.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646"
|
||||
dependencies = [
|
||||
"roxmltree",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fontdb"
|
||||
version = "0.23.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905"
|
||||
dependencies = [
|
||||
"fontconfig-parser",
|
||||
"log",
|
||||
"memmap2",
|
||||
"slotmap",
|
||||
"tinyvec",
|
||||
"ttf-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "foreign-types"
|
||||
@@ -425,6 +508,15 @@ version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
|
||||
|
||||
[[package]]
|
||||
name = "frontend"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"peg",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-core"
|
||||
version = "0.3.34"
|
||||
@@ -482,6 +574,19 @@ dependencies = [
|
||||
"r-efi 6.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "harfrust"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9da2e5ae821f6e96664977bf974d6d6a2d6682f9ccee23e62ec1d134246845f9"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bytemuck",
|
||||
"core_maths",
|
||||
"read-fonts 0.37.0",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.17.1"
|
||||
@@ -611,6 +716,12 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libm"
|
||||
version = "0.2.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
|
||||
|
||||
[[package]]
|
||||
name = "libredox"
|
||||
version = "0.1.25"
|
||||
@@ -623,6 +734,12 @@ dependencies = [
|
||||
"redox_syscall 0.9.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "linebender_resource_handle"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.4.15"
|
||||
@@ -984,6 +1101,10 @@ dependencies = [
|
||||
"objc2-foundation 0.2.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objects"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
@@ -1009,6 +1130,33 @@ dependencies = [
|
||||
"ttf-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "peg"
|
||||
version = "0.8.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0aad070be5b63aa72103f2fcdd70a83adbd5e90112ce5b574171ff1c65501773"
|
||||
dependencies = [
|
||||
"peg-macros",
|
||||
"peg-runtime",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "peg-macros"
|
||||
version = "0.8.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ddd8ef6825cae95355031ae26a99b616a2a21f22ba2de0197c43dfb05acbe7ee"
|
||||
dependencies = [
|
||||
"peg-runtime",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "peg-runtime"
|
||||
version = "0.8.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7011d97b484a5ebdc4b1fdb3b12d5e4bbbea56e9d22b688f2e79e04b65a7d8a6"
|
||||
|
||||
[[package]]
|
||||
name = "percent-encoding"
|
||||
version = "2.3.2"
|
||||
@@ -1115,12 +1263,40 @@ version = "6.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||
|
||||
[[package]]
|
||||
name = "rangemap"
|
||||
version = "1.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d"
|
||||
|
||||
[[package]]
|
||||
name = "raw-window-handle"
|
||||
version = "0.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.37.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7b634fabf032fab15307ffd272149b622260f55974d9fad689292a5d33df02e5"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"core_maths",
|
||||
"font-types 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.41.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"font-types 0.12.7",
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_syscall"
|
||||
version = "0.4.1"
|
||||
@@ -1148,6 +1324,18 @@ dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "roxmltree"
|
||||
version = "0.20.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
|
||||
|
||||
[[package]]
|
||||
name = "rustc-hash"
|
||||
version = "2.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
|
||||
|
||||
[[package]]
|
||||
name = "rustc_version"
|
||||
version = "0.4.1"
|
||||
@@ -1217,6 +1405,12 @@ dependencies = [
|
||||
"tiny-skia",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "self_cell"
|
||||
version = "1.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813"
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.28"
|
||||
@@ -1288,12 +1482,41 @@ version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
|
||||
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.40.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7fbdfe3d2475fbd7ddd1f3e5cf8288a30eb3e5f95832829570cd88115a7434ac"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"read-fonts 0.37.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.44.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"read-fonts 0.41.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
||||
|
||||
[[package]]
|
||||
name = "slotmap"
|
||||
version = "1.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038"
|
||||
dependencies = [
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
version = "1.16.2"
|
||||
@@ -1334,6 +1557,12 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "smol_str"
|
||||
version = "0.3.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4aaa7368fcf4852a4c2dd92df0cace6a71f2091ca0a23391ce7f3a31833f1523"
|
||||
|
||||
[[package]]
|
||||
name = "softbuffer"
|
||||
version = "0.4.8"
|
||||
@@ -1372,6 +1601,17 @@ version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"
|
||||
|
||||
[[package]]
|
||||
name = "swash"
|
||||
version = "0.2.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c2499c2d826531388872b2268718aed907a39bd785ab0dcfe57fab26283f92e"
|
||||
dependencies = [
|
||||
"skrifa 0.44.0",
|
||||
"yazi",
|
||||
"zeno",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
@@ -1394,16 +1634,32 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sys-locale"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tessera"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"font8x8",
|
||||
"compiler",
|
||||
"core",
|
||||
"cosmic-text",
|
||||
"frontend",
|
||||
"objc2 0.5.2",
|
||||
"objc2-app-kit",
|
||||
"objc2-foundation 0.2.2",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"softbuffer",
|
||||
"tiny_http",
|
||||
"unicode-segmentation",
|
||||
"winit",
|
||||
]
|
||||
|
||||
@@ -1497,6 +1753,12 @@ dependencies = [
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinyvec"
|
||||
version = "1.13.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.53.2"
|
||||
@@ -1557,6 +1819,15 @@ name = "ttf-parser"
|
||||
version = "0.25.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"
|
||||
dependencies = [
|
||||
"core_maths",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-bidi"
|
||||
version = "0.3.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
@@ -1564,6 +1835,18 @@ version = "1.0.26"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-linebreak"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-script"
|
||||
version = "0.5.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "383ad40bb927465ec0ce7720e033cb4ca06912855fc35db31b5755d0de75b1ee"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-segmentation"
|
||||
version = "1.13.3"
|
||||
@@ -1921,7 +2204,7 @@ dependencies = [
|
||||
"rustix 0.38.44",
|
||||
"sctk-adwaita",
|
||||
"smithay-client-toolkit",
|
||||
"smol_str",
|
||||
"smol_str 0.2.2",
|
||||
"tracing",
|
||||
"unicode-segmentation",
|
||||
"wasm-bindgen",
|
||||
@@ -2010,6 +2293,18 @@ version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"
|
||||
|
||||
[[package]]
|
||||
name = "yazi"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e01738255b5a16e78bbb83e7fbba0a1e7dd506905cfc53f4622d89015a03fbb5"
|
||||
|
||||
[[package]]
|
||||
name = "zeno"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6df3dc4292935e51816d896edcd52aa30bc297907c26167fec31e2b0c6a32524"
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.59"
|
||||
|
||||
@@ -2,18 +2,28 @@
|
||||
name = "tessera"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.91"
|
||||
description = "Cross-platform desktop rendering client"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0"
|
||||
font8x8 = "0.3"
|
||||
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_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
|
||||
|
||||
@@ -1,24 +1,63 @@
|
||||
# Tessera
|
||||
|
||||
Tessera is a clean desktop rendering host. It starts with an empty page. Coding agents submit source code to a namespace through a local CRUD API; Tessera parses that code, builds its architecture tree, compiles it to drawing commands, and renders the result.
|
||||
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 application starts with one managed New tab, implemented in Endor.
|
||||
|
||||
## Start
|
||||
For the current architecture, UML diagrams and implementation status, start with
|
||||
the [中文架构与进展导览](docs/architecture/README.md).
|
||||
|
||||
## Source and library integration
|
||||
|
||||
`vendor/aster` is an independent Git submodule pinned to a published Aster commit.
|
||||
Cargo path dependencies directly use its `frontend`, `compiler` and `core`
|
||||
(library name `endor_core`) packages, which bring in `objects`. The Aster workspace
|
||||
and history remain independent. See [vendor](vendor/README.md) for initialization
|
||||
and version updates, and [src](src/README.md) for the implementation map.
|
||||
|
||||
The runtime now uses Aster's Reader, Parser, AST, Compiler and VM. Tessera's former
|
||||
experimental `namespace` / `export scene` / `render` parser has been removed.
|
||||
Host UI integration lives in Tessera; Aster needs no Tessera-specific changes.
|
||||
Lyra CLI and Hestia Server are independent hosts and are not application dependencies.
|
||||
|
||||
## Native build and start
|
||||
|
||||
Use Rust 1.91 or newer. Initialize the source submodule following the dedicated
|
||||
codex-bot SSH identity instructions in [vendor](vendor/README.md), then build:
|
||||
|
||||
```bash
|
||||
cargo run --release
|
||||
git submodule update --init --recursive
|
||||
cargo build --release --locked
|
||||
./target/release/tessera
|
||||
```
|
||||
|
||||
Tessera listens only on `127.0.0.1:4737`.
|
||||
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.
|
||||
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:
|
||||
|
||||
Start every agent integration by reading the live Markdown guide:
|
||||
```bash
|
||||
sh scripts/build-macos-app.sh
|
||||
```
|
||||
|
||||
Open `target/release/Tessera.app`. See [packaging](scripts/README.md); this local
|
||||
bundle does not include distribution signing, notarization or an installer.
|
||||
|
||||
The API listens only on `127.0.0.1:4737`. Start integrations with its live guide:
|
||||
|
||||
```bash
|
||||
curl http://127.0.0.1:4737/agent
|
||||
```
|
||||
|
||||
## Namespace code API
|
||||
## Submit Endor
|
||||
|
||||
The initial active namespace is `app.main`. Tessera has no file concept.
|
||||
The active namespace starts as `app.main`:
|
||||
|
||||
```text
|
||||
GET /v1/namespaces/app.main/code
|
||||
@@ -26,49 +65,557 @@ PUT /v1/namespaces/app.main/code
|
||||
DELETE /v1/namespaces/app.main/code
|
||||
```
|
||||
|
||||
Submit code as plain text:
|
||||
Submit the [complete example](examples/page.endor):
|
||||
|
||||
```bash
|
||||
curl \
|
||||
--request PUT \
|
||||
--header 'Content-Type: text/plain; charset=utf-8' \
|
||||
--data-binary @- \
|
||||
http://127.0.0.1:4737/v1/namespaces/app.main/code <<'TESSERA'
|
||||
namespace app.main
|
||||
|
||||
use tessera.ui::{Column, Text}
|
||||
|
||||
export scene Main {
|
||||
render {
|
||||
Column(gap: 12, padding: 24) {
|
||||
Text("Hello", role: .title)
|
||||
Text("Rendered by Tessera")
|
||||
}
|
||||
}
|
||||
}
|
||||
TESSERA
|
||||
curl --request PUT --header 'Content-Type: text/plain; charset=utf-8' \
|
||||
--data-binary @examples/page.endor \
|
||||
http://127.0.0.1:4737/v1/namespaces/app.main/code
|
||||
```
|
||||
|
||||
Updates are atomic. Invalid code returns diagnostics with HTTP 422 and preserves the last successfully rendered revision.
|
||||
A minimal program is:
|
||||
|
||||
```endor
|
||||
let heading = ui.text("Hello Endor", 2, "#242422")
|
||||
let rectangle = ui.rect(240, 80, 12, "#DCE8FF")
|
||||
let myui = ui.page()
|
||||
myui.render(ui.column(24, 12, heading, rectangle))
|
||||
```
|
||||
|
||||
The namespace comes from the request path. `ui` is a host global declared to
|
||||
Aster's compiler and injected into the candidate VM. Top-level variables share
|
||||
that VM's globals within this source submission. No `main` wrapper is generated.
|
||||
Complete top-level inputs are separated by newlines; multiline calls and function
|
||||
bodies are grouped before being handed to Aster's existing Interactive parser and
|
||||
compiler. Expression continuations such as a member read on the following line
|
||||
remain in the same input. Aster still owns every token, syntax rule, AST and
|
||||
bytecode operation; the host only batches inputs and restores original AST offsets.
|
||||
|
||||
The older [main-returning-View example](examples/main.endor) and the richer
|
||||
[function example](examples/hello.endor) remain supported. A source consisting
|
||||
entirely of function declarations uses Aster's Module entry and calls zero-argument
|
||||
`main`. Mixed function declarations, bindings and expression statements use
|
||||
Interactive inputs in source order. Type annotations remain syntactic in Aster;
|
||||
Tessera checks actual UI values. The sample files are client-side material; the
|
||||
API itself stores source by namespace.
|
||||
|
||||
## UI host API
|
||||
|
||||
All arguments are positional. Defaults below describe omitted trailing arguments,
|
||||
not Endor keyword argument syntax.
|
||||
|
||||
| Member | Arguments and defaults |
|
||||
| --- | --- |
|
||||
| `ui.text` | String, integer size (default 1, range 1..8), color (default `#242422`) |
|
||||
| `ui.rect` | Width, height, radius (default 0), color (default `#DCE8FF`) |
|
||||
| `ui.column` | Padding, gap, followed by zero or more UI children |
|
||||
| `ui.row` | Padding, gap, followed by zero or more UI children |
|
||||
| `ui.spacer` | Size |
|
||||
| `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 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
|
||||
installed system fonts and per-glyph fallback (including Chinese when a CJK font
|
||||
is installed). UI text uses a proportional sans-serif font; developer source uses
|
||||
a monospace font. The existing size argument remains a 1..8 multiplier: size 1
|
||||
is 14 logical pixels with a 20-pixel line height; size 2 is 28/40. Row/Column layout
|
||||
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 installed locally.
|
||||
|
||||
## Candidate execution and publication
|
||||
|
||||
A dedicated worker performs source parsing, AST budget checks and compilation in
|
||||
a fresh candidate VM. It executes each script input with shared globals (or module
|
||||
initialization and zero-argument `main` for function-only source), checks the
|
||||
selected UI root, extracts native data, builds and validates the frame, then
|
||||
cleans up all VM roots. The window receives no VM handles. It relays out the owned
|
||||
native tree during redraw and display scale changes without rerunning Endor.
|
||||
|
||||
Aster's scoped NativeContext allocates actual managed Block objects on demand.
|
||||
Blocks own managed Cells and data objects; child, history and forwarding edges
|
||||
are traced by the same VM collector. Native methods capture their owner through
|
||||
declared heap edges. No fixed node/page pool or separate mutable Arc graph remains.
|
||||
The desktop's tab registry holds open Pages. close releases that registry edge;
|
||||
referenced Pages remain usable and unreferenced cycles are collected between inputs.
|
||||
The bridge's diagnostic object index uses non-owning WeakObjectRef values.
|
||||
|
||||
Limits are 1 MiB source, 10000 visited AST nodes with a 64-level visitor depth,
|
||||
4096 retained visual objects, 64 retained pages, 10000 expanded graph/layout visits
|
||||
and 16 KiB per text. Every execution has a 128-frame limit. Script inputs each
|
||||
receive an equal share of a total 1000000-instruction allowance; function-only
|
||||
module initialization and main execution each retain a 1000000-instruction budget. Repeated children count again during layout, preventing a
|
||||
small shared tree from expanding without bound. The build queue holds eight
|
||||
pending requests.
|
||||
|
||||
GET reads the last successful source while the worker executes. PUT waits for its
|
||||
result; a successful response includes submission and committed revision numbers.
|
||||
Parsing, compilation, execution, argument or layout errors return 422 with
|
||||
explanations and preserve the last successful document. Source diagnostics include
|
||||
line, column and byte ranges; VM tracebacks currently identify function starts and
|
||||
instruction offsets, not an exact source location for every instruction.
|
||||
|
||||
A newer accepted PUT invalidates older work. DELETE clears the document immediately
|
||||
and invalidates both queued and executing candidates. Superseded requests return
|
||||
409 and cannot republish their page. A full or unavailable queue returns 503;
|
||||
rejected queue entries do not invalidate accepted work. Failed builds do not
|
||||
increment the committed revision. A worker-caught panic discards the entire
|
||||
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.
|
||||
Managed tab chrome 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
|
||||
|
||||
The developer sidebar is closed by default.
|
||||
Native visual protocols are under active implementation: Text/Rect/Row/Column,
|
||||
container append/insert/remove/replace/move, Page open/close/navigation, ui.present,
|
||||
ui.state(value), ui.textOf(state, "value"), and button.onClick/click are available
|
||||
in the persistent Console. Method bodies can call other methods without a trailing
|
||||
return. Bound text tracks its source property; clean derived subtrees and unchanged measurements are reused. Buttons have a native background, focus ring and pointer/keyboard activation.
|
||||
`Page()`, `TextBlock(...)`, `Row(...)`, `Column(...)`, `ScrollBlock(...)` and `Button(...)` are callable managed type objects; `Page.base` is ContainerBlock and `page.type` is Page. `isInstance(page, Block)` and `isSubtype(Page, Block)` query nominal relations. Object and Type are explicitly bootstrapped in the same GC heap. Ordinary source class declarations, positional field construction, member assignment and inherited method dispatch are supported; source subclasses of concrete native visual types now reuse their real native allocator; abstract types remain unconstructible. Explicit host-registered capabilities are available; formal trait syntax and full type/effect checks remain pending. Native visual methods now live on their nominal type tables and use the same receiver binding as source methods. See [managed-types.endor](examples/managed-types.endor), [classes.endor](examples/classes.endor) and [native-subclasses.endor](examples/native-subclasses.endor).
|
||||
|
||||
- macOS: `Command-Option-I` or `F12`
|
||||
- Windows/Linux: `Control-Shift-I` or `F12`
|
||||
Source native subclass construction takes native arguments first, followed by all inherited and own declared fields. For example, a TextBlock subclass with one field accepts `CustomText("text", 2, "#242422", fieldValue)`; optional native arguments can be omitted before the required field suffix. Field storage belongs to the current shared Block content: replacement updates aliases and bindings and releases the previous fields through Aster. This is an implementation subset; field annotations are not yet runtime checked.
|
||||
|
||||
The upper section displays the compiler-produced architecture tree. Selecting a node shows the corresponding source range below it.
|
||||
Events use `block.on("click", callback)` or `block.on("click", callback, "capture")`, returning a managed Subscription with `disconnect()` and `isConnected()`. A Block owns its connections; tokens refer to connections weakly and do not retain the target or callback. Dropping a token leaves the listener registered. Disconnection releases the callback and is safe to repeat.
|
||||
|
||||
## Current syntax experiment
|
||||
`block.dispatch(Event("custom"))` returns the dispatched Event. `block.click()` creates a click Event and uses the same dispatcher as native activation. An optional Mount selects one occurrence: `block.dispatch(event, mount)` or `block.click(mount)`. Without a Mount only the target is visited. With one, capture walks from Page through ancestors, then target capture, the object's `onEvent(self, event)` method and target listeners, then ancestors/Page in bubble order. The target method runs before non-capture target listeners. Event fields expose `kind`, `target`, `mount`, `currentTarget`, `currentMount` and `phase` (`capture`, `target`, `bubble`, then `none`). Source subclasses can override onEvent.
|
||||
|
||||
The first parser intentionally supports only enough syntax to test the architecture:
|
||||
Event methods `stopPropagation()`, `stopImmediatePropagation()`, `preventDefault()` and `isDefaultPrevented()` control delivery or report cancellation; there is currently no additional host default action to cancel. stopPropagation permits remaining listeners on the current occurrence, while the immediate variant stops them too. Listener order is snapshotted at dispatch start; disconnection before a listener's turn skips it, new connections wait for the next dispatch. The existing onClick setter remains a single compatibility callback, called after other non-capture listeners on that Block. All handlers share the VM call budget, with an explicit 10000-delivery limit that reports failure instead of truncating propagation. Reentrant dispatch of the same active Event is rejected; a completed Event can be reused. See [events.endor](examples/events.endor).
|
||||
|
||||
- `namespace`
|
||||
- namespace-only `use`
|
||||
- one `export scene`
|
||||
- one `render` root
|
||||
- `Column`, `Row`, `Spacer`, and `Text`
|
||||
- `gap`, `padding`, and `.title`
|
||||
Visual objects also inherit `onMount(self, mount)` and `onUnmount(self, mount)` no-op methods, which source subclasses can override. Notifications occur once per actual occurrence transition: parents before children when attaching, children before parents when detaching. Updating text, color or geometry keeps an existing Mount and does not remount it. Shared content keeps its Block identity when replaced; hooks describe Mount attachment rather than each mutation of that content. Replacing a container child or switching Page produces the appropriate occurrence transitions, even when two Pages display the same root object. Mount lifecycle follows the active presentation in each native window.
|
||||
|
||||
There are no files, HTML, CSS, JavaScript, DOM, or resource-network concepts in the runtime.
|
||||
Mount synchronization queues hooks after links and geometry are coherent. Hooks execute outside the session lock, under one VM budget per batch, after the source input or native event and before final publication. They may update objects or containers; resulting layout/notification work settles before a complete frame is published. A scalar Console result is evaluated before these deferred hooks. The rendering work budget explicitly fails on non-converging feedback. A hook failure after mount mutation stops that runtime and retains its previously displayed frame; failed PUT candidates preserve the old runtime. Hooks are never invoked by GC or by discarding an execution domain.
|
||||
|
||||
Saved detached Mounts expose `mounted = false`, cleared parent/child/sibling links and a weak Page query for cleanup; geometry, focus and hit-test operations reject them. Reopening creates new contexts and never revives an old saved Mount. `layoutVersion` is refreshed even when only paint inputs change. See [mount-lifecycle.endor](examples/mount-lifecycle.endor).
|
||||
|
||||
Native visual methods are now available on Block: `measure(mount, Constraints(minWidth, minHeight, maxWidth, maxHeight))`, `arrange(mount, Bounds(x, y, width, height))`, `paint(mount, Bounds(...))` and `hitTest(mount, Point(x, y))`. The Mount must be live and belong to that exact Block occurrence. These query methods return managed MeasureResult, Arrangement and DisplayList objects, using the renderer's native geometry and painting functions. They do not publish geometry or pixels. Results are readable in Endor: `result.width`, `arrangement.children.at(0).x`, `drawing.commands.at(0).color`; indexed ObjectList results provide count, first and at(index), with traced references. Arrangement child bounds also carry their stable slot. Paint returns only that object's own commands; descendants are separate occurrences.
|
||||
|
||||
Outside a renderer layout call, native measurement queries find intrinsic native subtree size and clamp it to the given constraints. During layout, native base methods use the staged measured children of that occurrence. Native Row/Column arrangement uses child sizes, padding and gaps; it does not stretch children to fill the supplied bounds. Hit testing uses local coordinates against the current Mount dimensions. Coordinates/dimensions must be finite and remain within the native layout limit. Width/height and constraint ranges cannot be negative or inverted. The value constructors preserve fields as ordinary objects with declared-field type checks; methods also validate their geometry when used. Whole-program static typing remains pending.
|
||||
|
||||
Visual, EventTarget, Children and Presentable are explicit managed Trait definitions. Block declares Visual (measure/arrange/paint/hitTest) and EventTarget (on/dispatch/onEvent); ContainerBlock declares Children (append/insert/remove/replace/move/children), inherited by Page. `ui.supports(value, capability)` queries an instance; `ui.implements(type, capability)` queries a type. `ui.implement(type, capability)` checks required methods and establishes an explicit relation. Matching member names alone never declare a capability. Aster checks source positional parameter counts, including self, when registering, creating subclasses or replacing methods; declaration and ancestor updates also validate existing affected descendants. Source and native positional intervals are checked against the canonical call count, including self; native methods without metadata cannot declare a capability; source argument/return annotations are checked at invocation as described below. Typed requirements also compare parameter/return types and known native effects. Runtime calls check actual results across delegation. Conservative bytecode and current call-graph proofs recognize ReadOnly source functions; general effect inference and formal trait syntax remain pending.
|
||||
|
||||
A plain source object can declare Presentable by implementing `present(self, window: Window): Block` and calling `ui.implement(MyType, Presentable)`. `ui.present(value)` invokes this method with the calling window and checks the returned actual Block; `ui.open(value)` also opens the result in a Page. Block values pass through directly. The existing summary viewer remains the fallback for unregistered values, and merely viewing a function does not execute it. Presentation runs through the same bounded VM call sequence; there is no recursive host evaluator. A source adapter can keep the original object through fields/callbacks/bindings; [presentable.endor](examples/presentable.endor) shows a source-preserving view and GUI calls to the original object's method. Presentation methods are ordinary calls; visual measure/arrange/paint/hitTest still run read-only and check their nominal results at runtime. Source implementations of EventTarget.on/dispatch must provide the contract's canonical 3/2 arguments after self; native methods retain their existing optional convenience arguments.
|
||||
|
||||
`ScrollBlock(width, height, child)` is a ContainerBlock with a bounded viewport. Its `axis` attribute defaults to `"both"`, preserving unconstrained content measurement. `"vertical"` wraps/restricts content to the actual occurrence viewport width minus padding, while `"horizontal"` restricts its height. The disabled axis has a zero offset/limit, including after a live axis change. Source-arranged viewport dimensions participate in remeasurement. Child stacking remains Column-like; use a Row child for horizontal composition. See [scroll-axis.endor](examples/scroll-axis.endor). It also supports inherited child operations and padding/gap. Its width/height are managed attributes and can be bound or assigned. Each attached Mount owns its scroll offset; two occurrences of the same ScrollBlock scroll independently. Moving/remounting content creates a new Mount and starts at zero. Changes to content or viewport clamp offsets to the new limits.
|
||||
|
||||
`mount.scrollTo(x,y)` and `scrollBy(dx,dy)` update that occurrence; multiple relative requests in one input accumulate. `scrollPosition()` returns a snapshot with x/y/maxX/maxY from the last committed layout. `mount.scrollIntoView()` minimally adjusts all scrollable ancestors, and requestFocus() uses it too. Requests settle at the same successful input/event boundary as other UI changes. Detached mounts and mutations during read-only rendering are rejected. Wheel input selects an eligible scrolling ancestor of the foremost visible occurrence, with outer scrolling when the inner range is exhausted; Shift+wheel selects the horizontal axis. A diagonal gesture currently goes to one eligible container rather than splitting axes across ancestors. Scrollbars/thumb dragging, touch inertia and PageUp/PageDown are not yet implemented.
|
||||
|
||||
Native/source painting, focus outlines, pointer selection and Mount.hitTest share the final translated geometry and intersected ancestor clip rectangles. A clipped descendant keeps its identity and state but cannot receive pointer clicks outside the viewport. This does not remove it from the managed object graph. Paint x/y may be negative within the existing coordinate budget after projection; dimensions and radii remain nonnegative. See [scroll.endor](examples/scroll.endor) for a shared object tree in two independent native windows.
|
||||
|
||||
`block.bind(property, compute)` binds an existing managed field to a zero-argument function and returns a Subscription with disconnect()/isConnected(). Targets are Block fields, including source-defined fields; arbitrary non-Block objects are not binding targets yet. Native visual fields are now ordinary attributes: TextBlock.text/size/color, RectBlock.width/height/radius/color, Spacer.size and container padding/gap. Direct assignments and native setters feed the same visual snapshot. Text size remains 1..8, geometry must be finite/nonnegative and within the existing limits, and colors use the existing color parser. Legacy textOf still owns its derived text until setText or a text binding replaces it.
|
||||
|
||||
The target's managed content owns its bindings; each binding traces the actual compute function and its captures. Tokens and the host registry hold weak references. Rebinding a field disconnects its previous binding; disconnecting leaves the last value in place. Hidden but still-referenced Blocks update at successful input/event/viewport stabilization boundaries. Functions run read-only against existing objects; they may construct result objects. Dependencies are recorded from actual VM reads, with object-level versions and conservative global-dictionary invalidation. This replaces the earlier candidate API's explicit source list. Binding results are settled before frame publication, including across windows and after lifecycle changes. Values read earlier in the same input precede this batch boundary. Explicit dependencies and property-level dependency precision remain future work.
|
||||
|
||||
One Block can have up to 128 active bindings. Each computation has 100000 instructions/128 frames, and a refresh rejects after 10000 computations if dependencies do not stabilize; it reports an error and preserves the published picture instead of silently truncating propagation. A live binding-computation failure stops that runtime. General type/effect checking remains pending. See [property-bindings.endor](examples/property-bindings.endor) for actual Endor source.
|
||||
|
||||
Declared fields now use the same runtime type-check switch as source functions, enabled in Tessera. Ordinary and native subclass constructors validate field arguments before allocating/opening native objects. Subsequent source assignments, native set_attr calls and binding writes check the actual declaring field before changing its storage; an error preserves that field's old value. Declared fields cannot be deleted while checks are enabled. Inherited fields use their declaring ancestor and environment. The declaring class name means that actual definition, so REPL redefinition preserves old self-type fields; other names resolve dynamically from the declaration's globals/builtins. Shared Block forwarding selects the current content's type and storage. See [field-contracts.endor](examples/field-contracts.endor).
|
||||
|
||||
These are checks at construction/write boundaries. Enabling does not scan old objects, and changing a referenced object's shared content does not revalidate every field that refers to it. Trusted hosts still own low-level payload/storage/attach operations. Complete initialization, local/captured type-name resolution, override variance, static and effect typing remain pending.
|
||||
|
||||
`invalidate("paint")` requests a frame while retaining measurement caches; `invalidate("layout")` also clears affected intrinsic measurements; `invalidate("content")` also invalidates derived content and ancestor dependencies. The default reason is layout. Requests coalesce at the refresh boundary, cover all aliases/occurrences of the same current content and preserve Mount identities. Hidden objects do not force visible frames. See [visual-protocols.endor](examples/visual-protocols.endor). Source measure/arrange overrides now participate in actual layout with structural Mount contexts available before first measurement. Source paint and hitTest also run in the frame/input pipeline. Full parameter/return type and effect contracts, more precise context dependencies and additional container allocation policies remain future work.
|
||||
|
||||
A source subclass can override `measure(self, mount, constraints): MeasureResult` and `arrange(self, mount, geometry): Arrangement`. The persistent renderer creates stable Mount identities and parent/child/sibling links before measuring. Measurement proceeds bottom-up with the current logical viewport as the Page constraints (headless callers default to 0..1000000); native parents and explicit native base calls use the current occurrence's measured child sizes, including source overrides. Arrangement proceeds top-down; each child Bounds must be assigned exactly once using its stable slot, with nominal result types and finite geometry checked. Source arrangements can resize or move children; omission, duplicate/foreign slots and invalid geometry reject the frame. See [source-layout.endor](examples/source-layout.endor).
|
||||
|
||||
Source layout now repeats bottom-up measurement and top-down arrangement inside one read-only VM call until input constraints, desired sizes and all allocated bounds repeat unchanged. Source-arranged dimensions that differ from a child's measured size become exact constraints for that axis during this solve. Native parents then account for the newly measured size. A source container measurement that differs from native measurement also constrains its content on the relevant policy axis. Selected limits remain until this solve finishes; the next input/resize starts fresh. Ordinary native intrinsic-size policies are retained. See [layout-negotiation.endor](examples/layout-negotiation.endor).
|
||||
|
||||
The solver detects a previously visited nonconsecutive state as a cycle. It has no fixed propagation/pass cutoff: the whole solve shares the existing 1000000-instruction/128-frame VM budget, and exhaustion is an explicit failure. It reuses one bytecode driver frame rather than nesting one frame per pass. All measurement phases clear provisional geometry from every Mount, and only the complete settled result is committed. Failed candidates preserve the active program; live layout failures stop the domain and preserve its published picture. This is not a resumable layout scheduler or an optimal/general flex solver.
|
||||
|
||||
`ui.stats().layoutPasses` reports passes for the latest layout (native-only fast path uses one). Measured/arranged/cache counters include the work of all solve passes. Source annotation validation is distinguished from actual content reads: merely checking a Mount parameter's type no longer disables measurement caching, while program reads of Mount layoutVersion/geometry still bypass it conservatively. Other type/validation dependencies remain version-checked. Runtime type checks stay enabled.
|
||||
|
||||
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).
|
||||
|
||||
`container.insert(position, block)` inserts at a zero-based position from 0 through the current child count and returns a new stable slot. Existing slots and attached Mount identities survive insertion. Invalid positions and cyclic child graphs fail before replacing the child list. `page.moveTab(position)` moves the same Page to a final zero-based position in its owning window; a code reorder does not implicitly activate it.
|
||||
|
||||
Native dragging starts after 12 logical pixels and shows a blue insertion marker. Same-window drops call the actual Page `moveTab` and `activate`; cross-window drops first call `moveToWindow`. Source overrides participate. An override that declines or redirects the window move prevents the remaining destination reorder. Page identity and Page-owned tasks survive movement, while a cross-window move replaces Mounts and cancels old Mount tasks. Invalid source/target generations, layout versions or unpublished tab orders are rejected before callbacks. Callback failure stops the domain; earlier writes do not roll back. Escape cancels a drag. Overflow drops use visible gaps; drag auto-scroll remains pending. See [tab-placement.endor](examples/tab-placement.endor).
|
||||
|
||||
`window.moveTo(x, y)` queues a native outer-window origin in signed physical desktop pixels, within +/-1000000 per axis. A detached tab uses the release point and saved grab offset to place its new window. The window manager may adjust placement. Global coordinates are required for cross-window drops; unsupported native placement reports a diagnostic. This host tracks its own focus order when resolving overlapping windows; external-app occlusion and mixed-DPI dragging have not been fully verified.
|
||||
|
||||
`window.close()` and a secondary native close button call the same managed method. Closing first removes Page ownership, then commits unmounts and removes that context from the runtime registry; the native resource disappears after successful publication. Retained Pages can be opened in another live Window; otherwise Aster reclaims them normally. Window resource objects may remain referenced after closing, but reject resource operations; id/pages remain queryable. A retained leaf Mount uses a weak context link and cannot keep a closed window alive through its query methods. The primary shell still defines the application's lifetime: closing its OS window exits Tessera. Full application-exit notifications remain follow-up work.
|
||||
|
||||
A secondary window can also be closed after a callback/rendering failure or Console reset. A stopped VM uses host teardown to detach Mounts and release window-owned Page roots without invoking source close/unmount callbacks; it remains stopped. A preserved picture from a discarded generation is removed without touching a fresh Console VM, even when both generations use the same numeric window ID. Secondary viewport inputs are likewise scoped to their runtime generation. If host teardown fails, that VM is discarded and remaining pictures have input disabled. Native initialization and software-surface failures are reported instead of panicking; a failed secondary creation leaves its managed resource inspectable and closable from Console. Automatic retry and complete application-exit notifications remain future work.
|
||||
|
||||
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).
|
||||
|
||||
The macOS title strip occupies 44 logical pixels and shares its row with the native window controls. The left rail and title strip form one neutral chrome surface. Content is inset by a 56-pixel rail, an 8-pixel top gap, and 8 pixels at the right and bottom. Page constraints use the remaining height; published Mount geometry and event coordinates remain relative to the content area. Window viewport snapshots continue to report the full native inner size. The host translates drawing and native pointer coordinates at this boundary. Console reset preserves the last picture with input disabled until a new live frame is published.
|
||||
|
||||
`window.resize(width, height)`, `setTitle(text)` and `focus()` project requests to the GUI thread. `id()` returns an opaque runtime resource ID and `viewport()` reports actual logical dimensions. Requests are asynchronous and coalesced by kind; queried dimensions change when the native window reports them, and platform bounds can adjust requested sizes. This host accepts sizes from 1 to 4096 logical pixels per axis, with a native minimum of 720 by 480. Titles are UTF-8 text up to 4096 bytes with no control characters. See [window.endor](examples/window.endor).
|
||||
|
||||
Native creation and commands remain local until the input/candidate succeeds. Failed inputs discard pending commands; failed PUT candidates preserve the live native window. Accepted projections carry the runtime session, so replacement/reset/discard clears old requests. GUI publication and native operations are serialized through the namespace boundary. Read-only rendering rejects window side effects. The private transport queue contains only resource IDs/scalars, introduces no Page roots, and is drained without incrementing object versions. Tab UI, move/detach and secondary native windows use the same resource pipeline.
|
||||
|
||||
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.
|
||||
|
||||
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).
|
||||
|
||||
The native app sends both press and release positions with the click. Both targets are resolved against the current published frame and heap when the release is processed; only matching Mount identities dispatch a click. These selectors share one read-only VM call and budget, and must return Bool. Callback execution starts after the read-only scope has ended. This is semantic click handling, not a raw pointer-down/up event stream or pointer capture. Keyboard/programmatic activation retains its semantic target and bypasses spatial filtering. API pointer events carry `point: [x, y]` and `press_point: [x, y]` together; GET code exposes X-Tessera-Session and X-Tessera-Layout-Version headers for clients to obtain current metadata without evaluating more source.
|
||||
|
||||
Native TextBlock measurement now uses the occurrence's maximum width, with word wrapping and glyph fallback for long words. Width changes affect measured height and propagate through native Column/Button sibling placement. The shared text cache includes wrap width; the native shape cache also includes the incoming width. Native base measure queries use the supplied constraints both during source layout and when called directly. Shared Blocks retain separate geometry per Mount and can wrap differently in different windows. See [wrapped-text.endor](examples/wrapped-text.endor).
|
||||
|
||||
Native TextBlock painting carries its allocated width/height into the immutable frame and clips glyphs to those bounds as well as any enclosing scroll clip. Measurement and drawing use the same font/shaping implementation; drawing shapes at the device font size. Zero-width or zero-height paint bounds draw nothing. Management UI text keeps its existing single-line/explicit-newline behavior.
|
||||
|
||||
Source `PaintCommand` text may supply both `wrapWidth` and `wrapHeight` as finite nonnegative logical dimensions up to 1000000. Omitting both preserves unwrapped text; supplying only one is rejected. `TextBlock.paint` returns these fields, so a source override can preserve or explicitly change the boundary. Changing paint bounds does not renegotiate layout: source arrange supplies child Bounds and changed dimensions participate in the layout solve. Bounded flex allocation is described below. ScrollBlock's axis policy now controls cross-axis wrapping and scrolling. Fractional-DPI wrap boundaries need broader platform validation.
|
||||
|
||||
A source subclass can override `paint(self, mount, geometry): DisplayList`. The renderer invokes that method for each occurrence, after Mount synchronization and hooks, using current logical Bounds. Its commands replace that occurrence's native paint in preorder. Calling `RectBlock.paint(self, mount, geometry)` or another native base method obtains a fresh result that can be modified before returning. `DisplayList(ObjectList(command, ...))` builds multiple commands; ObjectList accepts objects and has a 10000-member bound. PaintCommand fields use kind (`roundedRect`, `strokeRoundedRect` or `text`), x/y/color and the corresponding width/height/radius, strokeWidth, or text/size fields. Commands must pass the same native validation and a total 10000-command frame limit. See [source-paint.endor](examples/source-paint.endor), including a Button source method that updates the same tint field used by two occurrences.
|
||||
|
||||
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.
|
||||
|
||||
The application starts with one managed New tab. The + button and Cmd/Ctrl+T
|
||||
create additional managed Pages; Cmd/Ctrl+W closes the active Page. New tabs expand
|
||||
from left to right while existing tabs interpolate to their new bounds when space
|
||||
becomes limited. Hover and selection use the same capsule geometry, and animated
|
||||
pointer hits use the rendered bounds. Source and page identity remain in the VM;
|
||||
chrome animation retains only projected scalar IDs and rectangles. Tabs are capped at
|
||||
208 logical pixels wide, with a 40-pixel strip and equal 4-pixel vertical insets.
|
||||
The leading page symbol and close control have matching slots and edge spacing.
|
||||
|
||||
The default page is implemented in `src/bridge/ui_bridge/start_page.endor`, compiled once
|
||||
per VM into a private namespace. Its buttons create a Page, open a working shared
|
||||
counter, or show composed Blocks. `ui.newTab()` constructs the same ordinary Page
|
||||
used by native + and the keyboard shortcut. Layout, callbacks, state and bindings
|
||||
are Endor objects; the host does not paint an introduction over the guest page.
|
||||
|
||||
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 and have no permanent rail/menu launchers. Their future
|
||||
discovery UI is intentionally deferred. 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
|
||||
Expression/Script selector. The current prompt, submitted commands and results
|
||||
share one scrollable surface, with no separate input box, editor splitter or Run
|
||||
toolbar. Typing appears at the prompt immediately; Enter executes it and the result
|
||||
appears directly below. Shift-Enter inserts a newline. Each command and its result
|
||||
are followed by a thin neutral horizontal separator. Input focus uses a text caret,
|
||||
without a blue field border or hover fill. The prompt, history and caret share the
|
||||
same scroll offset; typing and cursor navigation reveal the current insertion point.
|
||||
Create objects with bare assignment or `let`, then mount them when ready:
|
||||
|
||||
```endor
|
||||
title = ui.text("你好,Tessera", 2, "#243047")
|
||||
```
|
||||
|
||||
At this point the object exists in Console memory and the page stays unchanged.
|
||||
Later inputs can refer to it:
|
||||
|
||||
```endor
|
||||
note = ui.text("这是 Endor 渲染的页面", 1, "#637082")
|
||||
card = ui.rect(320, 100, 16, "#DCE8FF")
|
||||
page = ui.page()
|
||||
page.render(ui.column(24, 16, title, note, card))
|
||||
```
|
||||
|
||||
Ordinary values keep normal name assignment. UI references opt into Aster's
|
||||
managed `ObjectPayload::assignment_cell` protocol: assigning another UI object updates the
|
||||
existing shared reference and preserves its identity. Aliases and mounted parents
|
||||
therefore observe the same replacement, including across function-local slots.
|
||||
For example, after `other = card` and `page.render(other)`, assigning
|
||||
`card = ui.rect(640, 200, 32)` updates the page without another render. This is
|
||||
shared-reference semantics, not variable-name tracking. Assigning a non-UI value
|
||||
uses normal value assignment; it does not unmount the old UI reference.
|
||||
|
||||
`page.render(root)` mounts a live root and selects its page. Changes to mounted
|
||||
references publish a new frame after a successful input; unrelated objects do not.
|
||||
`page.unmount()` releases that page's mount and clears the frame if it was active.
|
||||
Replacing a container updates its whole mounted position. Repeated aliases are
|
||||
allowed; replacements that would create a cycle or exceed graph limits are rejected
|
||||
before mutation. Scalar constructor arguments are evaluated once, as ordinary values.
|
||||
|
||||
Bare assignment creates/updates a name; `let` remains a declaration. Aster owns this
|
||||
syntax, AST and bytecode; Tessera never inserts `let` or replays history. The actual
|
||||
last value is also bound to `_`. Text editing supports cursor positioning, arrow
|
||||
keys, Home/End, grapheme-safe deletion, select-all, macOS copy/cut/paste and IME.
|
||||
Up/Down recall single-line history; Command/Control-Up/Down recall multiline history.
|
||||
|
||||
Console sends `POST /v1/namespaces/app.main/repl` as UTF-8 text/plain. Responses
|
||||
include value, session/input IDs, bindings, `persistent: true`, rendered flag and
|
||||
revision. Before the first mount, object creation never publishes a page or advances revision.
|
||||
After mounting, changed shared UI references publish automatically. The last explicit
|
||||
render in an input selects the active page, only after that input succeeds. Syntax and
|
||||
compilation errors run no statements; runtime errors can retain earlier successful
|
||||
statements from that input, while preserving the previously displayed page.
|
||||
|
||||
Reset session (`DELETE .../repl`) drops the VM and all bindings/objects, preserving
|
||||
the displayed immutable frame. Clear only hides the transcript. Limits per session
|
||||
are 256 executed inputs, 1 MiB transcript, 10000 cumulative AST nodes, 4096 UI nodes
|
||||
and 64 retained pages. Unreachable objects and cycles are reclaimed between inputs; reset releases the whole session. Code and objects are never stored on disk.
|
||||
|
||||
Existing `PUT .../code` remains a complete program replacement with a fresh VM;
|
||||
function-only source still invokes main. On success the new VM remains live for Console and GUI events; a failed replacement preserves the old VM. Accepted PUT/code DELETE invalidate older queued Console inputs. The compatibility `POST .../evaluate`
|
||||
endpoint remains isolated for existing clients, but is not a Console mode. All use
|
||||
the bounded eight-entry worker queue. GET /code returns the displayed source: exact
|
||||
PUT source, or annotated Console transcript after a REPL render, distinguished by
|
||||
`X-Tessera-Source-Kind`. The transcript shows actual executed input and can contain
|
||||
failed statements; it is not guaranteed to replay as a standalone program.
|
||||
|
||||
External HTTP activity appears in the same transcript. Unsupported language
|
||||
operations (currently numeric arithmetic bytecode) show actual diagnostics. Transport
|
||||
failures appear in the Console footer and restore an otherwise empty draft.
|
||||
|
||||
Sources shows the full source snapshot or Console transcript with line numbers, Aster's
|
||||
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/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
|
||||
`127.0.0.1:4737`, including pending requests, method, path, status, server duration,
|
||||
request/response headers and bodies. Filter matches method, path or status. Clear
|
||||
clears the Network view without changing the document or Console transcript. A bounded
|
||||
ring retains 80 requests with explicitly marked 32 KiB body previews. Request
|
||||
headers are allowlisted to Content-Type and Content-Length; credentials and cookies
|
||||
are not captured. No external browser or operating-system traffic is represented.
|
||||
Console and Network share the bounded capture ring and have independent clear
|
||||
markers. Clicking a Console record opens its Network details and restores that view.
|
||||
|
||||
Settings applies six accent presets or a custom six-digit hex color immediately.
|
||||
Very bright custom colors are darkened to keep accents visible on white. Execution
|
||||
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/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;
|
||||
dragging outside cancels. Tab/Shift-Tab navigate enabled controls and Enter/Space
|
||||
activate focused buttons. Plain Tab still indents at the Console prompt. Empty
|
||||
Clear actions are disabled. Splitters are painted and registered above all pane
|
||||
backgrounds, toolbars and status bars, so their entire length stays visible and
|
||||
draggable. macOS clipboard reads and writes explicitly use
|
||||
UTF-8 even when launched from Finder, and decoding errors are surfaced.
|
||||
|
||||
## Validation
|
||||
|
||||
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
|
||||
|
||||
Tessera enables Aster runtime checks for source parameter and return annotations.
|
||||
`Object` accepts any live value, `Unit` accepts nil, `Number`, `String`/`Text` and
|
||||
`Bool` check their value kinds. `Function` accepts source/native functions and
|
||||
bound methods; callable class definitions remain `Type`. Newly created functions
|
||||
share the actual managed Function type, so `isInstance(callback, Function)` works.
|
||||
`View` is retained as a global compatibility alias for Block.
|
||||
|
||||
Other annotation names resolve through the function's own globals and captured
|
||||
builtins on each invocation. A real Type requires nominal inheritance; a Trait
|
||||
requires an explicit implementation. A method's own declaring-class annotation
|
||||
uses its receiver's actual owning definition, allowing saved bound methods on old
|
||||
instances to survive a REPL class-name redefinition. Other global type names are
|
||||
not frozen when a function is defined. TypeMismatch reports the function,
|
||||
parameter/return and expected/actual names. Unknown annotations and argument
|
||||
mismatches reject before the body; a bad return does not roll back completed writes.
|
||||
The per-call return definition remains rooted until success/error cleanup.
|
||||
|
||||
See [function-types.endor](examples/function-types.endor) for actual Endor source.
|
||||
Declared-field construction/write checks are described above. Static inference, generics,
|
||||
static effect typing and complete native signature coverage remain pending. Native APIs retain their domain-specific value and resource checks.
|
||||
|
||||
|
||||
Native methods publish positional argument intervals through Aster CallArity. The VM checks counts before invoking them, and trait registration/descendant updates verify that each source or native method accepts the canonical argument count. Optional/default parameters are included; bound receiver counts are removed for callback queries. Generic Type construction still uses its host constructor rules. CallSignature adds optional resolved parameter/return types and host effect metadata, as described below.
|
||||
|
||||
Native typed contracts now cover measure(Block, Mount, Constraints): MeasureResult, arrange(Block, Mount, Bounds): Arrangement, paint(Block, Mount, Bounds): DisplayList and hitTest(Block, Mount, Point): Bool, plus Point geometry queries and Window, Block/Container/Page, Mount, Task, Event, Subscription and ObjectList.at methods. The explicit receiver is checked before binding dispatch. Aster checks types before invoking the implementation and checks actual returns, including final results delegated to Endor functions. Signature definitions are traced managed edges; pending delegated return checks retain execution roots and use the existing VM frame/budget machinery. Wrong returns release temporary results but do not roll back earlier writes.
|
||||
|
||||
Host CallEffect distinguishes ReadOnly, Delegated, Mutating and External. Delegated means the native wrapper itself is read-only while its continuation has dynamic effects; ui.present uses this category and the actual callback remains in the same VM scope. It is not a static purity proof. A declared mutating/external call is rejected before invocation during read-only rendering; declaring ReadOnly does not bypass the existing heap write barrier. Legacy missing metadata remains unknown, and trusted native code still must obey its I/O contract. CallType supports single types and flat nonempty unions, retaining every branch definition. Page.open accepts Window or nil, Page.window returns Window or nil, and Block.on accepts Bool or String for its optional phase. Mount parent/child/sibling/Page queries have nullable results; bounds() returns an actual Bounds object so Point.inside(mount.bounds()) composes directly. Scope/resource eligibility, numeric ranges and phase names keep their domain checks. This adds native contract metadata, not Endor union syntax.
|
||||
|
||||
Public ui functions, captured state set/increment methods and native constructor factories now publish signatures. Bootstrap fills immutable signatures after all referenced types exist, preserving function identities. A native factory first separates the requested subclass fields from native options; its envelope checks the Type receiver/general result/effect, then the concrete options and declared fields are checked before allocation or window effects. Optional Rect/Text options and variadic Row/Column children therefore do not consume subclass fields. Event/ObjectList factories retain their own field/member validation. Generic Type construction still has no single fixed reflected signature. See [constructor-contracts.endor](examples/constructor-contracts.endor).
|
||||
|
||||
Source overrides now check contravariant parameters and covariant returns at class construction, method replacement and before invocation with dynamically resolved annotations. Ancestor replacement checks overriding descendants before mutation. Forward names may defer until invocation, where unresolved or incompatible contracts fail before the body. Known native effects may only shrink; source effects remain unknown and read-only execution retains its barriers.
|
||||
|
||||
Visual, EventTarget, Children and Presentable now use typed Trait requirements. Registration checks parameter/return substitution and known native effects before recording the declaration, including existing descendants. Runtime calls recheck dynamic annotations and final Trait results, including delegated source/native returns. Concrete implementations retain wider parameters and optional convenience forms. Source functions outside the conservative read-only bytecode proof remain unknown; general effect inference remains pending. See [method-contracts.endor](examples/method-contracts.endor) for real Endor widening parameters to Object and returning a MeasureResult subclass. Existing [visual-protocols.endor](examples/visual-protocols.endor) and [layout-negotiation.endor](examples/layout-negotiation.endor) exercise the typed visual methods with actual Endor code.
|
||||
|
||||
Event listeners and onClick callbacks must be Functions with known metadata accepting zero arguments or one Event. If both forms work, the dispatcher passes Event. Binding computes and Task callbacks must accept zero arguments, checked before replacing a binding, adding a connection or scheduling work. Native and source callbacks follow the same rule. See [native-signatures.endor](examples/native-signatures.endor) for real native one-argument and zero-argument handlers. Event and ObjectList subclass allocators also check declared field suffixes before allocation.
|
||||
|
||||
### Owner-managed asynchronous tasks
|
||||
|
||||
`ui.after(owner, key, milliseconds, callback)` returns a managed `Task` and runs
|
||||
its zero-argument callback on the existing VM worker after the monotonic deadline.
|
||||
The callback must return Unit. Delay is an integer from 0 to 86,400,000 ms; zero
|
||||
means a later worker turn. The worker currently polls at up to 100-ms idle intervals,
|
||||
so deadlines are minimum delays rather than exact timing guarantees. No timer thread
|
||||
reads or changes VM objects. Ready work shares the same heap as code and native events;
|
||||
bindings, lifecycle and all affected windows settle before publishing a new frame.
|
||||
|
||||
Owners can be Blocks, attached Mounts, open Pages, live Windows, or ordinary objects
|
||||
with attribute storage. Use `ui` for application lifetime. Each owner owns a traced
|
||||
task scope, and tasks trace callbacks/captures. The scheduler and task-to-owner link
|
||||
are weak. Hidden but still-referenced objects keep updating; keeping a task token
|
||||
alone does not keep its owner alive unless the callback explicitly captures it.
|
||||
A source function's normal global environment remains a managed capture.
|
||||
|
||||
The same owner/key supersedes its previous pending task, using the actual managed
|
||||
task identity as the request generation. `task.cancel()` cancels pending work and
|
||||
returns whether it was active. `task.active()` queries eligibility; `task.status()`
|
||||
returns pending/running/completed/cancelled/failed. Cancellation and completion drop
|
||||
the callback and remove the owner slot, including when the caller retained the Task.
|
||||
Already running synchronous callbacks finish before the next input can be processed.
|
||||
|
||||
Closing a Page cancels its tasks and its Mount tasks immediately, including closing
|
||||
and reopening in one input. Switching away or replacing content cancels detached
|
||||
Mount tasks; Page and ordinary Block tasks remain. Moving a Page between windows
|
||||
preserves Page tasks and cancels old Mount tasks. Closing a Window cancels its tasks
|
||||
and the Pages it owns. Reset, DELETE and successful program replacement discard the
|
||||
old scheduler with its VM; the worker validates submission/runtime generation before
|
||||
publication, so stale work cannot update the new heap. A failed replacement keeps
|
||||
the previous runtime and its tasks. Callback errors stop the shared runtime, cancel
|
||||
remaining tasks and preserve the last valid picture; completed writes do not roll back.
|
||||
Scheduling/cancelling in read-only render/binding calls is rejected.
|
||||
|
||||
Limits are 64 pending tasks per owner, 1024 per runtime, and 64 ready callbacks per
|
||||
worker poll, each with 128 frames/100,000 instructions. Remaining ready work stays
|
||||
pending for later polls. Timers and asynchronous UTF-8 file reads use the same task lifecycle.
|
||||
Network providers, await/coroutines and interrupting a blocked native callback remain unimplemented. See [owned-tasks.endor](examples/owned-tasks.endor)
|
||||
for real Endor code and native buttons.
|
||||
|
||||
Typed capability methods cannot be shadowed by instance attributes. Aster checks ordinary writes, type attachment and capability declaration before changing state; queries and method invocation reject backing-store conflicts introduced through trusted host access. The render cache subscribes to these method attribute keys and validates dirty Blocks before native dispatch, so direct storage changes cannot silently leave source calls and rendering on different methods. Removing the conflicting attribute restores the instance. Class method overrides and event subscriptions keep their existing APIs.
|
||||
|
||||
Aster `ObjectStore::call_effect` queries known native or conservatively proved source effects, including bound methods, without executing the function. Proved source ReadOnly methods constrain known native overrides. Shared local assignment, unresolved dynamic calls and other unproved instructions remain unknown; the runtime read-only barrier still follows actual calls and delegation. This does not establish a full source call graph or prove trusted host I/O safe.
|
||||
|
||||
Known source call graphs can now be proved ReadOnly using current globals/builtins, closure Cells and resolved receivers. Analysis follows control-flow joins and recursive call graphs with explicit queues, executes no function body and retains no cross-query cache. Rebinding triggers fresh analysis. Unresolved targets/results, shared assignments and calls outside the ReadOnly proof remain unknown; actual runtime barriers and native target checks still apply.
|
||||
|
||||
Native layout/paint fast paths and the default event classification inspect the actual ContextNativeFunction implementation and operation. They do not use the current mutable Block method table as an intrinsic baseline. Replacing a base method or a function payload therefore takes the new implementation path. Visual snapshots depend on each protocol function's version and include it in the protocol key, so payload changes at a stable function identity invalidate cached visuals and interactivity.
|
||||
|
||||
Block.click returns the generated Event and Block.dispatch returns the delivered Event, preserving the event object from the dispatch pipeline. Native return signatures match these actual results, including GUI activation.
|
||||
|
||||
Event dispatch/click and lifecycle entry points publish External as their allowed effect bound: handlers may mutate application state or use host I/O APIs. The built-in no-op bodies do not make the overridable handler contract ReadOnly. These entry points still reject invocation inside read-only rendering.
|
||||
|
||||
ContainerBlock.mainAlign is a managed attribute with start (default), center, end and space-between policies. It positions children in the allocated main-axis space after padding and the configured minimum gap. Center/end use remaining positive space; space-between adds it between two or more children. Overflow keeps start positions and existing sizes; alignment does not imply flex sizing. Native arrange queries and rendering use the same actual Bounds. Source arrange overrides retain their explicit placements.
|
||||
|
||||
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. See [flex.endor](examples/flex.endor) for shared text reflow and native button updates.
|
||||
|
||||
|
||||
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). Viewport and idle-task refresh park Pending across worker turns; newer viewport targets can cancel and replace unpublished work. Source/event callbacks execute atomically; their refresh can park across worker turns. 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. The worker can park viewport and idle-task refresh jobs; cancellation restores still-pending Mount preparation.
|
||||
|
||||
|
||||
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; 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.
|
||||
|
||||
|
||||
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.
|
||||
|
||||
|
||||
Large intrinsic layout trees (more than 64 occurrences) now use the resumable per-occurrence driver too. Native measurement caches remain active, and a single native callback remains atomic; VM instruction boundaries between nodes allow the worker to yield and replace an obsolete viewport. Small intrinsic trees retain the allocation-free native fast path. Structural extraction, driver preparation, settling checks and final command projection still run atomically; this is not a wall-clock preemption guarantee.
|
||||
|
||||
|
||||
Idle timer delivery now processes at most one ready callback (or one ineligible task cancellation) before starting an incremental refresh. No further task is delivered while that refresh is pending. Viewport changes can replace its unfinished layout without replaying the completed task callback. Task effects and native window commands publish only after settling; a previously completed resize may publish separately. Explicit input still drains pending work first. Synchronous host callers retain a maximum of 64 task deliveries per poll.
|
||||
|
||||
|
||||
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.
|
||||
|
||||
|
||||
ui.stats().dependencyInvalidations counts observed layout/paint dependency mismatches. lastInvalidDependency records the phase and invalidating identity/name or snapshot-cache cause without rendering its fields or retaining it. windowDependencyDiagnostics reports nonempty reasons from all windows. Source rendering observes the global names it reads, so unrelated global changes do not require repainting; compare idle document versions before diagnosing a refresh loop.
|
||||
|
||||
examples/gc-lifecycle.endor demonstrates an actual Page/Block/Task/await-frame reference cycle. Record ui.stats().objects, call mountCycle(), and inspect phase.value (1 while awaiting) and pending.value.status(). Closing the tab removes its navigation root; a retained Block's own workflow continues. Call releaseCycle() to release both external references, then query objects again to trigger the normal between-input collection and compare with the same baseline. Cached layout/paint metadata borrows identities and must not keep that cycle alive. The baseline is specific to that VM/program, not a fixed object count across programs.
|
||||
|
||||
|
||||
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 until failed, then 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 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.
|
||||
|
||||
|
||||
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.
|
||||
|
||||
Property bind computations also use precise global-name observations. Unrelated REPL/global changes keep valid cached outputs; changing an observed name or business object recalculates the binding, including hidden retained Blocks. A direct overwrite of a bound property is repaired by its compute function. ui.stats().bindingEvaluations counts computations in completed binding refreshes over this VM's lifetime, including initial computations; querying it does not itself force valid bindings to recompute. General dictionary-content reads still conservatively observe the dictionary.
|
||||
|
||||
@@ -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 图。
|
||||
|
||||

|
||||
|
||||
[放大 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 传输 | 有超时、大小和协议限制;不是业务服务 |
|
||||
|
||||

|
||||
|
||||
[放大 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`。
|
||||
@@ -0,0 +1,43 @@
|
||||
# 02 · 对象模型、展示位置与所有权
|
||||
|
||||
## 托管语义与原生快照是两种东西
|
||||
|
||||
业务对象、Block、Window、Mount、Task 等语义对象位于 Aster 堆中。Rust 的 `ObjectRef` 只是受检查的堆身份;能否存活由 VM 根及 `trace` 边决定。窗口侧的 `Arc<UiNode>`、Frame、Tab 是提取后的原生值,不能用来复活或直接修改语义对象。
|
||||
|
||||
下面是简化 UML 类图;实线关联表示有强引用/直接持有,虚线标明弱引用或派生关系。它省略类型表、回调捕获边和桌面的内部字典,不能当成完整 GC 根枚举。
|
||||
|
||||

|
||||
|
||||
[放大 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 协作完成。
|
||||
@@ -0,0 +1,50 @@
|
||||
# 03 · Endor 执行、并发请求与发布
|
||||
|
||||
## 完整程序提交的时序
|
||||
|
||||

|
||||
|
||||
[放大 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 的活对象修改不能混为一谈。
|
||||
|
||||
## 代际与失败边界
|
||||
|
||||

|
||||
|
||||
[放大 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。
|
||||
|
||||

|
||||
|
||||
[放大 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,不是无限吞吐。
|
||||
|
||||
这些预算帮助限制失控工作,**不构成执行任意不可信代码的安全沙箱**。当前程序仍运行在桌面进程内,文件和网络能力没有完成产品级权限治理。
|
||||
@@ -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 方法。
|
||||
|
||||
## 点击如何回到对象
|
||||
|
||||

|
||||
|
||||
[放大 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;本次没有改变该调度算法。
|
||||
@@ -0,0 +1,39 @@
|
||||
# 05 · 标签、窗口、默认页与开发工具
|
||||
|
||||
## 三层身份
|
||||
|
||||
| 层次 | 负责什么 | 不负责什么 |
|
||||
| --- | --- | --- |
|
||||
| 托管 Page / ManagedWindow | 页面内容、打开/关闭、所属窗口、脚本覆盖行为和对象可达性 | 像素级 hover、原生按钮位置 |
|
||||
| 已发布 Tab / Frame / Window Envelope | 传输不透明 ID、标题、活动状态、窗口命令和版本 | 保留 VM 堆对象 |
|
||||
| TesseraApp / tabs::Motion / winit Window | 绘制、命中、拖动、滚动、原生资源及即时交互 | 执行业务回调、复制业务对象图 |
|
||||
|
||||

|
||||
|
||||
[放大 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 类型有明确区别。
|
||||
@@ -0,0 +1,51 @@
|
||||
# 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)
|
||||
|
||||
项目已移除 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. 在增加可信外部运行能力前明确权限、执行隔离与分发机制。
|
||||
@@ -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` 和本轮验收记录。逐文件清单是本次迁移快照,不要求以后每次新增模块都伪装成同一轮迁移。
|
||||
@@ -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` 生成,不使用在线渲染服务。
|
||||
|
||||

|
||||
|
||||
[放大组件图 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 私有模块别名,让本次迁移不同时改写全部调用路径;详见设计决策。
|
||||
@@ -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。
|
||||
@@ -0,0 +1,67 @@
|
||||
# UML 图册
|
||||
|
||||
下面直接显示已渲染的 PNG,不需要安装 Markdown 插件。打开 SVG 可以放大阅读;`.puml` 保留可编辑源码。画布为不透明白底,避免深色查看器把黑色文字和连线淹没。
|
||||
|
||||
## 组件与主要数据流
|
||||
|
||||

|
||||
|
||||
[放大 SVG](rendered/components.svg) · [编辑源码](components.puml)
|
||||
|
||||
## 进程与线程部署
|
||||
|
||||

|
||||
|
||||
[放大 SVG](rendered/deployment.svg) · [编辑源码](deployment.puml)
|
||||
|
||||
## 对象模型与引用关系
|
||||
|
||||

|
||||
|
||||
[放大 SVG](rendered/domain.svg) · [编辑源码](domain.puml)
|
||||
|
||||
## 完整程序执行与发布时序
|
||||
|
||||

|
||||
|
||||
[放大 SVG](rendered/publication.svg) · [编辑源码](publication.puml)
|
||||
|
||||
## 候选与活跃运行时状态
|
||||
|
||||

|
||||
|
||||
[放大 SVG](rendered/runtime.svg) · [编辑源码](runtime.puml)
|
||||
|
||||
## 原生输入与事件分发时序
|
||||
|
||||

|
||||
|
||||
[放大 SVG](rendered/input.svg) · [编辑源码](input.puml)
|
||||
|
||||
## 异步任务状态
|
||||
|
||||

|
||||
|
||||
[放大 SVG](rendered/tasks.svg) · [编辑源码](tasks.puml)
|
||||
|
||||
## 页面展示与可达性状态
|
||||
|
||||

|
||||
|
||||
[放大 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 导出。脚本对渲染错误图做检查,失败则停止;修改源码后应重新生成并查看图片。
|
||||
|
||||
字体取自本机,跨机器重建可能有微小的排版差异。源图中的概念状态与省略字段范围以各篇架构说明为准;渲染不会把概念图变成自动提取的完整代码模型。
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
After Width: | Height: | Size: 317 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 264 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 469 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 251 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 376 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 227 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 226 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 169 KiB |
|
After Width: | Height: | Size: 8.4 KiB |
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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)。
|
||||
没有登录或查看需要账户的学校数据。
|
||||
@@ -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 课程主页同步进度与成绩
|
||||
@@ -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.
|
||||
@@ -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 脚本,也未因纯示例新增而重复构建。
|
||||
@@ -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.
|
||||
@@ -0,0 +1,32 @@
|
||||
# Endor UI examples
|
||||
|
||||
| File | Purpose |
|
||||
| --- | --- |
|
||||
| [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. |
|
||||
| [tabs.endor](tabs.endor) | Three real Page tabs, shared counter state, source titles, native switching/closing and reopening through code. |
|
||||
| [window.endor](window.endor) | A managed native Window resizes the actual shell; source callbacks update it and layout follows reported dimensions. |
|
||||
| [layout-cache.endor](layout-cache.endor) | Per-occurrence source measurement caches, separate size/paint models, and a band using the logical viewport input. |
|
||||
| [source-layout.endor](source-layout.endor) | Source measurement reads its initial Mount parent; source arrangement moves a child and a click updates the shared layout model. |
|
||||
| [source-hit.endor](source-hit.endor) | Source circle hit testing, ordinary Block click subscriptions and fallback to the parent through transparent space. |
|
||||
| [source-paint.endor](source-paint.endor) | Source paint overrides render checked commands in the window; a source Button method updates the shared tint model. |
|
||||
| [visual-protocols.endor](visual-protocols.endor) | Real source calls for constrained native measurement, arrangement and managed paint-command results from live Mounts. |
|
||||
| [mount-lifecycle.endor](mount-lifecycle.endor) | Source onMount/onUnmount methods, two occurrences of one object, ordered notifications and retained Mount lifetime. |
|
||||
| [events.endor](events.endor) | Managed event subscriptions, source onEvent override and numbered capture/target/bubble steps from native input. |
|
||||
| [native-subclasses.endor](native-subclasses.endor) | Real native TextBlock/Button/Page source subclasses, inherited fields, method overrides and shared field bindings. |
|
||||
| [classes.endor](classes.endor) | Endor class fields, inheritance, overriding, a retained receiver and Event arguments; native keyboard input updates shared model properties. |
|
||||
| [managed-types.endor](managed-types.endor) | Callable managed Endor types, one shared counter, two bound displays and a language callback invoked from native Button input. |
|
||||
| [page.endor](page.endor) | Four top-level statements construct text, a rectangle and a page, then call page.render; no main wrapper. |
|
||||
| [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. |
|
||||
|
||||
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 file is client-side sample material; Tessera's API stores source by namespace.
|
||||
|
||||
Return to the [project guide](../README.md).
|
||||
@@ -0,0 +1,22 @@
|
||||
class FileReader {
|
||||
output: TextBlock
|
||||
problem: TextBlock
|
||||
status: TextBlock
|
||||
task: Object
|
||||
function apply(self: FileReader): Unit {
|
||||
self.output.text = self.task.result()
|
||||
}
|
||||
function read(self: FileReader, path: String): Unit {
|
||||
self.task = ui.readText(self, "file", path, self.apply)
|
||||
self.output.text = ""
|
||||
self.status.bind("text", self.task.status)
|
||||
self.problem.bind("text", self.task.error)
|
||||
}
|
||||
}
|
||||
output = TextBlock("尚未读取文件")
|
||||
problem = TextBlock("")
|
||||
status = TextBlock("")
|
||||
reader = FileReader(output, problem, status, ui.state(0))
|
||||
page = Page()
|
||||
page.title = "异步文件"
|
||||
page.render(Column(24,16,TextBlock("在 REPL 调用 reader.read(绝对路径字符串)",2),status,output,problem))
|
||||
@@ -0,0 +1,25 @@
|
||||
class TextFetcher {
|
||||
output: TextBlock
|
||||
problem: TextBlock
|
||||
status: TextBlock
|
||||
task: Object
|
||||
response: String
|
||||
function apply(self: TextFetcher): Unit {
|
||||
self.response = self.task.result()
|
||||
self.output.text = "请求完成;在 REPL 查看 fetcher.response"
|
||||
}
|
||||
function fetch(self: TextFetcher, url: String): Unit {
|
||||
self.task = ui.fetchText(self, "request", url, self.apply)
|
||||
self.response = ""
|
||||
self.output.text = ""
|
||||
self.status.bind("text", self.task.status)
|
||||
self.problem.bind("text", self.task.error)
|
||||
}
|
||||
}
|
||||
output = TextBlock("尚未请求网络")
|
||||
problem = TextBlock("")
|
||||
status = TextBlock("")
|
||||
fetcher = TextFetcher(output, problem, status, ui.state(0), "")
|
||||
page = Page()
|
||||
page.title = "异步网络"
|
||||
page.render(Column(24,16,TextBlock("在 REPL 调用 fetcher.fetch(HTTP 或 HTTPS 地址字符串)",2),status,problem,output))
|
||||
@@ -0,0 +1,25 @@
|
||||
class AwaitReader {
|
||||
output: TextBlock
|
||||
status: TextBlock
|
||||
task: Object
|
||||
file: Object
|
||||
response: String
|
||||
function apply(self: AwaitReader): String {
|
||||
self.response = await self.file
|
||||
self.output.text = "读取完成;在 REPL 查看 reader.response 或 reader.task.result()"
|
||||
return self.response
|
||||
}
|
||||
function read(self: AwaitReader, path: String): Unit {
|
||||
self.file = ui.readText(self, "file", path)
|
||||
self.task = ui.spawn(self, "workflow", self.apply)
|
||||
self.response = ""
|
||||
self.output.text = "等待文件"
|
||||
self.status.bind("text", self.task.status)
|
||||
}
|
||||
}
|
||||
output = TextBlock("在 REPL 调用 reader.read(绝对路径字符串)")
|
||||
status = TextBlock("")
|
||||
reader = AwaitReader(output,status,ui.state(0),ui.state(0),"")
|
||||
page = Page()
|
||||
page.title = "await 文件"
|
||||
page.render(Column(24,16,status,output))
|
||||
@@ -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()
|
||||
@@ -0,0 +1,28 @@
|
||||
class Counter {
|
||||
value: Number
|
||||
lastEvent: String
|
||||
|
||||
function activate(self: Counter, event: Event): Unit {
|
||||
self.lastEvent = event.kind
|
||||
self.change()
|
||||
}
|
||||
|
||||
function change(self: Counter): Unit {
|
||||
self.value = 10
|
||||
}
|
||||
}
|
||||
|
||||
class DemoCounter: Counter {
|
||||
function change(self: DemoCounter): Unit {
|
||||
self.value = 12
|
||||
}
|
||||
}
|
||||
|
||||
model = DemoCounter(9, "等待点击")
|
||||
first = ui.textOf(model, "value", 2)
|
||||
second = ui.textOf(model, "value", 2)
|
||||
eventName = ui.textOf(model, "lastEvent")
|
||||
button = Button("调用继承方法,再分派到覆盖方法")
|
||||
button.onClick(model.activate)
|
||||
page = Page()
|
||||
page.render(Column(24, 16, TextBlock("Endor class:继承、self 与动态方法分派", 2), Row(0, 16, first, second), button, eventName))
|
||||
@@ -0,0 +1,18 @@
|
||||
class TaggedRect: RectBlock { tag: String }
|
||||
class TaggedColumn: Column { tag: String }
|
||||
class TaggedEvent: Event { tag: String }
|
||||
class TaggedList: ObjectList { tag: String }
|
||||
class Actions {
|
||||
rect: TaggedRect
|
||||
function recolor(self: Actions): Unit { self.rect.color = "#237A45" }
|
||||
}
|
||||
rect = TaggedRect(180, 60, "省略 radius/color 后的字段")
|
||||
event = TaggedEvent("click", "事件字段")
|
||||
items = TaggedList(rect, event, "列表成员之后的字段")
|
||||
actions = Actions(rect)
|
||||
button = Button("调用原对象方法")
|
||||
button.onClick(actions.recolor)
|
||||
root = TaggedColumn(24, 16, TextBlock("原生选项与子类字段分别检查", 2), rect, ui.textOf(rect, "tag"), ui.textOf(event, "tag"), ui.textOf(items, "tag"), button, "可变子项之后的字段")
|
||||
page = Page()
|
||||
page.title = "构造器契约"
|
||||
page.render(root)
|
||||
@@ -0,0 +1,80 @@
|
||||
class CooperativeWork {
|
||||
steps: Object
|
||||
function run(self: CooperativeWork): Unit {
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
self.steps.increment()
|
||||
}
|
||||
}
|
||||
left = CooperativeWork(ui.state(0))
|
||||
right = CooperativeWork(ui.state(0))
|
||||
leftTask = ui.spawn(left,"work",left.run)
|
||||
rightTask = ui.spawn(right,"work",right.run)
|
||||
leftStatus = TextBlock("")
|
||||
rightStatus = TextBlock("")
|
||||
leftStatus.bind("text",leftTask.status)
|
||||
rightStatus.bind("text",rightTask.status)
|
||||
page = Page()
|
||||
page.title = "独立暂停调用"
|
||||
page.render(Column(24,16,TextBlock("两个任务分别保存执行帧;在 REPL 查看 left.steps.value / right.steps.value",2),leftStatus,rightStatus))
|
||||
@@ -0,0 +1,39 @@
|
||||
class EventLog {
|
||||
count: Object
|
||||
captureStep: Number
|
||||
methodStep: Number
|
||||
targetStep: Number
|
||||
bubbleStep: Number
|
||||
phase: String
|
||||
function capture(self: EventLog, event: Event): Unit {
|
||||
self.count.increment()
|
||||
self.captureStep = self.count.value
|
||||
self.phase = event.phase
|
||||
}
|
||||
function target(self: EventLog, event: Event): Unit {
|
||||
self.count.increment()
|
||||
self.targetStep = self.count.value
|
||||
self.phase = event.phase
|
||||
}
|
||||
function bubble(self: EventLog, event: Event): Unit {
|
||||
self.count.increment()
|
||||
self.bubbleStep = self.count.value
|
||||
self.phase = event.phase
|
||||
}
|
||||
}
|
||||
class EventButton: Button {
|
||||
model: EventLog
|
||||
function onEvent(self: EventButton, event: Event): Unit {
|
||||
self.model.count.increment()
|
||||
self.model.methodStep = self.model.count.value
|
||||
self.model.phase = event.phase
|
||||
}
|
||||
}
|
||||
model = EventLog(ui.state(0), 0, 0, 0, 0, "等待点击")
|
||||
button = EventButton("捕获 → 对象方法 → 监听器 → 冒泡", model)
|
||||
root = Column(24, 16, TextBlock("同一对象系统中的事件分派", 2), button, ui.textOf(model.count, "value"), ui.textOf(model, "phase"))
|
||||
capture = root.on("click", model.capture, "capture")
|
||||
target = button.on("click", model.target)
|
||||
bubble = root.on("click", model.bubble)
|
||||
page = Page()
|
||||
page.render(root)
|
||||
@@ -0,0 +1,17 @@
|
||||
class ExitText: TextBlock {
|
||||
log: Object
|
||||
function onUnmount(self: ExitText, mount: Mount): Unit {
|
||||
self.log.increment()
|
||||
}
|
||||
}
|
||||
log = ui.state(0)
|
||||
watched = ExitText("关闭副窗口可观察卸载计数;退出应用也会卸载剩余位置",2,log)
|
||||
page = Page()
|
||||
page.title = "退出生命周期"
|
||||
page.render(Column(24,16,watched,ui.textOf(log,"value")))
|
||||
second = Window()
|
||||
second.setTitle("Exit lifecycle secondary")
|
||||
other = Page()
|
||||
other.render(watched)
|
||||
other.moveToWindow(second)
|
||||
pending = ui.sleep(ui,"pending",30000)
|
||||
@@ -0,0 +1,16 @@
|
||||
class CounterText: TextBlock {
|
||||
value: Number
|
||||
function change(self: CounterText, event: Event): Unit {
|
||||
self.value = 10
|
||||
}
|
||||
}
|
||||
class Model {
|
||||
target: Block
|
||||
}
|
||||
counter = CounterText("共享的原生子类对象", 9)
|
||||
model = Model(counter)
|
||||
button = Button("把 Number 字段改成 10")
|
||||
connection = button.on("click", counter.change)
|
||||
page = Page()
|
||||
page.title = "字段类型契约"
|
||||
page.render(Column(24, 16, counter, ui.textOf(counter, "value"), button, TextBlock("GUI 和源码写入同一个受检查的字段")))
|
||||
@@ -0,0 +1,40 @@
|
||||
class Strip: Row {
|
||||
function measure(self: Strip, mount: Mount, constraints: Constraints): MeasureResult {
|
||||
return MeasureResult(340, 60)
|
||||
}
|
||||
}
|
||||
class Actions {
|
||||
first: RectBlock
|
||||
second: RectBlock
|
||||
function grow(self: Actions): Unit {
|
||||
self.first.flexMin = 0
|
||||
self.first.flexMax = 105
|
||||
self.first.flexBasis = 100
|
||||
self.second.flexBasis = 100
|
||||
self.first.flex = 1
|
||||
self.second.flex = 3
|
||||
}
|
||||
function shrink(self: Actions): Unit {
|
||||
self.first.flexMax = 300
|
||||
self.first.flexMin = 150
|
||||
self.first.flexBasis = 200
|
||||
self.second.flexBasis = 200
|
||||
self.first.flex = 0
|
||||
self.second.flex = 0
|
||||
self.first.flexShrink = 1
|
||||
self.second.flexShrink = 1
|
||||
}
|
||||
}
|
||||
first = RectBlock(20, 20, 4, "#A4C8F0")
|
||||
second = RectBlock(40, 20, 4, "#A6D8B2")
|
||||
fixed = RectBlock(60, 20, 4, "#E8C990")
|
||||
actions = Actions(first, second)
|
||||
grow = Button("增长:上限后重新分配")
|
||||
grow.onClick(actions.grow)
|
||||
shrink = Button("收缩:最小尺寸后重新分配")
|
||||
shrink.onClick(actions.shrink)
|
||||
actions.grow()
|
||||
strip = Strip(10, 10, first, second, fixed)
|
||||
page = Page()
|
||||
page.title = "基础尺寸与边界"
|
||||
page.render(Column(20, 12, Row(0, 10, grow, shrink), strip, TextBlock("增长:105 / 135 / 60;收缩:150 / 90 / 60。")))
|
||||
@@ -0,0 +1,19 @@
|
||||
class Actions {
|
||||
filler: RectBlock
|
||||
function balanced(self: Actions): Unit { self.filler.flex = 1 }
|
||||
function narrow(self: Actions): Unit { self.filler.flex = 3 }
|
||||
}
|
||||
paragraph = TextBlock("GUI 和代码操控同一套 Aster 内存对象系统。对象只有一份,但每次挂载都有自己的约束和布局。这里用同一个 TextBlock 在两个容器中显示不同的换行。修改权重会重新测量文字高度,随后更新相邻布局。GUI 和代码操控同一套 Aster 内存对象系统。对象只有一份,但每次挂载都有自己的约束和布局。这里用同一个 TextBlock 在两个容器中显示不同的换行。修改权重会重新测量文字高度,随后更新相邻布局。")
|
||||
paragraph.flex = 1
|
||||
filler = RectBlock(20, 20)
|
||||
filler.flex = 1
|
||||
actions = Actions(filler)
|
||||
balanced = Button("等比例分配")
|
||||
balanced.onClick(actions.balanced)
|
||||
narrow = Button("文字只占四分之一")
|
||||
narrow.onClick(actions.narrow)
|
||||
first = Row(10, 10, paragraph, filler)
|
||||
second = Row(10, 10, paragraph, RectBlock(300, 20))
|
||||
page = Page()
|
||||
page.title = "按权重分配与文字重排"
|
||||
page.render(Column(10, 10, Row(0, 10, balanced, narrow), first, second))
|
||||
@@ -0,0 +1,5 @@
|
||||
let title = ui.text("Hello Endor · 你好,Tessera", 2, "#242422")
|
||||
let detail = ui.text("中文 English 123 — café", 1, "#606060")
|
||||
let row = ui.row(0, 12, ui.text("iiii"), ui.rect(24, 20, 4, "#DCE8FF"), ui.text("WWWW"), ui.rect(24, 20, 4, "#DCE8FF"))
|
||||
let page = ui.page()
|
||||
page.render(ui.column(24, 12, title, detail, row))
|
||||
@@ -0,0 +1,20 @@
|
||||
function identity(value: Number): Number { return value }
|
||||
function callNumber(callback: Function): Number { return callback() }
|
||||
function visual(value: Visual): Block { return value }
|
||||
class Actions {
|
||||
state: Object
|
||||
function read(self: Actions): Number { return self.state.value }
|
||||
function click(self: Actions, event: Event): Unit { self.state.increment() }
|
||||
}
|
||||
state = ui.state(0)
|
||||
actions = Actions(state)
|
||||
savedFunction = actions.read
|
||||
initial = identity(callNumber(savedFunction))
|
||||
button = Button("调用带类型检查的对象方法")
|
||||
connection = button.on("click",actions.click)
|
||||
root = visual(Column(24,16,TextBlock("源码、原生与绑定方法统一为 Function"),ui.textOf(state,"value"),button))
|
||||
page = Page()
|
||||
page.title = "函数类型检查"
|
||||
page.render(root)
|
||||
// identity("wrong") 会在进入函数体前报类型错误。
|
||||
// callNumber(RectBlock) 会拒绝把类型构造器作为 Function。
|
||||
@@ -0,0 +1,42 @@
|
||||
// Record ui.stats().objects, call mountCycle(), then inspect phase.value and
|
||||
// pending.value.status(). Close the tab: the referenced Block still waits.
|
||||
// releaseCycle() removes both external references; the next objects query
|
||||
// should return to the same baseline before the five-minute wait finishes.
|
||||
holder = ui.state(0)
|
||||
pending = ui.state(0)
|
||||
phase = ui.state(0)
|
||||
class CycleRect: RectBlock {
|
||||
peer: Object
|
||||
function wait(self: CycleRect): Unit {
|
||||
gate = ui.sleep(self,"sleep",300000)
|
||||
phase.set(1)
|
||||
done = await gate
|
||||
phase.set(2)
|
||||
self.peer.title = "等待已结束"
|
||||
}
|
||||
function measure(self: CycleRect, mount: Mount, constraints: Constraints): MeasureResult {
|
||||
observed = self.peer.title
|
||||
return MeasureResult(180,40)
|
||||
}
|
||||
function paint(self: CycleRect, mount: Mount, geometry: Bounds): DisplayList {
|
||||
observed = self.peer.title
|
||||
return RectBlock.paint(self,mount,geometry)
|
||||
}
|
||||
}
|
||||
function mountCycle(): Unit {
|
||||
transient = Page()
|
||||
transient.title = "临时引用环"
|
||||
rect = CycleRect(180,40,8,"#3868D9",transient)
|
||||
transient.render(rect)
|
||||
holder.set(transient)
|
||||
phase.set(0)
|
||||
pending.set(ui.spawn(rect,"workflow",rect.wait))
|
||||
}
|
||||
function releaseCycle(): Unit {
|
||||
holder.value.close()
|
||||
holder.set(0)
|
||||
pending.set(0)
|
||||
}
|
||||
base = Page()
|
||||
base.title = "GC 基线"
|
||||
base.render(TextBlock("关闭临时 Page 后应回收引用环",2))
|
||||
@@ -0,0 +1,12 @@
|
||||
color = "#ED6A5A"
|
||||
class GlobalPaint: RectBlock {
|
||||
function paint(self: GlobalPaint, mount: Mount, geometry: Bounds): DisplayList {
|
||||
drawing = RectBlock.paint(self,mount,geometry)
|
||||
drawing.commands.at(0).color = color
|
||||
return drawing
|
||||
}
|
||||
}
|
||||
rect = GlobalPaint(480,120,12,"#DDEEFF")
|
||||
page = Page()
|
||||
page.title = "全局名字依赖"
|
||||
page.render(Column(24,16,TextBlock("在 REPL 求值 42 不重绘;修改 color 会更新矩形颜色",2),rect))
|
||||
@@ -0,0 +1,10 @@
|
||||
function heading(value: Text): View {
|
||||
return ui.text(value, 2, "#242422")
|
||||
}
|
||||
|
||||
function main(): View {
|
||||
let title = heading("Hello Endor")
|
||||
let rectangle = ui.rect(240, 80, 12, "#DCE8FF")
|
||||
let detail = ui.row(0, 12, ui.text("Aster VM"), ui.spacer(8), ui.text("Tessera UI"))
|
||||
return ui.column(24, 12, title, rectangle, detail)
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
class WidthModel {
|
||||
width: Number
|
||||
function expand(self: WidthModel, event: Event): Unit {
|
||||
self.width = 260
|
||||
}
|
||||
}
|
||||
class Tint {
|
||||
color: String
|
||||
function blue(self: Tint, event: Event): Unit {
|
||||
self.color = "#526AC7"
|
||||
}
|
||||
}
|
||||
class CachedRect: RectBlock {
|
||||
dimensions: WidthModel
|
||||
tint: Tint
|
||||
function measure(self: CachedRect, mount: Mount, constraints: Constraints): MeasureResult {
|
||||
return MeasureResult(self.dimensions.width, 60)
|
||||
}
|
||||
function paint(self: CachedRect, mount: Mount, geometry: Bounds): DisplayList {
|
||||
drawing = RectBlock.paint(self, mount, geometry)
|
||||
drawing.commands.at(0).color = self.tint.color
|
||||
return drawing
|
||||
}
|
||||
}
|
||||
class ViewportBand: RectBlock {
|
||||
function measure(self: ViewportBand, mount: Mount, constraints: Constraints): MeasureResult {
|
||||
return MeasureResult(ui.viewport().width, 24)
|
||||
}
|
||||
}
|
||||
dimensions = WidthModel(200)
|
||||
tint = Tint("#ED6A5A")
|
||||
rect = CachedRect(80, 20, 0, "#ED6A5A", dimensions, tint)
|
||||
band = ViewportBand(80, 24, 0, "#237A45")
|
||||
blue = Button("只改绘制颜色")
|
||||
expand = Button("修改测量依赖")
|
||||
blueConnection = blue.on("click", tint.blue)
|
||||
expandConnection = expand.on("click", dimensions.expand)
|
||||
root = Column(24, 16, TextBlock("改变颜色保留测量缓存;改变宽度重新测量"), band, rect, blue, expand)
|
||||
page = Page()
|
||||
page.render(root)
|
||||
@@ -0,0 +1,35 @@
|
||||
class Policy {
|
||||
width: Number
|
||||
function narrow(self: Policy, event: Event): Unit { self.width = 280 }
|
||||
function wide(self: Policy, event: Event): Unit { self.width = 560 }
|
||||
}
|
||||
class ArrangedColumn: Column {
|
||||
policy: Policy
|
||||
function arrange(self: ArrangedColumn, mount: Mount, geometry: Bounds): Arrangement {
|
||||
result = Column.arrange(self, mount, geometry)
|
||||
result.children.at(0).width = self.policy.width
|
||||
return result
|
||||
}
|
||||
}
|
||||
class MeasuredColumn: Column {
|
||||
width: Number
|
||||
function measure(self: MeasuredColumn, mount: Mount, constraints: Constraints): MeasureResult {
|
||||
result = Column.measure(self, mount, constraints)
|
||||
result.width = self.width
|
||||
return result
|
||||
}
|
||||
}
|
||||
policy = Policy(280)
|
||||
paragraph = TextBlock("源码 arrange 改变分配宽度后,文字会按实际宽度重新测量。增加的高度继续影响容器和相邻对象,直到整棵布局稳定后才发布。这里与下面使用的是同一个 TextBlock;每个 Mount 都有自己的约束与几何。同一套内存对象不需要复制业务状态,也不通过丢弃传播来结束更新。")
|
||||
tail = TextBlock("这一行跟随上方段落。")
|
||||
arranged = ArrangedColumn(0, 12, paragraph, tail, policy)
|
||||
measured = MeasuredColumn(0, 12, paragraph, TextBlock("这一段的宽度来自源码 measure。"), 360)
|
||||
narrow = Button("arrange 为 280")
|
||||
wide = Button("arrange 为 560")
|
||||
narrowConnection = narrow.on("click", policy.narrow)
|
||||
wideConnection = wide.on("click", policy.wide)
|
||||
page = Page()
|
||||
page.title = "约束协商"
|
||||
page.render(Column(24, 16, Row(0, 12, narrow, wide), arranged, measured))
|
||||
ui.window().resize(850, 700)
|
||||
ui.window().setTitle("测量与排列直到稳定")
|
||||
@@ -0,0 +1,5 @@
|
||||
function main(): View {
|
||||
let heading = ui.text("Hello Endor", 2, "#242422")
|
||||
let rectangle = ui.rect(240, 80, 12, "#DCE8FF")
|
||||
return ui.column(24, 12, heading, rectangle)
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
counter = ui.state(9)
|
||||
first = ui.textOf(counter, "value", 2)
|
||||
second = ui.textOf(counter, "value", 2)
|
||||
title = TextBlock("Endor:同一份对象,代码与 GUI 共同操作", 2)
|
||||
button = Button("增加计数")
|
||||
function increment(): Unit { counter.increment() }
|
||||
button.onClick(increment)
|
||||
page = Page()
|
||||
page.render(Column(24, 16, title, Row(0, 16, first, second, button)))
|
||||
@@ -0,0 +1,29 @@
|
||||
class Sized: MeasureResult {}
|
||||
class BaseRect: RectBlock {
|
||||
function measure(self: BaseRect, mount: Mount, constraints: Constraints): MeasureResult {
|
||||
return RectBlock.measure(self, mount, constraints)
|
||||
}
|
||||
}
|
||||
class WideRect: BaseRect {
|
||||
function measure(self: WideRect, mount: Object, constraints: Object): Sized {
|
||||
measured = BaseRect.measure(self, mount, constraints)
|
||||
return Sized(measured.width, measured.height)
|
||||
}
|
||||
}
|
||||
class Actions {
|
||||
rect: WideRect
|
||||
count: Object
|
||||
function widen(self: Actions): Unit {
|
||||
self.rect.width = 260
|
||||
self.count.increment()
|
||||
}
|
||||
}
|
||||
rect = WideRect(180, 60, 8, "#ED6A5A")
|
||||
count = ui.state(0)
|
||||
actions = Actions(rect, count)
|
||||
button = Button("扩大矩形")
|
||||
button.onClick(actions.widen)
|
||||
root = Column(24, 16, TextBlock("参数可以更宽,返回类型可以更具体", 2), rect, button, ui.textOf(count, "value"))
|
||||
page = Page()
|
||||
page.title = "方法覆写契约"
|
||||
page.render(root)
|
||||
@@ -0,0 +1,42 @@
|
||||
class LifecycleLog {
|
||||
order: Object
|
||||
mounted: Object
|
||||
unmounted: Object
|
||||
parentMounted: Number
|
||||
childMounted: Number
|
||||
parentUnmounted: Number
|
||||
childUnmounted: Number
|
||||
latest: Object
|
||||
}
|
||||
class WatchedText: TextBlock {
|
||||
log: LifecycleLog
|
||||
function onMount(self: WatchedText, mount: Mount): Unit {
|
||||
self.log.order.increment()
|
||||
self.log.mounted.increment()
|
||||
self.log.childMounted = self.log.order.value
|
||||
self.log.latest.set(mount)
|
||||
self.setText("同一个对象,两个独立挂载位置")
|
||||
}
|
||||
function onUnmount(self: WatchedText, mount: Mount): Unit {
|
||||
self.log.order.increment()
|
||||
self.log.unmounted.increment()
|
||||
self.log.childUnmounted = self.log.order.value
|
||||
self.log.latest.set(mount)
|
||||
}
|
||||
}
|
||||
class WatchedColumn: Column {
|
||||
log: LifecycleLog
|
||||
function onMount(self: WatchedColumn, mount: Mount): Unit {
|
||||
self.log.order.increment()
|
||||
self.log.parentMounted = self.log.order.value
|
||||
}
|
||||
function onUnmount(self: WatchedColumn, mount: Mount): Unit {
|
||||
self.log.order.increment()
|
||||
self.log.parentUnmounted = self.log.order.value
|
||||
}
|
||||
}
|
||||
log = LifecycleLog(ui.state(0), ui.state(0), ui.state(0), 0, 0, 0, 0, ui.state(0))
|
||||
child = WatchedText("等待挂载", 2, log)
|
||||
root = WatchedColumn(24, 16, child, child, TextBlock("挂载次数"), ui.textOf(log.mounted, "value"), TextBlock("卸载次数"), ui.textOf(log.unmounted, "value"), log)
|
||||
page = Page()
|
||||
page.render(root)
|
||||
@@ -0,0 +1,12 @@
|
||||
received = ui.state(Event("waiting"))
|
||||
count = ui.state(0)
|
||||
function eventKind(): String { return received.value.kind }
|
||||
label = TextBlock("waiting")
|
||||
subscription = label.bind("text", eventKind)
|
||||
withEvent = Button("传递 Event 给原生 set")
|
||||
firstConnection = withEvent.on("click", received.set)
|
||||
withoutEvent = Button("调用零参数原生 increment")
|
||||
secondConnection = withoutEvent.on("click", count.increment)
|
||||
page = Page()
|
||||
page.title = "原生方法签名"
|
||||
page.render(Column(24, 16, TextBlock("源码和原生回调共用参数契约"), label, ui.textOf(count, "value"), withEvent, withoutEvent))
|
||||
@@ -0,0 +1,35 @@
|
||||
class StatusText: TextBlock {
|
||||
activeColor: String
|
||||
|
||||
function activate(self: StatusText, event: Event): Unit {
|
||||
self.setText("继承的原生文本已更新")
|
||||
self.setColor(self.activeColor)
|
||||
}
|
||||
}
|
||||
|
||||
class CustomStatus: StatusText {
|
||||
message: String
|
||||
|
||||
function activate(self: CustomStatus, event: Event): Unit {
|
||||
TextBlock.setText(self, self.message)
|
||||
self.setColor(self.activeColor)
|
||||
}
|
||||
}
|
||||
|
||||
class ActionButton: Button {
|
||||
target: Block
|
||||
|
||||
function activate(self: ActionButton, event: Event): Unit {
|
||||
self.target.activate(event)
|
||||
}
|
||||
}
|
||||
|
||||
class CustomPage: Page {
|
||||
caption: String
|
||||
}
|
||||
|
||||
label = CustomStatus("点击按钮更新同一个自定义文本对象", 2, "#242422", "#237A45", "源码子类与原生载荷共同工作")
|
||||
button = ActionButton("调用源码子类方法", label)
|
||||
button.onClick(button.activate)
|
||||
page = CustomPage("Endor 原生类型的源码继承")
|
||||
page.render(Column(24, 16, TextBlock(page.caption, 2), label, label, button, ui.textOf(label, "message")))
|
||||
@@ -0,0 +1,24 @@
|
||||
class Actions {
|
||||
owner: Object
|
||||
state: Object
|
||||
function complete(self: Actions): Unit { self.state.increment() }
|
||||
function schedule(self: Actions, event: Event): Unit {
|
||||
ui.after(self.owner, "load", 1500, self.complete)
|
||||
}
|
||||
}
|
||||
state = ui.state(0)
|
||||
hidden = TextBlock("这个 Block 没有挂载,也能拥有任务")
|
||||
page = Page()
|
||||
page.title = "任务生命周期"
|
||||
pageActions = Actions(page, state)
|
||||
blockActions = Actions(hidden, state)
|
||||
appActions = Actions(ui, state)
|
||||
pageButton = Button("Page 任务:关闭 Tab 会取消")
|
||||
blockButton = Button("隐藏 Block 任务:关闭 Tab 仍继续")
|
||||
appButton = Button("应用任务:关闭 Tab 仍继续")
|
||||
pageConnection = pageButton.on("click", pageActions.schedule)
|
||||
blockConnection = blockButton.on("click", blockActions.schedule)
|
||||
appConnection = appButton.on("click", appActions.schedule)
|
||||
page.render(Column(24, 16, TextBlock("1.5 秒后更新同一个状态对象;重复点击只保留最新任务"), ui.textOf(state, "value"), pageButton, blockButton, appButton))
|
||||
initial = ui.after(ui, "initial", 500, appActions.complete)
|
||||
ui.window().setTitle("Owned Tasks")
|
||||
@@ -0,0 +1,4 @@
|
||||
let heading = ui.text("Hello Endor", 2, "#242422")
|
||||
let rectangle = ui.rect(240, 80, 12, "#DCE8FF")
|
||||
let myui = ui.page()
|
||||
myui.render(ui.column(24, 12, heading, rectangle))
|
||||
@@ -0,0 +1,27 @@
|
||||
class Product {
|
||||
name: String
|
||||
color: String
|
||||
function label(self: Product): String { return self.name }
|
||||
function shade(self: Product): String { return self.color }
|
||||
function update(self: Product, event: Event): Unit {
|
||||
self.name = "原业务对象已更新"
|
||||
self.color = "#237A45"
|
||||
}
|
||||
function present(self: Product, window: Window): Block {
|
||||
title = TextBlock(self.name)
|
||||
swatch = RectBlock(180,48,8,self.color)
|
||||
titleBinding = title.bind("text",self.label)
|
||||
colorBinding = swatch.bind("color",self.shade)
|
||||
button = Button("调用业务对象方法")
|
||||
connection = button.on("click",self.update)
|
||||
result = Column(24,16,title,swatch,button)
|
||||
result.source = self
|
||||
result.contextWindow = window.id()
|
||||
return result
|
||||
}
|
||||
}
|
||||
ui.implement(Product,Presentable)
|
||||
product = Product("普通对象的显式展示能力", "#526AC7")
|
||||
view = ui.present(product)
|
||||
page = ui.open(view)
|
||||
page.title = "Presentable"
|
||||
@@ -0,0 +1,29 @@
|
||||
class Model {
|
||||
width: Number
|
||||
color: String
|
||||
label: String
|
||||
function getWidth(self: Model): Number { return self.width }
|
||||
function getColor(self: Model): String { return self.color }
|
||||
function getLabel(self: Model): String { return self.label }
|
||||
function expand(self: Model, event: Event): Unit {
|
||||
self.width = 260
|
||||
self.color = "#237A45"
|
||||
self.label = "绑定已更新"
|
||||
}
|
||||
}
|
||||
model = Model(120, "#526AC7", "点击更新共享对象")
|
||||
rect = RectBlock(120, 40, 8, "#526AC7")
|
||||
label = TextBlock("初始化")
|
||||
widthBinding = rect.bind("width", model.getWidth)
|
||||
colorBinding = rect.bind("color", model.getColor)
|
||||
labelBinding = label.bind("text", model.getLabel)
|
||||
button = Button("更新宽度、颜色和文字")
|
||||
clickConnection = button.on("click", model.expand)
|
||||
root = Column(24, 16, label, rect, button)
|
||||
page = Page()
|
||||
page.title = "通用属性绑定"
|
||||
page.render(root)
|
||||
second = Page()
|
||||
second.title = "同一组 Block"
|
||||
second.render(root)
|
||||
page.activate()
|
||||
@@ -0,0 +1,30 @@
|
||||
class Actions {
|
||||
vertical: ScrollBlock
|
||||
horizontal: ScrollBlock
|
||||
function down(self: Actions): Unit { self.vertical.mounts().at(0).scrollBy(0, 60) }
|
||||
function right(self: Actions): Unit { self.horizontal.mounts().at(0).scrollBy(60, 0) }
|
||||
function reset(self: Actions): Unit {
|
||||
self.vertical.mounts().at(0).scrollTo(0, 0)
|
||||
self.horizontal.mounts().at(0).scrollTo(0, 0)
|
||||
}
|
||||
function both(self: Actions): Unit { self.vertical.axis = "both" }
|
||||
}
|
||||
paragraph = TextBlock("这里展示的是同一个 TextBlock。左侧只允许纵向滚动,文字会按照这个 Mount 的实际视口宽度换行;右侧只允许横向滚动,文字保留横向展开。对象的文字和业务状态只有一份,每次展示的约束、几何和滚动位置分别保存。修改滚动轴也会重新测量受影响内容,并将已经不再允许的偏移夹回零。布局传播持续到受影响部分稳定,不会按固定跳数丢弃后续更新。这里展示的是同一个 TextBlock,两个视图可以拥有不同的换行结果。")
|
||||
vertical = ScrollBlock(260, 140, paragraph)
|
||||
vertical.padding = 8
|
||||
vertical.axis = "vertical"
|
||||
horizontal = ScrollBlock(260, 140, paragraph)
|
||||
horizontal.padding = 8
|
||||
horizontal.axis = "horizontal"
|
||||
actions = Actions(vertical, horizontal)
|
||||
down = Button("向下滚动")
|
||||
down.onClick(actions.down)
|
||||
right = Button("向右滚动")
|
||||
right.onClick(actions.right)
|
||||
reset = Button("回到起点")
|
||||
reset.onClick(actions.reset)
|
||||
both = Button("左侧恢复双轴")
|
||||
both.onClick(actions.both)
|
||||
page = Page()
|
||||
page.title = "滚动轴"
|
||||
page.render(Column(24, 16, TextBlock("同一个对象,不同的滚动轴", 2), Row(0, 24, Column(0, 8, TextBlock("vertical"), vertical), Column(0, 8, TextBlock("horizontal"), horizontal)), Row(0, 12, down, right, reset, both)))
|
||||
@@ -0,0 +1,30 @@
|
||||
class Painted: RectBlock {
|
||||
function paint(self: Painted, mount: Mount, geometry: Bounds): DisplayList {
|
||||
return RectBlock.paint(self,mount,geometry)
|
||||
}
|
||||
}
|
||||
class Actions {
|
||||
count: Object
|
||||
function click(self: Actions, event: Event): Unit { self.count.increment() }
|
||||
}
|
||||
count = ui.state(0)
|
||||
actions = Actions(count)
|
||||
first = Button("顶部按钮")
|
||||
middle = Button("中间按钮")
|
||||
last = Button("底部按钮")
|
||||
firstConnection = first.on("click",actions.click)
|
||||
middleConnection = middle.on("click",actions.click)
|
||||
lastConnection = last.on("click",actions.click)
|
||||
body = Column(12,12,first,Painted(520,180,8,"#DCE8FF"),middle,RectBlock(520,180,8,"#E3EFE5"),last)
|
||||
scroller = ScrollBlock(320,180,body)
|
||||
root = Column(24,16,TextBlock("同一 Block,两处 Mount 独立滚动"),ui.textOf(count,"value"),scroller)
|
||||
page = Page()
|
||||
page.title = "滚动示例"
|
||||
page.render(root)
|
||||
other = Window()
|
||||
other.setTitle("Scroll Secondary")
|
||||
second = Page()
|
||||
second.title = "独立滚动位置"
|
||||
second.open(other)
|
||||
second.render(root)
|
||||
ui.window().setTitle("Scroll Primary")
|
||||
@@ -0,0 +1,23 @@
|
||||
class CircleTarget: RectBlock {
|
||||
hits: Object
|
||||
function hitTest(self: CircleTarget, mount: Mount, point: Point): Bool {
|
||||
return point.inCircle(40, 40, 40)
|
||||
}
|
||||
function paint(self: CircleTarget, mount: Mount, geometry: Bounds): DisplayList {
|
||||
drawing = RectBlock.paint(self, mount, geometry)
|
||||
drawing.commands.at(0).width = 80
|
||||
drawing.commands.at(0).radius = 40
|
||||
return drawing
|
||||
}
|
||||
function onEvent(self: CircleTarget, event: Event): Unit {
|
||||
self.hits.increment()
|
||||
event.stopPropagation()
|
||||
}
|
||||
}
|
||||
hits = ui.state(0)
|
||||
background = ui.state(0)
|
||||
circle = CircleTarget(160, 80, 0, "#237A45", hits)
|
||||
root = Column(24, 16, circle, TextBlock("点击圆内计入圆;透明右半区域交给父容器"), TextBlock("圆内点击"), ui.textOf(hits, "value"), TextBlock("父容器点击"), ui.textOf(background, "value"))
|
||||
connection = root.on("click", background.increment)
|
||||
page = Page()
|
||||
page.render(root)
|
||||
@@ -0,0 +1,29 @@
|
||||
class Metrics {
|
||||
width: Number
|
||||
left: Number
|
||||
function expand(self: Metrics, event: Event): Unit {
|
||||
self.width = 260
|
||||
self.left = 68
|
||||
}
|
||||
}
|
||||
class MeasuredRect: RectBlock {
|
||||
function measure(self: MeasuredRect, mount: Mount, constraints: Constraints): MeasureResult {
|
||||
parent = mount.parent()
|
||||
return MeasureResult(parent.block.metrics.width, 60)
|
||||
}
|
||||
}
|
||||
class OffsetColumn: Column {
|
||||
metrics: Metrics
|
||||
function arrange(self: OffsetColumn, mount: Mount, geometry: Bounds): Arrangement {
|
||||
positions = Column.arrange(self, mount, geometry)
|
||||
positions.children.at(0).x = self.metrics.left
|
||||
return positions
|
||||
}
|
||||
}
|
||||
metrics = Metrics(200, 44)
|
||||
rect = MeasuredRect(80, 20, 0, "#526AC7")
|
||||
button = Button("更新布局")
|
||||
root = OffsetColumn(24, 16, rect, TextBlock("尺寸来自源码 measure,位置来自源码 arrange"), button, metrics)
|
||||
connection = button.on("click", metrics.expand)
|
||||
page = Page()
|
||||
page.render(root)
|
||||
@@ -0,0 +1,36 @@
|
||||
class TintRect: RectBlock {
|
||||
tint: String
|
||||
function paint(self: TintRect, mount: Mount, geometry: Bounds): DisplayList {
|
||||
drawing = RectBlock.paint(self, mount, geometry)
|
||||
drawing.commands.at(0).color = self.tint
|
||||
return drawing
|
||||
}
|
||||
}
|
||||
class Badge: TextBlock {
|
||||
background: String
|
||||
function paint(self: Badge, mount: Mount, geometry: Bounds): DisplayList {
|
||||
fill = PaintCommand()
|
||||
fill.kind = "roundedRect"
|
||||
fill.x = geometry.x
|
||||
fill.y = geometry.y
|
||||
fill.width = geometry.width
|
||||
fill.height = geometry.height
|
||||
fill.radius = 6
|
||||
fill.color = self.background
|
||||
text = TextBlock.paint(self, mount, geometry).commands.at(0)
|
||||
text.color = "#FFFFFF"
|
||||
return DisplayList(ObjectList(fill, text))
|
||||
}
|
||||
}
|
||||
class RecolorButton: Button {
|
||||
target: TintRect
|
||||
function onEvent(self: RecolorButton, event: Event): Unit {
|
||||
self.target.tint = "#526AC7"
|
||||
}
|
||||
}
|
||||
rect = TintRect(200, 60, 12, "#DDEEFF", "#ED6A5A")
|
||||
badge = Badge("Endor 源码正在绘制这个背景", 2, "#237A45")
|
||||
button = RecolorButton("通过对象方法改变绘制颜色", rect)
|
||||
root = Column(24, 16, TextBlock("源码 paint 进入真实窗口", 2), rect, rect, badge, button)
|
||||
page = Page()
|
||||
page.render(root)
|
||||
@@ -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")))
|
||||
@@ -0,0 +1,45 @@
|
||||
class TrackedPage: Page {
|
||||
calls: Object
|
||||
function moveToWindow(self: TrackedPage, window: Window): Page {
|
||||
self.calls.increment()
|
||||
return Page.moveToWindow(self, window)
|
||||
}
|
||||
function moveTab(self: TrackedPage, position: Number): Page {
|
||||
self.calls.increment()
|
||||
return Page.moveTab(self, position)
|
||||
}
|
||||
}
|
||||
class Actions {
|
||||
list: Column
|
||||
function insert(self: Actions, event: Event): Unit {
|
||||
self.list.insert(1, TextBlock("插入的新对象"))
|
||||
}
|
||||
}
|
||||
calls = ui.state(0)
|
||||
list = Column(0, 8, TextBlock("第一个子项"), TextBlock("最后一个子项"))
|
||||
actions = Actions(list)
|
||||
button = Button("在位置 1 插入 Block")
|
||||
connection = button.on("click", actions.insert)
|
||||
shared = Column(24, 16, TextBlock("拖动 Tab 重排、移入另一个窗口,或拖出独立窗口"), TextBlock("Page 方法调用次数"), ui.textOf(calls,"value"), button, list)
|
||||
first = TrackedPage(calls)
|
||||
first.title = "A · 共享内容"
|
||||
first.render(shared)
|
||||
second = TrackedPage(calls)
|
||||
second.title = "B · 单独内容"
|
||||
second.render(Column(24, 16, TextBlock("这是 B,Page 身份随 Tab 移动保留")))
|
||||
third = TrackedPage(calls)
|
||||
third.title = "C · 同一对象"
|
||||
third.render(shared)
|
||||
other = Window()
|
||||
other.resize(720,520)
|
||||
other.setTitle("Tab Target")
|
||||
other.moveTo(1700,80)
|
||||
target = TrackedPage(calls)
|
||||
target.title = "目标窗口"
|
||||
target.render(shared)
|
||||
target.open(other)
|
||||
first.activate()
|
||||
ui.window().resize(800,600)
|
||||
ui.window().setTitle("Tab Source")
|
||||
ui.window().moveTo(50,80)
|
||||
ui.window().focus()
|
||||
@@ -0,0 +1,17 @@
|
||||
// Code and tab chrome operate the same Page objects.
|
||||
first = Page()
|
||||
first.title = "共享计数"
|
||||
count = ui.state(0)
|
||||
increment = Button("加一")
|
||||
connection = increment.on("click", count.increment)
|
||||
first.render(Column(24,16,TextBlock("切换页面后,计数对象继续存在"),ui.textOf(count,"value"),increment))
|
||||
|
||||
second = Page()
|
||||
second.title = "另一个页面"
|
||||
second.render(Column(24,16,TextBlock("点击上方 Tab 切换;× 关闭页面"),TextBlock("Ctrl+Tab 切换,Cmd/Ctrl+W 关闭;代码可调用 first.open() 重开")))
|
||||
|
||||
third = Page()
|
||||
third.title = "窗口与布局"
|
||||
third.render(Column(24,16,TextBlock("每个 Tab 都是同一个 VM 中的 Page 对象"),RectBlock(240,80,8,"#237A45")))
|
||||
first.activate()
|
||||
ui.window().setTitle("Endor Pages")
|
||||
@@ -0,0 +1,30 @@
|
||||
class VisualResults {
|
||||
width: Number
|
||||
height: Number
|
||||
childX: Number
|
||||
childY: Number
|
||||
color: String
|
||||
}
|
||||
class ProbeRect: RectBlock {
|
||||
results: VisualResults
|
||||
function onMount(self: ProbeRect, mount: Mount): Unit {
|
||||
measured = self.measure(mount, Constraints(0, 0, 120, 80))
|
||||
self.results.width = measured.width
|
||||
self.results.height = measured.height
|
||||
drawing = self.paint(mount, Bounds(12, 18, 200, 60))
|
||||
self.results.color = drawing.commands.at(0).color
|
||||
}
|
||||
}
|
||||
class ProbeColumn: Column {
|
||||
results: VisualResults
|
||||
function onMount(self: ProbeColumn, mount: Mount): Unit {
|
||||
positions = self.arrange(mount, Bounds(20, 30, 500, 300))
|
||||
self.results.childX = positions.children.at(0).x
|
||||
self.results.childY = positions.children.at(0).y
|
||||
}
|
||||
}
|
||||
results = VisualResults(0, 0, 0, 0, "等待挂载")
|
||||
rect = ProbeRect(200, 60, 12, "#DDEEFF", results)
|
||||
root = ProbeColumn(24, 16, TextBlock("对象的原生视觉协议", 2), rect, TextBlock("约束测量宽度"), ui.textOf(results, "width"), TextBlock("绘制颜色"), ui.textOf(results, "color"), results)
|
||||
page = Page()
|
||||
page.render(root)
|
||||
@@ -0,0 +1,26 @@
|
||||
class WindowActions {
|
||||
window: Window
|
||||
function compact(self: WindowActions, event: Event): Unit {
|
||||
self.window.resize(900, 600)
|
||||
}
|
||||
function wide(self: WindowActions, event: Event): Unit {
|
||||
self.window.resize(1120, 720)
|
||||
}
|
||||
}
|
||||
class WindowBand: RectBlock {
|
||||
function measure(self: WindowBand, mount: Mount, constraints: Constraints): MeasureResult {
|
||||
return MeasureResult(constraints.maxWidth, 32)
|
||||
}
|
||||
}
|
||||
window = ui.window()
|
||||
actions = WindowActions(window)
|
||||
band = WindowBand(80, 32, 0, "#237A45")
|
||||
compact = Button("紧凑窗口 900 × 600")
|
||||
wide = Button("宽窗口 1120 × 720")
|
||||
compactConnection = compact.on("click", actions.compact)
|
||||
wideConnection = wide.on("click", actions.wide)
|
||||
page = Page()
|
||||
page.render(Column(24, 16, TextBlock("代码与 GUI 操作同一个受管窗口对象"), band, compact, wide))
|
||||
page.open(window)
|
||||
window.setTitle("Endor Window")
|
||||
window.resize(1120, 720)
|
||||
@@ -0,0 +1,18 @@
|
||||
// Both native windows use one Aster VM and one shared business object.
|
||||
count = ui.state(0)
|
||||
leftButton = Button("共享计数 +1")
|
||||
leftConnection = leftButton.on("click",count.increment)
|
||||
left = Page()
|
||||
left.title = "主窗口页面"
|
||||
left.render(Column(24,16,TextBlock("两个窗口操作同一个计数对象"),ui.textOf(count,"value"),leftButton))
|
||||
|
||||
other = Window()
|
||||
rightButton = Button("另一个窗口 +1")
|
||||
rightConnection = rightButton.on("click",count.increment)
|
||||
right = Page()
|
||||
right.title = "独立窗口页面"
|
||||
right.render(Column(24,16,TextBlock("关闭窗口会解除 Page 归属,保留的对象仍可重开"),ui.textOf(count,"value"),rightButton))
|
||||
right.open(other)
|
||||
ui.window().setTitle("Endor Main")
|
||||
other.setTitle("Endor Shared")
|
||||
other.resize(960,640)
|
||||
@@ -0,0 +1,45 @@
|
||||
class Paragraph: TextBlock {
|
||||
function measure(self: Paragraph, mount: Mount, constraints: Constraints): MeasureResult {
|
||||
return TextBlock.measure(self, mount, constraints)
|
||||
}
|
||||
function paint(self: Paragraph, mount: Mount, geometry: Bounds): DisplayList {
|
||||
return TextBlock.paint(self, mount, geometry)
|
||||
}
|
||||
}
|
||||
class Actions {
|
||||
window: Window
|
||||
paragraph: TextBlock
|
||||
full: String
|
||||
function narrow(self: Actions, event: Event): Unit { self.window.resize(800, 650) }
|
||||
function wide(self: Actions, event: Event): Unit { self.window.resize(1200, 650) }
|
||||
function short(self: Actions, event: Event): Unit { self.paragraph.setText("短文本:同一个对象、同一个 Mount。") }
|
||||
function restore(self: Actions, event: Event): Unit { self.paragraph.setText(self.full) }
|
||||
}
|
||||
full = "GUI 和代码操控同一套 Aster 内存对象。这个段落同时出现在两个窗口:对象内容相同,每个 Mount 根据自己的可用宽度换行。窗口变窄,段落高度增加,后面的对象向下移动;窗口变宽,段落高度减小,后面的对象向上移动。对象身份和已有 Mount 身份保持稳定。English words wrap at word boundaries; a_long_unbroken_identifier_also_wraps_when_it_cannot_fit_on_one_line. 中文、组合字符 é 与 emoji 👩💻 使用同一套字体整形。再次修改文字会重新计算高度,并更新两个窗口,不需要复制业务对象。"
|
||||
paragraph = Paragraph(full)
|
||||
tail = TextBlock("这一行的位置由前面段落的实际高度决定。")
|
||||
actions = Actions(ui.window(), paragraph, full)
|
||||
narrow = Button("变窄")
|
||||
wide = Button("变宽")
|
||||
short = Button("短文本")
|
||||
restore = Button("恢复段落")
|
||||
narrowConnection = narrow.on("click", actions.narrow)
|
||||
wideConnection = wide.on("click", actions.wide)
|
||||
shortConnection = short.on("click", actions.short)
|
||||
restoreConnection = restore.on("click", actions.restore)
|
||||
page = Page()
|
||||
page.title = "约束下的文字换行"
|
||||
page.render(Column(24, 16, Row(0, 12, narrow, wide, short, restore), paragraph, tail))
|
||||
other = Window()
|
||||
other.resize(720, 500)
|
||||
other.setTitle("同一个段落 · 另一组宽度")
|
||||
other.moveTo(1700, 80)
|
||||
second = Page()
|
||||
second.title = "共享 Paragraph"
|
||||
second.render(Column(24, 16, paragraph))
|
||||
second.open(other)
|
||||
page.activate()
|
||||
ui.window().resize(800, 650)
|
||||
ui.window().setTitle("文字换行与相邻布局")
|
||||
ui.window().moveTo(50, 80)
|
||||
ui.window().focus()
|
||||
@@ -0,0 +1,29 @@
|
||||
# Native packaging
|
||||
|
||||
`build-macos-app.sh` builds the release executable with the normal Cargo lockfile
|
||||
and creates `target/release/Tessera.app`. It uses the local Rust toolchain;
|
||||
no mirror or Docker configuration is installed, and no automated tests run.
|
||||
Additional arguments are forwarded to Cargo, such as `--offline` to reuse an
|
||||
already populated cache or temporary `--config` options for a dependency mirror
|
||||
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.
|
||||
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).
|
||||
|
||||
## Local verification
|
||||
|
||||
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 或远程渲染服务。
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/bin/sh
|
||||
# Native macOS build and app bundle. No Docker, mirror configuration, or tests.
|
||||
set -eu
|
||||
if [ "$(uname -s)" != Darwin ]; then
|
||||
echo "Build this app bundle on macOS." >&2
|
||||
exit 1
|
||||
fi
|
||||
cd "$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)"
|
||||
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"
|
||||
cp target/release/tessera "$bundle/Contents/MacOS/tessera.new"
|
||||
mv -f "$bundle/Contents/MacOS/tessera.new" "$bundle/Contents/MacOS/tessera"
|
||||
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">
|
||||
<plist version="1.0"><dict>
|
||||
<key>CFBundleIdentifier</key><string>com.entroia.tessera</string>
|
||||
<key>CFBundleName</key><string>Tessera</string>
|
||||
<key>CFBundleDisplayName</key><string>Tessera</string>
|
||||
<key>CFBundleExecutable</key><string>tessera</string>
|
||||
<key>CFBundlePackageType</key><string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key><string>$version</string>
|
||||
<key>CFBundleVersion</key><string>$version</string>
|
||||
<key>NSHighResolutionCapable</key><true/>
|
||||
</dict></plist>
|
||||
PLIST
|
||||
mv -f "$bundle/Contents/Info.plist.new" "$bundle/Contents/Info.plist"
|
||||
printf '%s\n' "$bundle"
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/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() {
|
||||
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) => {
|
||||
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);
|
||||
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})`);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
# Tessera 源码导航
|
||||
|
||||
整体设计和当前进展从 [架构导览](../docs/architecture/README.md) 开始;本轮每个文件的迁移对应见 [逐文件清单](../docs/architecture/file-map.md)。
|
||||
|
||||
`main.rs` 只负责组合启动,并保留 crate 私有模块路径别名。五组目录仍在同一个 binary crate 中,不是严格单向分层。
|
||||
|
||||
| 目录 | 责任 |
|
||||
| --- | --- |
|
||||
| `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) | 共享标签绘制/命中、密集布局、滚动、拖放及动画 |
|
||||
|
||||
## 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) | 页面、标签、插入标记和开发工具画面合成 |
|
||||
| [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/`。
|
||||
- 现有 API 和宿主测试:`runtime/api/tests.rs`、`runtime/endor_host/tests.rs`;其他模块中也保留原单元测试。
|
||||
|
||||
VM 和托管根只由执行 worker 操作。原生窗口收到已发布值,不收到 ObjectRef。完整 PUT 成功才接替活跃程序;Console 保留实际 VM;失败和清理语义见架构文档。
|
||||
|
||||
当前开发与验证在本机使用原生 Rust 工具链完成:格式、现有测试、Clippy、原生构建和人工运行检查。CI/CD 工作流与 Docker 检查入口已移除;具体命令见 [项目验证说明](../README.md#validation)。历史验收记录只代表当时实际执行的检查。
|
||||
@@ -1,306 +0,0 @@
|
||||
use std::{
|
||||
io::Read,
|
||||
sync::{Arc, RwLock},
|
||||
thread,
|
||||
};
|
||||
|
||||
use anyhow::{Context as _, Result};
|
||||
use tiny_http::{Header, Method, Request, Response, Server, StatusCode};
|
||||
use winit::event_loop::EventLoopProxy;
|
||||
|
||||
use crate::{
|
||||
app::AppEvent,
|
||||
compiler,
|
||||
document::{NamespaceState, RenderDocument},
|
||||
};
|
||||
|
||||
pub const API_ADDRESS: &str = "127.0.0.1:4737";
|
||||
const MAX_CODE_SIZE: u64 = 1_048_576;
|
||||
|
||||
pub fn start(
|
||||
namespace: Arc<RwLock<NamespaceState>>,
|
||||
proxy: EventLoopProxy<AppEvent>,
|
||||
) -> Result<()> {
|
||||
let server = Server::http(API_ADDRESS)
|
||||
.map_err(|error| anyhow::anyhow!(error))
|
||||
.with_context(|| format!("bind Tessera API to {API_ADDRESS}"))?;
|
||||
thread::Builder::new()
|
||||
.name("tessera-agent-api".to_owned())
|
||||
.spawn(move || {
|
||||
for request in server.incoming_requests() {
|
||||
handle(request, &namespace, &proxy);
|
||||
}
|
||||
})
|
||||
.context("start Tessera agent API thread")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle(
|
||||
mut request: Request,
|
||||
namespace: &Arc<RwLock<NamespaceState>>,
|
||||
proxy: &EventLoopProxy<AppEvent>,
|
||||
) {
|
||||
let method = request.method().clone();
|
||||
let path = request
|
||||
.url()
|
||||
.split('?')
|
||||
.next()
|
||||
.unwrap_or(request.url())
|
||||
.to_owned();
|
||||
|
||||
let response = if method == Method::Get && path == "/agent" {
|
||||
match namespace.read() {
|
||||
Ok(namespace) => markdown(StatusCode(200), agent_guide(&namespace)),
|
||||
Err(_) => error_response(StatusCode(500), "namespace lock is poisoned"),
|
||||
}
|
||||
} else if let Some(addressed_namespace) = namespace_from_path(&path).map(str::to_owned) {
|
||||
code_request(&mut request, method, &addressed_namespace, namespace, proxy)
|
||||
} else if method == Method::Options {
|
||||
text(StatusCode(204), "", "text/plain")
|
||||
} else {
|
||||
error_response(StatusCode(404), "route not found; start with GET /agent")
|
||||
};
|
||||
|
||||
let _ = request.respond(response);
|
||||
}
|
||||
|
||||
fn code_request(
|
||||
request: &mut Request,
|
||||
method: Method,
|
||||
addressed_namespace: &str,
|
||||
namespace: &Arc<RwLock<NamespaceState>>,
|
||||
proxy: &EventLoopProxy<AppEvent>,
|
||||
) -> Response<std::io::Cursor<Vec<u8>>> {
|
||||
let Ok(current) = namespace.read() else {
|
||||
return error_response(StatusCode(500), "namespace lock is poisoned");
|
||||
};
|
||||
if addressed_namespace != current.name {
|
||||
return error_response(
|
||||
StatusCode(404),
|
||||
format!(
|
||||
"namespace `{addressed_namespace}` is not active; current namespace is `{}`",
|
||||
current.name
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if method == Method::Get {
|
||||
let mut response = text(
|
||||
StatusCode(200),
|
||||
¤t.document.source,
|
||||
"text/plain; charset=utf-8",
|
||||
);
|
||||
add_header(
|
||||
&mut response,
|
||||
"X-Tessera-Revision",
|
||||
¤t.revision.to_string(),
|
||||
);
|
||||
return response;
|
||||
}
|
||||
drop(current);
|
||||
|
||||
match method {
|
||||
Method::Put => match read_code(request) {
|
||||
Ok(code) => match compiler::compile(&code, addressed_namespace) {
|
||||
Ok(document) => {
|
||||
if let Err(error) = document.validate() {
|
||||
return compile_error(error.to_string());
|
||||
}
|
||||
match namespace.write() {
|
||||
Ok(mut current) => {
|
||||
current.revision += 1;
|
||||
current.document = document;
|
||||
let revision = current.revision;
|
||||
drop(current);
|
||||
let _ = proxy.send_event(AppEvent::DocumentUpdated);
|
||||
json(
|
||||
StatusCode(200),
|
||||
serde_json::json!({
|
||||
"ok": true,
|
||||
"namespace": addressed_namespace,
|
||||
"revision": revision,
|
||||
"diagnostics": []
|
||||
}),
|
||||
)
|
||||
}
|
||||
Err(_) => error_response(StatusCode(500), "namespace lock is poisoned"),
|
||||
}
|
||||
}
|
||||
Err(error) => compile_error(error.to_string()),
|
||||
},
|
||||
Err(error) => error_response(StatusCode(400), error.to_string()),
|
||||
},
|
||||
Method::Delete => match namespace.write() {
|
||||
Ok(mut current) => {
|
||||
current.revision += 1;
|
||||
current.document = RenderDocument::default();
|
||||
let revision = current.revision;
|
||||
drop(current);
|
||||
let _ = proxy.send_event(AppEvent::DocumentUpdated);
|
||||
json(
|
||||
StatusCode(200),
|
||||
serde_json::json!({
|
||||
"ok": true,
|
||||
"namespace": addressed_namespace,
|
||||
"revision": revision
|
||||
}),
|
||||
)
|
||||
}
|
||||
Err(_) => error_response(StatusCode(500), "namespace lock is poisoned"),
|
||||
},
|
||||
Method::Options => text(StatusCode(204), "", "text/plain"),
|
||||
_ => error_response(StatusCode(405), "code supports GET, PUT, and DELETE"),
|
||||
}
|
||||
}
|
||||
|
||||
fn namespace_from_path(path: &str) -> Option<&str> {
|
||||
path.strip_prefix("/v1/namespaces/")?
|
||||
.strip_suffix("/code")
|
||||
.filter(|namespace| !namespace.is_empty() && !namespace.contains('/'))
|
||||
}
|
||||
|
||||
fn read_code(request: &mut Request) -> Result<String> {
|
||||
if request
|
||||
.body_length()
|
||||
.is_some_and(|length| length as u64 > MAX_CODE_SIZE)
|
||||
{
|
||||
anyhow::bail!("code exceeds the 1 MiB limit");
|
||||
}
|
||||
let mut code = String::new();
|
||||
request
|
||||
.as_reader()
|
||||
.take(MAX_CODE_SIZE + 1)
|
||||
.read_to_string(&mut code)
|
||||
.context("read code")?;
|
||||
if code.len() as u64 > MAX_CODE_SIZE {
|
||||
anyhow::bail!("code exceeds the 1 MiB limit");
|
||||
}
|
||||
Ok(code)
|
||||
}
|
||||
|
||||
fn agent_guide(namespace: &NamespaceState) -> String {
|
||||
format!(
|
||||
r#"# Tessera Agent API
|
||||
|
||||
Current namespace: `{name}`
|
||||
Current revision: `{revision}`
|
||||
|
||||
Tessera stores code by namespace. It has no files. Submit code only; Tessera parses,
|
||||
checks, compiles, and renders it.
|
||||
|
||||
## Code CRUD
|
||||
|
||||
- Read: `GET http://{address}/v1/namespaces/{name}/code`
|
||||
- Create or update: `PUT http://{address}/v1/namespaces/{name}/code`
|
||||
- Delete: `DELETE http://{address}/v1/namespaces/{name}/code`
|
||||
|
||||
Send PUT bodies as `text/plain; charset=utf-8`.
|
||||
|
||||
## Minimal syntax
|
||||
|
||||
```tessera
|
||||
namespace {name}
|
||||
|
||||
use tessera.ui::{{Column, Row, Spacer, Text}}
|
||||
|
||||
export scene Main {{
|
||||
render {{
|
||||
Column(gap: 12, padding: 24) {{
|
||||
Text("Hello", role: .title)
|
||||
Text("Rendered by Tessera")
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
```
|
||||
|
||||
Supported by this syntax experiment: one exported scene, one render root,
|
||||
`Column`, `Row`, `Spacer`, `Text`, `gap`, `padding`, and `.title`.
|
||||
Compilation errors reject the update and preserve the last rendered revision.
|
||||
"#,
|
||||
name = namespace.name,
|
||||
revision = namespace.revision,
|
||||
address = API_ADDRESS
|
||||
)
|
||||
}
|
||||
|
||||
fn compile_error(message: String) -> Response<std::io::Cursor<Vec<u8>>> {
|
||||
json(
|
||||
StatusCode(422),
|
||||
serde_json::json!({
|
||||
"ok": false,
|
||||
"diagnostics": [{
|
||||
"severity": "error",
|
||||
"message": message
|
||||
}]
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
fn error_response(
|
||||
status: StatusCode,
|
||||
message: impl Into<String>,
|
||||
) -> Response<std::io::Cursor<Vec<u8>>> {
|
||||
json(status, serde_json::json!({ "error": message.into() }))
|
||||
}
|
||||
|
||||
fn json(status: StatusCode, value: serde_json::Value) -> Response<std::io::Cursor<Vec<u8>>> {
|
||||
text(
|
||||
status,
|
||||
&value.to_string(),
|
||||
"application/json; charset=utf-8",
|
||||
)
|
||||
}
|
||||
|
||||
fn markdown(status: StatusCode, value: String) -> Response<std::io::Cursor<Vec<u8>>> {
|
||||
text(status, &value, "text/markdown; charset=utf-8")
|
||||
}
|
||||
|
||||
fn text(status: StatusCode, value: &str, content_type: &str) -> Response<std::io::Cursor<Vec<u8>>> {
|
||||
let mut response = Response::from_string(value).with_status_code(status);
|
||||
add_header(&mut response, "Content-Type", content_type);
|
||||
add_header(
|
||||
&mut response,
|
||||
"Access-Control-Allow-Origin",
|
||||
"http://127.0.0.1",
|
||||
);
|
||||
add_header(
|
||||
&mut response,
|
||||
"Access-Control-Allow-Methods",
|
||||
"GET, PUT, DELETE, OPTIONS",
|
||||
);
|
||||
add_header(
|
||||
&mut response,
|
||||
"Access-Control-Allow-Headers",
|
||||
"Content-Type",
|
||||
);
|
||||
response
|
||||
}
|
||||
|
||||
fn add_header(response: &mut Response<std::io::Cursor<Vec<u8>>>, name: &str, value: &str) {
|
||||
if let Ok(header) = Header::from_bytes(name, value) {
|
||||
response.add_header(header);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn extracts_namespace_only_from_code_routes() {
|
||||
assert_eq!(
|
||||
namespace_from_path("/v1/namespaces/app.main/code"),
|
||||
Some("app.main")
|
||||
);
|
||||
assert_eq!(namespace_from_path("/v1/namespaces/app.main"), None);
|
||||
assert_eq!(namespace_from_path("/v1/namespaces/a/b/code"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guide_contains_only_code_crud_routes() {
|
||||
let guide = agent_guide(&NamespaceState::default());
|
||||
assert!(guide.contains("Code CRUD"));
|
||||
assert!(guide.contains("PUT http://127.0.0.1:4737"));
|
||||
assert!(!guide.contains("display_list"));
|
||||
}
|
||||
}
|
||||
@@ -1,193 +0,0 @@
|
||||
use std::{
|
||||
num::NonZeroU32,
|
||||
sync::{Arc, RwLock},
|
||||
};
|
||||
|
||||
use softbuffer::{Context, Surface};
|
||||
use winit::{
|
||||
application::ApplicationHandler,
|
||||
dpi::{LogicalSize, PhysicalPosition},
|
||||
event::{ElementState, MouseButton, WindowEvent},
|
||||
event_loop::ActiveEventLoop,
|
||||
keyboard::{Key, ModifiersState, NamedKey},
|
||||
window::{Window, WindowAttributes, WindowId},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
developer_tools::DeveloperToolsState,
|
||||
document::NamespaceState,
|
||||
geometry::Point,
|
||||
scene::{self, SceneLayout},
|
||||
software_renderer::SoftwareRenderer,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum AppEvent {
|
||||
DocumentUpdated,
|
||||
}
|
||||
|
||||
pub struct TesseraApp {
|
||||
window: Option<Arc<Window>>,
|
||||
context: Option<Context<Arc<Window>>>,
|
||||
surface: Option<Surface<Arc<Window>, Arc<Window>>>,
|
||||
namespace: Arc<RwLock<NamespaceState>>,
|
||||
developer_tools: DeveloperToolsState,
|
||||
layout: SceneLayout,
|
||||
pointer: Point,
|
||||
modifiers: ModifiersState,
|
||||
}
|
||||
|
||||
impl TesseraApp {
|
||||
pub fn new(namespace: Arc<RwLock<NamespaceState>>) -> Self {
|
||||
Self {
|
||||
window: None,
|
||||
context: None,
|
||||
surface: None,
|
||||
namespace,
|
||||
developer_tools: DeveloperToolsState::default(),
|
||||
layout: SceneLayout::default(),
|
||||
pointer: Point::default(),
|
||||
modifiers: ModifiersState::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn request_redraw(&self) {
|
||||
if let Some(window) = &self.window {
|
||||
window.request_redraw();
|
||||
}
|
||||
}
|
||||
|
||||
fn toggle_developer_tools(&mut self) {
|
||||
if let Ok(namespace) = self.namespace.read() {
|
||||
self.developer_tools.toggle(&namespace.document);
|
||||
}
|
||||
self.request_redraw();
|
||||
}
|
||||
|
||||
fn document_updated(&mut self) {
|
||||
if let Ok(namespace) = self.namespace.read() {
|
||||
self.developer_tools.document_updated(&namespace.document);
|
||||
}
|
||||
self.request_redraw();
|
||||
}
|
||||
|
||||
fn handle_keyboard(&mut self, event: &winit::event::KeyEvent) {
|
||||
if event.state != ElementState::Pressed || event.repeat {
|
||||
return;
|
||||
}
|
||||
let is_f12 = matches!(event.logical_key, Key::Named(NamedKey::F12));
|
||||
let is_i =
|
||||
matches!(&event.logical_key, Key::Character(value) if value.eq_ignore_ascii_case("i"));
|
||||
let mac_shortcut = self.modifiers.super_key() && self.modifiers.alt_key() && is_i;
|
||||
let other_shortcut = self.modifiers.control_key() && self.modifiers.shift_key() && is_i;
|
||||
if is_f12 || mac_shortcut || other_shortcut {
|
||||
self.toggle_developer_tools();
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_click(&mut self) {
|
||||
let Some(node_id) = self.layout.developer_tools.node_at(self.pointer) else {
|
||||
return;
|
||||
};
|
||||
self.developer_tools.selected_node_id = Some(node_id.to_owned());
|
||||
self.request_redraw();
|
||||
}
|
||||
|
||||
fn redraw(&mut self) {
|
||||
let (Some(window), Some(surface)) = (self.window.as_ref(), self.surface.as_mut()) else {
|
||||
return;
|
||||
};
|
||||
let size = window.inner_size();
|
||||
let (Some(width), Some(height)) =
|
||||
(NonZeroU32::new(size.width), NonZeroU32::new(size.height))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
let Ok(namespace) = self.namespace.read() else {
|
||||
return;
|
||||
};
|
||||
let scene = scene::build_scene(
|
||||
size.width,
|
||||
size.height,
|
||||
window.scale_factor() as f32,
|
||||
&namespace.document,
|
||||
&self.developer_tools,
|
||||
);
|
||||
drop(namespace);
|
||||
self.layout = scene.layout;
|
||||
|
||||
surface
|
||||
.resize(width, height)
|
||||
.expect("resize software surface");
|
||||
let mut buffer = surface.buffer_mut().expect("acquire software buffer");
|
||||
SoftwareRenderer::render(&scene.display_list, &mut buffer, size.width, size.height);
|
||||
buffer.present().expect("present software-rendered frame");
|
||||
}
|
||||
}
|
||||
|
||||
impl ApplicationHandler<AppEvent> for TesseraApp {
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
if self.window.is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
let attributes = WindowAttributes::default()
|
||||
.with_title("Tessera")
|
||||
.with_inner_size(LogicalSize::new(1_280.0, 800.0))
|
||||
.with_min_inner_size(LogicalSize::new(720.0, 480.0));
|
||||
let window = Arc::new(
|
||||
event_loop
|
||||
.create_window(attributes)
|
||||
.expect("create Tessera window"),
|
||||
);
|
||||
let context = Context::new(window.clone()).expect("create software-rendering context");
|
||||
let surface =
|
||||
Surface::new(&context, window.clone()).expect("create software-rendering surface");
|
||||
|
||||
self.window = Some(window.clone());
|
||||
self.context = Some(context);
|
||||
self.surface = Some(surface);
|
||||
window.request_redraw();
|
||||
}
|
||||
|
||||
fn user_event(&mut self, _event_loop: &ActiveEventLoop, event: AppEvent) {
|
||||
match event {
|
||||
AppEvent::DocumentUpdated => self.document_updated(),
|
||||
}
|
||||
}
|
||||
|
||||
fn window_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
window_id: WindowId,
|
||||
event: WindowEvent,
|
||||
) {
|
||||
let Some(window) = self.window.as_ref() else {
|
||||
return;
|
||||
};
|
||||
if window.id() != window_id {
|
||||
return;
|
||||
}
|
||||
|
||||
match event {
|
||||
WindowEvent::CloseRequested => event_loop.exit(),
|
||||
WindowEvent::Resized(_) | WindowEvent::ScaleFactorChanged { .. } => {
|
||||
window.request_redraw()
|
||||
}
|
||||
WindowEvent::CursorMoved {
|
||||
position: PhysicalPosition { x, y },
|
||||
..
|
||||
} => self.pointer = Point::new(x as f32, y as f32),
|
||||
WindowEvent::MouseInput {
|
||||
state: ElementState::Released,
|
||||
button: MouseButton::Left,
|
||||
..
|
||||
} => self.handle_click(),
|
||||
WindowEvent::ModifiersChanged(modifiers) => self.modifiers = modifiers.state(),
|
||||
WindowEvent::KeyboardInput { event, .. } => self.handle_keyboard(&event),
|
||||
WindowEvent::RedrawRequested => self.redraw(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
// Module ownership follows the directory; crate-root aliases keep internal call sites stable.
|
||||
pub(crate) mod ui_bridge;
|
||||
@@ -0,0 +1,397 @@
|
||||
//! 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),
|
||||
("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")),
|
||||
("Row", "ContainerBlock", Some("row")),
|
||||
("Column", "ContainerBlock", Some("column")),
|
||||
("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,
|
||||
"button" => Operation::Button,
|
||||
"page" => Operation::Page,
|
||||
"window-create" => Operation::NewWindow,
|
||||
_ => return Err(invalid("unknown native type allocator").into()),
|
||||
};
|
||||
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![]),
|
||||
] {
|
||||
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),
|
||||
"button" => Some(Operation::Button),
|
||||
"page" => Some(Operation::Page),
|
||||
"window-create" => Some(Operation::NewWindow),
|
||||
"event" | "object-list" => None,
|
||||
_ => return Err(invalid("unknown deferred factory").into()),
|
||||
};
|
||||
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),
|
||||
("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)
|
||||
}
|
||||
@@ -0,0 +1,789 @@
|
||||
//! Native Block operations executed on the owning VM worker.
|
||||
use super::*;
|
||||
|
||||
impl NativeCallable for Function {
|
||||
fn signature(&self) -> Option<CallSignature> {
|
||||
self.signature.clone()
|
||||
}
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(self.operation.arity())
|
||||
}
|
||||
|
||||
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, 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 => Some(Data::new(
|
||||
if matches!(self.operation, Row) {
|
||||
Kind::Row
|
||||
} 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)),
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
//! Developer workspaces are managed Pages, using the same roots and placement API.
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct OpenTool {
|
||||
session: Shared,
|
||||
ui: ObjectRef,
|
||||
}
|
||||
impl NativeCallable for OpenTool {
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::exact(1))
|
||||
}
|
||||
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.
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
//! Canonical contracts for native Block methods and constructors.
|
||||
use super::*;
|
||||
|
||||
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 {
|
||||
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)
|
||||
}
|
||||
|
||||
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 => (
|
||||
vec![Number, Number],
|
||||
Some(nominal("Block")?),
|
||||
nominal(if matches!(operation, Row) {
|
||||
"Row"
|
||||
} else {
|
||||
"Column"
|
||||
})?,
|
||||
CallEffect::ReadOnly,
|
||||
),
|
||||
Button => (
|
||||
vec![TextType],
|
||||
None,
|
||||
nominal("Button")?,
|
||||
CallEffect::ReadOnly,
|
||||
),
|
||||
Page => (vec![], None, nominal("Page")?, 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,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// Tessera's start page is an ordinary Endor Page, including its layout and actions.
|
||||
// This module has its own globals; creating tabs does not replace user bindings.
|
||||
class StartPage: Page {
|
||||
function measure(self: StartPage, mount: Mount, constraints: Constraints): MeasureResult {
|
||||
return MeasureResult(constraints.maxWidth, constraints.maxHeight)
|
||||
}
|
||||
}
|
||||
class StartRow: Row {
|
||||
function measure(self: StartRow, mount: Mount, constraints: Constraints): MeasureResult {
|
||||
measured = Row.measure(self, mount, constraints)
|
||||
return MeasureResult(constraints.maxWidth, measured.height)
|
||||
}
|
||||
}
|
||||
// Quiet action rows retain native hit targets and keyboard focus without card chrome.
|
||||
class StartButton: Button {
|
||||
function measure(self: StartButton, mount: Mount, constraints: Constraints): MeasureResult {
|
||||
return MeasureResult(360, 40)
|
||||
}
|
||||
function paint(self: StartButton, mount: Mount, geometry: Bounds): DisplayList {
|
||||
return DisplayList(ObjectList())
|
||||
}
|
||||
}
|
||||
class StartLine: Row {
|
||||
function measure(self: StartLine, mount: Mount, constraints: Constraints): MeasureResult {
|
||||
measured = Row.measure(self, mount, constraints)
|
||||
return MeasureResult(360, measured.height)
|
||||
}
|
||||
}
|
||||
class StartActions {
|
||||
home: Page
|
||||
function blank(self: StartActions, event: Event): Unit {
|
||||
page = Page()
|
||||
page.title = "未命名页面"
|
||||
back = Button("返回开始页")
|
||||
back.onClick(self.home.activate)
|
||||
page.render(Column(32, 16, TextBlock("未命名页面", 2), TextBlock("一个新的 Page 对象,已加入当前窗口。"), TextBlock("用 Endor 的 page.render(...) 组织内容。"), back))
|
||||
}
|
||||
function counter(self: StartActions, event: Event): Unit {
|
||||
count = ui.state(0)
|
||||
add = Button("增加计数")
|
||||
add.onClick(count.increment)
|
||||
page = Page()
|
||||
page.title = "共享对象"
|
||||
page.render(Column(32, 16, TextBlock("一个对象,两个视图", 2), TextBlock("点击一次,两处展示同时更新。切换标签后,状态仍然保留。"), Row(0, 32, ui.textOf(count, "value", 3), ui.textOf(count, "value", 3)), add))
|
||||
}
|
||||
function compose(self: StartActions, event: Event): Unit {
|
||||
label = TextBlock("对象可以被多处引用")
|
||||
page = Page()
|
||||
page.title = "组合页面"
|
||||
page.render(Column(32, 20, TextBlock("把对象组合成界面", 2), TextBlock("Column 组织纵向内容,Row 组织横向内容。"), Row(0, 16, RectBlock(100, 64, 12, "#DCE8FF"), RectBlock(100, 64, 12, "#E3ECDC"), RectBlock(100, 64, 12, "#F3E4DB")), label, Row(0, 24, label, label)))
|
||||
}
|
||||
}
|
||||
function newTab(): Page {
|
||||
page = StartPage()
|
||||
page.title = "新标签页"
|
||||
actions = StartActions(page)
|
||||
blank = StartButton("+ 创建页面")
|
||||
counter = StartButton("↗ 共享对象示例")
|
||||
compose = StartButton("◇ 界面组合示例")
|
||||
blank.on("click", actions.blank)
|
||||
counter.on("click", actions.counter)
|
||||
compose.on("click", actions.compose)
|
||||
heading = StartLine(0, 0, TextBlock("Endor", 2, "#30343B"))
|
||||
heading.mainAlign = "center"
|
||||
subtitle = StartLine(0, 0, TextBlock("创建页面,或从一个示例开始。", 1, "#80858D"))
|
||||
subtitle.mainAlign = "center"
|
||||
newHint = StartLine(0, 0, TextBlock("新建标签页", 1, "#8A8F97"), TextBlock("⌘ T / Ctrl + T", 1, "#747B85"))
|
||||
newHint.mainAlign = "space-between"
|
||||
closeHint = StartLine(0, 0, TextBlock("关闭标签页", 1, "#8A8F97"), TextBlock("⌘ W / Ctrl + W", 1, "#747B85"))
|
||||
closeHint.mainAlign = "space-between"
|
||||
content = Column(0, 8,
|
||||
heading, subtitle, Spacer(20),
|
||||
blank, counter, compose, Spacer(20),
|
||||
newHint, closeHint)
|
||||
row = StartRow(24, 0, content)
|
||||
row.mainAlign = "center"
|
||||
page.mainAlign = "center"
|
||||
page.render(row)
|
||||
return page
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
//! Owned immutable visual derivation; no managed VM handles.
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct UiNode {
|
||||
pub flex: f32,
|
||||
pub flex_policy: crate::layout::FlexPolicy,
|
||||
pub main_align: crate::layout::MainAlign,
|
||||
pub block_id: String,
|
||||
pub protocol_key: String,
|
||||
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::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()
|
||||
}
|
||||
|
||||
pub fn shallow_eq(&self, other: &Self) -> bool {
|
||||
if self.flex_policy != other.flex_policy
|
||||
|| self.flex != other.flex
|
||||
|| self.main_align != other.main_align
|
||||
|| 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::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 {
|
||||
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>>,
|
||||
},
|
||||
}
|
||||