@native-sdk/cli 0.0.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (373) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +50 -1
  3. package/app.zon +30 -0
  4. package/assets/icon.icns +0 -0
  5. package/assets/icon.ico +0 -0
  6. package/assets/icon.png +0 -0
  7. package/assets/icon.svg +15 -0
  8. package/assets/native-sdk.entitlements +10 -0
  9. package/assets/native-sdk.manifest +12 -0
  10. package/bin/native.js +156 -0
  11. package/build/app.zig +716 -0
  12. package/build.zig +2593 -0
  13. package/build.zig.zon +24 -0
  14. package/native-sdk.d.ts +615 -0
  15. package/package.json +45 -8
  16. package/skill-data/automation/SKILL.md +248 -0
  17. package/skill-data/core/SKILL.md +249 -0
  18. package/skill-data/core/references/app-model-runtime.md +141 -0
  19. package/skill-data/core/references/bridge-security-native-capabilities.md +230 -0
  20. package/skill-data/core/references/frontend-assets.md +124 -0
  21. package/skill-data/core/references/project-anatomy.md +108 -0
  22. package/skill-data/core/references/web-engines-packaging-debugging.md +199 -0
  23. package/skill-data/native-ui/SKILL.md +1080 -0
  24. package/skills/native-sdk/SKILL.md +33 -0
  25. package/src/app_runner/root.zig +740 -0
  26. package/src/assets/root.zig +20 -0
  27. package/src/automation/protocol.zig +285 -0
  28. package/src/automation/root.zig +13 -0
  29. package/src/automation/server.zig +506 -0
  30. package/src/automation/snapshot.zig +1202 -0
  31. package/src/automation/watcher.zig +165 -0
  32. package/src/bridge/root.zig +507 -0
  33. package/src/debug/root.zig +246 -0
  34. package/src/embed/app_exports.zig +11 -0
  35. package/src/embed/c_api.zig +793 -0
  36. package/src/embed/c_exports.zig +10 -0
  37. package/src/embed/chrome.zig +168 -0
  38. package/src/embed/conversions.zig +359 -0
  39. package/src/embed/host.zig +960 -0
  40. package/src/embed/root.zig +81 -0
  41. package/src/embed/tests.zig +2552 -0
  42. package/src/embed/types.zig +382 -0
  43. package/src/embed/ui_host.zig +289 -0
  44. package/src/extensions/root.zig +197 -0
  45. package/src/frontend/root.zig +48 -0
  46. package/src/js/root.zig +65 -0
  47. package/src/platform/android/NativeSdkActivity.java +1370 -0
  48. package/src/platform/android/android_host.c +696 -0
  49. package/src/platform/android/files.zig +9 -0
  50. package/src/platform/android/native_sdk_app.h +237 -0
  51. package/src/platform/ios/files.zig +8 -0
  52. package/src/platform/ios/native_sdk_app.h +289 -0
  53. package/src/platform/ios/uikit_host.m +2739 -0
  54. package/src/platform/linux/cef_host.cpp +599 -0
  55. package/src/platform/linux/gtk_host.c +5362 -0
  56. package/src/platform/linux/gtk_host.h +265 -0
  57. package/src/platform/linux/root.zig +1519 -0
  58. package/src/platform/macos/appkit_host.h +604 -0
  59. package/src/platform/macos/appkit_host.m +10392 -0
  60. package/src/platform/macos/automation_host.h +14 -0
  61. package/src/platform/macos/automation_host.m +12 -0
  62. package/src/platform/macos/cef_host.mm +3028 -0
  63. package/src/platform/macos/root.zig +2260 -0
  64. package/src/platform/null_platform.zig +2232 -0
  65. package/src/platform/null_platform_tests.zig +670 -0
  66. package/src/platform/policy_values.zig +14 -0
  67. package/src/platform/root.zig +181 -0
  68. package/src/platform/types.zig +2681 -0
  69. package/src/platform/windows/cef_host.cpp +3 -0
  70. package/src/platform/windows/root.zig +1521 -0
  71. package/src/platform/windows/webview2_host.cpp +6230 -0
  72. package/src/primitives/app_dirs/root.zig +440 -0
  73. package/src/primitives/app_manifest/root.zig +109 -0
  74. package/src/primitives/app_manifest/tests.zig +758 -0
  75. package/src/primitives/app_manifest/types.zig +587 -0
  76. package/src/primitives/app_manifest/validation.zig +828 -0
  77. package/src/primitives/assets/root.zig +520 -0
  78. package/src/primitives/canvas/a11y_audit.zig +390 -0
  79. package/src/primitives/canvas/a11y_audit_tests.zig +225 -0
  80. package/src/primitives/canvas/app_icon.zig +1590 -0
  81. package/src/primitives/canvas/chart.zig +392 -0
  82. package/src/primitives/canvas/chart_tests.zig +751 -0
  83. package/src/primitives/canvas/commands.zig +446 -0
  84. package/src/primitives/canvas/drawing.zig +309 -0
  85. package/src/primitives/canvas/equality.zig +316 -0
  86. package/src/primitives/canvas/events.zig +696 -0
  87. package/src/primitives/canvas/font_coverage.zig +118 -0
  88. package/src/primitives/canvas/font_ttf.zig +510 -0
  89. package/src/primitives/canvas/font_ttf_tests.zig +280 -0
  90. package/src/primitives/canvas/fonts/Geist-Regular.ttf +0 -0
  91. package/src/primitives/canvas/fonts/GeistMono-Regular.ttf +0 -0
  92. package/src/primitives/canvas/frame.zig +679 -0
  93. package/src/primitives/canvas/frame_metrics.zig +462 -0
  94. package/src/primitives/canvas/gpu.zig +639 -0
  95. package/src/primitives/canvas/hash.zig +112 -0
  96. package/src/primitives/canvas/icons/alert.svg +1 -0
  97. package/src/primitives/canvas/icons/archive.svg +1 -0
  98. package/src/primitives/canvas/icons/arrow-down.svg +1 -0
  99. package/src/primitives/canvas/icons/arrow-right.svg +1 -0
  100. package/src/primitives/canvas/icons/arrow-up.svg +1 -0
  101. package/src/primitives/canvas/icons/check-circle.svg +1 -0
  102. package/src/primitives/canvas/icons/check.svg +1 -0
  103. package/src/primitives/canvas/icons/chevron-down.svg +1 -0
  104. package/src/primitives/canvas/icons/chevron-left.svg +1 -0
  105. package/src/primitives/canvas/icons/chevron-right.svg +1 -0
  106. package/src/primitives/canvas/icons/chevron-up.svg +1 -0
  107. package/src/primitives/canvas/icons/circle-dot.svg +1 -0
  108. package/src/primitives/canvas/icons/clock.svg +1 -0
  109. package/src/primitives/canvas/icons/copy.svg +1 -0
  110. package/src/primitives/canvas/icons/download.svg +1 -0
  111. package/src/primitives/canvas/icons/edit.svg +1 -0
  112. package/src/primitives/canvas/icons/ellipsis.svg +1 -0
  113. package/src/primitives/canvas/icons/external-link.svg +1 -0
  114. package/src/primitives/canvas/icons/eye.svg +1 -0
  115. package/src/primitives/canvas/icons/file-text.svg +1 -0
  116. package/src/primitives/canvas/icons/folder-open.svg +1 -0
  117. package/src/primitives/canvas/icons/folder.svg +1 -0
  118. package/src/primitives/canvas/icons/git-branch.svg +1 -0
  119. package/src/primitives/canvas/icons/git-merge.svg +1 -0
  120. package/src/primitives/canvas/icons/git-pull-request.svg +1 -0
  121. package/src/primitives/canvas/icons/info.svg +1 -0
  122. package/src/primitives/canvas/icons/menu.svg +1 -0
  123. package/src/primitives/canvas/icons/missing.svg +1 -0
  124. package/src/primitives/canvas/icons/moon.svg +1 -0
  125. package/src/primitives/canvas/icons/music.svg +1 -0
  126. package/src/primitives/canvas/icons/panel-left.svg +1 -0
  127. package/src/primitives/canvas/icons/panel-right.svg +1 -0
  128. package/src/primitives/canvas/icons/pause.svg +1 -0
  129. package/src/primitives/canvas/icons/play.svg +1 -0
  130. package/src/primitives/canvas/icons/plus.svg +1 -0
  131. package/src/primitives/canvas/icons/refresh-cw.svg +1 -0
  132. package/src/primitives/canvas/icons/repeat.svg +1 -0
  133. package/src/primitives/canvas/icons/save.svg +1 -0
  134. package/src/primitives/canvas/icons/search.svg +1 -0
  135. package/src/primitives/canvas/icons/send.svg +1 -0
  136. package/src/primitives/canvas/icons/settings.svg +1 -0
  137. package/src/primitives/canvas/icons/shuffle.svg +1 -0
  138. package/src/primitives/canvas/icons/skip-back.svg +1 -0
  139. package/src/primitives/canvas/icons/skip-forward.svg +1 -0
  140. package/src/primitives/canvas/icons/sun.svg +1 -0
  141. package/src/primitives/canvas/icons/terminal.svg +1 -0
  142. package/src/primitives/canvas/icons/trash.svg +1 -0
  143. package/src/primitives/canvas/icons/volume.svg +1 -0
  144. package/src/primitives/canvas/icons/wrench.svg +1 -0
  145. package/src/primitives/canvas/icons/x-circle.svg +1 -0
  146. package/src/primitives/canvas/icons/x.svg +1 -0
  147. package/src/primitives/canvas/icons.zig +249 -0
  148. package/src/primitives/canvas/layout_audit.zig +744 -0
  149. package/src/primitives/canvas/layout_audit_tests.zig +426 -0
  150. package/src/primitives/canvas/markdown.zig +1031 -0
  151. package/src/primitives/canvas/markdown_hostile_tests.zig +471 -0
  152. package/src/primitives/canvas/markdown_tests.zig +538 -0
  153. package/src/primitives/canvas/plan_key_index.zig +120 -0
  154. package/src/primitives/canvas/png.zig +355 -0
  155. package/src/primitives/canvas/reference.zig +1457 -0
  156. package/src/primitives/canvas/reference_blur.zig +104 -0
  157. package/src/primitives/canvas/reference_memo.zig +322 -0
  158. package/src/primitives/canvas/reference_paths.zig +184 -0
  159. package/src/primitives/canvas/reference_tests.zig +1650 -0
  160. package/src/primitives/canvas/render.zig +747 -0
  161. package/src/primitives/canvas/render_effects.zig +255 -0
  162. package/src/primitives/canvas/render_fingerprints.zig +256 -0
  163. package/src/primitives/canvas/render_generic_resources.zig +376 -0
  164. package/src/primitives/canvas/render_images.zig +247 -0
  165. package/src/primitives/canvas/render_layers.zig +260 -0
  166. package/src/primitives/canvas/render_paths.zig +347 -0
  167. package/src/primitives/canvas/render_resources.zig +51 -0
  168. package/src/primitives/canvas/render_tests.zig +3186 -0
  169. package/src/primitives/canvas/root.zig +744 -0
  170. package/src/primitives/canvas/serialization.zig +1528 -0
  171. package/src/primitives/canvas/svg_icon.zig +636 -0
  172. package/src/primitives/canvas/svg_icon_tests.zig +312 -0
  173. package/src/primitives/canvas/test_support.zig +422 -0
  174. package/src/primitives/canvas/testdata/markdown_document.md +83 -0
  175. package/src/primitives/canvas/tests.zig +30 -0
  176. package/src/primitives/canvas/text.zig +82 -0
  177. package/src/primitives/canvas/text_atlas.zig +408 -0
  178. package/src/primitives/canvas/text_batch_tests.zig +431 -0
  179. package/src/primitives/canvas/text_interaction.zig +615 -0
  180. package/src/primitives/canvas/text_layout.zig +1069 -0
  181. package/src/primitives/canvas/text_layout_cache.zig +281 -0
  182. package/src/primitives/canvas/text_layout_hash.zig +113 -0
  183. package/src/primitives/canvas/text_layout_types.zig +128 -0
  184. package/src/primitives/canvas/text_measure_cache.zig +279 -0
  185. package/src/primitives/canvas/text_metrics.zig +309 -0
  186. package/src/primitives/canvas/text_metrics_tests.zig +262 -0
  187. package/src/primitives/canvas/text_span_tests.zig +608 -0
  188. package/src/primitives/canvas/text_spans.zig +1010 -0
  189. package/src/primitives/canvas/text_tests.zig +1949 -0
  190. package/src/primitives/canvas/themes/geist.zig +470 -0
  191. package/src/primitives/canvas/tokens.zig +1522 -0
  192. package/src/primitives/canvas/ui.zig +2686 -0
  193. package/src/primitives/canvas/ui_markup.zig +3791 -0
  194. package/src/primitives/canvas/ui_markup_binary.zig +522 -0
  195. package/src/primitives/canvas/ui_markup_binary_tests.zig +591 -0
  196. package/src/primitives/canvas/ui_markup_compiled.zig +2565 -0
  197. package/src/primitives/canvas/ui_markup_compiled_tests.zig +1669 -0
  198. package/src/primitives/canvas/ui_markup_contract.zig +1620 -0
  199. package/src/primitives/canvas/ui_markup_contract_tests.zig +953 -0
  200. package/src/primitives/canvas/ui_markup_edit.zig +416 -0
  201. package/src/primitives/canvas/ui_markup_edit_tests.zig +341 -0
  202. package/src/primitives/canvas/ui_markup_expr.zig +1152 -0
  203. package/src/primitives/canvas/ui_markup_expr_tests.zig +779 -0
  204. package/src/primitives/canvas/ui_markup_huge_model_tests.zig +505 -0
  205. package/src/primitives/canvas/ui_markup_reflect.zig +127 -0
  206. package/src/primitives/canvas/ui_markup_tests.zig +1545 -0
  207. package/src/primitives/canvas/ui_markup_view.zig +2352 -0
  208. package/src/primitives/canvas/ui_markup_view_tests.zig +3709 -0
  209. package/src/primitives/canvas/ui_provenance.zig +96 -0
  210. package/src/primitives/canvas/ui_provenance_tests.zig +186 -0
  211. package/src/primitives/canvas/ui_schema.zig +825 -0
  212. package/src/primitives/canvas/ui_schema_tests.zig +128 -0
  213. package/src/primitives/canvas/ui_tests.zig +1432 -0
  214. package/src/primitives/canvas/vector.zig +919 -0
  215. package/src/primitives/canvas/vector_tests.zig +547 -0
  216. package/src/primitives/canvas/virtual_extent_tests.zig +317 -0
  217. package/src/primitives/canvas/virtual_extents.zig +540 -0
  218. package/src/primitives/canvas/widget_access.zig +208 -0
  219. package/src/primitives/canvas/widget_anchored_tests.zig +264 -0
  220. package/src/primitives/canvas/widget_builtin_tests.zig +3160 -0
  221. package/src/primitives/canvas/widget_invalidation.zig +748 -0
  222. package/src/primitives/canvas/widget_layout.zig +2055 -0
  223. package/src/primitives/canvas/widget_layout_tests.zig +2691 -0
  224. package/src/primitives/canvas/widget_metrics.zig +228 -0
  225. package/src/primitives/canvas/widget_render.zig +2534 -0
  226. package/src/primitives/canvas/widget_render_controls.zig +1563 -0
  227. package/src/primitives/canvas/widget_render_scroll.zig +136 -0
  228. package/src/primitives/canvas/widget_render_style.zig +626 -0
  229. package/src/primitives/canvas/widget_render_surfaces.zig +794 -0
  230. package/src/primitives/canvas/widget_routing.zig +475 -0
  231. package/src/primitives/canvas/widget_runtime.zig +307 -0
  232. package/src/primitives/canvas/widget_runtime_tests.zig +3015 -0
  233. package/src/primitives/canvas/widget_semantics.zig +480 -0
  234. package/src/primitives/canvas/widget_semantics_tests.zig +2129 -0
  235. package/src/primitives/canvas/widget_tests.zig +8 -0
  236. package/src/primitives/canvas/widget_text_input.zig +351 -0
  237. package/src/primitives/canvas/widget_text_select.zig +147 -0
  238. package/src/primitives/canvas/widget_tree.zig +232 -0
  239. package/src/primitives/canvas/widgets.zig +1319 -0
  240. package/src/primitives/diagnostics/root.zig +445 -0
  241. package/src/primitives/geometry/root.zig +889 -0
  242. package/src/primitives/json/root.zig +272 -0
  243. package/src/primitives/platform_info/root.zig +450 -0
  244. package/src/primitives/trace/root.zig +569 -0
  245. package/src/root.zig +165 -0
  246. package/src/runtime/api.zig +431 -0
  247. package/src/runtime/async_bridge.zig +49 -0
  248. package/src/runtime/automation_commands.zig +686 -0
  249. package/src/runtime/automation_liveness_tests.zig +140 -0
  250. package/src/runtime/automation_snapshot.zig +246 -0
  251. package/src/runtime/automation_widget_dispatch.zig +617 -0
  252. package/src/runtime/bridge_dispatch_tests.zig +202 -0
  253. package/src/runtime/bridge_payload.zig +194 -0
  254. package/src/runtime/bridge_permission_tests.zig +551 -0
  255. package/src/runtime/bridge_responses.zig +414 -0
  256. package/src/runtime/builtin_bridge.zig +554 -0
  257. package/src/runtime/canvas_budget_edge_tests.zig +415 -0
  258. package/src/runtime/canvas_font_tests.zig +410 -0
  259. package/src/runtime/canvas_fonts.zig +229 -0
  260. package/src/runtime/canvas_frame.zig +1734 -0
  261. package/src/runtime/canvas_frame_animation_tests.zig +609 -0
  262. package/src/runtime/canvas_frame_cache_tests.zig +333 -0
  263. package/src/runtime/canvas_frame_helpers.zig +414 -0
  264. package/src/runtime/canvas_frame_invalidation_tests.zig +544 -0
  265. package/src/runtime/canvas_frame_packet_tests.zig +1353 -0
  266. package/src/runtime/canvas_frame_patch_tests.zig +1051 -0
  267. package/src/runtime/canvas_frame_retained_tests.zig +753 -0
  268. package/src/runtime/canvas_frame_tests.zig +9 -0
  269. package/src/runtime/canvas_frame_text_layout_budget_tests.zig +149 -0
  270. package/src/runtime/canvas_image_tests.zig +362 -0
  271. package/src/runtime/canvas_images.zig +224 -0
  272. package/src/runtime/canvas_limits.zig +317 -0
  273. package/src/runtime/canvas_screenshot_tests.zig +289 -0
  274. package/src/runtime/canvas_widget_accessibility_tests.zig +1494 -0
  275. package/src/runtime/canvas_widget_anchored_tests.zig +678 -0
  276. package/src/runtime/canvas_widget_chart_tests.zig +249 -0
  277. package/src/runtime/canvas_widget_clipboard_tests.zig +399 -0
  278. package/src/runtime/canvas_widget_context_menu.zig +318 -0
  279. package/src/runtime/canvas_widget_context_menu_tests.zig +462 -0
  280. package/src/runtime/canvas_widget_control_tests.zig +2164 -0
  281. package/src/runtime/canvas_widget_disclosure_tests.zig +440 -0
  282. package/src/runtime/canvas_widget_display.zig +677 -0
  283. package/src/runtime/canvas_widget_event_tests.zig +1779 -0
  284. package/src/runtime/canvas_widget_events.zig +1098 -0
  285. package/src/runtime/canvas_widget_floating_tests.zig +695 -0
  286. package/src/runtime/canvas_widget_layout_tests.zig +26 -0
  287. package/src/runtime/canvas_widget_runtime.zig +1335 -0
  288. package/src/runtime/canvas_widget_scroll_driver_tests.zig +582 -0
  289. package/src/runtime/canvas_widget_scroll_drivers.zig +202 -0
  290. package/src/runtime/canvas_widget_scroll_tests.zig +1549 -0
  291. package/src/runtime/canvas_widget_semantics_tests.zig +810 -0
  292. package/src/runtime/canvas_widget_split_tree_tests.zig +1031 -0
  293. package/src/runtime/canvas_widget_state.zig +798 -0
  294. package/src/runtime/canvas_widget_text_tests.zig +2104 -0
  295. package/src/runtime/canvas_widget_window_drag_tests.zig +284 -0
  296. package/src/runtime/clock.zig +231 -0
  297. package/src/runtime/core.zig +927 -0
  298. package/src/runtime/effects.zig +4197 -0
  299. package/src/runtime/effects_audio_tests.zig +690 -0
  300. package/src/runtime/effects_clipboard_tests.zig +317 -0
  301. package/src/runtime/effects_fetch_tests.zig +1031 -0
  302. package/src/runtime/effects_file_tests.zig +407 -0
  303. package/src/runtime/effects_tests.zig +1251 -0
  304. package/src/runtime/flow.zig +1175 -0
  305. package/src/runtime/frame_profile.zig +221 -0
  306. package/src/runtime/gpu_surface_events.zig +639 -0
  307. package/src/runtime/launch_timing.zig +59 -0
  308. package/src/runtime/markdown_app_tests.zig +224 -0
  309. package/src/runtime/native_command_event_tests.zig +431 -0
  310. package/src/runtime/platform_bridge_tests.zig +8 -0
  311. package/src/runtime/platform_config_tests.zig +392 -0
  312. package/src/runtime/root.zig +150 -0
  313. package/src/runtime/runtime_event_tests.zig +1079 -0
  314. package/src/runtime/session_journal.zig +1522 -0
  315. package/src/runtime/session_record.zig +332 -0
  316. package/src/runtime/session_replay.zig +274 -0
  317. package/src/runtime/session_state.zig +30 -0
  318. package/src/runtime/session_tests.zig +399 -0
  319. package/src/runtime/shell_layout.zig +472 -0
  320. package/src/runtime/shell_layout_tests.zig +1246 -0
  321. package/src/runtime/shell_view_tests.zig +604 -0
  322. package/src/runtime/state.zig +110 -0
  323. package/src/runtime/system_services.zig +392 -0
  324. package/src/runtime/test_support.zig +79 -0
  325. package/src/runtime/tests.zig +30 -0
  326. package/src/runtime/ui_app.zig +3290 -0
  327. package/src/runtime/ui_app_huge_model_tests.zig +351 -0
  328. package/src/runtime/ui_app_provenance.zig +370 -0
  329. package/src/runtime/ui_app_tests.zig +3254 -0
  330. package/src/runtime/ui_app_virtual_variable_tests.zig +485 -0
  331. package/src/runtime/ui_app_window_tests.zig +442 -0
  332. package/src/runtime/validation.zig +206 -0
  333. package/src/runtime/view.zig +908 -0
  334. package/src/runtime/view_canvas.zig +850 -0
  335. package/src/runtime/view_widget_control.zig +433 -0
  336. package/src/runtime/view_widget_scroll.zig +360 -0
  337. package/src/runtime/view_widget_text.zig +275 -0
  338. package/src/runtime/view_widget_tree.zig +843 -0
  339. package/src/runtime/webview_view_bridge_tests.zig +664 -0
  340. package/src/runtime/widget_bridge.zig +231 -0
  341. package/src/runtime/window_command_bridge_tests.zig +403 -0
  342. package/src/runtime/window_storage.zig +255 -0
  343. package/src/runtime/window_view_runtime.zig +727 -0
  344. package/src/runtime/window_views.zig +334 -0
  345. package/src/security/root.zig +118 -0
  346. package/src/tooling/android.zig +1172 -0
  347. package/src/tooling/assets.zig +128 -0
  348. package/src/tooling/buildgraph.zig +379 -0
  349. package/src/tooling/cef.zig +671 -0
  350. package/src/tooling/codesign.zig +172 -0
  351. package/src/tooling/components/identity_tests.zig +185 -0
  352. package/src/tooling/components/stepper.zig +113 -0
  353. package/src/tooling/components/timeline.native +27 -0
  354. package/src/tooling/components/timeline_item.zig +131 -0
  355. package/src/tooling/default_icon.icns +0 -0
  356. package/src/tooling/default_icon.png +0 -0
  357. package/src/tooling/dev.zig +172 -0
  358. package/src/tooling/doctor.zig +349 -0
  359. package/src/tooling/eject_components.zig +170 -0
  360. package/src/tooling/embedlib.zig +290 -0
  361. package/src/tooling/ios.zig +528 -0
  362. package/src/tooling/manifest.zig +1939 -0
  363. package/src/tooling/package.zig +2388 -0
  364. package/src/tooling/process_tree.zig +114 -0
  365. package/src/tooling/raw_manifest.zig +193 -0
  366. package/src/tooling/root.zig +22 -0
  367. package/src/tooling/templates.zig +3191 -0
  368. package/src/tooling/toolchain.zig +371 -0
  369. package/src/tooling/verbs.zig +204 -0
  370. package/src/tooling/web_engine.zig +135 -0
  371. package/src/tooling/xcodeproj.zig +462 -0
  372. package/src/window_state/root.zig +507 -0
  373. package/index.js +0 -2
@@ -0,0 +1,3290 @@
1
+ //! Runtime-owned application loop for the declarative ui builder.
2
+ //!
3
+ //! `UiApp(Model, Msg)` wraps an elm-style app — model value, `update`
4
+ //! function, `view` function — as a `native_sdk.App`, owning everything the
5
+ //! builder examples previously hand-rolled: the two-arena rebuild swap, the
6
+ //! first-frame install choreography (`setCanvasWidgetLayout` +
7
+ //! `emitCanvasWidgetDisplayList`), presentation buffers, resize handling,
8
+ //! and typed pointer/keyboard dispatch through the tree's handler table.
9
+ //!
10
+ //! An app becomes: declare `Model` and `Msg`, write `update` and `view`,
11
+ //! and hand them to `UiApp` with a shell scene containing one `gpu_surface`
12
+ //! view. Shell command events can map into messages through `on_command`.
13
+ //!
14
+ //! Secondary windows are model-declared: `Options.windows_fn` returns the
15
+ //! window descriptors that should exist right now (presence IS
16
+ //! visibility), `Options.window_view` builds each declared window's
17
+ //! canvas tree, the runtime reconciles declared against live windows
18
+ //! after every rebuild, input from any window dispatches Msgs with its
19
+ //! window identity, and a user close dispatches the descriptor's
20
+ //! `on_close` Msg — the dismissal precedent, applied to windows.
21
+ //!
22
+ //! Markup apps choose an engine per build: `Options.markup` runs the
23
+ //! runtime parser/interpreter (dev, hot reload), while
24
+ //! `canvas.CompiledMarkupView(Model, Msg, source).build` handed to
25
+ //! `Options.view` compiles the same source at comptime (release, no parser
26
+ //! in the binary — pair with `UiAppWithFeatures(..., .{ .runtime_markup =
27
+ //! false })` so the watch machinery compiles out too). Setting both keeps
28
+ //! the compiled view until the watched file first changes on disk.
29
+
30
+ const std = @import("std");
31
+ const builtin = @import("builtin");
32
+ const geometry = @import("geometry");
33
+ const canvas = @import("canvas");
34
+ const app_manifest = @import("app_manifest");
35
+ const platform = @import("../platform/root.zig");
36
+ const core = @import("core.zig");
37
+ const canvas_frame = @import("canvas_frame.zig");
38
+ const canvas_limits = @import("canvas_limits.zig");
39
+ const launch_timing = @import("launch_timing.zig");
40
+ const runtime_effects = @import("effects.zig");
41
+ const ui_app_provenance = @import("ui_app_provenance.zig");
42
+
43
+ const Runtime = core.Runtime;
44
+ const App = core.App;
45
+ const Event = core.Event;
46
+
47
+ const ui_app_log = std.log.scoped(.zero_ui_app);
48
+
49
+ /// Maximum number of webview panes a `UiApp` can drive (`Options.web_panes`).
50
+ pub const max_web_panes: usize = 4;
51
+
52
+ /// Approach-end hysteresis for `on_reach_end`, in viewports from the
53
+ /// content end: fire when the offset comes within one viewport, re-arm
54
+ /// only past one and a half — so the fire and re-arm boundaries never
55
+ /// chatter, and a freshly appended batch (which grows the extent) is
56
+ /// what re-arms the next approach.
57
+ pub const reach_end_fire_ratio: f32 = 1.0;
58
+ pub const reach_end_rearm_ratio: f32 = 1.5;
59
+
60
+ /// Approach-START hysteresis for `on_reach_start` (load older history in
61
+ /// tail-anchored transcripts): the mirror of the reach-end band — fire
62
+ /// when the offset comes within one viewport of the content start,
63
+ /// re-arm only past one and a half. Prepending a batch re-arms on its
64
+ /// own because the offset grows by the prepended extent (the viewport
65
+ /// anchor), exactly as appending re-arms reach-end by growing the
66
+ /// extent.
67
+ pub const reach_start_fire_ratio: f32 = 1.0;
68
+ pub const reach_start_rearm_ratio: f32 = 1.5;
69
+
70
+ /// A correction of at least this many points (the anchor-preserving
71
+ /// offset delta a variable-extent window left pending after the measure
72
+ /// step) earns the one coverage-style retry build, so the first
73
+ /// presented frame after a mount or a big estimate miss is already
74
+ /// correction-consumed. Below it, the delta rides to the next rebuild —
75
+ /// offsets and geometry still shift together, atomically.
76
+ pub const virtual_correction_retry_threshold: f32 = 0.5;
77
+
78
+ /// Comptime feature selection for `UiAppWithFeatures`.
79
+ pub const UiAppFeatures = struct {
80
+ /// Ship the runtime markup engine (parser + interpreter) in the app.
81
+ /// Required for `Options.markup` — runtime-parsed embedded sources and
82
+ /// watch-based hot reload. Disable it in builds whose view comes from
83
+ /// `canvas.CompiledMarkupView` so no parser code (or its diagnostics)
84
+ /// ships in the binary; the markup machinery then compiles to nothing.
85
+ runtime_markup: bool = true,
86
+ };
87
+
88
+ pub fn UiApp(comptime ModelT: type, comptime MsgT: type) type {
89
+ return UiAppWithFeatures(ModelT, MsgT, .{});
90
+ }
91
+
92
+ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime features: UiAppFeatures) type {
93
+ return struct {
94
+ const Self = @This();
95
+
96
+ pub const Ui = canvas.Ui(MsgT);
97
+
98
+ pub const MarkupView = canvas.MarkupView(ModelT, MsgT);
99
+
100
+ /// The fragment watch exists only where BOTH the runtime markup
101
+ /// engine (the interpreter that builds reloaded fragments) and a
102
+ /// Debug build (the dev loop) are present; everywhere else its
103
+ /// state, polling, and registration collapse to nothing.
104
+ const fragment_watch_enabled = features.runtime_markup and builtin.mode == .Debug;
105
+
106
+ /// Fixed budget of watched fragments per app. Registrations past
107
+ /// it are not watched (a teaching warning names the budget when
108
+ /// the watch arms) — a view embedding more compiled fragments
109
+ /// than this wants consolidation more than it wants polling.
110
+ pub const max_watched_fragments: usize = 16;
111
+
112
+ /// One registered fragment's hot-reload state.
113
+ const MarkupFragmentSlot = struct {
114
+ /// Two-arena swap, the `markup_arenas` discipline: a reload
115
+ /// resolves into the inactive arena and adopts on success, so
116
+ /// the live document — still referenced by the retained tree
117
+ /// — survives failed parses and failed rebuilds; the inactive
118
+ /// arena is reset only when the next reload attempt begins.
119
+ arenas: [2]std.heap.ArenaAllocator,
120
+ arena_index: usize = 0,
121
+ /// The adopted override document the compiled fragment's
122
+ /// build swaps in through the Ui seam; null while the disk
123
+ /// closure matches the embedded baseline, which keeps the
124
+ /// comptime-compiled path (and drops back to it when an edit
125
+ /// is reverted byte for byte).
126
+ document: ?canvas.ui_markup.MarkupDocument = null,
127
+ /// Hash of the embedded source closure the fragment was
128
+ /// compiled from, computed when the watch arms.
129
+ baseline_hash: u64 = 0,
130
+ /// Hash of the last disk closure seen — the change detector,
131
+ /// updated on every divergence (including failed parses, so
132
+ /// one bad save teaches once, not once per poll).
133
+ hash: u64 = 0,
134
+ };
135
+
136
+ fn markupFragmentSlotsInit(backing: std.mem.Allocator) [max_watched_fragments]MarkupFragmentSlot {
137
+ var slots: [max_watched_fragments]MarkupFragmentSlot = undefined;
138
+ for (&slots) |*slot| {
139
+ slot.* = .{ .arenas = .{
140
+ std.heap.ArenaAllocator.init(backing),
141
+ std.heap.ArenaAllocator.init(backing),
142
+ } };
143
+ }
144
+ return slots;
145
+ }
146
+
147
+ /// The app's effect system (TEA's Cmd half): `fx.spawn` /
148
+ /// `fx.fetch` / `fx.writeFile` / `fx.readFile` / `fx.cancel`
149
+ /// from an `update_fx`-style update. See `runtime/effects.zig`
150
+ /// for capacities and semantics.
151
+ pub const Effects = runtime_effects.Effects(MsgT);
152
+
153
+ /// One app font face registered on the installing frame (see
154
+ /// `Options.fonts`). The face parses at registration —
155
+ /// registration is where invalid files fail, loudly, with a
156
+ /// teaching error naming this entry's `name` — and the id then
157
+ /// resolves everywhere a `canvas.FontId` rides: token overrides
158
+ /// (`typography.font_id` / `mono_font_id`), both renderers,
159
+ /// atlas keys, fingerprints. Glyphs the face does not cover keep
160
+ /// the same per-glyph notdef fallback as the built-in faces —
161
+ /// a registered face never silently cascades into another
162
+ /// family.
163
+ pub const FontRegistration = struct {
164
+ /// App-chosen id, at or above `canvas.min_registered_font_id`
165
+ /// (lower ids are reserved for built-in faces). Permanent for
166
+ /// the app's lifetime; store it in tokens, not handles.
167
+ id: canvas.FontId,
168
+ /// Human name for teaching errors — the asset's file name is
169
+ /// the right choice. Never rendered.
170
+ name: []const u8,
171
+ /// Raw TrueType (`glyf`) bytes: `@embedFile` of a bundled
172
+ /// asset, or bytes loaded before the app starts. Copied at
173
+ /// registration, so transient buffers are fine.
174
+ ttf: []const u8,
175
+ };
176
+
177
+ pub const ChromeOptions = struct {
178
+ /// Number of chrome commands preserved in front of the
179
+ /// widget-generated commands.
180
+ prefix_commands: usize,
181
+ /// Number of chrome commands preserved after the
182
+ /// widget-generated commands.
183
+ suffix_commands: usize = 0,
184
+ /// Builds the chrome display-list commands: exactly
185
+ /// `prefix_commands` commands followed by `suffix_commands`
186
+ /// commands.
187
+ build: *const fn (model: *const ModelT, builder: *canvas.Builder, size: geometry.SizeF, tokens: canvas.DesignTokens) anyerror!void,
188
+ };
189
+
190
+ /// A live webview region hosted alongside the canvas — the "both
191
+ /// per window" seam. The scene declares the webview shell view
192
+ /// (kind `.webview`, ideally with `.parent` set to the canvas
193
+ /// view's label so pane frames share the canvas coordinate
194
+ /// space); the pane then keeps that webview snapped to a canvas
195
+ /// widget's layout frame and drives navigation from the model.
196
+ pub const WebViewPane = struct {
197
+ /// Shell view label of the scene-declared webview this pane
198
+ /// drives.
199
+ label: []const u8,
200
+ /// Semantics label of the canvas widget whose layout frame
201
+ /// becomes the webview's bounds — typically an empty panel
202
+ /// that reserves the region in the view
203
+ /// (`.semantics = .{ .label = "preview-pane" }`). When null,
204
+ /// `frame` positions the webview directly.
205
+ anchor: ?[]const u8 = null,
206
+ /// Explicit frame used when no `anchor` is set. Canvas-local
207
+ /// when the webview is parented to the canvas view.
208
+ frame: geometry.RectF = geometry.RectF.init(0, 0, 0, 0),
209
+ /// Current URL. Changing it navigates the webview, subject to
210
+ /// the app's `security.navigation.allowed_origins` policy.
211
+ url: []const u8,
212
+ /// Bump to reload the current URL without changing it (the
213
+ /// `reloadToken` consumer shape).
214
+ reload_token: u64 = 0,
215
+ };
216
+
217
+ /// Menu-bar extra: a status-bar item with a command menu
218
+ /// (macOS `NSStatusItem`; the system tray elsewhere, where
219
+ /// supported). Selecting a menu item dispatches its `command`
220
+ /// through `on_command` with source `.tray`.
221
+ pub const StatusItemOptions = struct {
222
+ /// Menu-bar button title (used when no icon resolves; macOS
223
+ /// falls back to the app name's first letter when both are
224
+ /// empty).
225
+ title: []const u8 = "",
226
+ /// Template-image path for the status button icon.
227
+ icon_path: []const u8 = "",
228
+ tooltip: []const u8 = "",
229
+ /// Menu items: `label` is the visible title, `command` the
230
+ /// name handed to `on_command`, `id` a unique non-zero id.
231
+ items: []const platform.TrayMenuItem = &.{},
232
+ };
233
+
234
+ /// Model-derived status-item state returned by
235
+ /// `Options.status_item_fn`: the live button title and menu.
236
+ /// Slices may point at the scratch the fn received, the model, or
237
+ /// static strings — they only need to outlive the apply (the
238
+ /// runtime and platform copy what they keep).
239
+ pub const StatusItemState = struct {
240
+ title: []const u8 = "",
241
+ items: []const platform.TrayMenuItem = &.{},
242
+ };
243
+
244
+ /// Scratch handed to `status_item_fn` so a derived title
245
+ /// (`std.fmt.bufPrint(&scratch.title_buffer, "{d} open", ...)`)
246
+ /// and a built-up item list need no model-side storage. Lives on
247
+ /// the app struct, so returned slices stay valid until the next
248
+ /// apply.
249
+ pub const StatusItemScratch = struct {
250
+ title_buffer: [platform.max_tray_title_bytes]u8 = undefined,
251
+ items: [platform.max_tray_items]platform.TrayMenuItem = undefined,
252
+ };
253
+
254
+ /// Budget for model-declared secondary windows (see
255
+ /// `canvas_limits.max_ui_app_windows` for the sizing rationale).
256
+ pub const max_ui_windows: usize = canvas_limits.max_ui_app_windows;
257
+
258
+ /// A model-declared secondary window (`Options.windows_fn`):
259
+ /// settings, about, inspectors. Identity is `label`; PRESENCE in
260
+ /// the returned slice is visibility — the runtime reconciles the
261
+ /// declared set against live windows after every rebuild,
262
+ /// creating the missing and closing the no-longer-declared.
263
+ /// There is deliberately no `visible` flag: the platform window
264
+ /// channel is create/focus/close with no hide, so a
265
+ /// hidden-but-open descriptor would lie about what exists. The
266
+ /// model bool that `windows_fn` consults IS the visibility
267
+ /// channel, exactly like a dismissible surface's open flag.
268
+ pub const WindowDescriptor = struct {
269
+ /// Window label: the stable identity across rebuilds, and
270
+ /// the label automation snapshots print for the window.
271
+ label: []const u8,
272
+ /// The gpu_surface view label inside this window:
273
+ /// `window_view` builds its tree, input events route back
274
+ /// through it, and automation verbs address it. Must be
275
+ /// unique across the app — distinct from the main
276
+ /// `canvas_label` and every other descriptor's.
277
+ canvas_label: []const u8,
278
+ /// Window title, applied at creation (the platform window
279
+ /// channel has no retitle; re-create under a new label for a
280
+ /// different title).
281
+ title: []const u8 = "",
282
+ width: f32 = 480,
283
+ height: f32 = 360,
284
+ x: ?f32 = null,
285
+ y: ?f32 = null,
286
+ resizable: bool = true,
287
+ /// Content min-size floor the WINDOW enforces (macOS
288
+ /// `contentMinSize`): the user's resize stops at the floor
289
+ /// instead of the layout clamping/clipping panes below
290
+ /// their declared minimums. The window knows the floor the
291
+ /// framework already knows. 0 = no floor on that axis.
292
+ min_width: f32 = 0,
293
+ min_height: f32 = 0,
294
+ /// Titlebar chrome: `.hidden_inset` extends content under a
295
+ /// transparent titlebar with the title hidden (macOS keeps
296
+ /// the traffic lights) — the modern editor-app pattern —
297
+ /// and `.hidden_inset_tall` is the same shape with the
298
+ /// unified-toolbar-height band (traffic lights vertically
299
+ /// centered, the tall unified-toolbar look). Drag regions and
300
+ /// traffic-light-aware header layout are the dedicated
301
+ /// titlebar-control channel's scope, not this field's.
302
+ /// Platforms without the concept keep standard chrome.
303
+ titlebar: app_manifest.WindowTitlebarStyle = .standard,
304
+ /// Msg dispatched when the USER closes the window (never for
305
+ /// a reconcile close the model itself initiated). The
306
+ /// dismissal precedent: the window is already gone as an
307
+ /// optimistic echo; the model clears its open flag in
308
+ /// `update` — or keeps declaring the window and the next
309
+ /// rebuild re-creates it (source wins).
310
+ on_close: ?MsgT = null,
311
+ };
312
+
313
+ /// Scratch handed to `windows_fn` (the `status_item_fn` shape)
314
+ /// so a derived descriptor list needs no model-side storage.
315
+ /// Lives on the app struct; returned slices stay valid until the
316
+ /// next apply.
317
+ pub const WindowsScratch = struct {
318
+ windows: [max_ui_windows]WindowDescriptor = undefined,
319
+ };
320
+
321
+ pub const MarkupOptions = struct {
322
+ /// Markup source embedded into the binary: parsed on the first
323
+ /// build when no `view` is set, and otherwise the baseline the
324
+ /// watched file is compared against. (Release builds should
325
+ /// prefer `canvas.CompiledMarkupView(...).build` on `view`,
326
+ /// which parses at comptime instead.)
327
+ source: []const u8,
328
+ /// Embedded sources for the document's `<import>` closure:
329
+ /// one entry per imported file, paths relative to the root
330
+ /// file's directory — the same set `canvas.
331
+ /// CompiledMarkupImports` takes, so one list feeds both
332
+ /// engines. Used to resolve the embedded `source`; watch
333
+ /// reloads resolve against the file system instead (edits to
334
+ /// imported files hot reload too). Leave empty when the
335
+ /// markup imports nothing.
336
+ sources: []const canvas.ui_markup.SourceFile = &.{},
337
+ /// Optional file to poll in dev: when the file — or any file
338
+ /// its imports reach — changes on disk, the closure is
339
+ /// re-resolved and the next rebuild uses the new view,
340
+ /// keeping model state. Parse failures keep the last good view
341
+ /// and set `markup_diagnostic`. Requires `io`. Watching runs a
342
+ /// low-cost repeating runtime timer (`markup_watch_timer_id`),
343
+ /// so leave it unset in release builds.
344
+ watch_path: ?[]const u8 = null,
345
+ io: ?std.Io = null,
346
+ };
347
+
348
+ /// Dev-mode hot reload for HYBRID roots: a Zig builder view that
349
+ /// embeds compiled markup fragments registers each fragment's
350
+ /// on-disk source here (`CompiledHeaderView.fragment("src/header.native")`),
351
+ /// and in Debug runs the markup watch polls every registered file
352
+ /// — plus every file each fragment's imports reach — reloading
353
+ /// exactly the fragments a changed file serves. The same degrade
354
+ /// family as the single-root watch: a bad save keeps the last
355
+ /// good view and records the file:line teaching diagnostic, the
356
+ /// next good save recovers. Outside Debug the registration
357
+ /// handles are empty by construction (see `canvas.MarkupFragment`)
358
+ /// and the watch compiles to nothing, so release binaries carry
359
+ /// no source paths and no polling.
360
+ pub const MarkupFragmentWatch = struct {
361
+ /// One handle per compiled fragment, from the fragment
362
+ /// type's `fragment(path)`.
363
+ fragments: []const canvas.MarkupFragment,
364
+ io: std.Io,
365
+ };
366
+
367
+ pub const Options = struct {
368
+ name: []const u8,
369
+ scene: app_manifest.ShellConfig,
370
+ canvas_label: []const u8,
371
+ /// Fixed design tokens for an app that owns its look. Leave
372
+ /// null (the default) and the stock tokens FOLLOW THE SYSTEM
373
+ /// appearance: light/dark scheme, high contrast, and reduced
374
+ /// motion derive from the OS setting live — flipping the
375
+ /// system appearance re-themes the running app without a
376
+ /// restart. Set explicit tokens (or `tokens_fn`) to opt out.
377
+ tokens: ?canvas.DesignTokens = null,
378
+ /// Model-derived design tokens. When set, this is consulted on
379
+ /// every install and rebuild instead of the static `tokens`,
380
+ /// and `pixel_snap.scale` is stamped with the live surface
381
+ /// scale afterwards: the model owns scheme/contrast/motion,
382
+ /// the runtime owns the surface scale.
383
+ tokens_fn: ?*const fn (model: *const ModelT) canvas.DesignTokens = null,
384
+ /// Which built-in theme pack the stock tokens resolve when
385
+ /// the app claims neither `tokens` nor `tokens_fn`: the
386
+ /// pack composes with the live system appearance (scheme,
387
+ /// contrast, reduced motion), so a packed app still
388
+ /// re-themes on the OS light/dark flip. Apps that own their
389
+ /// tokens pick a pack themselves via `ThemeOptions.pack`.
390
+ /// The scaffold wires this to app.zon's `theme` field
391
+ /// through `app_runner.manifestThemePack()`.
392
+ theme: canvas.ThemePack = .house,
393
+ /// App font faces registered once, on the installing frame,
394
+ /// BEFORE the first view build — so the very first layout
395
+ /// already measures (and the first paint inks) with them.
396
+ /// Reference the entries' ids from `tokens`/`tokens_fn`
397
+ /// (`typography.font_id` for body, `mono_font_id` for mono
398
+ /// runs). A registration failure is a teaching error naming
399
+ /// the font and what is wrong, surfaced through the dispatch
400
+ /// error channel — it never crashes the app and never
401
+ /// silently substitutes a face at render time.
402
+ fonts: []const FontRegistration = &.{},
403
+ /// Non-widget chrome (backgrounds, gradients, titles) rebuilt
404
+ /// together with the widget display list on install, resize,
405
+ /// and every model rebuild via `setCanvasDisplayList` +
406
+ /// `emitCanvasWidgetDisplayListWithChrome`.
407
+ chrome: ?ChromeOptions = null,
408
+ /// Render animations derived from the model and current tree,
409
+ /// re-applied after every rebuild through
410
+ /// `setCanvasRenderAnimations` with the latest frame timestamp
411
+ /// as `start_ns`. Returns the number of animations written to
412
+ /// `out`.
413
+ animations: ?*const fn (model: *const ModelT, tree: *const Ui.Tree, start_ns: u64, out: []canvas.CanvasRenderAnimation) usize = null,
414
+ /// Layout tweens derived from the model and current tree,
415
+ /// re-declared after every rebuild through
416
+ /// `startCanvasWidgetLayoutTween` (idempotent: an armed
417
+ /// tween re-declared with the same target keeps its clock).
418
+ /// Where `animations` moves PIXELS (opacity/transform, no
419
+ /// reflow), a layout tween moves LAYOUT: the runtime eases
420
+ /// a split's first-pane fraction from its current rendered
421
+ /// value to the declared target, one step per presented
422
+ /// frame, and the neighboring pane reflows exactly as if
423
+ /// the divider were dragged — no hand-rolled per-frame
424
+ /// Msgs. Declare the RESTING target (derive `to` from the
425
+ /// model's collapsed flag); keep the split's `value` bound
426
+ /// the way drags already require. Reduced-motion
427
+ /// appearances snap instead of animating. Returns the
428
+ /// number of tweens written to `out`.
429
+ layout_tweens: ?*const fn (model: *const ModelT, tree: *const Ui.Tree, out: []canvas.CanvasWidgetLayoutTween) usize = null,
430
+ /// Elm-style update. Set exactly one of `update` and
431
+ /// `update_fx`: the plain form for pure apps, the `_fx` form
432
+ /// when update needs the effects channel. Both drive the
433
+ /// same loop; existing two-argument apps keep compiling
434
+ /// unchanged.
435
+ update: ?*const fn (model: *ModelT, msg: MsgT) void = null,
436
+ /// Effects-capable update: the third parameter spawns and
437
+ /// cancels subprocess effects (`fx.spawn(.{ ... })`,
438
+ /// `fx.cancel(key)`). Effects are update-side only — views
439
+ /// never spawn.
440
+ update_fx: ?*const fn (model: *ModelT, msg: MsgT, fx: *Effects) void = null,
441
+ /// TEA's init command: runs exactly once, on the installing
442
+ /// frame, after the effects channel is bound and before the
443
+ /// first view build — so a boot-time `fx.spawn`/`fx.fetch`
444
+ /// starts before anything renders and any loading state it
445
+ /// sets is in the very first paint. Results arrive as Msgs
446
+ /// through the ordinary update path (either update form).
447
+ /// This replaces the guarded-`on_frame` idiom for startup
448
+ /// effects; `on_frame` remains the per-frame hook for frame
449
+ /// diagnostics and presented-frame reactions.
450
+ init_fx: ?*const fn (model: *ModelT, fx: *Effects) void = null,
451
+ /// Hand-written or comptime-compiled view
452
+ /// (`canvas.CompiledMarkupView(Model, Msg, source).build` slots
453
+ /// in directly). At least one of `view` and `markup` must be
454
+ /// set. When both are set, this view renders until the watched
455
+ /// markup file first diverges from the embedded source, at
456
+ /// which point the interpreter takes over (compiled view for
457
+ /// release, hot reload in dev).
458
+ view: ?*const fn (ui: *Ui, model: *const ModelT) Ui.Node = null,
459
+ /// Runtime-parsed markup view. Requires
460
+ /// `UiAppFeatures.runtime_markup` (the default).
461
+ markup: ?MarkupOptions = null,
462
+ /// Debug-only hot reload for compiled markup fragments a Zig
463
+ /// `view` embeds (see `MarkupFragmentWatch`). Safe to set
464
+ /// unconditionally: outside Debug it degrades to nothing.
465
+ fragment_watch: ?MarkupFragmentWatch = null,
466
+ /// Optional mapping from shell command events (menus, shortcuts,
467
+ /// native controls) into messages.
468
+ on_command: ?*const fn (name: []const u8) ?MsgT = null,
469
+ /// Model-driven selection for declared platform chrome
470
+ /// (`scene.chrome.tabs`): returns the id of the tab the
471
+ /// model currently selects (one of the declared tab ids, or
472
+ /// "" for none). Consulted on install and after every
473
+ /// rebuild — the `status_item_fn` shape — and read by
474
+ /// projecting hosts through `chromeSelectedTab()`, so the
475
+ /// native bar is always a projection of the model: a tap
476
+ /// dispatches the tab's command id through `on_command`,
477
+ /// update moves the model, and this derivation moves the
478
+ /// bar. The bar itself is never the source of truth.
479
+ selected_tab_fn: ?*const fn (model: *const ModelT) []const u8 = null,
480
+ /// Model-driven navigation depth for platform push/pop
481
+ /// transitions: returns how many levels deep the model's
482
+ /// current page sits (0 = the root page, 1 = one push in,
483
+ /// ...). Consulted on install and after every rebuild — the
484
+ /// `selected_tab_fn` cadence — and read by projecting hosts
485
+ /// through `chromeNavigationDepth()`, which poll it and
486
+ /// present a REAL platform transition when the depth grows
487
+ /// (push) or shrinks (pop). The transition is presentation
488
+ /// only: the MODEL owns navigation state, the depth is a
489
+ /// pure derivation of it, and a journal replayed without a
490
+ /// host produces the identical model. Tab switches are
491
+ /// lateral, never depth: derive the depth of the CURRENT
492
+ /// tab's page stack, so switching tabs while a page is open
493
+ /// reads as a tab change (hosts reconcile without a
494
+ /// transition), not a pop.
495
+ navigation_depth_fn: ?*const fn (model: *const ModelT) usize = null,
496
+ /// The command id a projecting host dispatches when the
497
+ /// platform back affordance completes (iOS: the interactive
498
+ /// edge-swipe-back gesture finishing) — the same command
499
+ /// path tab taps and native header buttons ride, mapped to
500
+ /// a Msg in `on_command`, so a gesture-driven back and the
501
+ /// app's own back button are indistinguishable in the Msg
502
+ /// journal. A cancelled gesture dispatches nothing. Set it
503
+ /// together with `navigation_depth_fn`; hosts only arm the
504
+ /// back gesture when both exist (a pop that could dispatch
505
+ /// nothing would be a dead-end affordance).
506
+ navigation_back_command: []const u8 = "",
507
+ /// Optional app-level key FALLBACK for canvas keyboard
508
+ /// input: consulted for a key_down only after widget
509
+ /// routing declines it. The precedence rule (enforced in
510
+ /// `handleKeyboard`, in this order):
511
+ /// 1. A focused widget's bound handler wins — space on a
512
+ /// focused row activates THAT row, never the fallback.
513
+ /// 2. A focused widget that structurally consumes the key
514
+ /// — an activation/step intent it answers to, or any
515
+ /// editable text widget, where typing must stay typing
516
+ /// (`canvas.isWidgetTextEntry`, checked by KIND so an
517
+ /// unbound `on_input` changes nothing) — eats it
518
+ /// silently.
519
+ /// 3. Only then does the key fall through here, including
520
+ /// when nothing is focused at all.
521
+ /// This is the honest home for unmodified media keys (the
522
+ /// bare-space play/pause convention): chrome shortcuts
523
+ /// (`Shortcut`/`on_command`) deliberately REQUIRE a modifier
524
+ /// on character keys and space, precisely so registration
525
+ /// can never steal typing — a fallback that yields to every
526
+ /// consuming widget can carry them safely.
527
+ on_key: ?*const fn (keyboard: canvas.WidgetKeyboardEvent) ?MsgT = null,
528
+ /// Optional mapping from runtime timer events (started via
529
+ /// `runtime.startTimer`) into messages. Framework-reserved timer
530
+ /// ids (>= `platform.reserved_timer_id_base`) are handled
531
+ /// internally and never reach this callback — that includes fx
532
+ /// timers (`fx.startTimer`), which deliver their own `on_fire`
533
+ /// Msgs through the update path instead.
534
+ on_timer: ?*const fn (id: u64, timestamp_ns: u64) ?MsgT = null,
535
+ /// Optional mapping from system appearance changes into
536
+ /// messages so the model can own color scheme, contrast, and
537
+ /// reduce-motion state (and `tokens_fn` can derive from it).
538
+ on_appearance: ?*const fn (appearance: platform.Appearance) ?MsgT = null,
539
+ /// Optional mapping from the MAIN canvas window's chrome
540
+ /// overlay geometry into messages — the hidden-titlebar
541
+ /// (`titlebar = .hidden_inset`/`.hidden_inset_tall`)
542
+ /// coordination channel. `chrome.insets` names the bands
543
+ /// where OS window controls overlay the content (macOS:
544
+ /// titlebar band height on top — compact or tall — and
545
+ /// traffic-light extent on the leading edge), and
546
+ /// `chrome.buttons` is the traffic-light cluster's frame in
547
+ /// content coordinates so a header can vertically center
548
+ /// its controls against the lights; everything is all-zero
549
+ /// in fullscreen, on standard-chrome windows, and on
550
+ /// platforms without the concept. Delivered before the
551
+ /// first view build and again whenever the geometry changes
552
+ /// (fullscreen transitions). Main canvas window only —
553
+ /// declared secondary windows have no chrome hook yet (same
554
+ /// scope note as `sync`).
555
+ ///
556
+ /// Mobile hosts answer the same channel with the viewport's
557
+ /// safe-area insets (notch, status bar, home indicator), so
558
+ /// the padding an app derives here is the one code path on
559
+ /// every platform. Subscribing takes ownership of that
560
+ /// padding: the runtime stops pre-insetting widget layout by
561
+ /// the safe area (it keeps the keyboard's residual overlap),
562
+ /// so an unsubscribed app keeps today's automatic insets.
563
+ on_chrome: ?*const fn (chrome: platform.WindowChrome) ?MsgT = null,
564
+ /// Optional mapping from presented gpu frames (carrying the
565
+ /// renderer diagnostics the runtime recorded) into messages.
566
+ /// Called after presenting every frame except the installing
567
+ /// one.
568
+ on_frame: ?*const fn (model: *const ModelT, frame: platform.GpuFrame) ?MsgT = null,
569
+ /// Reads runtime-owned widget state (slider values, scroll
570
+ /// offsets) back into the model before update and rebuild so
571
+ /// the next source tree does not stomp it. Main canvas only:
572
+ /// declared secondary windows' widget state is runtime-owned
573
+ /// between rebuilds but has no sync hook yet — keep
574
+ /// continuous controls in the secondary windows model-driven
575
+ /// (echo `on_change`/`on_scroll` values back into `value`).
576
+ sync: ?*const fn (model: *ModelT, layout: canvas.WidgetLayoutTree) void = null,
577
+ /// Model-derived webview panes, re-applied after every rebuild
578
+ /// (so also on resize and every dispatched Msg): each pane
579
+ /// snaps its scene-declared webview to a canvas widget's
580
+ /// layout frame, navigates when its URL changes, and reloads
581
+ /// when its `reload_token` changes. Returns the number of
582
+ /// panes written to `out` (at most `max_web_panes`).
583
+ /// Engine-agnostic: the webview backend is whatever the build
584
+ /// selected (`-Dweb-engine=system|cef`); platforms without
585
+ /// child webviews log a warning and continue.
586
+ web_panes: ?*const fn (model: *const ModelT, out: []WebViewPane) usize = null,
587
+ /// Menu-bar extra installed once, on the installing frame.
588
+ /// macOS-proven (`NSStatusItem`); platforms without a
589
+ /// status-bar service log a warning and continue.
590
+ status_item: ?StatusItemOptions = null,
591
+ /// Model-derived status-item title and menu (e.g. an
592
+ /// open-count badge in the menu bar, a latest-items
593
+ /// dropdown), the `web_panes` pattern: consulted on install
594
+ /// and after every rebuild, re-applied only when the output
595
+ /// actually changed. Selections dispatch each item's
596
+ /// `command` through `on_command` with source `.tray` —
597
+ /// exactly the window-menu shape. With `status_item` also
598
+ /// set, the static options provide the icon and tooltip
599
+ /// (and the pre-install defaults); this fn owns title and
600
+ /// items from the installing frame on. Platforms without a
601
+ /// tray title seam keep the menu updates and log the title
602
+ /// gap once.
603
+ status_item_fn: ?*const fn (model: *const ModelT, scratch: *StatusItemScratch) StatusItemState = null,
604
+ /// Model-declared secondary windows, reconciled after every
605
+ /// rebuild (and on the installing frame): windows the model
606
+ /// declares exist, windows it stops declaring close — the
607
+ /// `status_item_fn` shape applied to the window set, so a
608
+ /// settings window is `if (model.settings_open)` declaring a
609
+ /// descriptor, opened by a Msg and closed by one. Requires
610
+ /// `window_view`. A user close dispatches the descriptor's
611
+ /// `on_close` Msg (the dismissal precedent: the engine
612
+ /// already closed it; the model's next declared set is
613
+ /// truth). Reconcile failures degrade to logged warnings —
614
+ /// a failed create never takes the render loop down.
615
+ windows_fn: ?*const fn (model: *const ModelT, scratch: *WindowsScratch) []const WindowDescriptor = null,
616
+ /// Per-window view for declared secondary windows, keyed by
617
+ /// the descriptor's window label — the `view` seam with the
618
+ /// window identity alongside. Rebuilt for every open window
619
+ /// on every dispatched Msg. Markup deliberately binds ONE
620
+ /// window's content (the main canvas): there is no `window`
621
+ /// element in the closed grammar because windows are shell
622
+ /// concerns, not view-tree concerns — a markup-authored
623
+ /// secondary window is a `canvas.CompiledMarkupView` whose
624
+ /// `build` this fn calls for the matching label.
625
+ window_view: ?*const fn (ui: *Ui, model: *const ModelT, window_label: []const u8) Ui.Node = null,
626
+ };
627
+
628
+ /// Last-navigated webview pane state, tracked per shell label so
629
+ /// rebuilds only navigate when the URL or reload token actually
630
+ /// changed. Frames are deliberately not cached: they reconcile
631
+ /// against the runtime's live webview state every apply.
632
+ const WebPaneState = struct {
633
+ label_storage: [app_manifest.max_view_label_bytes]u8 = undefined,
634
+ label_len: usize = 0,
635
+ url_storage: [platform.max_webview_url_bytes]u8 = undefined,
636
+ url_len: usize = 0,
637
+ reload_token: u64 = 0,
638
+
639
+ fn label(self: *const WebPaneState) []const u8 {
640
+ return self.label_storage[0..self.label_len];
641
+ }
642
+
643
+ fn url(self: *const WebPaneState) []const u8 {
644
+ return self.url_storage[0..self.url_len];
645
+ }
646
+ };
647
+
648
+ /// Live state for one model-declared secondary window: its own
649
+ /// tree and arena pair (the handler table must stay valid
650
+ /// between events, per window), the runtime window id, and the
651
+ /// close Msg. Slots are keyed by window label and reconciled by
652
+ /// `applyWindows`.
653
+ const WindowSlot = struct {
654
+ label_storage: [platform.max_window_label_bytes]u8 = undefined,
655
+ label_len: usize = 0,
656
+ canvas_label_storage: [app_manifest.max_view_label_bytes]u8 = undefined,
657
+ canvas_label_len: usize = 0,
658
+ window_id: platform.WindowId = 0,
659
+ on_close: ?MsgT = null,
660
+ installed: bool = false,
661
+ canvas_size: geometry.SizeF = .{ .width = 1, .height = 1 },
662
+ tree: ?Ui.Tree = null,
663
+ arena_index: usize = 0,
664
+ arenas: [2]std.heap.ArenaAllocator,
665
+
666
+ fn init(backing: std.mem.Allocator) WindowSlot {
667
+ return .{ .arenas = .{
668
+ std.heap.ArenaAllocator.init(backing),
669
+ std.heap.ArenaAllocator.init(backing),
670
+ } };
671
+ }
672
+
673
+ fn label(self: *const WindowSlot) []const u8 {
674
+ return self.label_storage[0..self.label_len];
675
+ }
676
+
677
+ fn canvasLabel(self: *const WindowSlot) []const u8 {
678
+ return self.canvas_label_storage[0..self.canvas_label_len];
679
+ }
680
+ };
681
+
682
+ fn windowSlotsInit(backing: std.mem.Allocator) [max_ui_windows]WindowSlot {
683
+ var slots: [max_ui_windows]WindowSlot = undefined;
684
+ for (&slots) |*slot| slot.* = WindowSlot.init(backing);
685
+ return slots;
686
+ }
687
+
688
+ model: ModelT,
689
+ options: Options,
690
+ arenas: [2]std.heap.ArenaAllocator,
691
+ arena_index: usize = 0,
692
+ tree: ?Ui.Tree = null,
693
+ canvas_size: geometry.SizeF = .{ .width = 1, .height = 1 },
694
+ canvas_window_id: platform.WindowId = 1,
695
+ installed: bool = false,
696
+ /// Exactly-once guard for `Options.fonts`: registration must not
697
+ /// retry on every frame after a teaching failure (ids that DID
698
+ /// register would then fail `FontIdInUse` and bury the real
699
+ /// error).
700
+ fonts_registered: bool = false,
701
+ /// Exactly-once guard for `Options.init_fx`, independent of
702
+ /// `installed` so a failed install rebuild cannot rerun it.
703
+ init_fx_ran: bool = false,
704
+ /// Last chrome overlay geometry delivered through `on_chrome`,
705
+ /// so resize-driven re-queries only dispatch on actual change
706
+ /// (fullscreen transitions flip it; ordinary resizes do not).
707
+ window_chrome: platform.WindowChrome = .{},
708
+ window_chrome_known: bool = false,
709
+ /// The model's current selected chrome tab id (`selected_tab_fn`
710
+ /// re-derived after every rebuild), stored so projecting hosts
711
+ /// can poll `chromeSelectedTab()` between frames without touching
712
+ /// the model. Command ids are capped by the manifest vocabulary.
713
+ chrome_selected_tab_storage: [app_manifest.max_command_id_bytes]u8 = undefined,
714
+ chrome_selected_tab_len: usize = 0,
715
+ /// The model's current navigation depth (`navigation_depth_fn`,
716
+ /// re-derived after every rebuild) plus whether a derivation has
717
+ /// happened yet, stored so projecting hosts can poll
718
+ /// `chromeNavigationDepth()` between frames without touching the
719
+ /// model. Before the first rebuild (and whenever the app declares
720
+ /// no derivation) hosts read -1 and project no transitions.
721
+ chrome_navigation_depth: usize = 0,
722
+ chrome_navigation_depth_known: bool = false,
723
+ /// The system appearance the platform last reported (delivered
724
+ /// before the first view build, then on every OS-side change).
725
+ /// The stock token derivation reads it when the app sets neither
726
+ /// `tokens` nor `tokens_fn`, so unthemed apps follow the OS
727
+ /// light/dark setting live. Test/null platforms never emit it,
728
+ /// so deterministic runs stay on the default light theme.
729
+ system_appearance: platform.Appearance = .{},
730
+ pixel_snap_scale: f32 = 1,
731
+ frame_timestamp_ns: u64 = 0,
732
+ markup_arenas: [2]std.heap.ArenaAllocator,
733
+ markup_arena_index: usize = 0,
734
+ markup_view: ?MarkupView = null,
735
+ markup_source_hash: u64 = 0,
736
+ /// Set when the embedded or watched markup failed to parse or build;
737
+ /// cleared on the next successful parse. Apps may render it. The
738
+ /// message and path slices point into the storage below (the
739
+ /// resolver formats some messages in the reload arena, which
740
+ /// resets on the next attempt).
741
+ markup_diagnostic: ?canvas.ui_markup.MarkupErrorInfo = null,
742
+ markup_diagnostic_message_storage: [512]u8 = undefined,
743
+ markup_diagnostic_path_storage: [canvas.ui_markup.max_import_path_len]u8 = undefined,
744
+ /// Fragment hot-reload slots (Debug dev runs only), one per
745
+ /// registered fragment in `Options.fragment_watch` order. Exists
746
+ /// only where the fragment watch does, so release binaries carry
747
+ /// none of this state. No default on purpose: every constructor
748
+ /// must initialize the arenas against the backing allocator.
749
+ markup_fragment_slots: if (fragment_watch_enabled) [max_watched_fragments]MarkupFragmentSlot else void,
750
+ /// Widget provenance (write-back's read half): the retained
751
+ /// structural-id -> authored-markup table the `provenance`
752
+ /// automation verb answers from. Exists only in markup-interpreter
753
+ /// builds; filled only while automation is enabled.
754
+ provenance: if (features.runtime_markup) ui_app_provenance.ProvenanceTable else void =
755
+ if (features.runtime_markup) .{} else {},
756
+ /// Import-closure staging for the file table: filled by the
757
+ /// hashing loader during a resolve, committed on adopt so a failed
758
+ /// mid-edit reload can never re-anchor spans to bytes the running
759
+ /// view was not built from.
760
+ provenance_closure: if (features.runtime_markup) ui_app_provenance.ClosureFiles else void =
761
+ if (features.runtime_markup) .{} else {},
762
+ layout_nodes: [canvas_limits.max_canvas_widget_nodes_per_view]canvas.WidgetLayoutNode = undefined,
763
+ gpu_commands: [canvas_limits.max_canvas_commands_per_view]canvas.CanvasGpuCommand = undefined,
764
+ /// Packet transport buffer, sized for the larger of the two wire
765
+ /// encodings (the compact binary bound; the JSON bound is
766
+ /// smaller and the runtime clamps JSON encodes to it), so a
767
+ /// text-heavy frame that fits either encoding rides the packet
768
+ /// path.
769
+ packet_bytes: [platform.max_gpu_surface_packet_binary_bytes]u8 = undefined,
770
+ /// Allocator backing the arenas and the lazily grown pixel
771
+ /// presentation buffers below.
772
+ backing: std.mem.Allocator,
773
+ /// CPU presentation scratch, used only on platforms without a GPU
774
+ /// packet presenter (or when packet presentation fails at runtime):
775
+ /// heap-allocated lazily, sized to the surface in device pixels, and
776
+ /// grown on resize. Platforms that present packets never allocate
777
+ /// these.
778
+ pixel_buffer: []u8 = &.{},
779
+ pixel_scratch: []u8 = &.{},
780
+ /// Worker threads, completion queue, and spawn slots for the
781
+ /// effect system. Fixed-capacity; lives with the app struct
782
+ /// (heap-allocated like the rest of it).
783
+ effects: Effects,
784
+ /// Applied webview-pane state (`Options.web_panes`), keyed by
785
+ /// shell label.
786
+ web_pane_states: [max_web_panes]WebPaneState = [_]WebPaneState{.{}} ** max_web_panes,
787
+ web_pane_state_count: usize = 0,
788
+ /// Exactly-once guard for `Options.status_item`/`status_item_fn`.
789
+ status_item_installed: bool = false,
790
+ /// True once `createTray` succeeded — the gate for model-driven
791
+ /// tray updates (`status_item_fn`).
792
+ tray_created: bool = false,
793
+ /// The platform reported no tray-title seam; stop retrying (menu
794
+ /// updates keep flowing).
795
+ tray_title_unsupported: bool = false,
796
+ /// Hashes of the last APPLIED model-derived tray state, so
797
+ /// rebuilds only touch the platform when the output changed.
798
+ tray_title_hash: u64 = 0,
799
+ tray_menu_hash: u64 = 0,
800
+ /// Scratch handed to `status_item_fn`; on the app struct so the
801
+ /// returned slices outlive the apply.
802
+ tray_scratch: StatusItemScratch = .{},
803
+ /// Press-and-hold gesture state (`ElementOptions.on_hold`): the
804
+ /// widget id whose press armed the hold timer, and whether the
805
+ /// timer fired for the current gesture (a fired hold suppresses
806
+ /// the release's ordinary press — one gesture, one Msg).
807
+ hold_armed_id: canvas.ObjectId = 0,
808
+ hold_fired: bool = false,
809
+ /// Which canvas the armed hold belongs to (one pointer, one
810
+ /// gesture — but it can be in any window): the view label and
811
+ /// window id recorded at arm time so the fire resolves the right
812
+ /// tree and dispatches with the right window identity.
813
+ hold_view_label_storage: [app_manifest.max_view_label_bytes]u8 = undefined,
814
+ hold_view_label_len: usize = 0,
815
+ hold_window_id: platform.WindowId = 1,
816
+ /// Context-menu presentation fallback state: the widget whose
817
+ /// declared menu is mounted as an anchored canvas surface because
818
+ /// the platform could not present it natively. Set by
819
+ /// `canvas_widget_context_menu_request`, cleared by selection,
820
+ /// dismissal, or the target vanishing from a rebuild. 0 = no
821
+ /// fallback menu open. The synthesized surface itself comes from
822
+ /// `Ui.finalize` (see `Ui.context_menu_fallback_target`).
823
+ context_menu_fallback_target: canvas.ObjectId = 0,
824
+ context_menu_fallback_window_id: platform.WindowId = 1,
825
+ context_menu_fallback_label_storage: [app_manifest.max_view_label_bytes]u8 = undefined,
826
+ context_menu_fallback_label_len: usize = 0,
827
+ /// The windowed virtual lists the LAST build declared
828
+ /// (`Ui.virtualList` records): scroll events on these regions
829
+ /// re-derive the view even without an app `on_scroll` binding,
830
+ /// and the coverage check re-runs a build whose fresh geometry
831
+ /// proved a window too small.
832
+ virtual_windows: [canvas.max_virtual_windows]canvas.VirtualWindowRecord = [_]canvas.VirtualWindowRecord{.{}} ** canvas.max_virtual_windows,
833
+ virtual_window_count: usize = 0,
834
+ /// Scroll regions whose `on_reach_end` fired and has not re-armed
835
+ /// (the approach-end hysteresis state, keyed by widget id).
836
+ reach_end_fired_ids: [canvas.max_virtual_windows]canvas.ObjectId = [_]canvas.ObjectId{0} ** canvas.max_virtual_windows,
837
+ /// The approach-START mirror (`on_reach_start` hysteresis).
838
+ reach_start_fired_ids: [canvas.max_virtual_windows]canvas.ObjectId = [_]canvas.ObjectId{0} ** canvas.max_virtual_windows,
839
+ /// Retained offset tables for VARIABLE-extent virtual lists,
840
+ /// claimed per list identity during builds (`Ui.virtualWindow`
841
+ /// through the extent source) and patched by the post-layout
842
+ /// measure step. Budgeted like the windows themselves — one per
843
+ /// declarable window; a build declaring more variable lists than
844
+ /// slots drops the excess to estimate-only math with a debug
845
+ /// warning.
846
+ virtual_extent_tables: [canvas.max_virtual_windows]canvas.VirtualExtentTable = [_]canvas.VirtualExtentTable{.{}} ** canvas.max_virtual_windows,
847
+ /// Live model-declared secondary windows (`Options.windows_fn`),
848
+ /// keyed by window label.
849
+ window_slots: [max_ui_windows]WindowSlot,
850
+ window_slot_count: usize = 0,
851
+ /// Scratch handed to `windows_fn`; on the app struct so returned
852
+ /// descriptor slices outlive the apply.
853
+ windows_scratch: WindowsScratch = .{},
854
+
855
+ /// By-value construction. The Model parameter and the returned
856
+ /// app both ride the caller's stack unless result-location
857
+ /// semantics happen to elide them — at multi-MB Model sizes that
858
+ /// is a stack-overflow trap (the multi-MB-by-value family: fine in
859
+ /// `main`, deadly in tests that keep any sizable local). Prefer
860
+ /// `create`/`destroy`, which never materialize the Model or the
861
+ /// app outside the heap allocation.
862
+ pub fn init(backing: std.mem.Allocator, model: ModelT, options: Options) Self {
863
+ assertOptions(options);
864
+ return .{
865
+ .model = model,
866
+ .options = options,
867
+ .backing = backing,
868
+ .arenas = .{
869
+ std.heap.ArenaAllocator.init(backing),
870
+ std.heap.ArenaAllocator.init(backing),
871
+ },
872
+ .markup_arenas = .{
873
+ std.heap.ArenaAllocator.init(backing),
874
+ std.heap.ArenaAllocator.init(backing),
875
+ },
876
+ .window_slots = windowSlotsInit(backing),
877
+ .markup_fragment_slots = if (comptime fragment_watch_enabled) markupFragmentSlotsInit(backing) else {},
878
+ .effects = Effects.init(backing),
879
+ };
880
+ }
881
+
882
+ /// Heap-allocate the app and construct every field — the
883
+ /// Model included — in place, so nothing app-sized ever rides
884
+ /// the stack. The Model starts as its default value; set fields
885
+ /// through the returned pointer before the app runs
886
+ /// (`app.model.count = 1`, `app.model.addTask(...)`). Pair with
887
+ /// `destroy`.
888
+ pub fn create(backing: std.mem.Allocator, options: Options) error{OutOfMemory}!*Self {
889
+ comptime {
890
+ for (@typeInfo(ModelT).@"struct".fields) |field| {
891
+ if (field.default_value_ptr == null) @compileError(
892
+ "UiApp.create default-initializes the Model in place, but Model field '" ++ field.name ++
893
+ "' has no default value - give every Model field a default, or use initInPlace and assign app.model through the pointer yourself",
894
+ );
895
+ }
896
+ }
897
+ const self = try backing.create(Self);
898
+ initInPlace(self, backing, options);
899
+ self.model = .{};
900
+ return self;
901
+ }
902
+
903
+ /// Counterpart to `create`: deinit and free the heap allocation.
904
+ /// Only for apps obtained from `create`.
905
+ pub fn destroy(self: *Self) void {
906
+ const backing = self.backing;
907
+ self.deinit();
908
+ backing.destroy(self);
909
+ }
910
+
911
+ /// In-place construction of everything BUT the Model, which is
912
+ /// left undefined: the seam for callers that produce the model
913
+ /// separately. Assign `self.model` immediately after — through
914
+ /// the pointer (`app.model = loadModel()` writes straight into
915
+ /// the app struct via result-location semantics, no stack copy
916
+ /// of the framework's making). Prefer `create` when the Model is
917
+ /// default-initializable.
918
+ pub fn initInPlace(self: *Self, backing: std.mem.Allocator, options: Options) void {
919
+ assertOptions(options);
920
+ self.* = .{
921
+ .model = undefined,
922
+ .options = options,
923
+ .backing = backing,
924
+ .arenas = .{
925
+ std.heap.ArenaAllocator.init(backing),
926
+ std.heap.ArenaAllocator.init(backing),
927
+ },
928
+ .markup_arenas = .{
929
+ std.heap.ArenaAllocator.init(backing),
930
+ std.heap.ArenaAllocator.init(backing),
931
+ },
932
+ .window_slots = windowSlotsInit(backing),
933
+ .markup_fragment_slots = if (comptime fragment_watch_enabled) markupFragmentSlotsInit(backing) else {},
934
+ .effects = Effects.init(backing),
935
+ };
936
+ }
937
+
938
+ fn assertOptions(options: Options) void {
939
+ std.debug.assert(options.view != null or options.markup != null);
940
+ std.debug.assert((options.update != null) != (options.update_fx != null));
941
+ // Declared windows need the per-window view to build them.
942
+ std.debug.assert(options.windows_fn == null or options.window_view != null);
943
+ if (comptime !features.runtime_markup) std.debug.assert(options.markup == null);
944
+ }
945
+
946
+ pub fn deinit(self: *Self) void {
947
+ // In an app main this usually runs AFTER the runner has
948
+ // already destroyed the platform and runtime (main's defer
949
+ // was declared first, so it fires last). The platform-facing
950
+ // half of this teardown therefore already happened in
951
+ // `stopFn` — effects.deinit is idempotent and severed its
952
+ // services binding there, so this second call frees app-side
953
+ // memory only and never touches the dead platform.
954
+ self.effects.deinit();
955
+ self.arenas[0].deinit();
956
+ self.arenas[1].deinit();
957
+ self.markup_arenas[0].deinit();
958
+ self.markup_arenas[1].deinit();
959
+ if (comptime fragment_watch_enabled) {
960
+ for (&self.markup_fragment_slots) |*slot| {
961
+ slot.arenas[0].deinit();
962
+ slot.arenas[1].deinit();
963
+ }
964
+ }
965
+ for (&self.window_slots) |*slot| {
966
+ slot.arenas[0].deinit();
967
+ slot.arenas[1].deinit();
968
+ }
969
+ if (self.pixel_buffer.len > 0) self.backing.free(self.pixel_buffer);
970
+ if (self.pixel_scratch.len > 0) self.backing.free(self.pixel_scratch);
971
+ self.pixel_buffer = &.{};
972
+ self.pixel_scratch = &.{};
973
+ }
974
+
975
+ pub fn app(self: *Self) App {
976
+ return .{
977
+ .context = self,
978
+ .name = self.options.name,
979
+ .scene_fn = sceneFn,
980
+ .event_fn = eventFn,
981
+ .stop_fn = stopFn,
982
+ .replay_fn = replayFn,
983
+ };
984
+ }
985
+
986
+ /// The app's stop hook (`App.stop`): the runtime guarantees it
987
+ /// runs before its loop returns, i.e. while the platform's
988
+ /// service table is still alive — and that is the LAST such
989
+ /// moment this app gets. Tear the effects channel down here in
990
+ /// full (silence a live audio player, disarm platform timers,
991
+ /// join effect workers that post through the platform's wake
992
+ /// service); the teardown also severs the channel's services
993
+ /// binding, so the `deinit` that main defers — which runs only
994
+ /// AFTER the runner has destroyed platform and runtime — repeats
995
+ /// none of these calls and answers inert instead of reaching
996
+ /// into freed memory.
997
+ fn stopFn(context: *anyopaque, runtime: *Runtime) anyerror!void {
998
+ _ = runtime;
999
+ const self: *Self = @ptrCast(@alignCast(context));
1000
+ self.effects.deinit();
1001
+ }
1002
+
1003
+ /// Bind the runtime-owned seams onto the effects channel (all
1004
+ /// first-bind-sticks): platform services, spawn environment,
1005
+ /// image registry, window verbs, and — while a session is being
1006
+ /// recorded — the recorder's result journal.
1007
+ fn bindEffectsChannel(self: *Self, runtime: *Runtime) void {
1008
+ self.effects.bindServices(&runtime.options.platform.services);
1009
+ self.effects.bindEnviron(runtime.options.environ);
1010
+ self.effects.bindImages(runtime.canvasImageRegistryBinding());
1011
+ self.effects.bindWindowActions(.{
1012
+ .context = runtime,
1013
+ .close_fn = effectsCloseWindowByLabel,
1014
+ .minimize_fn = effectsMinimizeWindowByLabel,
1015
+ });
1016
+ if (runtime.options.session_recorder) |recorder| {
1017
+ self.effects.bindJournal(recorder.effectJournal());
1018
+ }
1019
+ }
1020
+
1021
+ /// Session-replay control (`App.replay_fn`): arm the effects
1022
+ /// channel into replay mode before the first replayed event, and
1023
+ /// feed journaled results into the stub executor. `.timer`
1024
+ /// records never feed — fx-timer fires replay through the
1025
+ /// journaled platform `.timer` events, and rejection notices
1026
+ /// regenerate from the same deterministic validation.
1027
+ fn replayFn(context: *anyopaque, control: core.ReplayControl) anyerror!void {
1028
+ const self: *Self = @ptrCast(@alignCast(context));
1029
+ switch (control) {
1030
+ .arm => self.effects.armReplay(),
1031
+ .feed => |record| switch (record.kind) {
1032
+ .line => try self.effects.feedLine(record.key, record.payload),
1033
+ .exit => {
1034
+ if (record.payload.len > 0) try self.effects.feedOutput(record.key, record.payload);
1035
+ if (record.stderr_tail.len > 0) try self.effects.feedStderr(record.key, record.stderr_tail);
1036
+ try self.effects.feedExitReason(record.key, record.code, record.exit_reason);
1037
+ },
1038
+ .response => try self.effects.feedResponseOutcome(record.key, record.fetch_outcome, record.status, record.payload),
1039
+ .file => try self.effects.feedFileResult(record.key, record.file_outcome, record.payload),
1040
+ .clipboard => try self.effects.feedClipboardResult(record.key, record.clipboard_outcome, record.payload),
1041
+ .clock => try self.effects.pushReplayClock(record.clock_wall_ms),
1042
+ // Spectrum records feed through the band-carrying
1043
+ // helper so replay repaints identical bars; every
1044
+ // other audio kind rides the plain shape.
1045
+ .audio => if (record.audio_kind == .spectrum)
1046
+ try self.effects.feedAudioSpectrum(record.audio_bands, record.audio_position_ms, record.audio_duration_ms)
1047
+ else
1048
+ try self.effects.feedAudioEventBuffering(record.audio_kind, record.audio_position_ms, record.audio_duration_ms, record.audio_playing, record.audio_buffering),
1049
+ .timer => {},
1050
+ },
1051
+ }
1052
+ }
1053
+
1054
+ /// Apply a message and rebuild the widget tree. Runtime-owned
1055
+ /// widget state is synced into the model first so `update` sees
1056
+ /// current slider values and scroll offsets.
1057
+ pub fn dispatch(self: *Self, runtime: *Runtime, window_id: platform.WindowId, msg: MsgT) anyerror!void {
1058
+ self.bindEffectsChannel(runtime);
1059
+ self.syncModel(runtime, self.canvas_window_id);
1060
+ self.applyMsg(msg);
1061
+ self.publishAudioState(runtime);
1062
+ // Before the installing frame there is nothing to render
1063
+ // against: canvas size and scale arrive with the first frame
1064
+ // event, and the installing rebuild renders whatever model
1065
+ // state accumulated here. A pre-install rebuild is discarded
1066
+ // work at a default surface size — and appearance/chrome
1067
+ // events land before the first frame on every launch, so it
1068
+ // used to cost a full view build on the launch path.
1069
+ if (!self.installed) return;
1070
+ try self.rebuild(runtime, self.canvas_window_id);
1071
+ try self.rebuildWindowSlots(runtime);
1072
+ // A Msg dispatched FROM a secondary window still rebuilt the
1073
+ // main canvas above (one model, every window's view derives
1074
+ // from it); `window_id` names the dispatch origin for apps
1075
+ // that inspect it, not the rebuild target.
1076
+ _ = window_id;
1077
+ }
1078
+
1079
+ /// Run `update` through whichever form the app declared; the
1080
+ /// effects channel rides along for the `update_fx` form.
1081
+ fn applyMsg(self: *Self, msg: MsgT) void {
1082
+ if (self.options.update_fx) |update_fx| {
1083
+ update_fx(&self.model, msg, &self.effects);
1084
+ } else {
1085
+ self.options.update.?(&self.model, msg);
1086
+ }
1087
+ }
1088
+
1089
+ /// Drain the effect completion queue on the loop thread: every
1090
+ /// queued line/exit becomes a Msg through its stored constructor
1091
+ /// and runs through `update`; one rebuild follows. Called on
1092
+ /// `.effects_wake` (the platform marshalled a worker's `wake_fn`
1093
+ /// nudge) and each presented frame (host-pumped embeds have no
1094
+ /// wake delivery; their frame pump drains naturally).
1095
+ pub fn drainEffects(self: *Self, runtime: *Runtime) anyerror!void {
1096
+ if (!self.installed) return;
1097
+ if (!self.effects.hasPending()) return;
1098
+ self.bindEffectsChannel(runtime);
1099
+ self.syncModel(runtime, self.canvas_window_id);
1100
+ var dispatched = false;
1101
+ while (self.effects.takeMsg()) |msg| {
1102
+ self.applyMsg(msg);
1103
+ dispatched = true;
1104
+ }
1105
+ self.publishAudioState(runtime);
1106
+ if (dispatched) {
1107
+ try self.rebuild(runtime, self.canvas_window_id);
1108
+ try self.rebuildWindowSlots(runtime);
1109
+ }
1110
+ }
1111
+
1112
+ /// Mirror the effects channel's audio playback state into the
1113
+ /// runtime so the automation snapshot reports it honestly (the
1114
+ /// runtime is Msg-type-erased and cannot read the channel
1115
+ /// itself). Called wherever a dispatch or drain may have moved
1116
+ /// playback.
1117
+ fn publishAudioState(self: *Self, runtime: *Runtime) void {
1118
+ const audio = self.effects.audioSnapshot();
1119
+ runtime.audio_active = audio.active;
1120
+ runtime.audio_key = audio.key;
1121
+ runtime.audio_playing = audio.playing;
1122
+ runtime.audio_buffering = audio.buffering;
1123
+ runtime.audio_source = audio.source;
1124
+ runtime.audio_position_ms = audio.position_ms;
1125
+ runtime.audio_duration_ms = audio.duration_ms;
1126
+ runtime.audio_spectrum_bands = audio.spectrum_bands;
1127
+ runtime.audio_spectrum_events = audio.spectrum_events;
1128
+ }
1129
+
1130
+ /// The design tokens for the next rebuild: the model-derived
1131
+ /// `tokens_fn`, explicit static `tokens`, or — the default — the
1132
+ /// stock theme derived from the SYSTEM appearance the runtime
1133
+ /// tracks (scheme, contrast, reduced motion), so an unthemed app
1134
+ /// honors the OS light/dark setting live. Derived tokens carry
1135
+ /// the surface scale in `pixel_snap.scale`.
1136
+ pub fn effectiveTokens(self: *const Self) canvas.DesignTokens {
1137
+ if (self.options.tokens_fn) |tokens_fn| {
1138
+ var tokens = tokens_fn(&self.model);
1139
+ tokens.pixel_snap.scale = self.pixel_snap_scale;
1140
+ return tokens;
1141
+ }
1142
+ if (self.options.tokens) |static_tokens| return static_tokens;
1143
+ var tokens = canvas.DesignTokens.theme(.{
1144
+ .color_scheme = switch (self.system_appearance.color_scheme) {
1145
+ .light => .light,
1146
+ .dark => .dark,
1147
+ },
1148
+ .contrast = if (self.system_appearance.high_contrast) .high else .standard,
1149
+ .reduce_motion = self.system_appearance.reduce_motion,
1150
+ .pack = self.options.theme,
1151
+ });
1152
+ tokens.pixel_snap.scale = self.pixel_snap_scale;
1153
+ return tokens;
1154
+ }
1155
+
1156
+ /// Whether the stock tokens derive from the system appearance:
1157
+ /// true only when the app claims neither token override, so an
1158
+ /// appearance flip (or a surface-scale change) must re-derive
1159
+ /// and re-render.
1160
+ fn followsSystemAppearance(self: *const Self) bool {
1161
+ return self.options.tokens_fn == null and self.options.tokens == null;
1162
+ }
1163
+
1164
+ /// Whether tokens are derived per rebuild (model-owned or
1165
+ /// system-followed) rather than a fixed set.
1166
+ fn derivesTokens(self: *const Self) bool {
1167
+ return self.options.tokens_fn != null or self.followsSystemAppearance();
1168
+ }
1169
+
1170
+ /// Read runtime-owned widget state back into the model through the
1171
+ /// optional `sync` hook.
1172
+ fn syncModel(self: *Self, runtime: *Runtime, window_id: platform.WindowId) void {
1173
+ const sync = self.options.sync orelse return;
1174
+ if (self.tree == null) return;
1175
+ const layout = runtime.canvasWidgetLayout(window_id, self.options.canvas_label) catch return;
1176
+ sync(&self.model, layout);
1177
+ }
1178
+
1179
+ /// Rebuild the widget tree from the model and hand it to the
1180
+ /// runtime, which copies and reconciles it. The previous tree's
1181
+ /// arena stays alive until the following rebuild so the handler
1182
+ /// table remains valid between events. Apps with a `chrome` hook
1183
+ /// also rebuild the retained display list (chrome prefix + widget
1184
+ /// commands + chrome suffix) here.
1185
+ ///
1186
+ /// Windowed virtual lists (`Ui.virtualList`) get their window
1187
+ /// source installed here: each `ui.virtualWindow` request
1188
+ /// resolves against the RETAINED layout's scroll offset and
1189
+ /// viewport for the list's global identity (canvas height at
1190
+ /// offset 0 before the list first mounts). When the fresh
1191
+ /// layout's geometry proves a window under-covered — the first
1192
+ /// build guessed the viewport, or a resize widened it — the view
1193
+ /// is derived once more against the fresh geometry, so the
1194
+ /// window converges within the same rebuild instead of waiting
1195
+ /// for the next Msg.
1196
+ pub fn rebuild(self: *Self, runtime: *Runtime, window_id: platform.WindowId) anyerror!void {
1197
+ self.syncModel(runtime, window_id);
1198
+ if (comptime features.runtime_markup) {
1199
+ // Under automation, drive the interpreter from the first
1200
+ // frame even when a compiled view is present: provenance
1201
+ // (write-back's read half) is stamped by the interpreter,
1202
+ // and the engines are parity-proven, so the pixels and
1203
+ // structural ids do not change.
1204
+ if (runtime.options.automation != null and self.markup_view == null and self.options.markup != null) {
1205
+ self.reloadMarkup(self.options.markup.?.source) catch {};
1206
+ }
1207
+ }
1208
+ const tokens = runtime.tokensWithTextMeasure(self.effectiveTokens());
1209
+ const next_index = self.arena_index ^ 1;
1210
+ // Widget layout is inset by the runtime's viewport chrome
1211
+ // (safe areas + keyboard on mobile, zero on desktop); the
1212
+ // canvas itself stays surface-sized so chrome and the clear
1213
+ // color still paint edge to edge under notches and bars.
1214
+ const bounds = geometry.RectF.fromSize(self.canvas_size).deflate(self.layoutViewportInsets(runtime, window_id));
1215
+ var window_source = VirtualWindowResolver{
1216
+ .runtime = runtime,
1217
+ .window_id = window_id,
1218
+ .canvas_label = self.options.canvas_label,
1219
+ .fallback_viewport = bounds.height,
1220
+ };
1221
+ var tree: Ui.Tree = undefined;
1222
+ var layout: canvas.WidgetLayoutTree = undefined;
1223
+ var pass: usize = 0;
1224
+ while (true) {
1225
+ _ = self.arenas[next_index].reset(.retain_capacity);
1226
+ var ui = Ui.init(self.arenas[next_index].allocator());
1227
+ ui.virtual_window_context = @ptrCast(&window_source);
1228
+ ui.virtual_window_source = VirtualWindowResolver.resolve;
1229
+ ui.virtual_extent_context = @ptrCast(self);
1230
+ ui.virtual_extent_source = virtualExtentResolve;
1231
+ ui.context_menu_fallback_target = self.contextMenuFallbackTargetForLabel(self.options.canvas_label);
1232
+ self.armUiFragmentHost(&ui);
1233
+ if (comptime features.runtime_markup) {
1234
+ if (self.markup_view != null and runtime.options.automation != null) {
1235
+ self.provenance.resetRecords();
1236
+ ui.provenance_sink = self.provenance.sink();
1237
+ }
1238
+ }
1239
+ // Frame-profile stamps (no-ops unless profiling is on): the
1240
+ // view build fn + tree finalize is the `rebuild` stage, the
1241
+ // flex pass below is `layout`; reconcile/emit are stamped at
1242
+ // their runtime-side choke points so input-driven refreshes
1243
+ // are attributed too.
1244
+ const rebuild_begin = runtime.frame_profile.begin();
1245
+ const node = try self.buildViewNode(&ui);
1246
+ tree = try ui.finalizeWithTokens(node, tokens);
1247
+ runtime.frame_profile.end(.rebuild, rebuild_begin);
1248
+
1249
+ const layout_begin = runtime.frame_profile.begin();
1250
+ layout = canvas.layoutWidgetTreeWithTokens(tree.root, bounds, tokens, &self.layout_nodes) catch |err| {
1251
+ // Teach the fix at the failure site: the error name
1252
+ // alone never says which budget or where to trim.
1253
+ if (err == error.WidgetLayoutListFull) {
1254
+ ui_app_log.warn(
1255
+ "widget layout capacity exceeded for view '{s}': the per-view budget is {d} nodes (canvas_limits.max_canvas_widget_nodes_per_view) - reduce always-mounted widgets or virtualize lists",
1256
+ .{ self.options.canvas_label, canvas_limits.max_canvas_widget_nodes_per_view },
1257
+ );
1258
+ }
1259
+ return err;
1260
+ };
1261
+ runtime.frame_profile.end(.layout, layout_begin);
1262
+
1263
+ self.rememberVirtualWindows(&ui);
1264
+ // Measure the mounted rows of every variable-extent
1265
+ // list against the fresh layout and patch the retained
1266
+ // offset tables (anchored — see the table's contract).
1267
+ // A material correction earns the same one-retry pass a
1268
+ // coverage miss does, so the installed frame already
1269
+ // consumed it; a residual delta rides to the next
1270
+ // rebuild, atomically with the geometry either way.
1271
+ const corrected = self.measureVirtualWindows(layout);
1272
+ pass += 1;
1273
+ if (pass >= 2 or (!corrected and !self.virtualWindowsUndercovered(layout))) break;
1274
+ window_source.fresh = layout;
1275
+ }
1276
+ launch_timing.lapOnce("first_view_built");
1277
+
1278
+ if (self.options.chrome) |chrome| {
1279
+ try self.installChromeDisplayList(runtime, window_id, chrome, layout, tokens);
1280
+ } else {
1281
+ _ = try runtime.setCanvasWidgetLayout(window_id, self.options.canvas_label, layout);
1282
+ if (self.installed and self.derivesTokens()) {
1283
+ _ = try runtime.emitCanvasWidgetDisplayList(window_id, self.options.canvas_label, tokens);
1284
+ }
1285
+ }
1286
+
1287
+ self.tree = tree;
1288
+ self.arena_index = next_index;
1289
+ // The fallback menu's target vanished from this build (the
1290
+ // model dropped the row, or its menu emptied): the open state
1291
+ // has nothing to present, so it closes.
1292
+ if (self.contextMenuFallbackTargetForLabel(self.options.canvas_label) != 0 and tree.context_menu_fallback == null) {
1293
+ self.clearContextMenuFallback();
1294
+ }
1295
+ try self.scheduleAnimations(runtime, window_id);
1296
+ try self.scheduleLayoutTweens(runtime, window_id);
1297
+ self.applyWebPanes(runtime, window_id, layout);
1298
+ self.applyStatusItem(runtime);
1299
+ self.applyWindows(runtime);
1300
+ self.applyChromeSelection();
1301
+ self.applyChromeNavigation();
1302
+ }
1303
+
1304
+ /// Re-derive the model's selected chrome tab after a rebuild
1305
+ /// (`selected_tab_fn`, the `status_item_fn` cadence): the stored
1306
+ /// id is what a projecting host reads through
1307
+ /// `chromeSelectedTab()` to keep the native bar mirroring the
1308
+ /// model. Without the hook the stored id stays empty and hosts
1309
+ /// project no selection.
1310
+ fn applyChromeSelection(self: *Self) void {
1311
+ const derive = self.options.selected_tab_fn orelse return;
1312
+ const id = derive(&self.model);
1313
+ const len = @min(id.len, self.chrome_selected_tab_storage.len);
1314
+ @memcpy(self.chrome_selected_tab_storage[0..len], id[0..len]);
1315
+ self.chrome_selected_tab_len = len;
1316
+ }
1317
+
1318
+ /// The model's current selected chrome tab id ("" when the app
1319
+ /// declares no `selected_tab_fn`, or before the first rebuild).
1320
+ /// Read by embed hosts to project the declared tab set's
1321
+ /// selection onto the REAL native control.
1322
+ pub fn chromeSelectedTab(self: *const Self) []const u8 {
1323
+ return self.chrome_selected_tab_storage[0..self.chrome_selected_tab_len];
1324
+ }
1325
+
1326
+ /// Re-derive the model's navigation depth after a rebuild
1327
+ /// (`navigation_depth_fn`, the `applyChromeSelection` cadence):
1328
+ /// the stored depth is what a projecting host polls through
1329
+ /// `chromeNavigationDepth()` to decide push/pop transitions.
1330
+ /// Without the hook nothing is stored and hosts read -1.
1331
+ fn applyChromeNavigation(self: *Self) void {
1332
+ const derive = self.options.navigation_depth_fn orelse return;
1333
+ self.chrome_navigation_depth = derive(&self.model);
1334
+ self.chrome_navigation_depth_known = true;
1335
+ }
1336
+
1337
+ /// The model's current navigation depth, or -1 when the app
1338
+ /// declares no `navigation_depth_fn` (or before the first
1339
+ /// rebuild) — hosts treat -1 as "no navigation projection" and
1340
+ /// present no transitions. Read by embed hosts each tick; one
1341
+ /// integer, never a model touch.
1342
+ pub fn chromeNavigationDepth(self: *const Self) isize {
1343
+ if (!self.chrome_navigation_depth_known) return -1;
1344
+ return std.math.lossyCast(isize, self.chrome_navigation_depth);
1345
+ }
1346
+
1347
+ /// The declared back command a projecting host dispatches when
1348
+ /// the platform back gesture completes ("" when the app declares
1349
+ /// no navigation projection — hosts must not arm the gesture).
1350
+ /// Static app data, valid for the app's lifetime.
1351
+ pub fn chromeNavigationBackCommand(self: *const Self) []const u8 {
1352
+ if (self.options.navigation_depth_fn == null) return "";
1353
+ return self.options.navigation_back_command;
1354
+ }
1355
+
1356
+ /// The window source backing `Ui.virtualWindow` during a rebuild:
1357
+ /// resolves a virtual list's retained scroll state (offset of
1358
+ /// record + content viewport) by its global identity, preferring
1359
+ /// the freshly laid-out geometry on the coverage-retry pass. The
1360
+ /// fallback (offset 0 at the canvas height) makes the first
1361
+ /// build materialize enough rows to fill the window. Main canvas
1362
+ /// only — declared secondary windows have no window source yet
1363
+ /// (the `sync` scope note); their builds use each request's
1364
+ /// `viewport_fallback`.
1365
+ const VirtualWindowResolver = struct {
1366
+ runtime: *Runtime,
1367
+ window_id: platform.WindowId,
1368
+ canvas_label: []const u8,
1369
+ fallback_viewport: f32,
1370
+ fresh: ?canvas.WidgetLayoutTree = null,
1371
+
1372
+ fn resolve(context: ?*anyopaque, id: canvas.ObjectId) ?canvas.VirtualWindowState {
1373
+ const self: *VirtualWindowResolver = @ptrCast(@alignCast(context orelse return null));
1374
+ if (self.fresh) |fresh| {
1375
+ if (fresh.findById(id)) |node| return stateForNode(node);
1376
+ }
1377
+ const layout = self.runtime.canvasWidgetLayout(self.window_id, self.canvas_label) catch
1378
+ return .{ .offset = 0, .viewport_extent = self.fallback_viewport };
1379
+ if (layout.findById(id)) |node| return stateForNode(node);
1380
+ return .{ .offset = 0, .viewport_extent = self.fallback_viewport };
1381
+ }
1382
+
1383
+ fn stateForNode(node: canvas.WidgetLayoutNode) canvas.VirtualWindowState {
1384
+ const viewport = node.frame.inset(node.widget.layout.padding).normalized();
1385
+ return .{ .offset = node.widget.value, .viewport_extent = viewport.height, .mounted = true };
1386
+ }
1387
+ };
1388
+
1389
+ /// Keep this build's virtual-window records: the scroll handler
1390
+ /// re-derives the view for these regions even without an app
1391
+ /// `on_scroll` binding (the window follows the runtime offset).
1392
+ fn rememberVirtualWindows(self: *Self, ui: *const Ui) void {
1393
+ const records = ui.virtualWindows();
1394
+ self.virtual_window_count = records.len;
1395
+ @memcpy(self.virtual_windows[0..records.len], records);
1396
+ }
1397
+
1398
+ /// Whether any declared virtual window fails to cover the visible
1399
+ /// range its FRESH geometry implies (first-build viewport guess,
1400
+ /// resize growth): the trigger for the one coverage-retry build.
1401
+ fn virtualWindowsUndercovered(self: *const Self, layout: canvas.WidgetLayoutTree) bool {
1402
+ for (self.virtual_windows[0..self.virtual_window_count]) |record| {
1403
+ const node = layout.findById(record.id) orelse continue;
1404
+ const viewport = node.frame.inset(node.widget.layout.padding).normalized();
1405
+ if (viewport.isEmpty()) continue;
1406
+ if (record.variable) {
1407
+ const table = self.virtualExtentTableForId(record.id) orelse continue;
1408
+ if (record.item_count == 0) continue;
1409
+ const offset = @max(0, node.widget.value);
1410
+ const first_visible = table.indexAtOffset(offset);
1411
+ const visible_end = @min(record.item_count, table.indexAtOffset(offset + viewport.height) + 1);
1412
+ const start = if (first_visible > record.overscan) first_visible - record.overscan else 0;
1413
+ const end = @min(record.item_count, visible_end + record.overscan);
1414
+ if (start < record.start_index or end > record.end_index) return true;
1415
+ continue;
1416
+ }
1417
+ const item_extent = if (node.widget.layout.virtual_item_extent > 0)
1418
+ node.widget.layout.virtual_item_extent
1419
+ else
1420
+ record.item_extent;
1421
+ const range = canvas.virtualListRange(.{
1422
+ .item_count = record.item_count,
1423
+ .item_extent = item_extent,
1424
+ .item_gap = record.gap,
1425
+ .viewport_extent = viewport.height,
1426
+ .scroll_offset = node.widget.value,
1427
+ .overscan = record.overscan,
1428
+ });
1429
+ if (range.start_index < record.start_index or range.end_index > record.end_index) return true;
1430
+ }
1431
+ return false;
1432
+ }
1433
+
1434
+ /// The extent source backing `Ui.virtualWindow` for
1435
+ /// variable-extent lists: resolve (or claim) the retained offset
1436
+ /// table for a list identity. Slots follow the window budget;
1437
+ /// a stale table (its list no longer declared) is recycled
1438
+ /// before giving up.
1439
+ fn virtualExtentResolve(context: ?*anyopaque, id: canvas.ObjectId) ?*canvas.VirtualExtentTable {
1440
+ const self: *Self = @ptrCast(@alignCast(context orelse return null));
1441
+ return self.claimVirtualExtentTable(id);
1442
+ }
1443
+
1444
+ fn virtualExtentTableForId(self: *const Self, id: canvas.ObjectId) ?*canvas.VirtualExtentTable {
1445
+ if (id == 0) return null;
1446
+ for (&self.virtual_extent_tables) |*table| {
1447
+ if (table.id == id) return @constCast(table);
1448
+ }
1449
+ return null;
1450
+ }
1451
+
1452
+ fn claimVirtualExtentTable(self: *Self, id: canvas.ObjectId) ?*canvas.VirtualExtentTable {
1453
+ if (id == 0) return null;
1454
+ for (&self.virtual_extent_tables) |*table| {
1455
+ if (table.id == id) return table;
1456
+ }
1457
+ for (&self.virtual_extent_tables) |*table| {
1458
+ if (table.id == 0) return table;
1459
+ }
1460
+ // All slots busy: recycle one whose list the LAST build no
1461
+ // longer declared (per-document lists come and go; their
1462
+ // measured state is rebuildable by scrolling).
1463
+ recycle: for (&self.virtual_extent_tables) |*table| {
1464
+ for (self.virtual_windows[0..self.virtual_window_count]) |record| {
1465
+ if (record.id == table.id) continue :recycle;
1466
+ }
1467
+ table.reset();
1468
+ return table;
1469
+ }
1470
+ ui_app_log.warn(
1471
+ "more than {d} variable-extent virtual lists alive at once (canvas.ui_builder.max_virtual_windows) - the excess builds from estimates alone, without measured corrections",
1472
+ .{canvas.max_virtual_windows},
1473
+ );
1474
+ return null;
1475
+ }
1476
+
1477
+ /// Post-layout measure step for variable-extent virtual lists:
1478
+ /// read the freshly laid-out extent of every mounted row (the
1479
+ /// intrinsic heights the flex pass just computed) into the
1480
+ /// retained offset table, anchored on the first visible row so
1481
+ /// the pending offset delta keeps it visually fixed. Returns
1482
+ /// whether any table accumulated a correction worth the retry
1483
+ /// pass.
1484
+ fn measureVirtualWindows(self: *Self, layout: canvas.WidgetLayoutTree) bool {
1485
+ var corrected = false;
1486
+ for (self.virtual_windows[0..self.virtual_window_count]) |record| {
1487
+ if (!record.variable or record.item_count == 0) continue;
1488
+ const table = self.virtualExtentTableForId(record.id) orelse continue;
1489
+ var list_index: usize = 0;
1490
+ var found = false;
1491
+ for (layout.nodes, 0..) |node, index| {
1492
+ if (node.widget.id == record.id) {
1493
+ list_index = index;
1494
+ found = true;
1495
+ break;
1496
+ }
1497
+ }
1498
+ if (!found) continue;
1499
+ const list_node = layout.nodes[list_index];
1500
+ const content = list_node.frame.inset(list_node.widget.layout.padding).normalized();
1501
+ if (content.isEmpty()) continue;
1502
+ // The correction anchor is the row the layout pass
1503
+ // anchored the window on: it was PLACED at the table's
1504
+ // leading edge for it, so the table-belief baseline is
1505
+ // exactly its rendered position — corrections shift
1506
+ // the pending offset by however much the batch moves
1507
+ // that edge, and the anchored row stays under the
1508
+ // user's eyes.
1509
+ table.beginCorrections(list_node.widget.layout.virtual_anchor_index, null);
1510
+ for (layout.nodes) |node| {
1511
+ const parent = node.parent_index orelse continue;
1512
+ if (parent != list_index) continue;
1513
+ if (node.widget.layout.anchor != null) continue;
1514
+ const physical = node.widget.semantics.list_item_index orelse continue;
1515
+ table.recordMeasured(@intCast(physical), node.frame.normalized().height);
1516
+ }
1517
+ table.endCorrections();
1518
+ if (@abs(table.pending_offset_delta) > virtual_correction_retry_threshold) corrected = true;
1519
+ }
1520
+ return corrected;
1521
+ }
1522
+
1523
+ fn isVirtualWindowId(self: *const Self, id: canvas.ObjectId) bool {
1524
+ if (id == 0) return false;
1525
+ for (self.virtual_windows[0..self.virtual_window_count]) |record| {
1526
+ if (record.id == id) return true;
1527
+ }
1528
+ return false;
1529
+ }
1530
+
1531
+ /// Approach-end hysteresis (`on_reach_end`): fire when a scroll
1532
+ /// lands within `reach_end_fire_ratio` viewports of the content
1533
+ /// end and the region is armed; re-arm once the offset sits more
1534
+ /// than `reach_end_rearm_ratio` viewports from the end — which
1535
+ /// appending a batch causes on its own, since the extent grows
1536
+ /// under the unchanged offset. One Msg per approach, never a
1537
+ /// fetch storm from a user riding the end of the list.
1538
+ fn reachEndShouldFire(self: *Self, id: canvas.ObjectId, scroll_state: canvas.ScrollState) bool {
1539
+ if (id == 0 or scroll_state.viewport_extent <= 0) return false;
1540
+ const remaining = scroll_state.content_extent - scroll_state.viewport_extent - scroll_state.offset;
1541
+ if (remaining > scroll_state.viewport_extent * reach_end_rearm_ratio) {
1542
+ self.clearReachEndFired(id);
1543
+ return false;
1544
+ }
1545
+ if (remaining > scroll_state.viewport_extent * reach_end_fire_ratio) return false;
1546
+ if (self.reachEndFired(id)) return false;
1547
+ self.markReachEndFired(id);
1548
+ return true;
1549
+ }
1550
+
1551
+ fn reachEndFired(self: *const Self, id: canvas.ObjectId) bool {
1552
+ for (self.reach_end_fired_ids) |fired| {
1553
+ if (fired == id) return true;
1554
+ }
1555
+ return false;
1556
+ }
1557
+
1558
+ fn markReachEndFired(self: *Self, id: canvas.ObjectId) void {
1559
+ for (&self.reach_end_fired_ids) |*slot| {
1560
+ if (slot.* == 0 or slot.* == id) {
1561
+ slot.* = id;
1562
+ return;
1563
+ }
1564
+ }
1565
+ }
1566
+
1567
+ fn clearReachEndFired(self: *Self, id: canvas.ObjectId) void {
1568
+ for (&self.reach_end_fired_ids) |*slot| {
1569
+ if (slot.* == id) slot.* = 0;
1570
+ }
1571
+ }
1572
+
1573
+ /// Approach-START hysteresis (`on_reach_start`): the mirror of
1574
+ /// `reachEndShouldFire` measured from the content start — fire
1575
+ /// when a scroll lands within `reach_start_fire_ratio` viewports
1576
+ /// of offset 0 and the region is armed; re-arm once the offset
1577
+ /// sits more than `reach_start_rearm_ratio` viewports from the
1578
+ /// start, which prepending a batch causes on its own (the
1579
+ /// viewport anchor grows the offset by the prepended extent).
1580
+ /// Same programmatic-jump nuance as reach-end: hysteresis state
1581
+ /// only moves on scroll OBSERVATIONS, so a programmatic jump out
1582
+ /// of the band re-arms on the next user scroll, not instantly.
1583
+ fn reachStartShouldFire(self: *Self, id: canvas.ObjectId, scroll_state: canvas.ScrollState) bool {
1584
+ if (id == 0 or scroll_state.viewport_extent <= 0) return false;
1585
+ const remaining = scroll_state.offset;
1586
+ if (remaining > scroll_state.viewport_extent * reach_start_rearm_ratio) {
1587
+ self.clearReachStartFired(id);
1588
+ return false;
1589
+ }
1590
+ if (remaining > scroll_state.viewport_extent * reach_start_fire_ratio) return false;
1591
+ if (self.reachStartFired(id)) return false;
1592
+ self.markReachStartFired(id);
1593
+ return true;
1594
+ }
1595
+
1596
+ fn reachStartFired(self: *const Self, id: canvas.ObjectId) bool {
1597
+ for (self.reach_start_fired_ids) |fired| {
1598
+ if (fired == id) return true;
1599
+ }
1600
+ return false;
1601
+ }
1602
+
1603
+ fn markReachStartFired(self: *Self, id: canvas.ObjectId) void {
1604
+ for (&self.reach_start_fired_ids) |*slot| {
1605
+ if (slot.* == 0 or slot.* == id) {
1606
+ slot.* = id;
1607
+ return;
1608
+ }
1609
+ }
1610
+ }
1611
+
1612
+ fn clearReachStartFired(self: *Self, id: canvas.ObjectId) void {
1613
+ for (&self.reach_start_fired_ids) |*slot| {
1614
+ if (slot.* == id) slot.* = 0;
1615
+ }
1616
+ }
1617
+
1618
+ /// Reconcile the model-declared secondary windows against the
1619
+ /// live ones (the `status_item_fn` shape applied to the window
1620
+ /// set): close what the model stopped declaring, create what it
1621
+ /// started declaring. Failures degrade to logged warnings — a
1622
+ /// failed window create never takes the render loop down.
1623
+ fn applyWindows(self: *Self, runtime: *Runtime) void {
1624
+ const windows_fn = self.options.windows_fn orelse return;
1625
+ var declared = windows_fn(&self.model, &self.windows_scratch);
1626
+ if (declared.len > max_ui_windows) {
1627
+ ui_app_log.warn(
1628
+ "windows_fn declared {d} windows; the budget is {d} (canvas_limits.max_ui_app_windows) - the excess is ignored",
1629
+ .{ declared.len, max_ui_windows },
1630
+ );
1631
+ declared = declared[0..max_ui_windows];
1632
+ }
1633
+
1634
+ // Close first: a label leaving the declared set frees its
1635
+ // slot (and its runtime window label) before creations run.
1636
+ var index: usize = 0;
1637
+ while (index < self.window_slot_count) {
1638
+ if (declaredWindowIndex(declared, self.window_slots[index].label()) == null) {
1639
+ self.closeWindowSlot(runtime, index);
1640
+ continue;
1641
+ }
1642
+ index += 1;
1643
+ }
1644
+
1645
+ for (declared) |descriptor| {
1646
+ if (self.windowSlotIndexByLabel(descriptor.label)) |slot_index| {
1647
+ // Already live: the close Msg follows the model.
1648
+ self.window_slots[slot_index].on_close = descriptor.on_close;
1649
+ continue;
1650
+ }
1651
+ self.createWindowSlot(runtime, descriptor);
1652
+ }
1653
+ }
1654
+
1655
+ fn declaredWindowIndex(declared: []const WindowDescriptor, label: []const u8) ?usize {
1656
+ for (declared, 0..) |descriptor, index| {
1657
+ if (std.mem.eql(u8, descriptor.label, label)) return index;
1658
+ }
1659
+ return null;
1660
+ }
1661
+
1662
+ fn windowSlotIndexByLabel(self: *Self, label: []const u8) ?usize {
1663
+ for (self.window_slots[0..self.window_slot_count], 0..) |*slot, index| {
1664
+ if (std.mem.eql(u8, slot.label(), label)) return index;
1665
+ }
1666
+ return null;
1667
+ }
1668
+
1669
+ fn windowSlotByCanvasLabel(self: *Self, canvas_label: []const u8) ?*WindowSlot {
1670
+ for (self.window_slots[0..self.window_slot_count]) |*slot| {
1671
+ if (std.mem.eql(u8, slot.canvasLabel(), canvas_label)) return slot;
1672
+ }
1673
+ return null;
1674
+ }
1675
+
1676
+ fn windowSlotIndexByWindowId(self: *Self, window_id: platform.WindowId) ?usize {
1677
+ for (self.window_slots[0..self.window_slot_count], 0..) |*slot, index| {
1678
+ if (slot.window_id == window_id) return index;
1679
+ }
1680
+ return null;
1681
+ }
1682
+
1683
+ fn createWindowSlot(self: *Self, runtime: *Runtime, descriptor: WindowDescriptor) void {
1684
+ if (self.window_slot_count >= max_ui_windows) {
1685
+ ui_app_log.warn(
1686
+ "declared window '{s}' ignored: more than {d} secondary windows (canvas_limits.max_ui_app_windows)",
1687
+ .{ descriptor.label, max_ui_windows },
1688
+ );
1689
+ return;
1690
+ }
1691
+ if (descriptor.label.len == 0 or descriptor.label.len > platform.max_window_label_bytes or
1692
+ descriptor.canvas_label.len == 0 or descriptor.canvas_label.len > app_manifest.max_view_label_bytes)
1693
+ {
1694
+ ui_app_log.warn("declared window '{s}' ignored: window and canvas labels must be non-empty and fit the platform label budgets", .{descriptor.label});
1695
+ return;
1696
+ }
1697
+ if (std.mem.eql(u8, descriptor.canvas_label, self.options.canvas_label) or self.windowSlotByCanvasLabel(descriptor.canvas_label) != null) {
1698
+ ui_app_log.warn(
1699
+ "declared window '{s}' ignored: canvas label '{s}' is already bound - every window's canvas label must be unique",
1700
+ .{ descriptor.label, descriptor.canvas_label },
1701
+ );
1702
+ return;
1703
+ }
1704
+
1705
+ const shell_views = [_]app_manifest.ShellView{self.secondaryShellView(descriptor)};
1706
+ const info = runtime.createSourcelessShellWindow(.{
1707
+ .label = descriptor.label,
1708
+ .title = if (descriptor.title.len > 0) descriptor.title else null,
1709
+ .width = descriptor.width,
1710
+ .height = descriptor.height,
1711
+ .x = descriptor.x,
1712
+ .y = descriptor.y,
1713
+ .resizable = descriptor.resizable,
1714
+ .titlebar = descriptor.titlebar,
1715
+ .min_width = descriptor.min_width,
1716
+ .min_height = descriptor.min_height,
1717
+ // Deterministic reopen: the descriptor is the geometry
1718
+ // channel, not a persisted frame store.
1719
+ .restore_state = false,
1720
+ .views = &shell_views,
1721
+ }) catch |err| {
1722
+ ui_app_log.warn("declared window '{s}' create failed: {s}", .{ descriptor.label, @errorName(err) });
1723
+ return;
1724
+ };
1725
+
1726
+ const slot = &self.window_slots[self.window_slot_count];
1727
+ slot.label_len = descriptor.label.len;
1728
+ @memcpy(slot.label_storage[0..descriptor.label.len], descriptor.label);
1729
+ slot.canvas_label_len = descriptor.canvas_label.len;
1730
+ @memcpy(slot.canvas_label_storage[0..descriptor.canvas_label.len], descriptor.canvas_label);
1731
+ slot.window_id = info.id;
1732
+ slot.on_close = descriptor.on_close;
1733
+ slot.installed = false;
1734
+ slot.canvas_size = .{ .width = descriptor.width, .height = descriptor.height };
1735
+ slot.tree = null;
1736
+ slot.arena_index = 0;
1737
+ self.window_slot_count += 1;
1738
+ }
1739
+
1740
+ /// The gpu_surface shell view for a declared window: the
1741
+ /// descriptor's canvas label wearing the MAIN canvas's declared
1742
+ /// gpu options (backend, pixel format, present mode...), so a
1743
+ /// secondary window renders through whatever pipeline the app
1744
+ /// already chose for its platform.
1745
+ fn secondaryShellView(self: *const Self, descriptor: WindowDescriptor) app_manifest.ShellView {
1746
+ var view = app_manifest.ShellView{
1747
+ .label = descriptor.canvas_label,
1748
+ .kind = .gpu_surface,
1749
+ .fill = true,
1750
+ };
1751
+ for (self.options.scene.windows) |window| {
1752
+ for (window.views) |scene_view| {
1753
+ if (scene_view.kind != .gpu_surface) continue;
1754
+ if (!std.mem.eql(u8, scene_view.label, self.options.canvas_label)) continue;
1755
+ view.gpu_backend = scene_view.gpu_backend;
1756
+ view.gpu_pixel_format = scene_view.gpu_pixel_format;
1757
+ view.gpu_present_mode = scene_view.gpu_present_mode;
1758
+ view.gpu_alpha_mode = scene_view.gpu_alpha_mode;
1759
+ view.gpu_color_space = scene_view.gpu_color_space;
1760
+ view.gpu_vsync = scene_view.gpu_vsync;
1761
+ return view;
1762
+ }
1763
+ }
1764
+ return view;
1765
+ }
1766
+
1767
+ /// Remove the slot and close its runtime window (the reconcile
1768
+ /// close: the model stopped declaring it, so no `on_close` Msg —
1769
+ /// the model already knows).
1770
+ fn closeWindowSlot(self: *Self, runtime: *Runtime, index: usize) void {
1771
+ const window_id = self.window_slots[index].window_id;
1772
+ const last = self.window_slot_count - 1;
1773
+ var removed = self.window_slots[index];
1774
+ self.window_slots[index] = self.window_slots[last];
1775
+ self.window_slots[last] = WindowSlot.init(self.backing);
1776
+ self.window_slot_count = last;
1777
+ removed.arenas[0].deinit();
1778
+ removed.arenas[1].deinit();
1779
+ runtime.closeWindow(window_id) catch |err| {
1780
+ ui_app_log.warn("declared window close failed: {s}", .{@errorName(err)});
1781
+ };
1782
+ }
1783
+
1784
+ /// Drop a slot whose runtime window is ALREADY gone (the user
1785
+ /// closed it): bookkeeping only, no platform call.
1786
+ fn forgetWindowSlot(self: *Self, index: usize) ?MsgT {
1787
+ const on_close = self.window_slots[index].on_close;
1788
+ const last = self.window_slot_count - 1;
1789
+ var removed = self.window_slots[index];
1790
+ self.window_slots[index] = self.window_slots[last];
1791
+ self.window_slots[last] = WindowSlot.init(self.backing);
1792
+ self.window_slot_count = last;
1793
+ removed.arenas[0].deinit();
1794
+ removed.arenas[1].deinit();
1795
+ return on_close;
1796
+ }
1797
+
1798
+ /// Rebuild every installed secondary window's tree from the
1799
+ /// model — every dispatched Msg funnels through here after the
1800
+ /// main rebuild, so all open windows always render the same
1801
+ /// model generation.
1802
+ fn rebuildWindowSlots(self: *Self, runtime: *Runtime) anyerror!void {
1803
+ for (self.window_slots[0..self.window_slot_count]) |*slot| {
1804
+ if (!slot.installed) continue;
1805
+ try self.rebuildWindowSlot(runtime, slot);
1806
+ }
1807
+ }
1808
+
1809
+ fn rebuildWindowSlot(self: *Self, runtime: *Runtime, slot: *WindowSlot) anyerror!void {
1810
+ const window_view = self.options.window_view orelse return;
1811
+ const tokens = runtime.tokensWithTextMeasure(self.effectiveTokens());
1812
+ const next_index = slot.arena_index ^ 1;
1813
+ _ = slot.arenas[next_index].reset(.retain_capacity);
1814
+ var ui = Ui.init(slot.arenas[next_index].allocator());
1815
+ ui.context_menu_fallback_target = self.contextMenuFallbackTargetForLabel(slot.canvasLabel());
1816
+ self.armUiFragmentHost(&ui);
1817
+ const node = window_view(&ui, &self.model, slot.label());
1818
+ const tree = try ui.finalizeWithTokens(node, tokens);
1819
+ const bounds = geometry.RectF.fromSize(slot.canvas_size).deflate(runtime.viewportInsetsForWindow(slot.window_id));
1820
+ const layout = canvas.layoutWidgetTreeWithTokens(tree.root, bounds, tokens, &self.layout_nodes) catch |err| {
1821
+ if (err == error.WidgetLayoutListFull) {
1822
+ ui_app_log.warn(
1823
+ "widget layout capacity exceeded for window '{s}' view '{s}': the per-view budget is {d} nodes (canvas_limits.max_canvas_widget_nodes_per_view) - reduce always-mounted widgets or virtualize lists",
1824
+ .{ slot.label(), slot.canvasLabel(), canvas_limits.max_canvas_widget_nodes_per_view },
1825
+ );
1826
+ }
1827
+ return err;
1828
+ };
1829
+ _ = try runtime.setCanvasWidgetLayout(slot.window_id, slot.canvasLabel(), layout);
1830
+ if (slot.installed and self.derivesTokens()) {
1831
+ _ = try runtime.emitCanvasWidgetDisplayList(slot.window_id, slot.canvasLabel(), tokens);
1832
+ }
1833
+ slot.tree = tree;
1834
+ slot.arena_index = next_index;
1835
+ // Same close-on-vanish rule as the main canvas rebuild.
1836
+ if (self.contextMenuFallbackTargetForLabel(slot.canvasLabel()) != 0 and tree.context_menu_fallback == null) {
1837
+ self.clearContextMenuFallback();
1838
+ }
1839
+ }
1840
+
1841
+ /// Re-apply the model-derived webview panes against the freshly
1842
+ /// computed widget layout: resolve each pane's anchor widget to a
1843
+ /// frame, then patch the scene's webview shell view when the
1844
+ /// frame, URL, or reload token changed. Failures degrade to a
1845
+ /// logged warning so a missing webview or a denied origin never
1846
+ /// takes the render loop down.
1847
+ fn applyWebPanes(self: *Self, runtime: *Runtime, window_id: platform.WindowId, layout: canvas.WidgetLayoutTree) void {
1848
+ const panes_fn = self.options.web_panes orelse return;
1849
+ var panes: [max_web_panes]WebViewPane = undefined;
1850
+ const count = @min(panes_fn(&self.model, &panes), max_web_panes);
1851
+ for (panes[0..count]) |pane| self.applyWebPane(runtime, window_id, layout, pane);
1852
+ }
1853
+
1854
+ fn applyWebPane(self: *Self, runtime: *Runtime, window_id: platform.WindowId, layout: canvas.WidgetLayoutTree, pane: WebViewPane) void {
1855
+ var frame = pane.frame;
1856
+ if (pane.anchor) |anchor| {
1857
+ frame = webPaneAnchorFrame(layout, anchor) orelse {
1858
+ ui_app_log.warn(
1859
+ "webview pane '{s}': no canvas widget carries semantics label '{s}' - mark the region's widget with .semantics = .{{ .label = \"{s}\" }}",
1860
+ .{ pane.label, anchor, anchor },
1861
+ );
1862
+ return;
1863
+ };
1864
+ }
1865
+ // Platform webview frames require a positive size and a
1866
+ // non-negative origin; a collapsed or clipped anchor keeps
1867
+ // the last applied frame instead of erroring every rebuild.
1868
+ if (frame.width < 1 or frame.height < 1) return;
1869
+ frame.x = @max(frame.x, 0);
1870
+ frame.y = @max(frame.y, 0);
1871
+
1872
+ const state = self.webPaneState(pane.label) orelse {
1873
+ ui_app_log.warn("webview pane '{s}' ignored: more than {d} distinct pane labels", .{ pane.label, max_web_panes });
1874
+ return;
1875
+ };
1876
+ // Reconcile the frame against the runtime's actual webview
1877
+ // state rather than a cache: shell relayouts (window moves,
1878
+ // startup restores) reset scene webviews to their declared
1879
+ // frames behind the app's back, and each such reset
1880
+ // invalidates the canvas, so the next frame flows back
1881
+ // through here and re-snaps the pane.
1882
+ const actual_frame = runtime.webViewLocalFrame(window_id, pane.label) orelse {
1883
+ ui_app_log.warn(
1884
+ "webview pane '{s}': the scene declares no .webview shell view with this label",
1885
+ .{pane.label},
1886
+ );
1887
+ return;
1888
+ };
1889
+ var patch: platform.ViewPatch = .{};
1890
+ if (!rectsAlmostEqual(actual_frame, frame)) patch.frame = frame;
1891
+ const first_apply = state.url_len == 0;
1892
+ if (pane.url.len > 0 and (first_apply or !std.mem.eql(u8, state.url(), pane.url) or state.reload_token != pane.reload_token)) patch.url = pane.url;
1893
+ if (patch.frame == null and patch.url == null) return;
1894
+
1895
+ _ = runtime.updateView(window_id, pane.label, patch) catch |err| {
1896
+ ui_app_log.warn(
1897
+ "webview pane '{s}' update failed: {s} - the scene must declare a .webview shell view with this label and the URL's origin must be in security.navigation.allowed_origins",
1898
+ .{ pane.label, @errorName(err) },
1899
+ );
1900
+ return;
1901
+ };
1902
+ state.reload_token = pane.reload_token;
1903
+ const url_len = @min(pane.url.len, state.url_storage.len);
1904
+ @memcpy(state.url_storage[0..url_len], pane.url[0..url_len]);
1905
+ state.url_len = url_len;
1906
+ }
1907
+
1908
+ /// Find or insert the applied-state slot for a pane label.
1909
+ fn webPaneState(self: *Self, label: []const u8) ?*WebPaneState {
1910
+ for (self.web_pane_states[0..self.web_pane_state_count]) |*state| {
1911
+ if (std.mem.eql(u8, state.label(), label)) return state;
1912
+ }
1913
+ if (self.web_pane_state_count >= max_web_panes) return null;
1914
+ const state = &self.web_pane_states[self.web_pane_state_count];
1915
+ state.* = .{};
1916
+ const label_len = @min(label.len, state.label_storage.len);
1917
+ @memcpy(state.label_storage[0..label_len], label[0..label_len]);
1918
+ state.label_len = label_len;
1919
+ self.web_pane_state_count += 1;
1920
+ return state;
1921
+ }
1922
+
1923
+ /// The layout frame of the first widget whose semantics label
1924
+ /// matches `anchor`.
1925
+ fn webPaneAnchorFrame(layout: canvas.WidgetLayoutTree, anchor: []const u8) ?geometry.RectF {
1926
+ for (layout.nodes) |node| {
1927
+ if (std.mem.eql(u8, node.widget.semantics.label, anchor)) return node.frame;
1928
+ }
1929
+ return null;
1930
+ }
1931
+
1932
+ fn rectsAlmostEqual(a: geometry.RectF, b: geometry.RectF) bool {
1933
+ const epsilon: f32 = 0.25;
1934
+ return @abs(a.x - b.x) < epsilon and
1935
+ @abs(a.y - b.y) < epsilon and
1936
+ @abs(a.width - b.width) < epsilon and
1937
+ @abs(a.height - b.height) < epsilon;
1938
+ }
1939
+
1940
+ /// Rebuild the retained display list around the reconciled widget
1941
+ /// layout: chrome prefix, widget commands, chrome suffix. The
1942
+ /// runtime then regenerates the widget span on internal state
1943
+ /// changes while preserving the chrome via
1944
+ /// `emitCanvasWidgetDisplayListWithChrome`.
1945
+ fn installChromeDisplayList(self: *Self, runtime: *Runtime, window_id: platform.WindowId, chrome: ChromeOptions, layout: canvas.WidgetLayoutTree, tokens: canvas.DesignTokens) anyerror!void {
1946
+ var chrome_commands: [canvas_limits.max_canvas_commands_per_view]canvas.CanvasCommand = undefined;
1947
+ var chrome_builder = canvas.Builder.init(&chrome_commands);
1948
+ try chrome.build(&self.model, &chrome_builder, self.canvas_size, tokens);
1949
+ const chrome_list = chrome_builder.displayList();
1950
+ if (chrome_list.commands.len != chrome.prefix_commands + chrome.suffix_commands) {
1951
+ return error.InvalidChromeCommandCount;
1952
+ }
1953
+
1954
+ var commands: [canvas_limits.max_canvas_commands_per_view]canvas.CanvasCommand = undefined;
1955
+ var builder = canvas.Builder.init(&commands);
1956
+ for (chrome_list.commands[0..chrome.prefix_commands]) |command| try builder.append(command);
1957
+ try layout.emitDisplayList(&builder, tokens);
1958
+ for (chrome_list.commands[chrome.prefix_commands..]) |command| try builder.append(command);
1959
+
1960
+ _ = try runtime.setCanvasDisplayList(window_id, self.options.canvas_label, builder.displayList());
1961
+ _ = try runtime.setCanvasWidgetLayout(window_id, self.options.canvas_label, layout);
1962
+ _ = try runtime.emitCanvasWidgetDisplayListWithChrome(window_id, self.options.canvas_label, tokens, .{
1963
+ .prefix_command_count = chrome.prefix_commands,
1964
+ .suffix_command_count = chrome.suffix_commands,
1965
+ });
1966
+ }
1967
+
1968
+ /// Re-apply the model-derived render animations with the latest
1969
+ /// frame timestamp.
1970
+ fn scheduleAnimations(self: *Self, runtime: *Runtime, window_id: platform.WindowId) anyerror!void {
1971
+ const animations_fn = self.options.animations orelse return;
1972
+ const tree = &(self.tree orelse return);
1973
+ var animations: [canvas_limits.max_canvas_render_animations_per_view]canvas.CanvasRenderAnimation = undefined;
1974
+ const count = animations_fn(&self.model, tree, self.frame_timestamp_ns, &animations);
1975
+ _ = try runtime.setCanvasRenderAnimations(window_id, self.options.canvas_label, animations[0..count]);
1976
+ }
1977
+
1978
+ /// Re-declare the model-derived layout tweens after a rebuild.
1979
+ /// `startCanvasWidgetLayoutTween` is idempotent per target, so
1980
+ /// declaring on every rebuild arms a tween exactly when the
1981
+ /// declared target diverges from the rendered value — the
1982
+ /// declarative twin of `scheduleAnimations`. A stale id (the
1983
+ /// widget left the tree this rebuild) is skipped, not an error:
1984
+ /// the hook reads the CURRENT tree, so ids are normally fresh.
1985
+ fn scheduleLayoutTweens(self: *Self, runtime: *Runtime, window_id: platform.WindowId) anyerror!void {
1986
+ const layout_tweens_fn = self.options.layout_tweens orelse return;
1987
+ const tree = &(self.tree orelse return);
1988
+ var tweens: [canvas_limits.max_canvas_widget_layout_tweens_per_view]canvas.CanvasWidgetLayoutTween = undefined;
1989
+ const count = layout_tweens_fn(&self.model, tree, &tweens);
1990
+ for (tweens[0..@min(count, tweens.len)]) |tween| {
1991
+ _ = runtime.startCanvasWidgetLayoutTween(window_id, self.options.canvas_label, tween) catch |err| switch (err) {
1992
+ error.InvalidCommand => continue,
1993
+ else => return err,
1994
+ };
1995
+ }
1996
+ }
1997
+
1998
+ fn buildViewNode(self: *Self, ui: *Ui) anyerror!Ui.Node {
1999
+ if (comptime features.runtime_markup) {
2000
+ // A markup-only app parses its embedded source on the first
2001
+ // build; with both `view` and `markup` set, the compiled
2002
+ // view renders until the watch loads a changed source.
2003
+ if (self.markup_view == null and self.options.view == null) {
2004
+ try self.reloadMarkup(self.options.markup.?.source);
2005
+ }
2006
+ if (self.markup_view) |*view| {
2007
+ return view.build(ui, &self.model) catch |err| {
2008
+ if (err == error.MarkupBuild) {
2009
+ self.recordMarkupDiagnostic(.{
2010
+ .line = view.diagnostic.line,
2011
+ .column = view.diagnostic.column,
2012
+ .message = view.diagnostic.message,
2013
+ .path = view.diagnostic.path,
2014
+ });
2015
+ }
2016
+ return err;
2017
+ };
2018
+ }
2019
+ }
2020
+ const view = self.options.view.?;
2021
+ return view(ui, &self.model);
2022
+ }
2023
+
2024
+ /// Parse and activate a markup source (the reload seam: hot reload
2025
+ /// and tests go through this). Imports resolve against the
2026
+ /// embedded source set (`MarkupOptions.sources`). Failures keep
2027
+ /// the previous view and set `markup_diagnostic`.
2028
+ pub fn reloadMarkup(self: *Self, source: []const u8) anyerror!void {
2029
+ if (comptime !features.runtime_markup) return error.MarkupEngineDisabled;
2030
+ const sources: []const canvas.ui_markup.SourceFile = if (self.options.markup) |markup_options| markup_options.sources else &.{};
2031
+ var set_loader = canvas.ui_markup.SourceSetLoader{ .set = sources };
2032
+ var hashing = HashingLoader.init(set_loader.loader(), source, "");
2033
+ if (comptime features.runtime_markup) {
2034
+ self.provenance_closure.reset();
2035
+ hashing.closure = &self.provenance_closure;
2036
+ }
2037
+ const next_index = self.markup_arena_index ^ 1;
2038
+ _ = self.markup_arenas[next_index].reset(.retain_capacity);
2039
+ const arena = self.markup_arenas[next_index].allocator();
2040
+ const owned_source = try arena.dupe(u8, source);
2041
+ var diagnostic: canvas.ui_markup.MarkupErrorInfo = .{};
2042
+ const document = canvas.ui_markup.resolveImports(arena, "", owned_source, hashing.loader(), &diagnostic) catch |err| {
2043
+ if (err == error.MarkupSyntax or err == error.MarkupImport) self.recordMarkupDiagnostic(diagnostic);
2044
+ return err;
2045
+ };
2046
+ // The typed-document pass: attribute expressions parse once
2047
+ // here instead of on every frame's build.
2048
+ const canonical = try canvas.ui_markup.canonicalize(arena, document);
2049
+ self.adoptMarkupDocument(canonical, next_index, hashing.hasher.final());
2050
+ // Embedded resolve: root nodes carry an empty src_path, and
2051
+ // imported entries are markup-root-relative (joined onto the
2052
+ // watched file's directory for their on-disk location).
2053
+ self.commitProvenanceFiles("", owned_source, false);
2054
+ }
2055
+
2056
+ /// Activate a resolved document built into `arena_index`'s arena.
2057
+ fn adoptMarkupDocument(self: *Self, document: canvas.ui_markup.MarkupDocument, arena_index: usize, closure_hash: u64) void {
2058
+ self.markup_view = MarkupView.fromDocument(document);
2059
+ self.markup_arena_index = arena_index;
2060
+ self.markup_source_hash = closure_hash;
2061
+ self.markup_diagnostic = null;
2062
+ }
2063
+
2064
+ /// Wraps an ImportLoader so the watch's change signal covers the
2065
+ /// whole import closure: the hash folds in the root source plus
2066
+ /// every file the resolver loads, in resolution order, so an edit
2067
+ /// to an IMPORTED file reloads exactly like an edit to the root.
2068
+ /// Paths hash RELATIVE to the markup root (`strip_prefix` is the
2069
+ /// watched file's directory), so the embedded baseline — whose
2070
+ /// source-set paths are already root-relative — and the disk poll
2071
+ /// agree byte for byte when nothing changed.
2072
+ const HashingLoader = struct {
2073
+ inner: canvas.ui_markup.ImportLoader,
2074
+ hasher: std.hash.Wyhash,
2075
+ strip_prefix: []const u8 = "",
2076
+ /// Provenance staging: when set, every loaded file's
2077
+ /// resolver-relative path and content hash is recorded so the
2078
+ /// adopt step can commit them as write-back anchors.
2079
+ closure: ?*ui_app_provenance.ClosureFiles = null,
2080
+
2081
+ fn init(inner: canvas.ui_markup.ImportLoader, root_source: []const u8, strip_prefix: []const u8) HashingLoader {
2082
+ var hasher = std.hash.Wyhash.init(0);
2083
+ hasher.update(root_source);
2084
+ return .{ .inner = inner, .hasher = hasher, .strip_prefix = strip_prefix };
2085
+ }
2086
+
2087
+ fn loader(self: *HashingLoader) canvas.ui_markup.ImportLoader {
2088
+ return .{ .context = @ptrCast(self), .load = load };
2089
+ }
2090
+
2091
+ fn load(context: *const anyopaque, arena: std.mem.Allocator, path: []const u8) ?[]const u8 {
2092
+ const self: *HashingLoader = @ptrCast(@alignCast(@constCast(context)));
2093
+ const source = self.inner.load(self.inner.context, arena, path) orelse return null;
2094
+ var hashed_path = path;
2095
+ if (self.strip_prefix.len > 0 and path.len > self.strip_prefix.len and
2096
+ std.mem.startsWith(u8, path, self.strip_prefix) and path[self.strip_prefix.len] == '/')
2097
+ {
2098
+ hashed_path = path[self.strip_prefix.len + 1 ..];
2099
+ }
2100
+ self.hasher.update(hashed_path);
2101
+ self.hasher.update(&[_]u8{0});
2102
+ self.hasher.update(source);
2103
+ if (self.closure) |closure| closure.add(path, std.hash.Wyhash.hash(0, source));
2104
+ return source;
2105
+ }
2106
+ };
2107
+
2108
+ /// Commit the just-adopted closure into the provenance file
2109
+ /// table (write-back anchors: per-file loaded-bytes hashes and
2110
+ /// on-disk paths). `root_stamped` is the src_path the resolver
2111
+ /// stamped on root nodes; `entries_are_disk_paths` is true for
2112
+ /// the disk (watch) resolve, whose paths are already cwd-relative.
2113
+ /// Committed ONLY on adopt: a failed mid-edit reload keeps the
2114
+ /// last-good table so spans and hashes always describe the bytes
2115
+ /// the running view was built from.
2116
+ fn commitProvenanceFiles(self: *Self, root_stamped: []const u8, root_source: []const u8, entries_are_disk_paths: bool) void {
2117
+ if (comptime !features.runtime_markup) return;
2118
+ const markup_options = self.options.markup;
2119
+ const watch_path: ?[]const u8 = if (markup_options) |m| m.watch_path else null;
2120
+ self.provenance.resetFiles();
2121
+ self.provenance.watching = watch_path != null and (if (markup_options) |m| m.io != null else false);
2122
+ self.provenance.addFile(root_stamped, watch_path orelse "", std.hash.Wyhash.hash(0, root_source)) catch {};
2123
+ const disk_prefix: []const u8 = if (watch_path) |path| (std.fs.path.dirname(path) orelse "") else "";
2124
+ for (self.provenance_closure.entries[0..self.provenance_closure.len]) |*entry| {
2125
+ const stamped = entry.path[0..entry.path_len];
2126
+ var disk_buffer: [ui_app_provenance.max_path_bytes]u8 = undefined;
2127
+ const disk: []const u8 = if (entries_are_disk_paths)
2128
+ stamped
2129
+ else if (watch_path == null)
2130
+ ""
2131
+ else if (disk_prefix.len > 0)
2132
+ std.fmt.bufPrint(&disk_buffer, "{s}/{s}", .{ disk_prefix, stamped }) catch ""
2133
+ else
2134
+ stamped;
2135
+ self.provenance.addFile(stamped, disk, entry.hash) catch {};
2136
+ }
2137
+ }
2138
+
2139
+ /// Answer an automation `provenance` query for our canvas view
2140
+ /// from the retained table and publish the response artifact.
2141
+ /// Setting the runtime's handshake flag tells the dispatcher an
2142
+ /// answer landed (its fallback teaches when no app responds).
2143
+ fn handleProvenanceQuery(self: *Self, runtime: *Runtime, query: core.AutomationProvenanceEvent) anyerror!void {
2144
+ if (comptime !features.runtime_markup) return;
2145
+ if (!std.mem.eql(u8, query.view_label, self.options.canvas_label)) return;
2146
+ const server = runtime.options.automation orelse return;
2147
+ var buffer: [4096]u8 = undefined;
2148
+ var writer = std.Io.Writer.fixed(&buffer);
2149
+ try self.provenance.writeResponse(&writer, query.view_label, query.widget_id);
2150
+ try server.publishProvenanceResponse(writer.buffered());
2151
+ runtime.automation_provenance_published = true;
2152
+ }
2153
+
2154
+ /// Store a markup diagnostic and say it out loud once per distinct
2155
+ /// failure: build errors recur every frame, and a view that fails
2156
+ /// on its FIRST build has no last-good fallback - without a log
2157
+ /// line the developer faces a blank window and silence.
2158
+ /// Resolver messages can be arena-formatted (cycle paths, duplicate
2159
+ /// sites) and the arena resets on the next reload attempt, so the
2160
+ /// stored copy owns its bytes.
2161
+ fn recordMarkupDiagnostic(self: *Self, info: canvas.ui_markup.MarkupErrorInfo) void {
2162
+ const already_reported = if (self.markup_diagnostic) |current|
2163
+ current.line == info.line and current.column == info.column and
2164
+ std.mem.eql(u8, current.message, info.message) and std.mem.eql(u8, current.path, info.path)
2165
+ else
2166
+ false;
2167
+ if (!already_reported) {
2168
+ // std.debug.print, not std.log: the default scaffold app is
2169
+ // ReleaseFast (std.log only passes .err there), while
2170
+ // logged errors fail test suites that exercise bad markup
2171
+ // on purpose. Direct stderr is visible in both.
2172
+ if (info.path.len > 0) {
2173
+ std.debug.print("markup view failed to build ({s}:{d}:{d}): {s}\n", .{ info.path, info.line, info.column, info.message });
2174
+ } else {
2175
+ std.debug.print("markup view failed to build ({d}:{d}): {s}\n", .{ info.line, info.column, info.message });
2176
+ }
2177
+ }
2178
+ const message_len = @min(info.message.len, self.markup_diagnostic_message_storage.len);
2179
+ @memcpy(self.markup_diagnostic_message_storage[0..message_len], info.message[0..message_len]);
2180
+ const path_len = @min(info.path.len, self.markup_diagnostic_path_storage.len);
2181
+ @memcpy(self.markup_diagnostic_path_storage[0..path_len], info.path[0..path_len]);
2182
+ self.markup_diagnostic = .{
2183
+ .line = info.line,
2184
+ .column = info.column,
2185
+ .message = self.markup_diagnostic_message_storage[0..message_len],
2186
+ .path = self.markup_diagnostic_path_storage[0..path_len],
2187
+ };
2188
+ }
2189
+
2190
+ /// Dev-mode hot reload: start the repeating runtime timer that polls
2191
+ /// the watched markup file and every registered fragment. Runs
2192
+ /// once, on first install, and only when something is watchable —
2193
+ /// a root watch path with io, or (Debug only) registered fragments.
2194
+ fn startMarkupWatch(self: *Self, runtime: *Runtime) void {
2195
+ if (comptime !features.runtime_markup) return;
2196
+ const root_armed = if (self.options.markup) |markup_options|
2197
+ markup_options.watch_path != null and markup_options.io != null
2198
+ else
2199
+ false;
2200
+ if (root_armed) {
2201
+ const markup_options = self.options.markup.?;
2202
+ // With a compiled `view` also set, the embedded sources are
2203
+ // the baseline: the interpreter only takes over once the
2204
+ // watched closure diverges from them. The baseline hash must
2205
+ // be computed the way the poll computes it — over the whole
2206
+ // resolved import closure — or the first poll would flag a
2207
+ // phantom change.
2208
+ if (self.options.view != null and self.markup_source_hash == 0) {
2209
+ self.markup_source_hash = self.embeddedMarkupClosureHash(markup_options);
2210
+ }
2211
+ }
2212
+ const fragments_armed = self.armFragmentWatch();
2213
+ if (!root_armed and !fragments_armed) return;
2214
+ runtime.startTimer(markup_watch_timer_id, markup_watch_interval_ns, true) catch {};
2215
+ // Make the armed watch observable: the automation snapshot
2216
+ // header reports `markup_watch=armed|off`, so a dev loop can
2217
+ // check the watch instead of bisecting an app that never
2218
+ // reloads. The bit stays honest for hybrid apps: registered
2219
+ // fragments arm it in Debug, and in release — where the
2220
+ // fragment watch compiles out — a compiled-only app reports
2221
+ // off.
2222
+ if (comptime @hasDecl(Runtime, "setMarkupWatchArmed")) {
2223
+ runtime.setMarkupWatchArmed(true);
2224
+ }
2225
+ }
2226
+
2227
+ /// Seed every registered fragment slot's baseline hash from its
2228
+ /// embedded sources (computed the way the poll computes disk
2229
+ /// hashes, so an untouched file never phantom-reloads). Returns
2230
+ /// whether any fragment is actually watched.
2231
+ fn armFragmentWatch(self: *Self) bool {
2232
+ if (comptime !fragment_watch_enabled) return false;
2233
+ const fragment_watch = self.options.fragment_watch orelse return false;
2234
+ if (fragment_watch.fragments.len > max_watched_fragments) {
2235
+ ui_app_log.warn(
2236
+ "fragment watch: {d} fragments registered but the watch budget is {d} (max_watched_fragments) - the rest stay compiled-only; consolidate fragments or raise the budget",
2237
+ .{ fragment_watch.fragments.len, max_watched_fragments },
2238
+ );
2239
+ }
2240
+ const count = @min(fragment_watch.fragments.len, max_watched_fragments);
2241
+ for (fragment_watch.fragments[0..count], self.markup_fragment_slots[0..count]) |spec, *slot| {
2242
+ // Baseline into the slot's inactive arena — reset on the
2243
+ // next reload attempt, so this costs nothing durable.
2244
+ const scratch_index = slot.arena_index ^ 1;
2245
+ _ = slot.arenas[scratch_index].reset(.retain_capacity);
2246
+ slot.baseline_hash = embeddedClosureHash(slot.arenas[scratch_index].allocator(), spec.source, spec.sources);
2247
+ slot.hash = slot.baseline_hash;
2248
+ }
2249
+ return count > 0;
2250
+ }
2251
+
2252
+ fn embeddedMarkupClosureHash(self: *Self, markup_options: MarkupOptions) u64 {
2253
+ // Resolve into the inactive scratch arena purely for the
2254
+ // hashing side effect; the arena resets on the next reload.
2255
+ const scratch_index = self.markup_arena_index ^ 1;
2256
+ _ = self.markup_arenas[scratch_index].reset(.retain_capacity);
2257
+ return embeddedClosureHash(self.markup_arenas[scratch_index].allocator(), markup_options.source, markup_options.sources);
2258
+ }
2259
+
2260
+ /// Hash an embedded source closure exactly like the disk poll
2261
+ /// hashes the on-disk one: root bytes plus every loaded file's
2262
+ /// root-relative path and bytes, in resolution order.
2263
+ fn embeddedClosureHash(arena: std.mem.Allocator, source: []const u8, sources: []const canvas.ui_markup.SourceFile) u64 {
2264
+ if (sources.len == 0) {
2265
+ return std.hash.Wyhash.hash(0, source);
2266
+ }
2267
+ var set_loader = canvas.ui_markup.SourceSetLoader{ .set = sources };
2268
+ var hashing = HashingLoader.init(set_loader.loader(), source, "");
2269
+ var diagnostic: canvas.ui_markup.MarkupErrorInfo = .{};
2270
+ _ = canvas.ui_markup.resolveImports(
2271
+ arena,
2272
+ "",
2273
+ source,
2274
+ hashing.loader(),
2275
+ &diagnostic,
2276
+ ) catch {};
2277
+ return hashing.hasher.final();
2278
+ }
2279
+
2280
+ /// Timer-driven poll of the watched markup closure: re-resolve
2281
+ /// from disk (imports relative to the watched file) and re-parse
2282
+ /// when any file in the closure changes. A failed parse or resolve
2283
+ /// keeps the last good view running and records the diagnostic. A
2284
+ /// successful reload rebuilds, which invalidates the canvas and
2285
+ /// schedules the presenting frame.
2286
+ fn pollMarkupWatch(self: *Self, runtime: *Runtime, window_id: platform.WindowId) void {
2287
+ if (comptime !features.runtime_markup) return;
2288
+ const markup_options = self.options.markup orelse return;
2289
+ const watch_path = markup_options.watch_path orelse return;
2290
+ const io = markup_options.io orelse return;
2291
+
2292
+ const next_index = self.markup_arena_index ^ 1;
2293
+ _ = self.markup_arenas[next_index].reset(.retain_capacity);
2294
+ const arena = self.markup_arenas[next_index].allocator();
2295
+ const source = readMarkupFile(io, arena, watch_path) orelse return;
2296
+ var disk_loader = DiskImportLoader{ .io = io };
2297
+ const watch_dir = std.fs.path.dirname(watch_path) orelse "";
2298
+ var hashing = HashingLoader.init(disk_loader.loader(), source, watch_dir);
2299
+ if (comptime features.runtime_markup) {
2300
+ self.provenance_closure.reset();
2301
+ hashing.closure = &self.provenance_closure;
2302
+ }
2303
+ var diagnostic: canvas.ui_markup.MarkupErrorInfo = .{};
2304
+ const document = canvas.ui_markup.resolveImports(arena, watch_path, source, hashing.loader(), &diagnostic) catch |err| {
2305
+ const hash = hashing.hasher.final();
2306
+ if (hash == self.markup_source_hash) return;
2307
+ self.markup_source_hash = hash;
2308
+ if (err == error.MarkupSyntax or err == error.MarkupImport) {
2309
+ self.recordMarkupDiagnostic(diagnostic);
2310
+ }
2311
+ return;
2312
+ };
2313
+ const hash = hashing.hasher.final();
2314
+ if (hash == self.markup_source_hash) return;
2315
+ // Canonicalize for per-frame cost only; on OOM the raw
2316
+ // document builds identically through attrTyped's fallback.
2317
+ const canonical = canvas.ui_markup.canonicalize(arena, document) catch document;
2318
+ self.adoptMarkupDocument(canonical, next_index, hash);
2319
+ // Disk resolve: root nodes carry the watch path, and imported
2320
+ // entries are already cwd-relative disk paths.
2321
+ self.commitProvenanceFiles(watch_path, source, true);
2322
+ if (self.installed) self.rebuild(runtime, window_id) catch {};
2323
+ }
2324
+
2325
+ /// Timer-driven poll of every registered fragment (Debug dev runs
2326
+ /// only), riding the same reserved timer as the root watch. Each
2327
+ /// fragment's whole import closure is re-resolved and hashed per
2328
+ /// poll, so a change to a SHARED imported file reloads every
2329
+ /// fragment whose closure reaches it — one edit, one rebuild, all
2330
+ /// dependents fresh. Same degrade family as the root watch: a
2331
+ /// failed parse keeps that fragment's last good view and records
2332
+ /// the file:line diagnostic; a save matching the embedded
2333
+ /// baseline drops the fragment back to its compiled path.
2334
+ fn pollFragmentWatch(self: *Self, runtime: *Runtime) void {
2335
+ if (comptime !fragment_watch_enabled) return;
2336
+ const fragment_watch = self.options.fragment_watch orelse return;
2337
+ const count = @min(fragment_watch.fragments.len, max_watched_fragments);
2338
+ var any_adopted = false;
2339
+ for (fragment_watch.fragments[0..count], self.markup_fragment_slots[0..count]) |spec, *slot| {
2340
+ const next_index = slot.arena_index ^ 1;
2341
+ _ = slot.arenas[next_index].reset(.retain_capacity);
2342
+ const arena = slot.arenas[next_index].allocator();
2343
+ const source = readMarkupFile(fragment_watch.io, arena, spec.path) orelse continue;
2344
+ var disk_loader = DiskImportLoader{ .io = fragment_watch.io };
2345
+ const watch_dir = std.fs.path.dirname(spec.path) orelse "";
2346
+ var hashing = HashingLoader.init(disk_loader.loader(), source, watch_dir);
2347
+ var diagnostic: canvas.ui_markup.MarkupErrorInfo = .{};
2348
+ const document = canvas.ui_markup.resolveImports(arena, spec.path, source, hashing.loader(), &diagnostic) catch |err| {
2349
+ const hash = hashing.hasher.final();
2350
+ if (hash == slot.hash) continue;
2351
+ slot.hash = hash;
2352
+ if (err == error.MarkupSyntax or err == error.MarkupImport) {
2353
+ self.recordMarkupDiagnostic(diagnostic);
2354
+ }
2355
+ continue;
2356
+ };
2357
+ const hash = hashing.hasher.final();
2358
+ if (hash == slot.hash) continue;
2359
+ slot.hash = hash;
2360
+ if (hash == slot.baseline_hash) {
2361
+ // The edit was reverted byte for byte: back to the
2362
+ // comptime-compiled path, the release-identical one.
2363
+ slot.document = null;
2364
+ } else {
2365
+ // Canonicalize for per-frame cost only; on OOM the raw
2366
+ // document builds identically through attrTyped's
2367
+ // fallback.
2368
+ slot.document = canvas.ui_markup.canonicalize(arena, document) catch document;
2369
+ }
2370
+ slot.arena_index = next_index;
2371
+ // One diagnostic channel, adopt clears it — the root
2372
+ // watch's contract (`adoptMarkupDocument`): the dev loop
2373
+ // edits one file at a time, and the recovering save is
2374
+ // what should silence the teaching line.
2375
+ self.markup_diagnostic = null;
2376
+ any_adopted = true;
2377
+ }
2378
+ // Fragments build wherever the app's views embed them — the
2379
+ // main canvas and declared windows — so a reload re-derives
2380
+ // every open view.
2381
+ if (any_adopted and self.installed) self.rebuildAllViews(runtime) catch {};
2382
+ }
2383
+
2384
+ /// The `override` half of the fragment hot-reload seam (see
2385
+ /// `canvas.MarkupFragmentHost`): a compiled fragment asks by
2386
+ /// identity key whether the watch adopted a changed document for
2387
+ /// it. Null keeps the comptime-compiled path.
2388
+ fn markupFragmentOverride(context: *anyopaque, key: *const anyopaque) ?*const anyopaque {
2389
+ if (comptime !fragment_watch_enabled) return null;
2390
+ const self: *Self = @ptrCast(@alignCast(context));
2391
+ const fragment_watch = self.options.fragment_watch orelse return null;
2392
+ const count = @min(fragment_watch.fragments.len, max_watched_fragments);
2393
+ for (fragment_watch.fragments[0..count], self.markup_fragment_slots[0..count]) |spec, *slot| {
2394
+ const spec_key = spec.key orelse continue;
2395
+ if (spec_key != key) continue;
2396
+ if (slot.document) |*document| return @ptrCast(document);
2397
+ return null;
2398
+ }
2399
+ return null;
2400
+ }
2401
+
2402
+ /// The `report` half of the fragment hot-reload seam: a reloaded
2403
+ /// fragment that parses but cannot build against this Model/Msg
2404
+ /// surfaces the same file:line teaching diagnostic the root
2405
+ /// watch's build failures do.
2406
+ fn markupFragmentReport(context: *anyopaque, diagnostic: canvas.MarkupFragmentDiagnostic) void {
2407
+ if (comptime !fragment_watch_enabled) return;
2408
+ const self: *Self = @ptrCast(@alignCast(context));
2409
+ self.recordMarkupDiagnostic(.{
2410
+ .line = diagnostic.line,
2411
+ .column = diagnostic.column,
2412
+ .message = diagnostic.message,
2413
+ .path = diagnostic.path,
2414
+ });
2415
+ }
2416
+
2417
+ /// Arm the fragment hot-reload seam on a freshly initialized Ui
2418
+ /// (both the main canvas and declared-window builds), so compiled
2419
+ /// fragments built anywhere in the app can pick up their reloaded
2420
+ /// documents. No-op unless the fragment watch exists and the app
2421
+ /// registered fragments.
2422
+ fn armUiFragmentHost(self: *Self, ui: *Ui) void {
2423
+ if (comptime !fragment_watch_enabled) return;
2424
+ if (self.options.fragment_watch == null) return;
2425
+ ui.markup_fragment_host = .{
2426
+ .context = @ptrCast(self),
2427
+ .override = markupFragmentOverride,
2428
+ .report = markupFragmentReport,
2429
+ };
2430
+ }
2431
+
2432
+ /// Disk-backed import loader for the watch: paths come out of the
2433
+ /// resolver already relative to the process cwd (they are joined
2434
+ /// against the watched file's path, which is cwd-relative — the
2435
+ /// dev flow runs apps from the app root).
2436
+ const DiskImportLoader = struct {
2437
+ io: std.Io,
2438
+
2439
+ fn loader(self: *DiskImportLoader) canvas.ui_markup.ImportLoader {
2440
+ return .{ .context = @ptrCast(self), .load = load };
2441
+ }
2442
+
2443
+ fn load(context: *const anyopaque, arena: std.mem.Allocator, path: []const u8) ?[]const u8 {
2444
+ const self: *const DiskImportLoader = @ptrCast(@alignCast(context));
2445
+ return readMarkupFile(self.io, arena, path);
2446
+ }
2447
+ };
2448
+
2449
+ const max_markup_watch_file_bytes = 256 * 1024;
2450
+
2451
+ fn readMarkupFile(io: std.Io, arena: std.mem.Allocator, path: []const u8) ?[]const u8 {
2452
+ var file = std.Io.Dir.cwd().openFile(io, path, .{}) catch return null;
2453
+ defer file.close(io);
2454
+ const buffer = arena.alloc(u8, max_markup_watch_file_bytes) catch return null;
2455
+ const len = file.readPositionalAll(io, buffer, 0) catch return null;
2456
+ return buffer[0..len];
2457
+ }
2458
+
2459
+ /// Reserved framework timer id for the markup watch poll. Application
2460
+ /// timer ids must stay below `platform.reserved_timer_id_base`.
2461
+ pub const markup_watch_timer_id: u64 = platform.reserved_timer_id_base | 0x2e70_a11c;
2462
+ const markup_watch_interval_ns: u64 = 500 * std.time.ns_per_ms;
2463
+
2464
+ /// Reserved framework timer id for the press-and-hold gesture
2465
+ /// (`ElementOptions.on_hold`): armed on pointer-down over a widget
2466
+ /// with a hold handler, cancelled on release, dispatching the hold
2467
+ /// Msg when it fires first. One-shot; distinct from the markup
2468
+ /// watch id and the fx-timer range. Defined at the platform layer
2469
+ /// so `automate widget-hold` fires the same timer a real gesture
2470
+ /// arms.
2471
+ pub const press_hold_timer_id: u64 = platform.press_hold_timer_id;
2472
+ /// A desktop list-row register (press to open, hold for the
2473
+ /// menu): ~350 ms press-and-hold.
2474
+ pub const press_hold_duration_ns: u64 = 350 * std.time.ns_per_ms;
2475
+
2476
+ /// Install the menu-bar extra once, on the installing frame.
2477
+ /// Selecting one of its items dispatches the item's `command`
2478
+ /// through the ordinary `on_command` path (source `.tray`).
2479
+ /// Unsupported platforms degrade to a logged warning. With a
2480
+ /// `status_item_fn`, the model's derived title/items win from
2481
+ /// the very first frame (the static options keep icon+tooltip).
2482
+ fn installStatusItem(self: *Self, runtime: *Runtime) void {
2483
+ if (self.status_item_installed) return;
2484
+ if (self.options.status_item == null and self.options.status_item_fn == null) return;
2485
+ self.status_item_installed = true;
2486
+ const static = self.options.status_item orelse StatusItemOptions{};
2487
+ var title = static.title;
2488
+ var items = static.items;
2489
+ if (self.options.status_item_fn) |state_fn| {
2490
+ const state = state_fn(&self.model, &self.tray_scratch);
2491
+ title = state.title;
2492
+ items = state.items;
2493
+ }
2494
+ runtime.createTray(.{
2495
+ .title = title,
2496
+ .icon_path = static.icon_path,
2497
+ .tooltip = static.tooltip,
2498
+ .items = items,
2499
+ }) catch |err| {
2500
+ ui_app_log.warn("status item install failed: {s}", .{@errorName(err)});
2501
+ return;
2502
+ };
2503
+ self.tray_created = true;
2504
+ self.tray_title_hash = hashTrayTitle(title);
2505
+ self.tray_menu_hash = hashTrayMenu(items);
2506
+ }
2507
+
2508
+ /// Re-derive the tray state from the model after a rebuild and
2509
+ /// patch only what changed — the `web_panes` shape for the menu
2510
+ /// bar. Failures degrade to a logged warning; a rejected
2511
+ /// state is remembered so a static model does not warn per frame.
2512
+ fn applyStatusItem(self: *Self, runtime: *Runtime) void {
2513
+ const state_fn = self.options.status_item_fn orelse return;
2514
+ if (!self.tray_created) return;
2515
+ const state = state_fn(&self.model, &self.tray_scratch);
2516
+
2517
+ const title_hash = hashTrayTitle(state.title);
2518
+ if (title_hash != self.tray_title_hash) {
2519
+ self.tray_title_hash = title_hash;
2520
+ if (!self.tray_title_unsupported) {
2521
+ runtime.updateTrayTitle(state.title) catch |err| {
2522
+ if (err == error.UnsupportedService) {
2523
+ self.tray_title_unsupported = true;
2524
+ ui_app_log.warn("status item title updates unsupported on this platform: the menu keeps updating, the button title stays \"{s}\"-era static", .{state.title});
2525
+ } else {
2526
+ ui_app_log.warn("status item title update failed: {s}", .{@errorName(err)});
2527
+ }
2528
+ };
2529
+ }
2530
+ }
2531
+
2532
+ const menu_hash = hashTrayMenu(state.items);
2533
+ if (menu_hash != self.tray_menu_hash) {
2534
+ self.tray_menu_hash = menu_hash;
2535
+ runtime.updateTrayMenu(state.items) catch |err| {
2536
+ ui_app_log.warn("status item menu update failed: {s} (items must carry unique non-zero ids and validated command names)", .{@errorName(err)});
2537
+ };
2538
+ }
2539
+ }
2540
+
2541
+ fn sceneFn(context: *anyopaque) anyerror!app_manifest.ShellConfig {
2542
+ const self: *Self = @ptrCast(@alignCast(context));
2543
+ return self.options.scene;
2544
+ }
2545
+
2546
+ fn eventFn(context: *anyopaque, runtime: *Runtime, event_value: Event) anyerror!void {
2547
+ const self: *Self = @ptrCast(@alignCast(context));
2548
+ switch (event_value) {
2549
+ .command => |command| {
2550
+ const map = self.options.on_command orelse return;
2551
+ if (map(command.name)) |msg| {
2552
+ // Window-less command sources (status items, app
2553
+ // menus before any window focus) carry window id 0;
2554
+ // dispatch those against the canvas window.
2555
+ const window_id = if (command.window_id == 0) self.canvas_window_id else command.window_id;
2556
+ try self.dispatch(runtime, window_id, msg);
2557
+ }
2558
+ },
2559
+ .appearance_changed => |appearance| {
2560
+ const changed = !std.meta.eql(self.system_appearance, appearance);
2561
+ self.system_appearance = appearance;
2562
+ if (self.options.on_appearance) |map| {
2563
+ if (map(appearance)) |msg| {
2564
+ try self.dispatch(runtime, self.canvas_window_id, msg);
2565
+ return;
2566
+ }
2567
+ }
2568
+ // No app mapping consumed the change: when the stock
2569
+ // tokens follow the system, re-derive and re-render
2570
+ // live — flipping the OS appearance re-themes the
2571
+ // running app without a restart. Before install the
2572
+ // stored appearance alone is enough: the first build
2573
+ // reads it.
2574
+ if (changed and self.installed and self.followsSystemAppearance()) {
2575
+ try self.rebuild(runtime, self.canvas_window_id);
2576
+ if (self.options.chrome == null) {
2577
+ _ = try runtime.emitCanvasWidgetDisplayList(self.canvas_window_id, self.options.canvas_label, runtime.tokensWithTextMeasure(self.effectiveTokens()));
2578
+ }
2579
+ }
2580
+ },
2581
+ .timer => |timer_event| try self.handleTimer(runtime, timer_event),
2582
+ // Platform audio reports route back through the effects
2583
+ // channel into the app's `on_event` Msg (and journal on
2584
+ // the way — the recorded boundary).
2585
+ .audio => |audio_event| if (self.effects.takeAudioMsg(audio_event)) |msg| {
2586
+ try self.dispatch(runtime, self.canvas_window_id, msg);
2587
+ },
2588
+ .effects_wake => try self.drainEffects(runtime),
2589
+ .gpu_surface_frame => |frame_event| try self.handleFrame(runtime, frame_event),
2590
+ .gpu_surface_resized => |resize_event| try self.handleResize(runtime, resize_event),
2591
+ .canvas_widget_pointer => |pointer_event| try self.handlePointer(runtime, pointer_event),
2592
+ .canvas_widget_keyboard => |keyboard_event| try self.handleKeyboard(runtime, keyboard_event),
2593
+ .canvas_widget_scroll => |scroll_event| try self.handleScroll(runtime, scroll_event),
2594
+ .canvas_widget_context_menu => |menu_event| try self.handleContextMenu(runtime, menu_event),
2595
+ .canvas_widget_context_menu_request => |request_event| try self.handleContextMenuRequest(runtime, request_event),
2596
+ .canvas_widget_dismiss => |dismiss_event| try self.handleDismiss(runtime, dismiss_event),
2597
+ .canvas_widget_context_press => |press_event| try self.handleContextPress(runtime, press_event),
2598
+ .canvas_widget_resize => |resize_event| try self.handleWidgetResize(runtime, resize_event),
2599
+ .canvas_widget_change => |change_event| try self.handleWidgetChange(runtime, change_event),
2600
+ .window_closed => |closed| try self.handleWindowClosed(runtime, closed),
2601
+ .automation_provenance => |query| try self.handleProvenanceQuery(runtime, query),
2602
+ else => {},
2603
+ }
2604
+ }
2605
+
2606
+ /// The platform closed a window (the user clicked its close
2607
+ /// button): if it was one of ours, forget the slot — the window
2608
+ /// is already gone, the optimistic echo — and dispatch the
2609
+ /// descriptor's `on_close` Msg so the model owns the close. A
2610
+ /// model that keeps declaring the window gets it back on the
2611
+ /// next rebuild (source wins), exactly like a dismissed surface.
2612
+ fn handleWindowClosed(self: *Self, runtime: *Runtime, closed: core.WindowClosedEvent) anyerror!void {
2613
+ const index = self.windowSlotIndexByWindowId(closed.window_id) orelse return;
2614
+ const on_close = self.forgetWindowSlot(index);
2615
+ if (on_close) |msg| {
2616
+ try self.dispatch(runtime, self.canvas_window_id, msg);
2617
+ }
2618
+ }
2619
+
2620
+ /// The tree whose handler table owns events from `view_label`:
2621
+ /// the main canvas or a declared window's.
2622
+ fn treeForViewLabel(self: *Self, view_label: []const u8) ?*const Ui.Tree {
2623
+ if (std.mem.eql(u8, view_label, self.options.canvas_label)) {
2624
+ return if (self.tree) |*tree| tree else null;
2625
+ }
2626
+ if (self.windowSlotByCanvasLabel(view_label)) |slot| {
2627
+ return if (slot.tree) |*tree| tree else null;
2628
+ }
2629
+ return null;
2630
+ }
2631
+
2632
+ fn handleTimer(self: *Self, runtime: *Runtime, timer_event: platform.TimerEvent) anyerror!void {
2633
+ if (timer_event.id == markup_watch_timer_id) {
2634
+ self.pollMarkupWatch(runtime, self.canvas_window_id);
2635
+ self.pollFragmentWatch(runtime);
2636
+ return;
2637
+ }
2638
+ if (timer_event.id == press_hold_timer_id) {
2639
+ try self.firePressHold(runtime);
2640
+ return;
2641
+ }
2642
+ // Fired fx timers (`fx.startTimer`) map back to their
2643
+ // `on_fire` Msgs; their reserved-range ids never reach
2644
+ // `on_timer` (takeTimerMsg ignores ids outside the fx range).
2645
+ if (self.effects.takeTimerMsg(timer_event.id, timer_event.timestamp_ns)) |msg| {
2646
+ try self.dispatch(runtime, self.canvas_window_id, msg);
2647
+ return;
2648
+ }
2649
+ if (timer_event.id >= platform.reserved_timer_id_base) return;
2650
+ const map = self.options.on_timer orelse return;
2651
+ if (map(timer_event.id, timer_event.timestamp_ns)) |msg| {
2652
+ try self.dispatch(runtime, self.canvas_window_id, msg);
2653
+ }
2654
+ }
2655
+
2656
+ /// Register the app's declared font faces (`Options.fonts`) with
2657
+ /// the runtime, translating each failure into a teaching error
2658
+ /// naming the font and what is wrong before propagating it.
2659
+ fn registerDeclaredFonts(self: *Self, runtime: *Runtime) anyerror!void {
2660
+ for (self.options.fonts) |font| {
2661
+ runtime.registerCanvasFont(font.id, font.ttf) catch |err| {
2662
+ switch (err) {
2663
+ error.FontParseFailed => ui_app_log.warn(
2664
+ "font \"{s}\" (id {d}) failed to register: {s}",
2665
+ .{ font.name, font.id, canvas.font_ttf.parseFailureReason(font.ttf) orelse "not a parseable TrueType face" },
2666
+ ),
2667
+ error.FontTooLarge => ui_app_log.warn(
2668
+ "font \"{s}\" (id {d}) failed to register: the file is {d} bytes but the per-font budget is {d} bytes (canvas_limits.max_registered_canvas_font_bytes)",
2669
+ .{ font.name, font.id, font.ttf.len, canvas_limits.max_registered_canvas_font_bytes },
2670
+ ),
2671
+ error.FontRegistryFull => ui_app_log.warn(
2672
+ "font \"{s}\" (id {d}) failed to register: all {d} registered-font slots are in use (canvas_limits.max_registered_canvas_fonts)",
2673
+ .{ font.name, font.id, canvas_limits.max_registered_canvas_fonts },
2674
+ ),
2675
+ error.InvalidFontId => ui_app_log.warn(
2676
+ "font \"{s}\" failed to register: font id 0 is the \"inherit run font\" sentinel; choose an id at or above {d} (canvas.min_registered_font_id)",
2677
+ .{ font.name, canvas.min_registered_font_id },
2678
+ ),
2679
+ error.ReservedFontId => ui_app_log.warn(
2680
+ "font \"{s}\" (id {d}) failed to register: ids below {d} are reserved for built-in faces; choose an id at or above {d} (canvas.min_registered_font_id)",
2681
+ .{ font.name, font.id, canvas.min_registered_font_id, canvas.min_registered_font_id },
2682
+ ),
2683
+ error.FontIdInUse => ui_app_log.warn(
2684
+ "font \"{s}\" (id {d}) failed to register: that id already holds a registered face, and registered ids are permanent (atlas caches key glyphs by font id) — give each face its own id",
2685
+ .{ font.name, font.id },
2686
+ ),
2687
+ error.FontHostRegistrationUnsupported => ui_app_log.warn(
2688
+ "font \"{s}\" (id {d}) failed to register: this platform measures and draws text host-side but cannot learn app fonts, so the face could not be honored pixel-honestly",
2689
+ .{ font.name, font.id },
2690
+ ),
2691
+ else => ui_app_log.warn(
2692
+ "font \"{s}\" (id {d}) failed to register: {s}",
2693
+ .{ font.name, font.id, @errorName(err) },
2694
+ ),
2695
+ }
2696
+ return err;
2697
+ };
2698
+ }
2699
+ }
2700
+
2701
+ fn handleFrame(self: *Self, runtime: *Runtime, frame_event: platform.GpuSurfaceFrameEvent) anyerror!void {
2702
+ if (!std.mem.eql(u8, frame_event.label, self.options.canvas_label)) {
2703
+ return self.handleWindowSlotFrame(runtime, frame_event);
2704
+ }
2705
+ // Host-pumped embeds deliver no `.wake`; drain pending effect
2706
+ // results with the frame tick so this frame presents them.
2707
+ try self.drainEffects(runtime);
2708
+ self.canvas_window_id = frame_event.window_id;
2709
+ self.frame_timestamp_ns = frame_event.timestamp_ns;
2710
+ const scale = normalizedSurfaceScale(frame_event.scale_factor);
2711
+ var installing = false;
2712
+ if (!self.installed) {
2713
+ installing = true;
2714
+ self.canvas_size = frame_event.size;
2715
+ self.pixel_snap_scale = scale;
2716
+ // Fonts first: the installing rebuild below is the first
2717
+ // layout, and it must already measure with the registered
2718
+ // faces. Exactly-once, like init_fx — a failure surfaces
2719
+ // through the dispatch error channel and does not retry
2720
+ // every frame.
2721
+ if (!self.fonts_registered) {
2722
+ self.fonts_registered = true;
2723
+ try registerDeclaredFonts(self, runtime);
2724
+ }
2725
+ if (self.options.init_fx) |init_fx| {
2726
+ if (!self.init_fx_ran) {
2727
+ self.init_fx_ran = true;
2728
+ self.bindEffectsChannel(runtime);
2729
+ init_fx(&self.model, &self.effects);
2730
+ self.publishAudioState(runtime);
2731
+ // Launch lap (env-gated): boot-effect cost (asset
2732
+ // decode/registration) splits out of the
2733
+ // scene_loaded -> first_view_built window.
2734
+ launch_timing.lapOnce("init_fx_done");
2735
+ }
2736
+ }
2737
+ // Chrome insets reach the model BEFORE the first view
2738
+ // build (`applyMsg`, no dispatch — the installing
2739
+ // rebuild below is the one that renders it), so a
2740
+ // hidden-titlebar header is padded in the very first
2741
+ // paint.
2742
+ if (self.chromeInsetsMsg(runtime, frame_event.window_id)) |msg| {
2743
+ self.applyMsg(msg);
2744
+ }
2745
+ try self.rebuild(runtime, frame_event.window_id);
2746
+ if (self.options.chrome == null) {
2747
+ _ = try runtime.emitCanvasWidgetDisplayList(frame_event.window_id, self.options.canvas_label, runtime.tokensWithTextMeasure(self.effectiveTokens()));
2748
+ }
2749
+ self.installed = true;
2750
+ self.startMarkupWatch(runtime);
2751
+ self.installStatusItem(runtime);
2752
+ } else if (self.derivesTokens() and @abs(self.pixel_snap_scale - scale) > 0.001) {
2753
+ self.pixel_snap_scale = scale;
2754
+ try self.rebuild(runtime, frame_event.window_id);
2755
+ } else if (self.options.web_panes != null) {
2756
+ // Re-snap the webview panes each presented frame: a shell
2757
+ // relayout that stomped a pane frame also invalidated the
2758
+ // canvas, so the reconciliation ride-along here converges
2759
+ // without a dedicated event.
2760
+ if (runtime.canvasWidgetLayout(frame_event.window_id, self.options.canvas_label)) |layout| {
2761
+ self.applyWebPanes(runtime, frame_event.window_id, layout);
2762
+ } else |_| {}
2763
+ }
2764
+ try self.presentFrame(runtime, frame_event, self.options.canvas_label, installing);
2765
+ if (installing) return;
2766
+ const on_frame = self.options.on_frame orelse return;
2767
+ const gpu_frame = runtime.gpuSurfaceFrame(frame_event.window_id, self.options.canvas_label) catch return;
2768
+ if (on_frame(&self.model, gpu_frame)) |msg| {
2769
+ try self.dispatch(runtime, frame_event.window_id, msg);
2770
+ }
2771
+ }
2772
+
2773
+ /// A presented frame for one of the declared secondary windows:
2774
+ /// install its tree on the first frame (the same choreography as
2775
+ /// the main canvas — build, hand the layout to the runtime, emit
2776
+ /// the display list), then present through the shared planner
2777
+ /// buffers. Frames for labels no window owns are ignored.
2778
+ fn handleWindowSlotFrame(self: *Self, runtime: *Runtime, frame_event: platform.GpuSurfaceFrameEvent) anyerror!void {
2779
+ const slot = self.windowSlotByCanvasLabel(frame_event.label) orelse return;
2780
+ slot.window_id = frame_event.window_id;
2781
+ var installing = false;
2782
+ if (!slot.installed) {
2783
+ installing = true;
2784
+ slot.canvas_size = frame_event.size;
2785
+ try self.rebuildWindowSlot(runtime, slot);
2786
+ _ = try runtime.emitCanvasWidgetDisplayList(slot.window_id, slot.canvasLabel(), runtime.tokensWithTextMeasure(self.effectiveTokens()));
2787
+ slot.installed = true;
2788
+ }
2789
+ try self.presentFrame(runtime, frame_event, slot.canvasLabel(), installing);
2790
+ }
2791
+
2792
+ /// Present the planned canvas frame: GPU packet when the platform
2793
+ /// has a packet presenter (macOS/Metal — unchanged), otherwise the
2794
+ /// CPU reference-rendered pixel path (`presentGpuSurfacePixels`,
2795
+ /// e.g. Linux/GTK). A platform whose packet presenter exists but
2796
+ /// reports `UnsupportedService` at present time also falls back to
2797
+ /// pixels; that attempt forces a full repaint because the failed
2798
+ /// packet plan already recorded the frame's presented summary.
2799
+ fn presentFrame(self: *Self, runtime: *Runtime, frame_event: platform.GpuSurfaceFrameEvent, canvas_label: []const u8, installing: bool) anyerror!void {
2800
+ // The installing frame must paint unconditionally: on software
2801
+ // platforms with no window-manager-driven resizes, nothing else
2802
+ // invalidates before the first present, and the surface would
2803
+ // stay blank until the first input arrives.
2804
+ const services = runtime.options.platform.services;
2805
+ const clear_color = self.effectiveTokens().colors.background;
2806
+ var packet_attempted = false;
2807
+ if (services.present_gpu_surface_packet_fn != null or services.present_gpu_surface_packet_binary_fn != null) {
2808
+ packet_attempted = true;
2809
+ const packet_presented = blk: {
2810
+ _ = runtime.presentNextCanvasGpuPacketWithScale(
2811
+ frame_event.window_id,
2812
+ canvas_label,
2813
+ .{
2814
+ .frame_index = frame_event.frame_index,
2815
+ .timestamp_ns = frame_event.timestamp_ns,
2816
+ .surface_size = frame_event.size,
2817
+ .scale = frame_event.scale_factor,
2818
+ .full_repaint = frame_event.canvas_frame_full_repaint or installing,
2819
+ },
2820
+ runtime.canvasFrameScratchStorage(),
2821
+ clear_color,
2822
+ &self.gpu_commands,
2823
+ &self.packet_bytes,
2824
+ null,
2825
+ ) catch |err| switch (err) {
2826
+ error.UnsupportedService => break :blk false,
2827
+ else => return err,
2828
+ };
2829
+ break :blk true;
2830
+ };
2831
+ if (packet_presented) return;
2832
+ }
2833
+ if (services.present_gpu_surface_pixels_fn == null) return;
2834
+ self.ensurePixelBuffers(frame_event.size, frame_event.scale_factor) catch return;
2835
+ _ = runtime.presentNextCanvasFramePixels(
2836
+ frame_event.window_id,
2837
+ canvas_label,
2838
+ .{
2839
+ .frame_index = frame_event.frame_index,
2840
+ .timestamp_ns = frame_event.timestamp_ns,
2841
+ .surface_size = frame_event.size,
2842
+ .scale = frame_event.scale_factor,
2843
+ .full_repaint = frame_event.canvas_frame_full_repaint or packet_attempted or installing,
2844
+ },
2845
+ runtime.canvasFrameScratchStorage(),
2846
+ self.pixel_buffer,
2847
+ self.pixel_scratch,
2848
+ clear_color,
2849
+ ) catch |err| switch (err) {
2850
+ error.UnsupportedService, error.UnsupportedViewKind => {},
2851
+ else => return err,
2852
+ };
2853
+ }
2854
+
2855
+ /// Grow the heap pixel buffers to hold the surface at the given
2856
+ /// scale. No-op when they are already large enough.
2857
+ fn ensurePixelBuffers(self: *Self, surface_size: geometry.SizeF, scale_factor: f32) anyerror!void {
2858
+ const pixel_size = try canvas_frame.canvasSurfacePixelSize(surface_size, scale_factor);
2859
+ if (self.pixel_buffer.len < pixel_size.byte_len) {
2860
+ if (self.pixel_buffer.len > 0) self.backing.free(self.pixel_buffer);
2861
+ self.pixel_buffer = &.{};
2862
+ self.pixel_buffer = try self.backing.alloc(u8, pixel_size.byte_len);
2863
+ }
2864
+ if (self.pixel_scratch.len < pixel_size.byte_len) {
2865
+ if (self.pixel_scratch.len > 0) self.backing.free(self.pixel_scratch);
2866
+ self.pixel_scratch = &.{};
2867
+ self.pixel_scratch = try self.backing.alloc(u8, pixel_size.byte_len);
2868
+ }
2869
+ }
2870
+
2871
+ fn normalizedSurfaceScale(scale_factor: f32) f32 {
2872
+ if (!std.math.isFinite(scale_factor) or scale_factor <= 0) return 1;
2873
+ return scale_factor;
2874
+ }
2875
+
2876
+ /// Change-detection hashes for the model-derived tray state:
2877
+ /// field lengths are folded in so adjacent slices can
2878
+ /// never alias across boundaries.
2879
+ fn hashTrayTitle(title: []const u8) u64 {
2880
+ var hasher = std.hash.Wyhash.init(0x7261795f7469746c); // "ray_titl"
2881
+ hasher.update(title);
2882
+ return hasher.final();
2883
+ }
2884
+
2885
+ fn hashTrayMenu(items: []const platform.TrayMenuItem) u64 {
2886
+ var hasher = std.hash.Wyhash.init(0x7261795f6d656e75); // "ray_menu"
2887
+ hasher.update(std.mem.asBytes(&items.len));
2888
+ for (items) |item| {
2889
+ hasher.update(std.mem.asBytes(&item.id));
2890
+ hasher.update(std.mem.asBytes(&item.label.len));
2891
+ hasher.update(item.label);
2892
+ hasher.update(std.mem.asBytes(&item.command.len));
2893
+ hasher.update(item.command);
2894
+ hasher.update(&.{ @intFromBool(item.separator), @intFromBool(item.enabled) });
2895
+ }
2896
+ return hasher.final();
2897
+ }
2898
+
2899
+ fn handleResize(self: *Self, runtime: *Runtime, resize_event: platform.GpuSurfaceResizeEvent) anyerror!void {
2900
+ if (!std.mem.eql(u8, resize_event.label, self.options.canvas_label)) {
2901
+ const slot = self.windowSlotByCanvasLabel(resize_event.label) orelse return;
2902
+ slot.canvas_size = .{ .width = resize_event.frame.width, .height = resize_event.frame.height };
2903
+ if (slot.installed) try self.rebuildWindowSlot(runtime, slot);
2904
+ return;
2905
+ }
2906
+ self.canvas_size = .{ .width = resize_event.frame.width, .height = resize_event.frame.height };
2907
+ if (!self.installed) return;
2908
+ // Fullscreen transitions resize the canvas AND flip the
2909
+ // chrome overlay insets (macOS hides the titlebar band and
2910
+ // traffic lights); re-query on every resize and dispatch
2911
+ // only on change — `dispatch` already rebuilds, so the
2912
+ // plain-resize rebuild is the else arm.
2913
+ if (self.chromeInsetsMsg(runtime, resize_event.window_id)) |msg| {
2914
+ try self.dispatch(runtime, resize_event.window_id, msg);
2915
+ return;
2916
+ }
2917
+ try self.rebuild(runtime, resize_event.window_id);
2918
+ }
2919
+
2920
+ /// Layout insets for the main canvas: the runtime's viewport
2921
+ /// chrome, minus the safe-area share when the app subscribed to
2922
+ /// `on_chrome`. A chrome subscriber owns safe-area padding — the
2923
+ /// same contract the macOS hidden-titlebar band delivers over the
2924
+ /// identical channel — so mobile surfaces hand it the notch,
2925
+ /// status bar, and home indicator bands instead of pre-insetting
2926
+ /// layout (which would pad the same band twice). The keyboard is
2927
+ /// input avoidance, not chrome: the runtime keeps insetting by
2928
+ /// its residual overlap beyond the safe area, so a padded app's
2929
+ /// effective clearance still totals max(safe, keyboard) per edge.
2930
+ fn layoutViewportInsets(self: *const Self, runtime: *const Runtime, window_id: platform.WindowId) geometry.InsetsF {
2931
+ const combined = runtime.viewportInsetsForWindow(window_id);
2932
+ if (self.options.on_chrome == null) return combined;
2933
+ const safe = runtime.safeAreaInsetsForWindow(window_id);
2934
+ return .{
2935
+ .top = @max(combined.top - safe.top, 0),
2936
+ .right = @max(combined.right - safe.right, 0),
2937
+ .bottom = @max(combined.bottom - safe.bottom, 0),
2938
+ .left = @max(combined.left - safe.left, 0),
2939
+ };
2940
+ }
2941
+
2942
+ /// The `on_chrome` delivery gate: query the platform's chrome
2943
+ /// overlay geometry for the canvas window and map it to a Msg
2944
+ /// when the app subscribed AND the geometry actually changed.
2945
+ fn chromeInsetsMsg(self: *Self, runtime: *Runtime, window_id: platform.WindowId) ?MsgT {
2946
+ const map = self.options.on_chrome orelse return null;
2947
+ const chrome = runtime.options.platform.services.windowChrome(window_id);
2948
+ if (self.window_chrome_known and std.meta.eql(chrome, self.window_chrome)) return null;
2949
+ self.window_chrome = chrome;
2950
+ self.window_chrome_known = true;
2951
+ return map(chrome);
2952
+ }
2953
+
2954
+ /// Typed press dispatch resolves through the press target — the
2955
+ /// deepest widget on the hit path that claims presses — so a press
2956
+ /// on a pressable row's plain text children lands on the row's
2957
+ /// `on_press`, and a release that ended a text-selection drag
2958
+ /// (press_target = null) presses nothing. Press targets with an
2959
+ /// `on_hold` handler additionally arm the hold timer on `.down`;
2960
+ /// a fired hold suppresses the release's press (one gesture, one
2961
+ /// Msg), and any release/cancel disarms it.
2962
+ fn handlePointer(self: *Self, runtime: *Runtime, pointer_event: core.CanvasWidgetPointerEvent) anyerror!void {
2963
+ const tree = self.treeForViewLabel(pointer_event.view_label) orelse return;
2964
+ switch (pointer_event.pointer.phase) {
2965
+ .down => {
2966
+ self.disarmHold(runtime);
2967
+ if (pointer_event.press_target) |target| {
2968
+ if (tree.hasHoldHandler(target.id)) {
2969
+ self.hold_armed_id = target.id;
2970
+ self.hold_fired = false;
2971
+ // One pointer, one gesture — but it can be
2972
+ // in any window: remember whose tree armed
2973
+ // it so the fire resolves the right handler
2974
+ // table and window identity.
2975
+ const label_len = @min(pointer_event.view_label.len, self.hold_view_label_storage.len);
2976
+ @memcpy(self.hold_view_label_storage[0..label_len], pointer_event.view_label[0..label_len]);
2977
+ self.hold_view_label_len = label_len;
2978
+ self.hold_window_id = pointer_event.window_id;
2979
+ runtime.startTimer(press_hold_timer_id, press_hold_duration_ns, false) catch {};
2980
+ }
2981
+ }
2982
+ },
2983
+ .up, .cancel => {
2984
+ const suppressed = self.hold_fired;
2985
+ self.disarmHold(runtime);
2986
+ if (suppressed) return;
2987
+ },
2988
+ else => {},
2989
+ }
2990
+ // A pointer gesture that performed a text edit (the search
2991
+ // field's built-in clear) maps to the field's `on_input`
2992
+ // Msg — the runtime already applied the edit; the model
2993
+ // hears it here so a source-owned buffer clears too.
2994
+ if (pointer_event.edit) |edit| {
2995
+ if (pointer_event.target) |edit_target| {
2996
+ if (tree.msgForTextEdit(edit_target.id, edit)) |msg| {
2997
+ try self.dispatch(runtime, pointer_event.window_id, msg);
2998
+ }
2999
+ }
3000
+ }
3001
+ const target = pointer_event.press_target orelse return;
3002
+ // A released press on a synthesized fallback menu item is a
3003
+ // context-menu selection, not an ordinary press: it resolves
3004
+ // through the target's `.context_menu` handler entry and
3005
+ // closes the surface.
3006
+ if (pointer_event.pointer.phase == .up) {
3007
+ if (try self.dispatchContextMenuFallbackItem(runtime, tree, pointer_event.window_id, target.id)) return;
3008
+ }
3009
+ // The click count rides the release into typed dispatch: a
3010
+ // double-click's second release resolves the target's
3011
+ // `on_double_press` handler (falling back to the ordinary
3012
+ // press), while its first release already dispatched the
3013
+ // single press — select-then-act, the list convention.
3014
+ if (tree.msgForPointerClick(target.id, pointer_event.pointer.phase, pointer_event.pointer.click_count)) |msg| {
3015
+ try self.dispatch(runtime, pointer_event.window_id, msg);
3016
+ }
3017
+ }
3018
+
3019
+ fn disarmHold(self: *Self, runtime: *Runtime) void {
3020
+ if (self.hold_armed_id != 0 and !self.hold_fired) runtime.cancelTimer(press_hold_timer_id) catch {};
3021
+ self.hold_armed_id = 0;
3022
+ self.hold_fired = false;
3023
+ }
3024
+
3025
+ /// The hold timer fired while the press is still down: dispatch
3026
+ /// the armed widget's `on_hold` Msg — through the tree that
3027
+ /// armed it, main canvas or a declared window's — and remember
3028
+ /// that this gesture consumed its press.
3029
+ fn firePressHold(self: *Self, runtime: *Runtime) anyerror!void {
3030
+ const armed_id = self.hold_armed_id;
3031
+ if (armed_id == 0 or self.hold_fired) return;
3032
+ const hold_label = self.hold_view_label_storage[0..self.hold_view_label_len];
3033
+ const tree = self.treeForViewLabel(hold_label) orelse return;
3034
+ self.hold_fired = true;
3035
+ if (tree.msgForHold(armed_id)) |msg| {
3036
+ try self.dispatch(runtime, self.hold_window_id, msg);
3037
+ }
3038
+ }
3039
+
3040
+ /// A dismissible surface was dismissed (Escape, click outside,
3041
+ /// automation/accessibility dismiss): the model owns the close
3042
+ /// through the surface's `on_dismiss` Msg. The engine already hid
3043
+ /// the surface as an optimistic echo; this dispatch makes the
3044
+ /// model agree (or deliberately re-open on the next rebuild —
3045
+ /// source wins).
3046
+ fn handleDismiss(self: *Self, runtime: *Runtime, dismiss_event: core.CanvasWidgetDismissEvent) anyerror!void {
3047
+ const tree = self.treeForViewLabel(dismiss_event.view_label) orelse return;
3048
+ // The synthesized fallback menu surface has no app-declared
3049
+ // on_dismiss (its open state lives here, not in the model):
3050
+ // close the state and rebuild, agreeing with the engine's
3051
+ // optimistic hide.
3052
+ if (self.context_menu_fallback_target != 0) {
3053
+ if (tree.context_menu_fallback) |fallback| {
3054
+ if (fallback.surface_id == dismiss_event.id) {
3055
+ self.clearContextMenuFallback();
3056
+ try self.rebuildAllViews(runtime);
3057
+ return;
3058
+ }
3059
+ }
3060
+ }
3061
+ if (tree.msgForDismiss(dismiss_event.id)) |msg| {
3062
+ try self.dispatch(runtime, dismiss_event.window_id, msg);
3063
+ }
3064
+ }
3065
+
3066
+ /// A secondary click with no context menu anywhere on its route:
3067
+ /// the desktop press-and-hold alternative — dispatch the press
3068
+ /// target's `on_hold` Msg immediately.
3069
+ fn handleContextPress(self: *Self, runtime: *Runtime, press_event: core.CanvasWidgetContextPressEvent) anyerror!void {
3070
+ const tree = self.treeForViewLabel(press_event.view_label) orelse return;
3071
+ const target = press_event.press_target orelse return;
3072
+ if (tree.msgForHold(target.id)) |msg| {
3073
+ try self.dispatch(runtime, press_event.window_id, msg);
3074
+ }
3075
+ }
3076
+
3077
+ fn handleKeyboard(self: *Self, runtime: *Runtime, keyboard_event: core.CanvasWidgetKeyboardEvent) anyerror!void {
3078
+ const tree = self.treeForViewLabel(keyboard_event.view_label) orelse return;
3079
+ // Key precedence, top to bottom — the focused widget always
3080
+ // outranks the app-level fallback:
3081
+ // 1. a focused widget's bound handler consumes the key
3082
+ // (space on a focused track row plays THAT row);
3083
+ // 2. a focused widget that structurally answers the key —
3084
+ // a control intent it maps, or any editable text
3085
+ // widget, where typing must stay typing (checked by
3086
+ // widget KIND, never by whether a handler is bound) —
3087
+ // consumes it silently;
3088
+ // 3. only an unclaimed key_down falls through to
3089
+ // `Options.on_key` (a target-less event — nothing
3090
+ // focused — skips straight here).
3091
+ if (keyboard_event.target) |target| {
3092
+ // Keyboard activation (Enter/Space) of a synthesized fallback
3093
+ // menu item is a context-menu selection, same as the pointer
3094
+ // path.
3095
+ if (self.context_menu_fallback_target != 0) {
3096
+ if (tree.findWidget(target.id)) |widget| {
3097
+ if (canvas.widgetKeyboardControlIntent(widget, keyboard_event.keyboard)) |intent| {
3098
+ if (intent.kind == .press or intent.kind == .select) {
3099
+ if (try self.dispatchContextMenuFallbackItem(runtime, tree, keyboard_event.window_id, target.id)) return;
3100
+ }
3101
+ }
3102
+ }
3103
+ }
3104
+ if (tree.msgForKeyboard(target.id, keyboard_event.keyboard)) |msg| {
3105
+ try self.dispatch(runtime, keyboard_event.window_id, msg);
3106
+ return;
3107
+ }
3108
+ if (tree.findWidget(target.id)) |widget| {
3109
+ if (!widget.state.disabled) {
3110
+ if (canvas.isWidgetTextEntry(widget)) return;
3111
+ if (canvas.widgetKeyboardControlIntent(widget, keyboard_event.keyboard) != null) return;
3112
+ }
3113
+ }
3114
+ }
3115
+ const map = self.options.on_key orelse return;
3116
+ if (keyboard_event.keyboard.phase != .key_down) return;
3117
+ if (map(keyboard_event.keyboard)) |msg| {
3118
+ try self.dispatch(runtime, keyboard_event.window_id, msg);
3119
+ }
3120
+ }
3121
+
3122
+ /// Split-fraction changes route through the split's `on_resize`
3123
+ /// constructor. The payload is the fraction the runtime already
3124
+ /// applied, so a model that stores it and echoes it back into
3125
+ /// `value` never fights the split reconcile rule.
3126
+ fn handleWidgetResize(self: *Self, runtime: *Runtime, resize_event: core.CanvasWidgetResizeEvent) anyerror!void {
3127
+ const tree = self.treeForViewLabel(resize_event.view_label) orelse return;
3128
+ if (tree.msgForResize(resize_event.id, resize_event.fraction)) |msg| {
3129
+ try self.dispatch(runtime, resize_event.window_id, msg);
3130
+ }
3131
+ }
3132
+
3133
+ /// Slider value changes from pointer gestures (rail click, scrub
3134
+ /// drag) route through the slider's `on_value`/`on_change`
3135
+ /// handler. The payload is the value the runtime already applied
3136
+ /// (the optimistic echo), and `dispatch` runs the `sync` hook
3137
+ /// before update — so a model that mirrors slider state through
3138
+ /// `sync` reads the applied value first and its update arm acts
3139
+ /// on it, the same contract keyboard slider steps follow.
3140
+ fn handleWidgetChange(self: *Self, runtime: *Runtime, change_event: core.CanvasWidgetChangeEvent) anyerror!void {
3141
+ const tree = self.treeForViewLabel(change_event.view_label) orelse return;
3142
+ if (tree.msgForChange(change_event.id, change_event.value)) |msg| {
3143
+ try self.dispatch(runtime, change_event.window_id, msg);
3144
+ }
3145
+ }
3146
+
3147
+ /// Scroll offset changes route through the scroll container's
3148
+ /// `on_scroll` constructor. The payload is the offset the runtime
3149
+ /// already applied, so a model that stores it and echoes it back
3150
+ /// into `value` never fights the scroll reconcile rule.
3151
+ ///
3152
+ /// Two ride-alongs per scroll observation:
3153
+ /// - `on_reach_end` fires through the approach-end hysteresis
3154
+ /// (`reachEndShouldFire`) — the infinite-scroll fetch signal.
3155
+ /// - A windowed virtual list re-derives the view even with no
3156
+ /// Msg bound: its window follows the runtime-owned offset, so
3157
+ /// the scroll itself is the rebuild trigger (main canvas only,
3158
+ /// where the window source is installed).
3159
+ fn handleScroll(self: *Self, runtime: *Runtime, scroll_event: core.CanvasWidgetScrollEvent) anyerror!void {
3160
+ const tree = self.treeForViewLabel(scroll_event.view_label) orelse return;
3161
+ var rebuilt = false;
3162
+ if (tree.msgForScroll(scroll_event.id, scroll_event.scroll)) |msg| {
3163
+ try self.dispatch(runtime, scroll_event.window_id, msg);
3164
+ rebuilt = true;
3165
+ }
3166
+ if (tree.msgForReachEnd(scroll_event.id)) |msg| {
3167
+ if (self.reachEndShouldFire(scroll_event.id, scroll_event.scroll)) {
3168
+ try self.dispatch(runtime, scroll_event.window_id, msg);
3169
+ rebuilt = true;
3170
+ }
3171
+ }
3172
+ if (tree.msgForReachStart(scroll_event.id)) |msg| {
3173
+ if (self.reachStartShouldFire(scroll_event.id, scroll_event.scroll)) {
3174
+ try self.dispatch(runtime, scroll_event.window_id, msg);
3175
+ rebuilt = true;
3176
+ }
3177
+ }
3178
+ if (!rebuilt and self.installed and
3179
+ std.mem.eql(u8, scroll_event.view_label, self.options.canvas_label) and
3180
+ self.isVirtualWindowId(scroll_event.id))
3181
+ {
3182
+ try self.rebuild(runtime, scroll_event.window_id);
3183
+ }
3184
+ }
3185
+
3186
+ /// A native context-menu selection: resolve the selected
3187
+ /// item's declared `Msg` through the tree's handler table.
3188
+ fn handleContextMenu(self: *Self, runtime: *Runtime, menu_event: core.CanvasWidgetContextMenuEvent) anyerror!void {
3189
+ const tree = self.treeForViewLabel(menu_event.view_label) orelse return;
3190
+ // A selection on this menu closes it whatever the source: an
3191
+ // automation-invoked selection while the fallback surface is
3192
+ // open must not leave the surface mounted.
3193
+ if (self.context_menu_fallback_target == menu_event.target_id) {
3194
+ self.clearContextMenuFallback();
3195
+ }
3196
+ if (tree.msgForContextMenu(menu_event.target_id, menu_event.item_index)) |msg| {
3197
+ try self.dispatch(runtime, menu_event.window_id, msg);
3198
+ }
3199
+ }
3200
+
3201
+ /// The platform could not present a declared context menu
3202
+ /// natively: open the anchored-surface fallback — record which
3203
+ /// widget's menu is open and rebuild, so `Ui.finalize` mounts the
3204
+ /// same declared items as an anchored canvas surface on the
3205
+ /// target.
3206
+ fn handleContextMenuRequest(self: *Self, runtime: *Runtime, request_event: core.CanvasWidgetContextMenuRequestEvent) anyerror!void {
3207
+ const label_len = @min(request_event.view_label.len, self.context_menu_fallback_label_storage.len);
3208
+ @memcpy(self.context_menu_fallback_label_storage[0..label_len], request_event.view_label[0..label_len]);
3209
+ self.context_menu_fallback_label_len = label_len;
3210
+ self.context_menu_fallback_window_id = request_event.window_id;
3211
+ self.context_menu_fallback_target = request_event.target_id;
3212
+ try self.rebuildAllViews(runtime);
3213
+ }
3214
+
3215
+ fn contextMenuFallbackLabel(self: *const Self) []const u8 {
3216
+ return self.context_menu_fallback_label_storage[0..self.context_menu_fallback_label_len];
3217
+ }
3218
+
3219
+ /// The fallback target `Ui.finalize` should mount for a view
3220
+ /// being rebuilt, or 0 when the open fallback (if any) belongs to
3221
+ /// a different view.
3222
+ fn contextMenuFallbackTargetForLabel(self: *const Self, view_label: []const u8) canvas.ObjectId {
3223
+ if (self.context_menu_fallback_target == 0) return 0;
3224
+ if (!std.mem.eql(u8, view_label, self.contextMenuFallbackLabel())) return 0;
3225
+ return self.context_menu_fallback_target;
3226
+ }
3227
+
3228
+ fn clearContextMenuFallback(self: *Self) void {
3229
+ self.context_menu_fallback_target = 0;
3230
+ self.context_menu_fallback_label_len = 0;
3231
+ }
3232
+
3233
+ /// Rebuild every open view without a Msg dispatch — the fallback
3234
+ /// menu's open state lives here, not in the model, so opening and
3235
+ /// closing it re-derives the views directly.
3236
+ fn rebuildAllViews(self: *Self, runtime: *Runtime) anyerror!void {
3237
+ if (!self.installed) return;
3238
+ try self.rebuild(runtime, self.canvas_window_id);
3239
+ try self.rebuildWindowSlots(runtime);
3240
+ }
3241
+
3242
+ /// A pointer press or keyboard activation resolved to one of the
3243
+ /// fallback surface's synthesized items: close the surface and
3244
+ /// dispatch through `msgForContextMenu` — the SAME handler entry
3245
+ /// a native selection resolves. Returns true when the id was a
3246
+ /// fallback item (consumed either way).
3247
+ fn dispatchContextMenuFallbackItem(self: *Self, runtime: *Runtime, tree: *const Ui.Tree, window_id: platform.WindowId, id: canvas.ObjectId) anyerror!bool {
3248
+ if (self.context_menu_fallback_target == 0) return false;
3249
+ const fallback = tree.context_menu_fallback orelse return false;
3250
+ const item_index = fallback.itemIndex(id) orelse return false;
3251
+ self.clearContextMenuFallback();
3252
+ if (tree.msgForContextMenu(fallback.target_id, item_index)) |msg| {
3253
+ try self.dispatch(runtime, window_id, msg);
3254
+ } else {
3255
+ try self.rebuildAllViews(runtime);
3256
+ }
3257
+ return true;
3258
+ }
3259
+ };
3260
+ }
3261
+
3262
+ /// Window-action resolvers for the effects channel's
3263
+ /// `WindowActionBinding` (`Effects.closeWindow`/`minimizeWindow`): apps
3264
+ /// address windows by their declared LABEL (`ShellWindow.label`,
3265
+ /// `WindowDescriptor.label`), and these resolve the label against the
3266
+ /// runtime's live window table at call time — a closed or never-opened
3267
+ /// label is honestly a no-op. Loop-thread only, like every effect call.
3268
+ fn effectsWindowIdByLabel(runtime: *Runtime, window_label: []const u8) ?platform.WindowId {
3269
+ var buffer: [platform.max_windows]platform.WindowInfo = undefined;
3270
+ for (runtime.listWindows(&buffer)) |info| {
3271
+ if (info.open and std.mem.eql(u8, info.label, window_label)) return info.id;
3272
+ }
3273
+ return null;
3274
+ }
3275
+
3276
+ fn effectsCloseWindowByLabel(context: *anyopaque, window_label: []const u8) bool {
3277
+ const runtime: *Runtime = @ptrCast(@alignCast(context));
3278
+ const window_id = effectsWindowIdByLabel(runtime, window_label) orelse return false;
3279
+ // The runtime's own close: bookkeeping flips before the platform
3280
+ // call, exactly like a reconcile close — see `Runtime.closeWindow`.
3281
+ runtime.closeWindow(window_id) catch return false;
3282
+ return true;
3283
+ }
3284
+
3285
+ fn effectsMinimizeWindowByLabel(context: *anyopaque, window_label: []const u8) bool {
3286
+ const runtime: *Runtime = @ptrCast(@alignCast(context));
3287
+ const window_id = effectsWindowIdByLabel(runtime, window_label) orelse return false;
3288
+ runtime.minimizeWindow(window_id) catch return false;
3289
+ return true;
3290
+ }