@native-sdk/cli 0.10.1 → 0.11.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 (555) hide show
  1. package/README.md +8 -6
  2. package/bin/native.js +2 -1
  3. package/build/app.zig +393 -97
  4. package/build/corewire.zig +53 -0
  5. package/build/test_shards.zig +49 -0
  6. package/build/ts_run.mjs +3 -3
  7. package/build.zig +2030 -83
  8. package/native-sdk.d.ts +5 -1
  9. package/package.json +20 -14
  10. package/packages/core/compile-surface/core.ts +164 -72
  11. package/packages/core/package-lock.json +75 -357
  12. package/packages/core/package.json +25 -4
  13. package/packages/core/scripts/compiler_command.mjs +17 -12
  14. package/packages/core/scripts/compiler_typecheck.mjs +1 -0
  15. package/packages/core/scripts/gen_declarations.mjs +3 -2
  16. package/packages/core/scripts/gen_service_surface.mjs +22 -10
  17. package/packages/core/scripts/install_scriptc.mjs +182 -0
  18. package/packages/core/scripts/invoke_scriptc.mjs +18 -0
  19. package/packages/core/scripts/merge_static_archives.mjs +6 -1
  20. package/packages/core/scripts/npm_static_spike.mjs +2 -2
  21. package/packages/core/scripts/run_external_core_compiler.mjs +22 -10
  22. package/packages/core/scripts/run_external_service_compiler.mjs +15 -15
  23. package/packages/core/scripts/run_library_compiler.mjs +51 -0
  24. package/packages/core/scripts/run_native_tests.mjs +22 -0
  25. package/packages/core/scripts/scriptc-toolchain.json +101 -0
  26. package/packages/core/scripts/scriptc_toolchain.mjs +121 -0
  27. package/packages/core/scripts/stage_external_core.mjs +68 -1
  28. package/packages/core/scripts/surface_manifest_diff.mjs +19 -12
  29. package/packages/core/sdk/bytes.d.ts +2 -0
  30. package/packages/core/sdk/bytes.ts +86 -0
  31. package/packages/core/sdk/core.d.ts +332 -5
  32. package/packages/core/sdk/core.ts +371 -85
  33. package/packages/core/sdk/events.d.ts +252 -0
  34. package/packages/core/sdk/events.ts +240 -2
  35. package/packages/core/sdk/internal/image_identity.d.ts +7 -0
  36. package/packages/core/sdk/internal/image_identity.ts +71 -0
  37. package/packages/core/sdk/internal/markdown_policy.d.ts +5 -0
  38. package/packages/core/sdk/internal/markdown_policy.ts +878 -0
  39. package/packages/core/sdk/text.d.ts +27 -0
  40. package/packages/core/sdk/text.ts +206 -15
  41. package/packages/core/sdk/theme.d.ts +251 -0
  42. package/packages/core/sdk/theme.ts +267 -0
  43. package/packages/core/src/authorization.ts +137 -0
  44. package/packages/core/src/automation_commands.ts +201 -0
  45. package/packages/core/src/automation_interactions.ts +92 -0
  46. package/packages/core/src/bridge_descriptors.ts +104 -0
  47. package/packages/core/src/builtin_coordination.ts +172 -0
  48. package/packages/core/src/canvas_frame_coordination.ts +81 -0
  49. package/packages/core/src/canvas_presentation_lifecycle.ts +84 -0
  50. package/packages/core/src/canvas_scene_observation.ts +145 -0
  51. package/packages/core/src/chart_content.ts +161 -0
  52. package/packages/core/src/chart_plans.ts +432 -0
  53. package/packages/core/src/checker.ts +186 -19
  54. package/packages/core/src/cli.ts +2 -11
  55. package/packages/core/src/code_content.ts +580 -0
  56. package/packages/core/src/command_coordination.ts +140 -0
  57. package/packages/core/src/component_composition.ts +94 -0
  58. package/packages/core/src/component_construction.ts +149 -0
  59. package/packages/core/src/context_menus.ts +76 -0
  60. package/packages/core/src/contract.ts +25 -7
  61. package/packages/core/src/control_appearance.ts +232 -0
  62. package/packages/core/src/control_commands.ts +115 -0
  63. package/packages/core/src/control_content.ts +105 -0
  64. package/packages/core/src/control_geometry.ts +107 -0
  65. package/packages/core/src/control_payloads.ts +119 -0
  66. package/packages/core/src/control_primitives.ts +134 -0
  67. package/packages/core/src/devhost.ts +82 -7
  68. package/packages/core/src/devhost_journal.mjs +30 -7
  69. package/packages/core/src/diagnostics.ts +7 -0
  70. package/packages/core/src/effect_plans.ts +71 -0
  71. package/packages/core/src/extent_program.ts +53 -0
  72. package/packages/core/src/flow_measurement.ts +121 -0
  73. package/packages/core/src/font_registry.ts +37 -0
  74. package/packages/core/src/frontend.ts +12 -10
  75. package/packages/core/src/glyph_atlas.ts +86 -0
  76. package/packages/core/src/gpu_packet_preparation.ts +130 -0
  77. package/packages/core/src/gpu_planning.ts +123 -0
  78. package/packages/core/src/gpu_presentation.ts +55 -0
  79. package/packages/core/src/host_flow.ts +89 -0
  80. package/packages/core/src/host_input_regions.ts +165 -0
  81. package/packages/core/src/image_registry.ts +66 -0
  82. package/packages/core/src/indicator_plans.ts +132 -0
  83. package/packages/core/src/infer.ts +150 -8
  84. package/packages/core/src/input_composition.ts +116 -0
  85. package/packages/core/src/intrinsic_measure.ts +100 -0
  86. package/packages/core/src/layout_coordination.ts +207 -0
  87. package/packages/core/src/leaf_plans.ts +134 -0
  88. package/packages/core/src/markup_canonical.ts +140 -0
  89. package/packages/core/src/markup_construction.ts +189 -0
  90. package/packages/core/src/markup_development.ts +160 -0
  91. package/packages/core/src/markup_display.ts +43 -0
  92. package/packages/core/src/markup_document.ts +226 -0
  93. package/packages/core/src/markup_elements.ts +225 -0
  94. package/packages/core/src/markup_expressions.ts +79 -0
  95. package/packages/core/src/markup_imports.ts +146 -0
  96. package/packages/core/src/markup_parser.ts +228 -0
  97. package/packages/core/src/markup_runtime.ts +93 -0
  98. package/packages/core/src/markup_scalars.ts +143 -0
  99. package/packages/core/src/markup_shapes.ts +243 -0
  100. package/packages/core/src/markup_specialized.ts +242 -0
  101. package/packages/core/src/markup_text.ts +86 -0
  102. package/packages/core/src/markup_values.ts +336 -0
  103. package/packages/core/src/measurement_coordination.ts +185 -0
  104. package/packages/core/src/modules.ts +1 -1
  105. package/packages/core/src/motion_sampling.ts +100 -0
  106. package/packages/core/src/paragraph_layout.ts +192 -0
  107. package/packages/core/src/portable_sources.json +98 -0
  108. package/packages/core/src/portable_sources.ts +17 -0
  109. package/packages/core/src/registered_font.ts +92 -0
  110. package/packages/core/src/render_animation_lifecycle.ts +128 -0
  111. package/packages/core/src/render_coordination.ts +170 -0
  112. package/packages/core/src/render_resources.ts +234 -0
  113. package/packages/core/src/runtime_policy.ts +3954 -0
  114. package/packages/core/src/scalar_text.ts +82 -0
  115. package/packages/core/src/scroll_mutation.ts +86 -0
  116. package/packages/core/src/scroll_tree.ts +86 -0
  117. package/packages/core/src/service_contract.ts +55 -3
  118. package/packages/core/src/session_codecs.ts +309 -0
  119. package/packages/core/src/shell_admission.ts +126 -0
  120. package/packages/core/src/shell_coordination.ts +93 -0
  121. package/packages/core/src/sqlite_cli.ts +14 -46
  122. package/packages/core/src/sqlite_codegen.ts +84 -0
  123. package/packages/core/src/staged_rebuild.ts +60 -0
  124. package/packages/core/src/status_validation.ts +232 -0
  125. package/packages/core/src/stream_policy.ts +63 -0
  126. package/packages/core/src/surface_recipes.ts +136 -0
  127. package/packages/core/src/system_admission.ts +60 -0
  128. package/packages/core/src/terminal_paint.ts +436 -0
  129. package/packages/core/src/text_document_width.ts +81 -0
  130. package/packages/core/src/text_measurement_cache.ts +69 -0
  131. package/packages/core/src/text_query_layout.ts +179 -0
  132. package/packages/core/src/text_run_layout.ts +410 -0
  133. package/packages/core/src/text_span_queries.ts +355 -0
  134. package/packages/core/src/typed_ast.ts +18 -1
  135. package/packages/core/src/types.ts +7 -5
  136. package/packages/core/src/vector_effects.ts +98 -0
  137. package/packages/core/src/vector_raster.ts +243 -0
  138. package/packages/core/src/view_bridge.ts +161 -0
  139. package/packages/core/src/view_check.ts +145 -0
  140. package/packages/core/src/view_components.ts +2415 -0
  141. package/packages/core/src/view_coordination.ts +198 -0
  142. package/packages/core/src/view_evaluator.ts +823 -0
  143. package/packages/core/src/view_frontend.ts +1102 -0
  144. package/packages/core/src/view_program.ts +221 -0
  145. package/packages/core/src/view_reload.ts +166 -0
  146. package/packages/core/src/view_reload_watch.ts +98 -0
  147. package/packages/core/src/view_sources.ts +34 -0
  148. package/packages/core/src/virtual_windows.ts +88 -0
  149. package/packages/core/src/web_panes.ts +67 -0
  150. package/packages/core/src/widget_audits.ts +202 -0
  151. package/packages/core/src/widget_changes.ts +258 -0
  152. package/packages/core/src/widget_continuity.ts +37 -0
  153. package/packages/core/src/widget_metrics.ts +139 -0
  154. package/packages/core/src/widget_motion.ts +171 -0
  155. package/packages/core/src/widget_paint.ts +272 -0
  156. package/packages/core/src/widget_paint_walk.ts +203 -0
  157. package/packages/core/src/widget_presentation.ts +141 -0
  158. package/packages/core/src/widget_reconcile.ts +63 -0
  159. package/packages/core/src/widget_retention.ts +62 -0
  160. package/packages/core/src/widget_routing.ts +262 -0
  161. package/packages/core/src/window_lifecycle.ts +92 -0
  162. package/packages/core/testing/index.ts +430 -0
  163. package/schemas/app.schema.json +13 -0
  164. package/skill-data/core/SKILL.md +2 -2
  165. package/skill-data/native-ui/SKILL.md +77 -18
  166. package/skill-data/ts-core/SKILL.md +117 -11
  167. package/skill-data/ts-services/SKILL.md +1 -1
  168. package/skill-data/ts-services/references/service-surface.md +288 -144
  169. package/src/app_runner/root.zig +39 -12
  170. package/src/app_runner/ts_compiled_view.zig +1702 -0
  171. package/src/app_runner/ts_core_main.zig +185 -14
  172. package/src/app_runner/ts_core_mobile.zig +25 -13
  173. package/src/automation/server.zig +57 -6
  174. package/src/automation/snapshot.zig +9 -637
  175. package/src/automation/snapshot_reference.zig +656 -0
  176. package/src/automation/snapshot_serialization.zig +566 -0
  177. package/src/embed/host.zig +2 -0
  178. package/src/embed/tests.zig +2 -0
  179. package/src/embed/ui_host.zig +2 -0
  180. package/src/platform/keyboard_input.zig +32 -0
  181. package/src/platform/linux/gtk_host.c +36 -24
  182. package/src/platform/linux/gtk_pixels.h +118 -0
  183. package/src/platform/linux/gtk_pixels_test.c +241 -0
  184. package/src/platform/linux/root.zig +4 -0
  185. package/src/platform/macos/appkit_host.h +7 -2
  186. package/src/platform/macos/appkit_host.m +219 -39
  187. package/src/platform/macos/cef_host.mm +15 -1
  188. package/src/platform/macos/global_shortcuts.zig +138 -0
  189. package/src/platform/macos/key_codes.zig +102 -0
  190. package/src/platform/macos/keyboard_input.zig +81 -0
  191. package/src/platform/macos/pointer_motion_test.m +96 -0
  192. package/src/platform/macos/root.zig +25 -3
  193. package/src/platform/macos/scroll_driver_test.m +105 -0
  194. package/src/platform/macos/spectrum_bins.h +34 -0
  195. package/src/platform/macos/spectrum_bins_test.c +56 -0
  196. package/src/platform/macos/text_keyboard_test.m +80 -0
  197. package/src/platform/macos/webview_inspection_test.m +106 -0
  198. package/src/platform/macos/widget_focus_test.m +66 -0
  199. package/src/platform/null_platform.zig +130 -2
  200. package/src/platform/null_platform_tests.zig +13 -0
  201. package/src/platform/root.zig +15 -0
  202. package/src/platform/types.zig +115 -0
  203. package/src/platform/windows/global_shortcuts.zig +157 -0
  204. package/src/platform/windows/key_codes.zig +63 -0
  205. package/src/platform/windows/keyboard_input.zig +136 -0
  206. package/src/platform/windows/root.zig +17 -0
  207. package/src/platform/windows/webview2_host.cpp +7 -2
  208. package/src/primitives/app_manifest/comptime_scene.zig +1 -1
  209. package/src/primitives/app_manifest/root.zig +2 -0
  210. package/src/primitives/app_manifest/tests.zig +4 -1
  211. package/src/primitives/app_manifest/validation.zig +2 -0
  212. package/src/primitives/canvas/a11y_audit.zig +3 -1
  213. package/src/primitives/canvas/canvas_frame_coordination_policy.zig +134 -0
  214. package/src/primitives/canvas/chart_content_policy.zig +75 -0
  215. package/src/primitives/canvas/chart_plan_policy.zig +196 -0
  216. package/src/primitives/canvas/code_content_policy.zig +162 -0
  217. package/src/primitives/canvas/commands.zig +29 -1
  218. package/src/primitives/canvas/component_composition.zig +125 -0
  219. package/src/primitives/canvas/component_composition_policy.zig +44 -0
  220. package/src/primitives/canvas/component_construction_policy.zig +187 -0
  221. package/src/primitives/canvas/container_layout_policy.zig +87 -0
  222. package/src/primitives/canvas/control_appearance_policy.zig +142 -0
  223. package/src/primitives/canvas/control_command_policy.zig +75 -0
  224. package/src/primitives/canvas/control_content_policy.zig +90 -0
  225. package/src/primitives/canvas/control_geometry_policy.zig +165 -0
  226. package/src/primitives/canvas/control_payload_policy.zig +48 -0
  227. package/src/primitives/canvas/control_primitive_policy.zig +129 -0
  228. package/src/primitives/canvas/decision_reuse.zig +133 -0
  229. package/src/primitives/canvas/effect_plan_policy.zig +96 -0
  230. package/src/primitives/canvas/events.zig +1027 -1
  231. package/src/primitives/canvas/flow_measurement_policy.zig +237 -0
  232. package/src/primitives/canvas/font_ttf.zig +27 -3
  233. package/src/primitives/canvas/fonts/Geist-Bold.ttf +0 -0
  234. package/src/primitives/canvas/fonts/Geist-Medium.ttf +0 -0
  235. package/src/primitives/canvas/fonts/OFL.txt +93 -0
  236. package/src/primitives/canvas/fonts/README.md +15 -0
  237. package/src/primitives/canvas/frame.zig +92 -23
  238. package/src/primitives/canvas/glyph_atlas_policy.zig +40 -0
  239. package/src/primitives/canvas/gpu.zig +10 -0
  240. package/src/primitives/canvas/gpu_packet_preparation_policy.zig +325 -0
  241. package/src/primitives/canvas/gpu_planning_policy.zig +364 -0
  242. package/src/primitives/canvas/gpu_presentation_policy.zig +74 -0
  243. package/src/primitives/canvas/grid_layout_policy.zig +51 -0
  244. package/src/primitives/canvas/indicator_plan_policy.zig +128 -0
  245. package/src/primitives/canvas/intrinsic_layout_policy.zig +87 -0
  246. package/src/primitives/canvas/intrinsic_measure_policy.zig +131 -0
  247. package/src/primitives/canvas/layout_audit.zig +5 -2
  248. package/src/primitives/canvas/layout_coordination_policy.zig +262 -0
  249. package/src/primitives/canvas/leaf_plan_policy.zig +117 -0
  250. package/src/primitives/canvas/markdown.zig +13 -3
  251. package/src/primitives/canvas/markdown_content_policy.zig +227 -0
  252. package/src/primitives/canvas/markdown_image_binding.zig +81 -0
  253. package/src/primitives/canvas/markdown_tests.zig +3 -3
  254. package/src/primitives/canvas/measurement_coordination_policy.zig +288 -0
  255. package/src/primitives/canvas/numeric_capabilities.zig +14 -0
  256. package/src/primitives/canvas/reference.zig +15 -11
  257. package/src/primitives/canvas/reference_tests.zig +58 -0
  258. package/src/primitives/canvas/registered_font_policy.zig +152 -0
  259. package/src/primitives/canvas/render.zig +48 -0
  260. package/src/primitives/canvas/render_cache_policy.zig +184 -0
  261. package/src/primitives/canvas/render_coordination_policy.zig +163 -0
  262. package/src/primitives/canvas/render_damage_policy.zig +160 -0
  263. package/src/primitives/canvas/render_effects.zig +14 -0
  264. package/src/primitives/canvas/render_generic_resources.zig +14 -0
  265. package/src/primitives/canvas/render_images.zig +14 -0
  266. package/src/primitives/canvas/render_layers.zig +14 -0
  267. package/src/primitives/canvas/render_override_policy.zig +119 -0
  268. package/src/primitives/canvas/render_paths.zig +14 -0
  269. package/src/primitives/canvas/render_plan_policy.zig +199 -0
  270. package/src/primitives/canvas/render_resource_policy.zig +476 -0
  271. package/src/primitives/canvas/root.zig +107 -4
  272. package/src/primitives/canvas/semantic_tree_policy.zig +158 -0
  273. package/src/primitives/canvas/serialization.zig +8 -1
  274. package/src/primitives/canvas/surface_layout_policy.zig +36 -0
  275. package/src/primitives/canvas/surface_recipe_policy.zig +231 -0
  276. package/src/primitives/canvas/terminal_grid.zig +10 -696
  277. package/src/primitives/canvas/terminal_grid_reference.zig +709 -0
  278. package/src/primitives/canvas/terminal_paint_policy.zig +191 -0
  279. package/src/primitives/canvas/text.zig +1 -0
  280. package/src/primitives/canvas/text_atlas.zig +113 -0
  281. package/src/primitives/canvas/text_cache_policy.zig +94 -0
  282. package/src/primitives/canvas/text_document_policy.zig +120 -0
  283. package/src/primitives/canvas/text_layout.zig +51 -2
  284. package/src/primitives/canvas/text_layout_cache.zig +29 -0
  285. package/src/primitives/canvas/text_layout_hash.zig +1 -0
  286. package/src/primitives/canvas/text_layout_types.zig +3 -0
  287. package/src/primitives/canvas/text_measure_cache.zig +46 -0
  288. package/src/primitives/canvas/text_measurement_policy.zig +124 -0
  289. package/src/primitives/canvas/text_metrics.zig +53 -37
  290. package/src/primitives/canvas/text_metrics_tests.zig +52 -7
  291. package/src/primitives/canvas/text_query_policy.zig +295 -0
  292. package/src/primitives/canvas/text_run_policy.zig +252 -0
  293. package/src/primitives/canvas/text_scalar_policy.zig +234 -0
  294. package/src/primitives/canvas/text_span_query_policy.zig +232 -0
  295. package/src/primitives/canvas/text_spans.zig +280 -8
  296. package/src/primitives/canvas/text_tests.zig +10 -0
  297. package/src/primitives/canvas/tokens.zig +47 -0
  298. package/src/primitives/canvas/ui.zig +251 -83
  299. package/src/primitives/canvas/ui_markup.zig +207 -46
  300. package/src/primitives/canvas/ui_markup_canonical.zig +237 -0
  301. package/src/primitives/canvas/ui_markup_compiled.zig +1724 -80
  302. package/src/primitives/canvas/ui_markup_compiled_tests.zig +225 -0
  303. package/src/primitives/canvas/ui_markup_compiled_values.zig +76 -0
  304. package/src/primitives/canvas/ui_markup_construction.zig +146 -0
  305. package/src/primitives/canvas/ui_markup_contract.zig +146 -14
  306. package/src/primitives/canvas/ui_markup_contract_tests.zig +77 -0
  307. package/src/primitives/canvas/ui_markup_display.zig +82 -0
  308. package/src/primitives/canvas/ui_markup_document.zig +196 -0
  309. package/src/primitives/canvas/ui_markup_elements.zig +163 -0
  310. package/src/primitives/canvas/ui_markup_expr.zig +192 -2
  311. package/src/primitives/canvas/ui_markup_imports.zig +262 -0
  312. package/src/primitives/canvas/ui_markup_parser.zig +117 -0
  313. package/src/primitives/canvas/ui_markup_reflect.zig +56 -0
  314. package/src/primitives/canvas/ui_markup_runtime.zig +76 -0
  315. package/src/primitives/canvas/ui_markup_scalars.zig +115 -0
  316. package/src/primitives/canvas/ui_markup_shapes.zig +224 -0
  317. package/src/primitives/canvas/ui_markup_specialized.zig +106 -0
  318. package/src/primitives/canvas/ui_markup_tests.zig +116 -0
  319. package/src/primitives/canvas/ui_markup_text.zig +128 -0
  320. package/src/primitives/canvas/ui_markup_values.zig +368 -0
  321. package/src/primitives/canvas/ui_markup_view.zig +3026 -57
  322. package/src/primitives/canvas/ui_markup_view_tests.zig +142 -10
  323. package/src/primitives/canvas/ui_schema.zig +13 -1
  324. package/src/primitives/canvas/ui_schema_tests.zig +11 -7
  325. package/src/primitives/canvas/ui_tests.zig +1 -0
  326. package/src/primitives/canvas/vector.zig +36 -2
  327. package/src/primitives/canvas/vector_effect_policy.zig +236 -0
  328. package/src/primitives/canvas/vector_raster_policy.zig +190 -0
  329. package/src/primitives/canvas/virtual_extent_policy.zig +350 -0
  330. package/src/primitives/canvas/virtual_extents.zig +113 -3
  331. package/src/primitives/canvas/virtual_flow_policy.zig +108 -0
  332. package/src/primitives/canvas/widget_audit_policy.zig +293 -0
  333. package/src/primitives/canvas/widget_change_policy.zig +298 -0
  334. package/src/primitives/canvas/widget_invalidation.zig +113 -2
  335. package/src/primitives/canvas/widget_layout.zig +673 -128
  336. package/src/primitives/canvas/widget_layout_tests.zig +4 -0
  337. package/src/primitives/canvas/widget_metric_policy.zig +129 -0
  338. package/src/primitives/canvas/widget_metrics.zig +45 -6
  339. package/src/primitives/canvas/widget_paint_policy.zig +166 -0
  340. package/src/primitives/canvas/widget_paint_walk_policy.zig +252 -0
  341. package/src/primitives/canvas/widget_presentation_policy.zig +168 -0
  342. package/src/primitives/canvas/widget_render.zig +744 -74
  343. package/src/primitives/canvas/widget_render_controls.zig +1217 -133
  344. package/src/primitives/canvas/widget_render_scroll.zig +11 -3
  345. package/src/primitives/canvas/widget_render_style.zig +94 -0
  346. package/src/primitives/canvas/widget_render_surfaces.zig +61 -50
  347. package/src/primitives/canvas/widget_routing.zig +75 -0
  348. package/src/primitives/canvas/widget_routing_policy.zig +135 -0
  349. package/src/primitives/canvas/widget_runtime.zig +21 -1
  350. package/src/primitives/canvas/widget_semantics.zig +25 -0
  351. package/src/primitives/canvas/widget_text_input.zig +86 -23
  352. package/src/primitives/canvas/widget_text_select.zig +1 -0
  353. package/src/primitives/canvas/widget_tree.zig +8 -1
  354. package/src/primitives/canvas/widgets.zig +42 -12
  355. package/src/primitives/canvas/wrapped_layout_policy.zig +104 -0
  356. package/src/root.zig +26 -0
  357. package/src/runtime/accessibility_policy.zig +122 -0
  358. package/src/runtime/api.zig +29 -0
  359. package/src/runtime/app_dispatch_policy.zig +68 -0
  360. package/src/runtime/authorization_policy.zig +150 -0
  361. package/src/runtime/automation_command_policy.zig +241 -0
  362. package/src/runtime/automation_interaction_policy.zig +107 -0
  363. package/src/runtime/automation_snapshot.zig +52 -22
  364. package/src/runtime/automation_snapshot_reference.zig +290 -0
  365. package/src/runtime/automation_widget_dispatch.zig +267 -355
  366. package/src/runtime/automation_widget_dispatch_reference.zig +900 -0
  367. package/src/runtime/blob_policy.zig +58 -0
  368. package/src/runtime/blob_reference.zig +64 -0
  369. package/src/runtime/bridge_descriptor_policy.zig +206 -0
  370. package/src/runtime/bridge_payload.zig +2 -0
  371. package/src/runtime/builtin_bridge.zig +180 -44
  372. package/src/runtime/builtin_coordination_policy.zig +121 -0
  373. package/src/runtime/callback_policy_test_reference.zig +97 -0
  374. package/src/runtime/canvas_drag_policy.zig +94 -0
  375. package/src/runtime/canvas_fonts.zig +38 -10
  376. package/src/runtime/canvas_frame.zig +590 -134
  377. package/src/runtime/canvas_frame_helpers.zig +1 -0
  378. package/src/runtime/canvas_hover_policy.zig +131 -0
  379. package/src/runtime/canvas_images.zig +59 -30
  380. package/src/runtime/canvas_keyboard_focus_policy.zig +154 -0
  381. package/src/runtime/canvas_limits.zig +1 -1
  382. package/src/runtime/canvas_presentation_lifecycle_policy.zig +86 -0
  383. package/src/runtime/canvas_scene_observation_policy.zig +181 -0
  384. package/src/runtime/canvas_widget_context_menu.zig +183 -4
  385. package/src/runtime/canvas_widget_context_menu_test_cases.zig +1147 -0
  386. package/src/runtime/canvas_widget_context_menu_tests.zig +23 -1098
  387. package/src/runtime/canvas_widget_display.zig +110 -9
  388. package/src/runtime/canvas_widget_events.zig +718 -328
  389. package/src/runtime/canvas_widget_runtime.zig +720 -150
  390. package/src/runtime/canvas_widget_scroll_drivers.zig +39 -1
  391. package/src/runtime/canvas_widget_scroll_tests.zig +31 -0
  392. package/src/runtime/canvas_widget_state.zig +93 -56
  393. package/src/runtime/channel_sources.zig +80 -0
  394. package/src/runtime/command_policy.zig +161 -0
  395. package/src/runtime/component_policy.zig +83 -0
  396. package/src/runtime/context_menu_policy.zig +112 -0
  397. package/src/runtime/core.zig +170 -6
  398. package/src/runtime/desktop_files.zig +189 -0
  399. package/src/runtime/effects.zig +638 -33
  400. package/src/runtime/effects_host_tests.zig +25 -0
  401. package/src/runtime/effects_tests.zig +28 -0
  402. package/src/runtime/file_policy_test_reference.zig +113 -0
  403. package/src/runtime/flow.zig +419 -341
  404. package/src/runtime/flow_reference.zig +1427 -0
  405. package/src/runtime/font_registry_policy.zig +72 -0
  406. package/src/runtime/frame_profile.zig +24 -33
  407. package/src/runtime/global_shortcuts.zig +75 -0
  408. package/src/runtime/gpu_surface_events.zig +97 -35
  409. package/src/runtime/host_event_pump.zig +303 -0
  410. package/src/runtime/host_event_pump_reference.zig +268 -0
  411. package/src/runtime/host_flow_policy.zig +155 -0
  412. package/src/runtime/host_input_regions_policy.zig +156 -0
  413. package/src/runtime/image_registry_policy.zig +94 -0
  414. package/src/runtime/input_composition_policy.zig +138 -0
  415. package/src/runtime/journal_policy.zig +66 -0
  416. package/src/runtime/journal_reference.zig +53 -0
  417. package/src/runtime/keyboard_input.zig +86 -0
  418. package/src/runtime/lifecycle_policy_test_reference.zig +97 -0
  419. package/src/runtime/markup_development_policy.zig +91 -0
  420. package/src/runtime/media_surface.zig +40 -1
  421. package/src/runtime/motion_sampling_policy.zig +159 -0
  422. package/src/runtime/recording_policy.zig +42 -0
  423. package/src/runtime/render_animation_policy.zig +206 -0
  424. package/src/runtime/replay_policy.zig +66 -0
  425. package/src/runtime/replay_policy_reference.zig +326 -0
  426. package/src/runtime/replay_progress_policy.zig +64 -0
  427. package/src/runtime/replay_progress_reference.zig +34 -0
  428. package/src/runtime/request_policy_test_reference.zig +188 -0
  429. package/src/runtime/root.zig +16 -0
  430. package/src/runtime/scroll_mutation_policy.zig +130 -0
  431. package/src/runtime/scroll_mutation_runtime.zig +158 -0
  432. package/src/runtime/scroll_tree_policy.zig +99 -0
  433. package/src/runtime/session_blobs.zig +157 -58
  434. package/src/runtime/session_blobs_reference.zig +692 -0
  435. package/src/runtime/session_codec.zig +361 -0
  436. package/src/runtime/session_codec_reference.zig +1027 -0
  437. package/src/runtime/session_journal.zig +246 -983
  438. package/src/runtime/session_record.zig +231 -45
  439. package/src/runtime/session_replay.zig +157 -415
  440. package/src/runtime/session_tests.zig +552 -0
  441. package/src/runtime/shell_admission_policy.zig +225 -0
  442. package/src/runtime/shell_coordination_policy.zig +138 -0
  443. package/src/runtime/shell_layout.zig +126 -1
  444. package/src/runtime/snapshot_policy.zig +60 -0
  445. package/src/runtime/snapshot_reference.zig +64 -0
  446. package/src/runtime/staged_rebuild_policy.zig +83 -0
  447. package/src/runtime/state.zig +16 -0
  448. package/src/runtime/status_validation.zig +190 -0
  449. package/src/runtime/system_admission_policy.zig +140 -0
  450. package/src/runtime/system_services.zig +65 -36
  451. package/src/runtime/tests.zig +2 -0
  452. package/src/runtime/ts_canvas_hooks.zig +261 -0
  453. package/src/runtime/ts_canvas_hooks_tests.zig +279 -0
  454. package/src/runtime/ts_canvas_icons.zig +234 -0
  455. package/src/runtime/ts_core_host.zig +2451 -411
  456. package/src/runtime/ts_core_host_tests.zig +1982 -0
  457. package/src/runtime/ts_test_host.zig +699 -0
  458. package/src/runtime/ts_ui_app.zig +1111 -45
  459. package/src/runtime/ui_app.zig +1381 -650
  460. package/src/runtime/ui_app_provenance.zig +147 -5
  461. package/src/runtime/ui_app_provenance_reference.zig +370 -0
  462. package/src/runtime/ui_app_tests.zig +667 -188
  463. package/src/runtime/ui_app_window_tests.zig +222 -0
  464. package/src/runtime/view.zig +25 -0
  465. package/src/runtime/view_canvas.zig +30 -6
  466. package/src/runtime/view_coordination_policy.zig +147 -0
  467. package/src/runtime/view_reload.zig +226 -0
  468. package/src/runtime/view_widget_control.zig +51 -14
  469. package/src/runtime/view_widget_scroll.zig +46 -26
  470. package/src/runtime/view_widget_text.zig +153 -68
  471. package/src/runtime/view_widget_tree.zig +503 -69
  472. package/src/runtime/virtual_window_policy.zig +128 -0
  473. package/src/runtime/web_pane_policy.zig +111 -0
  474. package/src/runtime/web_pane_test_cases.zig +204 -0
  475. package/src/runtime/webview_view_bridge_tests.zig +2 -0
  476. package/src/runtime/widget_continuity_policy.zig +73 -0
  477. package/src/runtime/widget_motion_policy.zig +238 -0
  478. package/src/runtime/widget_reconcile_policy.zig +81 -0
  479. package/src/runtime/widget_retention_policy.zig +75 -0
  480. package/src/runtime/window_command_bridge_tests.zig +63 -0
  481. package/src/runtime/window_lifecycle_policy.zig +127 -0
  482. package/src/runtime/window_storage.zig +74 -8
  483. package/src/runtime/window_view_runtime.zig +148 -33
  484. package/src/runtime/window_views.zig +179 -11
  485. package/src/security/root.zig +1 -0
  486. package/src/tooling/components/identity_tests.zig +62 -36
  487. package/src/tooling/components/stepper.native +24 -0
  488. package/src/tooling/components/stepper.zig +0 -19
  489. package/src/tooling/components/timeline-item.native +22 -0
  490. package/src/tooling/components/timeline.native +5 -3
  491. package/src/tooling/components/timeline_item.zig +0 -32
  492. package/src/tooling/eject_components.zig +76 -8
  493. package/src/tooling/ios.zig +66 -12
  494. package/src/tooling/manifest.zig +35 -0
  495. package/src/tooling/raw_manifest.zig +6 -0
  496. package/src/tooling/templates.zig +23 -3
  497. package/src/tooling/ts_core.zig +97 -4
  498. package/src/tooling/verbs.zig +87 -1
  499. package/tools/corewire/build_profile.mjs +54 -0
  500. package/tools/corewire/contract_intake.ts +303 -0
  501. package/tools/corewire/contract_intake.zig +82 -0
  502. package/tools/corewire/core.test.ts +188 -0
  503. package/tools/corewire/core_abi.zig +55 -0
  504. package/tools/corewire/core_cases.ts +233 -0
  505. package/tools/corewire/core_contract.ts +407 -0
  506. package/tools/corewire/core_emission.ts +136 -0
  507. package/tools/corewire/core_emission.zig +69 -0
  508. package/tools/corewire/core_goldens.json +3110 -0
  509. package/tools/corewire/core_policy.ts +14 -0
  510. package/tools/corewire/core_policy.zig +48 -0
  511. package/tools/corewire/core_projection.ts +361 -0
  512. package/tools/corewire/core_vocabulary.ts +6 -0
  513. package/tools/corewire/emit.zig +19 -1590
  514. package/tools/corewire/emit_facade.ts +714 -0
  515. package/tools/corewire/emit_facade.zig +10 -3752
  516. package/tools/corewire/emit_mirror.ts +300 -0
  517. package/tools/corewire/emit_profile.ts +50 -0
  518. package/tools/corewire/emit_service.ts +331 -0
  519. package/tools/corewire/emit_service.zig +23 -842
  520. package/tools/corewire/entry.test.ts +95 -0
  521. package/tools/corewire/entry_coordination.ts +127 -0
  522. package/tools/corewire/entry_coordination.zig +190 -0
  523. package/tools/corewire/facade_templates.ts +85 -0
  524. package/tools/corewire/filesystem.test.ts +166 -0
  525. package/tools/corewire/filesystem_coordination.ts +213 -0
  526. package/tools/corewire/filesystem_coordination.zig +245 -0
  527. package/tools/corewire/intake.test.ts +39 -0
  528. package/tools/corewire/intake_cases.ts +55 -0
  529. package/tools/corewire/intake_goldens.json +12237 -0
  530. package/tools/corewire/invocation.test.ts +28 -0
  531. package/tools/corewire/invocation.ts +175 -0
  532. package/tools/corewire/invocation.zig +136 -0
  533. package/tools/corewire/invocation_cases.ts +60 -0
  534. package/tools/corewire/invocation_fixture.ts +33 -0
  535. package/tools/corewire/invocation_goldens.json +1143 -0
  536. package/tools/corewire/invocation_tests.zig +111 -0
  537. package/tools/corewire/invocation_usage.ts +2 -0
  538. package/tools/corewire/lossless_projection.ts +96 -0
  539. package/tools/corewire/main.zig +7 -680
  540. package/tools/corewire/main_reference.zig +415 -0
  541. package/tools/corewire/mirror_templates.ts +59 -0
  542. package/tools/corewire/profile.test.ts +248 -0
  543. package/tools/corewire/profile.zig +56 -0
  544. package/tools/corewire/profile_emission.ts +204 -0
  545. package/tools/corewire/profile_library.json +29 -0
  546. package/tools/corewire/profile_tests.zig +136 -0
  547. package/tools/corewire/service.test.ts +75 -0
  548. package/tools/corewire/service_cases.ts +61 -0
  549. package/tools/corewire/service_contract.zig +40 -146
  550. package/tools/corewire/service_goldens.json +650 -0
  551. package/tools/corewire/service_projection.zig +52 -0
  552. package/tools/corewire/service_templates.ts +14 -0
  553. package/tools/corewire/shim_rt.zig +9 -0
  554. package/tools/corewire/sidecar.zig +269 -1438
  555. package/tools/corewire/emit_profile.zig +0 -521
@@ -29,7 +29,10 @@
29
29
  //! false })` so the watch machinery compiles out too). Setting both keeps
30
30
  //! the compiled view until the watched file first changes on disk.
31
31
 
32
+ const authorization = @import("authorization_policy.zig");
32
33
  const std = @import("std");
34
+ pub const web_pane_policy = @import("web_pane_policy.zig");
35
+ pub const virtual_window_policy = @import("virtual_window_policy.zig");
33
36
  const builtin = @import("builtin");
34
37
  const geometry = @import("geometry");
35
38
  const canvas = @import("canvas");
@@ -38,12 +41,18 @@ const security = @import("../security/root.zig");
38
41
  const platform = @import("../platform/root.zig");
39
42
  const core = @import("core.zig");
40
43
  const canvas_frame = @import("canvas_frame.zig");
44
+ const view_reload = @import("view_reload.zig");
41
45
  const canvas_limits = @import("canvas_limits.zig");
42
46
  const canvas_widget_events = @import("canvas_widget_events.zig");
47
+ const drag_policy = @import("canvas_drag_policy.zig");
48
+ const dispatch_policy = @import("app_dispatch_policy.zig");
49
+ const component_policy = @import("component_policy.zig");
50
+ const hover_policy = @import("canvas_hover_policy.zig");
43
51
  const launch_timing = @import("launch_timing.zig");
44
52
  const runtime_effects = @import("effects.zig");
45
53
  const terminal_session = @import("terminal_session.zig");
46
54
  const ui_app_provenance = @import("ui_app_provenance.zig");
55
+ const markup_development = @import("markup_development_policy.zig");
47
56
 
48
57
  const Runtime = core.Runtime;
49
58
  const App = core.App;
@@ -96,6 +105,14 @@ pub const UiAppFeatures = struct {
96
105
  /// `canvas.CompiledMarkupView` so no parser code (or its diagnostics)
97
106
  /// ships in the binary; the markup machinery then compiles to nothing.
98
107
  runtime_markup: bool = true,
108
+ /// Generated TypeScript views observe compiled state directly. This
109
+ /// selects their stateless host handle instead of a decoded model mirror.
110
+ compiled_model: bool = false,
111
+ /// Debug builds of compiled views that reload markup edits
112
+ /// (view_reload.zig). Their views report where each widget was
113
+ /// authored, so `provenance` and write-back work without the
114
+ /// runtime markup engine.
115
+ view_reload: bool = false,
99
116
  };
100
117
 
101
118
  pub fn UiApp(comptime ModelT: type, comptime MsgT: type) type {
@@ -116,6 +133,16 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
116
133
  /// state, polling, and registration collapse to nothing.
117
134
  const fragment_watch_enabled = features.runtime_markup and builtin.mode == .Debug;
118
135
 
136
+ /// A compiled view's own development reload (Debug only; see
137
+ /// view_reload.zig). When the app wiring installs a hook, the
138
+ /// markup watch timer polls it; this app rebuilds every open window
139
+ /// from the reloaded view and reports failures through the markup
140
+ /// diagnostic, keeping the last good view.
141
+ const view_reload_enabled = builtin.mode == .Debug;
142
+ /// The widget provenance table: the markup interpreter's, or a
143
+ /// reloading compiled view's (Debug).
144
+ const provenance_enabled = features.runtime_markup or (features.view_reload and view_reload_enabled);
145
+
119
146
  /// Fixed budget of watched fragments per app. Registrations past
120
147
  /// it are not watched (a teaching warning names the budget when
121
148
  /// the watch arms) — a view embedding more compiled fragments
@@ -193,7 +220,8 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
193
220
  /// BUDGET instead: `build` may emit any count up to it.
194
221
  prefix_commands: usize,
195
222
  /// Number of chrome commands preserved after the
196
- /// widget-generated commands. Always exact.
223
+ /// widget-generated commands. Exact with the combined builder;
224
+ /// a budget when build_suffix supplies a separate derived layer.
197
225
  suffix_commands: usize = 0,
198
226
  /// The prefix length is whatever `build` emitted this
199
227
  /// rebuild (minus the fixed suffix) rather than an exact
@@ -209,6 +237,9 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
209
237
  /// commands (up to `prefix_commands` under
210
238
  /// `variable_prefix`).
211
239
  build: *const fn (model: *const ModelT, builder: *canvas.Builder, size: geometry.SizeF, tokens: canvas.DesignTokens) anyerror!void,
240
+ /// Optional independent suffix. The first builder supplies only
241
+ /// the prefix; both actual lengths are retained on every rebuild.
242
+ build_suffix: ?*const fn (model: *const ModelT, builder: *canvas.Builder, size: geometry.SizeF, tokens: canvas.DesignTokens) anyerror!void = null,
212
243
  };
213
244
 
214
245
  /// A live webview region hosted alongside the canvas — the "both
@@ -292,6 +323,10 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
292
323
  pack: ?canvas.ThemePack = null,
293
324
  color_scheme: ThemeColorScheme = .system,
294
325
  accent: ?canvas.Color = null,
326
+ /// Omission follows the OS; explicit values retain observed
327
+ /// accessibility appearance in the model during replay.
328
+ high_contrast: ?bool = null,
329
+ reduce_motion: ?bool = null,
295
330
  /// Adapter-only invalid declaration marker. Zig cores already
296
331
  /// pass a typed Color; the TS adapter retains malformed source
297
332
  /// text here so rebuild rejects it instead of silently inheriting.
@@ -479,8 +514,53 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
479
514
  };
480
515
 
481
516
  pub const Options = struct {
517
+ /// Resolve authored PTY names without exposing engine identities.
518
+ pty_key_resolver: ?*const fn ([]const u8) u64 = null,
482
519
  name: []const u8,
483
520
  scene: app_manifest.ShellConfig,
521
+ /// Portable dispatch/drain scheduling. Native owns messages,
522
+ /// queue boundaries, errors and capability execution; plans copy.
523
+ replay_policy: ?*const fn ([]const u8, []u8) usize = null,
524
+ recording_policy: ?*const fn ([]const u8, []u8) usize = null,
525
+ blob_policy: ?*const fn ([]const u8, []u8) usize = null,
526
+ app_dispatch_policy: dispatch_policy.Policy = null,
527
+ /// Portable context-menu and scroll coordination; native owns pins and latches.
528
+ component_policy: component_policy.Policy = null,
529
+ /// Portable construction is owned by the compiled app; the
530
+ /// builder copies descriptors into its existing generation arena.
531
+ composition_policy: ?canvas.ComponentCompositionPolicy.Policy = null,
532
+ code_content_policy: ?canvas.CodeContentPolicy.Policy = null,
533
+ paragraph_policy: ?*const fn ([]const u8, []u8) usize = null,
534
+ text_run_policy: ?*const fn ([]const u8, []u8) usize = null,
535
+ chart_content_policy: ?canvas.ChartContentPolicy.Policy = null,
536
+ markdown_content_policy: ?canvas.MarkdownContentPolicy.Policy = null,
537
+ construction_policy: ?canvas.ComponentConstructionPolicy.Policy = null,
538
+ expression_policy: ?*const fn ([]const u8, []u8) usize = null,
539
+ shell_layout_policy: ?*const fn ([]const u8, []u8) usize = null,
540
+ view_coordination_policy: ?*const fn ([]const u8, []u8) usize = null,
541
+ window_lifecycle_policy: ?*const fn ([]const u8, []u8) usize = null,
542
+ image_registry_policy: ?*const fn ([]const u8, []u8) usize = null,
543
+ font_registry_policy: ?*const fn ([]const u8, []u8) usize = null,
544
+ shell_coordination_policy: ?*const fn ([]const u8, []u8) usize = null,
545
+ shell_admission_policy: ?*const fn ([]const u8, []u8) usize = null,
546
+ system_admission_policy: ?*const fn ([]const u8, []u8) usize = null,
547
+ bridge_descriptor_policy: ?*const fn ([]const u8, []u8) usize = null,
548
+ authorization_policy: ?*const fn ([]const u8, []u8) usize = null,
549
+ builtin_coordination_policy: ?*const fn ([]const u8, []u8) usize = null,
550
+ automation_command_policy: ?*const fn ([]const u8, []u8) usize = null,
551
+ automation_interaction_policy: ?*const fn ([]const u8, []u8) usize = null,
552
+ snapshot_policy: ?*const fn ([]const u8, []u8) usize = null,
553
+ host_flow_policy: ?*const fn ([]const u8, []u8) usize = null,
554
+ /// Copied root/fragment reload and complete provenance programs.
555
+ markup_development_policy: markup_development.Policy = null,
556
+ /// Installed by TsUiApp for compiled command and status policy.
557
+ command_policy: ?*const fn ([]const u8, []u8) usize = null,
558
+ context_menu_policy: ?*const fn ([]const u8, []u8) usize = null,
559
+ text_cache_policy: ?*const fn ([]const u8, []u8) usize = null,
560
+ render_cache_policy: ?*const fn ([]const u8, []u8) usize = null,
561
+ render_plan_policy: ?*const fn ([]const u8, []u8) usize = null,
562
+ render_override_policy: ?*const fn ([]const u8, []u8) usize = null,
563
+ render_damage_policy: ?*const fn ([]const u8, []u8) usize = null,
484
564
  canvas_label: []const u8,
485
565
  /// Fixed design tokens for an app that owns its look. Leave
486
566
  /// null (the default) and the stock tokens FOLLOW THE SYSTEM
@@ -495,6 +575,33 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
495
575
  /// scale afterwards: the model owns scheme/contrast/motion,
496
576
  /// the runtime owns the surface scale.
497
577
  tokens_fn: ?*const fn (model: *const ModelT) canvas.DesignTokens = null,
578
+ /// Portable surface placement over native measurements, independent of theme overrides.
579
+ surface_layout_policy: ?*const fn ([]const u8, []u8) usize = null,
580
+ grid_layout_policy: ?*const fn ([]const u8, []u8) usize = null,
581
+ container_layout_policy: ?*const fn ([]const u8, []u8) usize = null,
582
+ measurement_coordination_policy: ?*const fn ([]const u8, []u8) usize = null,
583
+ flow_measurement_policy: ?*const fn ([]const u8, []u8) usize = null,
584
+ layout_coordination_policy: ?*const fn ([]const u8, []u8) usize = null,
585
+ render_coordination_policy: ?*const fn ([]const u8, []u8) usize = null,
586
+ control_command_policy: ?*const fn ([]const u8, []u8) usize = null,
587
+ intrinsic_layout_policy: ?*const fn ([]const u8, []u8) usize = null,
588
+ widget_motion_policy: ?*const fn ([]const u8, []u8) usize = null,
589
+ widget_audit_policy: ?*const fn ([]const u8, []u8) usize = null,
590
+ accessibility_policy: ?*const fn ([]const u8, []u8) usize = null,
591
+ widget_routing_policy: ?*const fn ([]const u8, []u8) usize = null,
592
+ widget_change_policy: ?*const fn ([]const u8, []u8) usize = null,
593
+ widget_retention_policy: ?*const fn ([]const u8, []u8) usize = null,
594
+ widget_reconcile_policy: ?*const fn ([]const u8, []u8) usize = null,
595
+ scroll_tree_policy: ?*const fn ([]const u8, []u8) usize = null,
596
+ scroll_mutation_policy: ?*const fn ([]const u8, []u8) usize = null,
597
+ widget_continuity_policy: ?*const fn ([]const u8, []u8) usize = null,
598
+ staged_rebuild_policy: ?*const fn ([]const u8, []u8) usize = null,
599
+ virtual_window_policy: ?virtual_window_policy.Policy = null,
600
+ widget_paint_policy: ?*const fn ([]const u8, []u8) usize = null,
601
+ widget_presentation_policy: ?*const fn ([]const u8, []u8) usize = null,
602
+ terminal_paint_policy: ?*const fn ([]const u8, []u8) usize = null,
603
+ widget_paint_walk_policy: ?*const fn ([]const u8, []u8) usize = null,
604
+ control_geometry_policy: ?*const fn ([]const u8, []u8) usize = null,
498
605
  /// Which built-in theme pack the stock tokens resolve when
499
606
  /// the app claims neither `tokens` nor `tokens_fn`: the
500
607
  /// pack composes with the live system appearance (scheme,
@@ -517,6 +624,10 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
517
624
  /// is mutually exclusive with it. Explicit `tokens_fn`/`tokens`
518
625
  /// still own the complete register and take precedence.
519
626
  theme_state_fn: ?*const fn (model: *const ModelT) ThemeState = null,
627
+ /// Model-derived overrides over the resolved stock register.
628
+ /// Explicit complete tokens retain precedence; device scale and
629
+ /// native measurement capabilities remain runtime-owned.
630
+ token_overrides_fn: ?*const fn (model: *const ModelT) canvas.DesignTokenOverrides = null,
520
631
  /// The app's ONE-accent brand statement over the stock
521
632
  /// tokens: when set (and the app claims neither `tokens`
522
633
  /// nor `tokens_fn` — apps that own their tokens own their
@@ -529,6 +640,9 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
529
640
  /// this to app.zon's `theme_accent` field through
530
641
  /// `app_runner.manifestThemeAccent()`.
531
642
  theme_accent: ?canvas.Color = null,
643
+ /// Optional portable stock-theme policy. Inputs carry explicit
644
+ /// presence/appearance facts; copied results retain dispatch lifetime.
645
+ theme_policy: ?*const fn ([]const u8, []u8) usize = null,
532
646
  /// App font faces registered once, on the installing frame,
533
647
  /// BEFORE the first view build — so the very first layout
534
648
  /// already measures (and the first paint inks) with them.
@@ -605,6 +719,8 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
605
719
  /// Optional mapping from shell command events (menus, shortcuts,
606
720
  /// native controls) into messages.
607
721
  on_command: ?*const fn (name: []const u8) ?MsgT = null,
722
+ /// A source window's label is input context, reduced before its event.
723
+ on_window_context: ?*const fn (model: *const ModelT, label: []const u8) ?MsgT = null,
608
724
  /// Optional mapping from app lifecycle events into messages.
609
725
  /// A single-window app can use activate/deactivate as its
610
726
  /// keyboard-focus signal for custom canvas chrome whose
@@ -783,10 +899,14 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
783
899
  /// selected (`-Dweb-engine=system|cef`); platforms without
784
900
  /// child webviews log a warning and continue.
785
901
  web_panes: ?*const fn (model: *const ModelT, out: []WebViewPane) usize = null,
902
+ web_pane_policy: ?web_pane_policy.Policy = null,
786
903
  /// Menu-bar extra installed once, on the installing frame.
787
904
  /// macOS-proven (`NSStatusItem`); platforms without a
788
905
  /// status-bar service log a warning and continue.
789
906
  status_item: ?StatusItemOptions = null,
907
+ /// Optional portable reconciliation. Requests borrow native facts;
908
+ /// results are copied without resetting the current dispatch frame.
909
+ status_policy: ?*const fn ([]const u8, []u8) usize = null,
790
910
  /// Model-derived status-item title and menu (e.g. an
791
911
  /// open-count badge in the menu bar, a latest-items
792
912
  /// dropdown), the `web_panes` pattern: consulted on install
@@ -819,6 +939,23 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
819
939
  /// no close Msg. Reconcile failures degrade to logged warnings
820
940
  /// — a failed create never takes the render loop down.
821
941
  windows_fn: ?*const fn (model: *const ModelT, scratch: *WindowsScratch) []const WindowDescriptor = null,
942
+ /// Optional portable reconciliation over native-owned window
943
+ /// facts. The callback copies its output; rebuild/view consumers
944
+ /// retain ownership of the compiler frame and descriptor storage.
945
+ window_policy: ?*const fn (request: []const u8, output: []u8) usize = null,
946
+ /// Optional portable hold coordination; native retains timer
947
+ /// capabilities, armed identities and owned handler tables.
948
+ press_hold_policy: ?*const fn (request: []const u8, output: []u8) usize = null,
949
+ /// Portable Tab order over retained-tree facts. Native keeps
950
+ /// identities, measured eligibility, reveal and OS focus.
951
+ tab_focus_policy: ?*const fn (request: []const u8, output: []u8) usize = null,
952
+ /// Portable anchored-surface selection; native retains paint
953
+ /// facts, identities and dismissal/focus side effects.
954
+ surface_scope_policy: ?*const fn (request: []const u8, output: []u8) usize = null,
955
+ /// Portable return-target selection for dismissed/unmounted surfaces.
956
+ focus_return_policy: ?*const fn (request: []const u8, output: []u8) usize = null,
957
+ /// Portable tooltip ownership and adoption-time binding survival.
958
+ tooltip_policy: ?*const fn (request: []const u8, output: []u8) usize = null,
822
959
  /// Per-window view for declared secondary windows, keyed by
823
960
  /// the descriptor's window label — the `view` seam with the
824
961
  /// window identity alongside. Rebuilt for every open window
@@ -1020,16 +1157,17 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1020
1157
  markup_fragment_slots: if (fragment_watch_enabled) [max_watched_fragments]MarkupFragmentSlot else void,
1021
1158
  /// Widget provenance (write-back's read half): the retained
1022
1159
  /// structural-id -> authored-markup table the `provenance`
1023
- /// automation verb answers from. Exists only in markup-interpreter
1024
- /// builds; filled only while automation is enabled.
1025
- provenance: if (features.runtime_markup) ui_app_provenance.ProvenanceTable else void =
1026
- if (features.runtime_markup) .{} else {},
1160
+ /// automation verb answers from. Exists in markup-interpreter builds
1161
+ /// and in reloading compiled-view builds (Debug); filled only while
1162
+ /// automation is enabled.
1163
+ provenance: if (provenance_enabled) ui_app_provenance.ProvenanceTable else void =
1164
+ if (provenance_enabled) .{} else {},
1027
1165
  /// Import-closure staging for the file table: filled by the
1028
1166
  /// hashing loader during a resolve, committed on adopt so a failed
1029
1167
  /// mid-edit reload can never re-anchor spans to bytes the running
1030
1168
  /// view was not built from.
1031
- provenance_closure: if (features.runtime_markup) ui_app_provenance.ClosureFiles else void =
1032
- if (features.runtime_markup) .{} else {},
1169
+ provenance_closure: if (provenance_enabled) ui_app_provenance.ClosureFiles else void =
1170
+ if (provenance_enabled) .{} else {},
1033
1171
  layout_nodes: [canvas_limits.max_canvas_widget_nodes_per_view]canvas.WidgetLayoutNode = undefined,
1034
1172
  gpu_commands: [canvas_limits.max_canvas_commands_per_view]canvas.CanvasGpuCommand = undefined,
1035
1173
  /// Packet transport buffer, sized for the larger of the two wire
@@ -1344,6 +1482,8 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1344
1482
  return .{
1345
1483
  .model = model,
1346
1484
  .options = options,
1485
+ .provenance = if (comptime provenance_enabled) .{ .policy = options.markup_development_policy, .allocator = backing } else {},
1486
+ .provenance_closure = if (comptime provenance_enabled) .{ .policy = options.markup_development_policy } else {},
1347
1487
  .backing = backing,
1348
1488
  .arenas = .{
1349
1489
  std.heap.ArenaAllocator.init(backing),
@@ -1410,6 +1550,8 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1410
1550
  self.* = .{
1411
1551
  .model = undefined,
1412
1552
  .options = options,
1553
+ .provenance = if (comptime provenance_enabled) .{ .policy = options.markup_development_policy, .allocator = backing } else {},
1554
+ .provenance_closure = if (comptime provenance_enabled) .{ .policy = options.markup_development_policy } else {},
1413
1555
  .backing = backing,
1414
1556
  .arenas = .{
1415
1557
  std.heap.ArenaAllocator.init(backing),
@@ -1474,9 +1616,34 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1474
1616
  .context = self,
1475
1617
  .name = self.options.name,
1476
1618
  .scene_fn = sceneFn,
1619
+ .shell_layout_policy = self.options.shell_layout_policy,
1620
+ .view_coordination_policy = self.options.view_coordination_policy,
1621
+ .window_lifecycle_policy = self.options.window_lifecycle_policy,
1622
+ .image_registry_policy = self.options.image_registry_policy,
1623
+ .font_registry_policy = self.options.font_registry_policy,
1624
+ .shell_coordination_policy = self.options.shell_coordination_policy,
1625
+ .shell_admission_policy = self.options.shell_admission_policy,
1626
+ .system_admission_policy = self.options.system_admission_policy,
1627
+ .bridge_descriptor_policy = self.options.bridge_descriptor_policy,
1628
+ .authorization_policy = self.options.authorization_policy,
1629
+ .builtin_coordination_policy = self.options.builtin_coordination_policy,
1630
+ .automation_command_policy = self.options.automation_command_policy,
1631
+ .automation_interaction_policy = self.options.automation_interaction_policy,
1632
+ .snapshot_policy = self.options.snapshot_policy,
1633
+ .host_flow_policy = self.options.host_flow_policy,
1634
+ .command_policy = self.options.command_policy,
1635
+ .context_menu_policy = self.options.context_menu_policy,
1636
+ .text_cache_policy = self.options.text_cache_policy,
1637
+ .render_cache_policy = self.options.render_cache_policy,
1638
+ .render_plan_policy = self.options.render_plan_policy,
1639
+ .render_override_policy = self.options.render_override_policy,
1640
+ .render_damage_policy = self.options.render_damage_policy,
1477
1641
  .event_fn = eventFn,
1478
1642
  .stop_fn = stopFn,
1479
1643
  .replay_fn = replayFn,
1644
+ .replay_policy = self.options.replay_policy,
1645
+ .recording_policy = self.options.recording_policy,
1646
+ .blob_policy = self.options.blob_policy,
1480
1647
  };
1481
1648
  }
1482
1649
 
@@ -1502,6 +1669,8 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1502
1669
  /// image registry, window verbs, and — while a session is being
1503
1670
  /// recorded — the recorder's result journal.
1504
1671
  fn bindEffectsChannel(self: *Self, runtime: *Runtime) void {
1672
+ self.effects.defer_desktop_capabilities = true;
1673
+ self.effects.system_admission_policy = self.options.system_admission_policy;
1505
1674
  self.effects.bindServices(&runtime.options.platform.services);
1506
1675
  self.effects.bindEnviron(runtime.options.environ);
1507
1676
  if (runtime.options.record_store) |binding| {
@@ -1514,7 +1683,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1514
1683
  .services = &runtime.options.platform.services,
1515
1684
  .service = runtime.options.platform.app_info.bundle_id,
1516
1685
  .permitted = runtime.options.credentials_enabled and
1517
- security.hasPermission(runtime.options.security.permissions, security.permission_credentials),
1686
+ authorization.hasPermission(runtime.authorization_policy, runtime.options.security.permissions, security.permission_credentials),
1518
1687
  });
1519
1688
  if (runtime.options.file_access) |binding| {
1520
1689
  self.effects.bindFileAccess(binding);
@@ -1524,7 +1693,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1524
1693
  // fake file requests must park without consulting live paths.
1525
1694
  self.effects.bindFileAccess(.{
1526
1695
  .roots = &.{},
1527
- .permitted = security.hasPermission(runtime.options.security.permissions, security.permission_filesystem),
1696
+ .permitted = authorization.hasPermission(runtime.authorization_policy, runtime.options.security.permissions, security.permission_filesystem),
1528
1697
  .enforce = true,
1529
1698
  });
1530
1699
  }
@@ -1536,6 +1705,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1536
1705
  .minimize_fn = effectsMinimizeWindowByLabel,
1537
1706
  .hide_fn = effectsHideWindowByLabel,
1538
1707
  .show_fn = effectsShowWindowByLabel,
1708
+ .replay_show_fn = effectsReplayShowWindowByLabel,
1539
1709
  .dock_presence_fn = effectsSetDockPresence,
1540
1710
  .quit_fn = effectsQuitApp,
1541
1711
  });
@@ -1544,8 +1714,16 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1544
1714
  .open_external_url_fn = effectsOpenExternalUrl,
1545
1715
  .reveal_path_fn = effectsRevealPath,
1546
1716
  .format_local_time_fn = effectsFormatLocalTime,
1717
+ .execute_capability_fn = effectsExecuteCapability,
1718
+ .replay_window_result_fn = effectsRestoreWindowResult,
1719
+ .keyboard_input = .{
1720
+ .context = runtime,
1721
+ .send_key_chord_fn = effectsSendKeyChord,
1722
+ .access_fn = effectsKeyboardInputAccess,
1723
+ },
1547
1724
  });
1548
1725
  if (runtime.options.session_recorder) |recorder| {
1726
+ if (self.options.recording_policy) |policy| recorder.recording_policy = policy;
1549
1727
  self.effects.bindJournal(recorder.effectJournal());
1550
1728
  }
1551
1729
  // The terminal-session seams (no-ops on stub builds): the
@@ -1593,7 +1771,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1593
1771
  .exit => {
1594
1772
  if (record.payload.len > 0) try self.effects.feedOutput(record.key, record.payload);
1595
1773
  if (record.stderr_tail.len > 0) try self.effects.feedStderr(record.key, record.stderr_tail);
1596
- try self.effects.feedExitReason(record.key, record.code, record.exit_reason);
1774
+ try self.effects.feedExitWithMetadata(record.key, record.code, record.exit_reason, .{
1775
+ .output_truncated = record.output_truncated,
1776
+ .stderr_truncated = record.stderr_truncated,
1777
+ .dropped_lines = record.dropped,
1778
+ });
1597
1779
  },
1598
1780
  .response => try self.effects.feedResponseOutcomeWithMetadata(
1599
1781
  record.key,
@@ -1619,6 +1801,8 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1619
1801
  // `.rejected` and regenerate from the same
1620
1802
  // deterministic validation, like `.timer` records.
1621
1803
  .host => try self.effects.feedHostResult(record.key, record.code == 0, record.payload),
1804
+ .window_execution => try self.effects.pushReplayWindowExecution(record),
1805
+ .channel_source => try self.effects.pushReplayChannelSource(record),
1622
1806
  .credentials => try self.effects.feedCredentialsResult(
1623
1807
  record.key,
1624
1808
  record.credentials_operation,
@@ -1700,13 +1884,15 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1700
1884
  // is still divergent input).
1701
1885
  .write => try self.effects.pushReplayPtyWriteVerdict(record.key, record.code == 1),
1702
1886
  },
1703
- // Spectrum records feed through the band-carrying
1704
- // helper so replay repaints identical bars; every
1705
- // other audio kind rides the plain shape.
1706
- .audio => if (record.audio_kind == .spectrum)
1707
- try self.effects.feedAudioSpectrum(record.audio_bands, record.audio_position_ms, record.audio_duration_ms)
1708
- else
1709
- try self.effects.feedAudioEventBuffering(record.audio_kind, record.audio_position_ms, record.audio_duration_ms, record.audio_playing, record.audio_buffering),
1887
+ .audio => try self.effects.feedAudioRecord(.{
1888
+ .key = record.key,
1889
+ .kind = record.audio_kind,
1890
+ .position_ms = record.audio_position_ms,
1891
+ .duration_ms = record.audio_duration_ms,
1892
+ .playing = record.audio_playing,
1893
+ .buffering = record.audio_buffering,
1894
+ .bands = record.audio_bands,
1895
+ }),
1710
1896
  // `.video` records feed the whole journaled shape —
1711
1897
  // dimensions included — routed by the journaled
1712
1898
  // load identity (`video_token`), so replay delivers
@@ -1746,120 +1932,110 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1746
1932
  /// widget state is synced into the model first so `update` sees
1747
1933
  /// current slider values and scroll offsets.
1748
1934
  pub fn dispatch(self: *Self, runtime: *Runtime, window_id: platform.WindowId, msg: MsgT) anyerror!void {
1749
- self.bindEffectsChannel(runtime);
1750
- self.syncModel(runtime, self.canvas_window_id);
1751
- self.applyMsg(msg);
1752
- self.publishAudioState(runtime);
1753
- // Before the installing frame there is nothing to render
1754
- // against: canvas size and scale arrive with the first frame
1755
- // event, and the installing rebuild renders whatever model
1756
- // state accumulated here. A pre-install rebuild is discarded
1757
- // work at a default surface size — and appearance/chrome
1758
- // events land before the first frame on every launch, so it
1759
- // used to cost a full view build on the launch path.
1760
- if (!self.installed) return;
1761
- // Hover edges the rebuilds produce (an unmounted hovered
1762
- // element's leave, an adoption re-hit-test's handoff)
1763
- // settle at this tail for DIRECT callers — command
1764
- // handlers, embedders, tests — without waiting for the
1765
- // next platform event, and on the REBUILD-ERROR path too:
1766
- // a failed secondary-window rebuild must not strand the
1767
- // leave the main rebuild already produced. Inside a runtime
1768
- // event the event's own tail drains instead, and the
1769
- // drain's own dispatches re-enter here guarded.
1770
- var rebuild_error: ?anyerror = null;
1771
- self.rebuild(runtime, self.canvas_window_id) catch |err| {
1772
- rebuild_error = err;
1773
- };
1774
- if (rebuild_error == null) self.rebuildWindowSlots(runtime) catch |err| {
1775
- rebuild_error = err;
1776
- };
1777
- if (self.hover_msg_event_depth == 0 and !self.hover_msg_draining) {
1778
- self.drainHoverMsgs(runtime) catch |err| {
1779
- if (rebuild_error == null) rebuild_error = err;
1780
- };
1935
+ for (self.dispatchPlan(.dispatch_begin, false, false)) |byte| {
1936
+ switch (@as(dispatch_policy.Action, @enumFromInt(byte))) {
1937
+ .end => break,
1938
+ .bind => self.bindEffectsChannel(runtime),
1939
+ .sync => self.syncModel(runtime, self.canvas_window_id),
1940
+ .apply => self.applyMsg(msg),
1941
+ .audio => self.publishAudioState(runtime),
1942
+ else => @panic("unexpected dispatch preparation action"),
1943
+ }
1781
1944
  }
1782
- if (rebuild_error) |err| return err;
1783
- // A Msg dispatched FROM a secondary window still rebuilt the
1784
- // main canvas above (one model, every window's view derives
1785
- // from it); `window_id` names the dispatch origin for apps
1786
- // that inspect it, not the rebuild target.
1945
+ // Installation is sampled after update, as in the native loop.
1946
+ const render = self.dispatchPlan(.dispatch_render, self.installed, false);
1947
+ if (render[0] == 0) return;
1948
+ var first_error: ?anyerror = null;
1949
+ try self.executeRebuildPlan(runtime, render, &first_error);
1950
+ try self.settleDispatch(runtime, &first_error);
1787
1951
  _ = window_id;
1788
1952
  }
1789
1953
 
1790
- /// Run `update` through whichever form the app declared; the
1791
- /// effects channel rides along for the `update_fx` form.
1954
+ fn dispatchPlan(self: *Self, stage: dispatch_policy.Stage, a: bool, b: bool) dispatch_policy.Plan {
1955
+ return dispatch_policy.plan(self.options.app_dispatch_policy, stage, @intFromBool(a), @intFromBool(b));
1956
+ }
1957
+
1958
+ fn selectDispatchError(self: *Self, first: *?anyerror, next: ?anyerror) void {
1959
+ const plan = self.dispatchPlan(.error_selection, first.* != null, next != null);
1960
+ for (plan) |byte| switch (@as(dispatch_policy.Action, @enumFromInt(byte))) {
1961
+ .end => break,
1962
+ .take_error => first.* = next,
1963
+ else => @panic("unexpected dispatch error action"),
1964
+ };
1965
+ }
1966
+
1967
+ fn executeRebuildPlan(self: *Self, runtime: *Runtime, plan: dispatch_policy.Plan, first: *?anyerror) anyerror!void {
1968
+ for (plan) |byte| switch (@as(dispatch_policy.Action, @enumFromInt(byte))) {
1969
+ .end => break,
1970
+ .main => {
1971
+ self.rebuild(runtime, self.canvas_window_id) catch |err| self.selectDispatchError(first, err);
1972
+ const secondary = self.dispatchPlan(.secondary, first.* != null, false);
1973
+ for (secondary) |action| switch (@as(dispatch_policy.Action, @enumFromInt(action))) {
1974
+ .end => break,
1975
+ .secondary => self.rebuildWindowSlots(runtime) catch |err| self.selectDispatchError(first, err),
1976
+ else => @panic("unexpected secondary rebuild action"),
1977
+ };
1978
+ },
1979
+ .video_query => {
1980
+ const changed = !std.meta.eql(self.video_rendered_snapshot, self.effects.videoSnapshot());
1981
+ try self.executeRebuildPlan(runtime, self.dispatchPlan(.video_rebuild, changed, false), first);
1982
+ },
1983
+ else => @panic("unexpected rebuild action"),
1984
+ };
1985
+ }
1986
+
1987
+ fn settleDispatch(self: *Self, runtime: *Runtime, first: *?anyerror) anyerror!void {
1988
+ const tail = self.dispatchPlan(.direct_tail, self.hover_msg_event_depth == 0, self.hover_msg_draining);
1989
+ for (tail) |byte| switch (@as(dispatch_policy.Action, @enumFromInt(byte))) {
1990
+ .end => break,
1991
+ .hover => self.drainHoverMsgs(runtime) catch |err| self.selectDispatchError(first, err),
1992
+ else => @panic("unexpected dispatch tail action"),
1993
+ };
1994
+ if (self.hover_msg_event_depth == 0 and !self.hover_msg_draining) self.effects.flushDesktopCapabilities();
1995
+ if (first.*) |err| return err;
1996
+ }
1997
+
1998
+ /// Execute a complete command batch before flushing relational reads.
1792
1999
  fn applyMsg(self: *Self, msg: MsgT) void {
1793
- if (self.options.update_fx) |update_fx| {
1794
- update_fx(&self.model, msg, &self.effects);
1795
- } else {
1796
- self.options.update.?(&self.model, msg);
1797
- }
1798
- // One update call is one complete command batch. Re-run live
1799
- // relational reads only after the batch has walked so several
1800
- // writes touching the same table still coalesce into one result.
1801
- self.effects.flushDbSubscriptions();
2000
+ for (self.dispatchPlan(.update, self.options.update_fx != null, false)) |byte| switch (@as(dispatch_policy.Action, @enumFromInt(byte))) {
2001
+ .end => break,
2002
+ .update_fx => self.options.update_fx.?(&self.model, msg, &self.effects),
2003
+ .update => self.options.update.?(&self.model, msg),
2004
+ .relational_flush => self.effects.flushDbSubscriptions(),
2005
+ else => @panic("unexpected update action"),
2006
+ };
1802
2007
  }
1803
2008
 
1804
- /// Drain the effect completion queue on the loop thread: every
1805
- /// queued line/exit becomes a Msg through its stored constructor
1806
- /// and runs through `update`; one rebuild follows. Called on
1807
- /// `.effects_wake` (the platform marshalled a worker's `wake_fn`
1808
- /// nudge) and each presented frame (host-pumped embeds have no
1809
- /// wake delivery; their frame pump drains naturally).
2009
+ /// Consume a captured causal boundary. Completions created by these
2010
+ /// updates remain queued for the next pass, with native-owned identities.
1810
2011
  pub fn drainEffects(self: *Self, runtime: *Runtime) anyerror!void {
1811
- if (!self.installed) return;
1812
- if (!self.effects.hasPending()) return;
1813
- self.bindEffectsChannel(runtime);
1814
- self.syncModel(runtime, self.canvas_window_id);
2012
+ const admission = self.dispatchPlan(.drain_installed, self.installed, false);
2013
+ var pending = false;
2014
+ for (admission) |byte| switch (@as(dispatch_policy.Action, @enumFromInt(byte))) {
2015
+ .end => break,
2016
+ .pending_query => pending = self.effects.hasPending(),
2017
+ else => @panic("unexpected effect admission action"),
2018
+ };
2019
+ const begin = self.dispatchPlan(.drain_pending, pending, false);
2020
+ if (begin[0] == 0) return;
1815
2021
  var dispatched = false;
1816
- // One pass consumes only completions that existed when it
1817
- // began: a load started by an update handler in THIS pass
1818
- // that finishes while the pass still runs waits for the wake
1819
- // its producer already nudged. That keeps the session
1820
- // journal's event boundaries causal — every result recorded
1821
- // ahead of this wake's event record answers a request from
1822
- // an earlier dispatch, so replay's file-order feed always
1823
- // finds the parked request (see Effects.DrainBoundary).
1824
- var boundary = self.effects.drainBoundary();
1825
- while (self.effects.takeMsgWithin(&boundary)) |msg| {
1826
- self.applyMsg(msg);
1827
- dispatched = true;
1828
- }
1829
- self.publishAudioState(runtime);
1830
- var rebuild_error: ?anyerror = null;
1831
- if (dispatched) {
1832
- self.rebuild(runtime, self.canvas_window_id) catch |err| {
1833
- rebuild_error = err;
1834
- };
1835
- if (rebuild_error == null) self.rebuildWindowSlots(runtime) catch |err| {
1836
- rebuild_error = err;
1837
- };
1838
- } else if (self.installed and
1839
- !std.meta.eql(self.video_rendered_snapshot, self.effects.videoSnapshot()))
1840
- {
1841
- // A drained Msg-less video terminal (a handler-less
1842
- // declarative playback's synchronous failure) moved
1843
- // the mirrors after the last build rendered them:
1844
- // re-render the chrome so its controls never keep
1845
- // advertising a playback that is gone.
1846
- self.rebuild(runtime, self.canvas_window_id) catch |err| {
1847
- rebuild_error = err;
1848
- };
1849
- if (rebuild_error == null) self.rebuildWindowSlots(runtime) catch |err| {
1850
- rebuild_error = err;
1851
- };
1852
- }
1853
- // Same tail as `dispatch`, same error-path duty: effect-
1854
- // driven rebuilds settle the hover edges they produced
1855
- // (this path is also public — host-pumped embeds call it
1856
- // directly).
1857
- if (self.hover_msg_event_depth == 0 and !self.hover_msg_draining) {
1858
- self.drainHoverMsgs(runtime) catch |err| {
1859
- if (rebuild_error == null) rebuild_error = err;
1860
- };
1861
- }
1862
- if (rebuild_error) |err| return err;
2022
+ for (begin) |byte| switch (@as(dispatch_policy.Action, @enumFromInt(byte))) {
2023
+ .end => break,
2024
+ .bind => self.bindEffectsChannel(runtime),
2025
+ .sync => self.syncModel(runtime, self.canvas_window_id),
2026
+ .capture_drain => {
2027
+ var boundary = self.effects.drainBoundary();
2028
+ while (self.effects.takeMsgWithin(&boundary)) |msg| {
2029
+ self.applyMsg(msg);
2030
+ dispatched = true;
2031
+ }
2032
+ },
2033
+ .audio => self.publishAudioState(runtime),
2034
+ else => @panic("unexpected effect drain action"),
2035
+ };
2036
+ var first_error: ?anyerror = null;
2037
+ try self.executeRebuildPlan(runtime, self.dispatchPlan(.drain_rebuild, dispatched, self.installed), &first_error);
2038
+ try self.settleDispatch(runtime, &first_error);
1863
2039
  }
1864
2040
 
1865
2041
  /// Mirror the effects channel's audio playback state into the
@@ -1901,6 +2077,39 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1901
2077
  runtime.video_height = video.height;
1902
2078
  }
1903
2079
 
2080
+ const ThemeControl = struct { mode: u8, follows_system: bool, derives: bool };
2081
+
2082
+ fn themeControl(self: *const Self, scheme: ThemeColorScheme) ThemeControl {
2083
+ const full_tokens = self.options.tokens_fn != null or self.options.tokens != null;
2084
+ if (self.options.theme_policy) |policy| {
2085
+ const request = [_]u8{ 2, @intFromBool(self.options.tokens_fn != null), @intFromBool(self.options.tokens != null), @intFromBool(self.options.theme_state_fn != null), themeSchemeByte(scheme), @intFromBool(self.options.token_overrides_fn != null) };
2086
+ var result: [4]u8 = undefined;
2087
+ if (policy(&request, &result) != result.len or result[0] > 2 or result[1] > 1 or result[2] > 1) @panic("invalid compiled theme control result");
2088
+ return .{ .mode = result[0], .follows_system = result[1] == 1, .derives = result[2] == 1 };
2089
+ }
2090
+ const follows = !full_tokens and (self.options.theme_state_fn == null or scheme == .system);
2091
+ return .{
2092
+ .mode = if (self.options.tokens_fn != null) 1 else if (self.options.tokens != null) 2 else 0,
2093
+ .follows_system = follows,
2094
+ .derives = self.options.tokens_fn != null or self.options.theme_state_fn != null or self.options.token_overrides_fn != null or follows,
2095
+ };
2096
+ }
2097
+
2098
+ fn themeSchemeByte(scheme: ThemeColorScheme) u8 {
2099
+ return switch (scheme) {
2100
+ .system => 0,
2101
+ .light => 1,
2102
+ .dark => 2,
2103
+ };
2104
+ }
2105
+
2106
+ fn themePackByte(pack: canvas.ThemePack) u8 {
2107
+ return switch (pack) {
2108
+ .house => 1,
2109
+ .geist => 2,
2110
+ };
2111
+ }
2112
+
1904
2113
  /// The design tokens for the next rebuild: the model-derived
1905
2114
  /// `tokens_fn`, explicit static `tokens`, or — the default — the
1906
2115
  /// stock theme derived from the SYSTEM appearance the runtime
@@ -1910,42 +2119,117 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1910
2119
  /// appearance, the runtime owns the device scale — so static
1911
2120
  /// tokens snap hairlines against the real surface density too.
1912
2121
  pub fn effectiveTokens(self: *const Self) canvas.DesignTokens {
1913
- if (self.options.tokens_fn) |tokens_fn| {
1914
- var tokens = tokens_fn(&self.model);
1915
- tokens.pixel_snap.scale = self.pixel_snap_scale;
1916
- return tokens;
1917
- }
1918
- if (self.options.tokens) |static_tokens| {
1919
- var tokens = static_tokens;
2122
+ const control = self.themeControl(.system);
2123
+ if (control.mode != 0) {
2124
+ var tokens = switch (control.mode) {
2125
+ 1 => self.options.tokens_fn.?(&self.model),
2126
+ 2 => self.options.tokens.?,
2127
+ else => unreachable,
2128
+ };
1920
2129
  tokens.pixel_snap.scale = self.pixel_snap_scale;
2130
+ tokens.surface_layout_policy = self.options.surface_layout_policy;
2131
+ tokens.grid_layout_policy = self.options.grid_layout_policy;
2132
+ tokens.container_layout_policy = self.options.container_layout_policy;
2133
+ tokens.intrinsic_layout_policy = self.options.intrinsic_layout_policy;
2134
+ tokens.measurement_coordination_policy = self.options.measurement_coordination_policy;
2135
+ tokens.flow_measurement_policy = self.options.flow_measurement_policy;
2136
+ tokens.layout_coordination_policy = self.options.layout_coordination_policy;
2137
+ tokens.render_coordination_policy = self.options.render_coordination_policy;
2138
+ tokens.control_command_policy = self.options.control_command_policy;
2139
+ tokens.widget_motion_policy = self.options.widget_motion_policy;
2140
+ tokens.widget_audit_policy = self.options.widget_audit_policy;
2141
+ tokens.accessibility_policy = self.options.accessibility_policy;
2142
+ tokens.widget_routing_policy = self.options.widget_routing_policy;
2143
+ tokens.widget_change_policy = self.options.widget_change_policy;
2144
+ tokens.widget_retention_policy = self.options.widget_retention_policy;
2145
+ tokens.widget_reconcile_policy = self.options.widget_reconcile_policy;
2146
+ tokens.scroll_tree_policy = self.options.scroll_tree_policy;
2147
+ tokens.scroll_mutation_policy = self.options.scroll_mutation_policy;
2148
+ tokens.widget_continuity_policy = self.options.widget_continuity_policy;
2149
+ tokens.staged_rebuild_policy = self.options.staged_rebuild_policy;
2150
+ tokens.widget_paint_policy = self.options.widget_paint_policy;
2151
+ tokens.widget_presentation_policy = self.options.widget_presentation_policy;
2152
+ tokens.widget_paint_walk_policy = self.options.widget_paint_walk_policy;
2153
+ tokens.terminal_paint_policy = self.options.terminal_paint_policy;
2154
+ tokens.control_geometry_policy = self.options.control_geometry_policy;
2155
+ tokens.code_content_policy = self.options.code_content_policy;
2156
+ tokens.paragraph_policy = self.options.paragraph_policy;
2157
+ tokens.text_run_policy = self.options.text_run_policy;
1921
2158
  return tokens;
1922
2159
  }
1923
2160
  const state = self.currentThemeState();
1924
- const color_scheme: canvas.ColorScheme = switch (state.color_scheme) {
1925
- .system => switch (self.system_appearance.color_scheme) {
2161
+ const high_contrast = state.high_contrast orelse self.system_appearance.high_contrast;
2162
+ const reduce_motion = state.reduce_motion orelse self.system_appearance.reduce_motion;
2163
+ // Preserve lazy legacy helper evaluation when a model pack exists.
2164
+ const fallback_pack = if (state.pack == null and self.options.theme_fn != null) self.options.theme_fn.?(&self.model) else self.options.theme;
2165
+ var pack: canvas.ThemePack = undefined;
2166
+ var color_scheme: canvas.ColorScheme = undefined;
2167
+ var accent: ?canvas.Color = undefined;
2168
+ if (self.options.theme_policy) |policy| {
2169
+ const request = [_]u8{
2170
+ 1, if (state.pack) |value| themePackByte(value) else 0, themePackByte(fallback_pack),
2171
+ themeSchemeByte(state.color_scheme), @intFromBool(self.system_appearance.color_scheme == .dark), @intFromBool(high_contrast),
2172
+ @intFromBool(state.accent != null), @intFromBool(self.options.theme_accent != null),
2173
+ };
2174
+ var result: [4]u8 = undefined;
2175
+ if (policy(&request, &result) != result.len or result[0] < 1 or result[0] > 2 or result[1] > 1 or result[2] > 2) @panic("invalid compiled stock theme result");
2176
+ pack = if (result[0] == 1) .house else .geist;
2177
+ color_scheme = if (result[1] == 0) .light else .dark;
2178
+ accent = switch (result[2]) {
2179
+ 0 => null,
2180
+ 1 => state.accent.?,
2181
+ 2 => self.options.theme_accent.?,
2182
+ else => unreachable,
2183
+ };
2184
+ } else {
2185
+ pack = state.pack orelse fallback_pack;
2186
+ color_scheme = switch (state.color_scheme) {
2187
+ .system => switch (self.system_appearance.color_scheme) {
2188
+ .light => .light,
2189
+ .dark => .dark,
2190
+ },
1926
2191
  .light => .light,
1927
2192
  .dark => .dark,
1928
- },
1929
- .light => .light,
1930
- .dark => .dark,
1931
- };
2193
+ };
2194
+ accent = if (high_contrast) null else state.accent orelse self.options.theme_accent;
2195
+ }
1932
2196
  var tokens = canvas.DesignTokens.theme(.{
1933
2197
  .color_scheme = color_scheme,
1934
- .contrast = if (self.system_appearance.high_contrast) .high else .standard,
1935
- .reduce_motion = self.system_appearance.reduce_motion,
1936
- .pack = state.pack orelse if (self.options.theme_fn) |theme_fn| theme_fn(&self.model) else self.options.theme,
2198
+ .contrast = if (high_contrast) .high else .standard,
2199
+ .reduce_motion = reduce_motion,
2200
+ .pack = pack,
1937
2201
  });
1938
- if (state.accent orelse self.options.theme_accent) |accent| {
1939
- // The manifest accent layers over the resolved pack —
1940
- // except under high contrast, where the pack's own loud
1941
- // register wins untouched (accessibility beats brand).
1942
- // The bundle takes the resolved scheme: the dark ring
1943
- // derives desaturated (canvas.accentFocusRing).
1944
- if (!self.system_appearance.high_contrast) {
1945
- tokens = tokens.withOverrides(canvas.accentOverrides(accent, color_scheme));
1946
- }
1947
- }
2202
+ if (accent) |value| tokens = tokens.withOverrides(canvas.accentOverrides(value, color_scheme));
2203
+ if (self.options.token_overrides_fn) |overrides| tokens = tokens.withOverrides(overrides(&self.model));
1948
2204
  tokens.pixel_snap.scale = self.pixel_snap_scale;
2205
+ tokens.surface_layout_policy = self.options.surface_layout_policy;
2206
+ tokens.grid_layout_policy = self.options.grid_layout_policy;
2207
+ tokens.container_layout_policy = self.options.container_layout_policy;
2208
+ tokens.intrinsic_layout_policy = self.options.intrinsic_layout_policy;
2209
+ tokens.measurement_coordination_policy = self.options.measurement_coordination_policy;
2210
+ tokens.flow_measurement_policy = self.options.flow_measurement_policy;
2211
+ tokens.layout_coordination_policy = self.options.layout_coordination_policy;
2212
+ tokens.render_coordination_policy = self.options.render_coordination_policy;
2213
+ tokens.control_command_policy = self.options.control_command_policy;
2214
+ tokens.widget_motion_policy = self.options.widget_motion_policy;
2215
+ tokens.widget_audit_policy = self.options.widget_audit_policy;
2216
+ tokens.accessibility_policy = self.options.accessibility_policy;
2217
+ tokens.widget_routing_policy = self.options.widget_routing_policy;
2218
+ tokens.widget_change_policy = self.options.widget_change_policy;
2219
+ tokens.widget_retention_policy = self.options.widget_retention_policy;
2220
+ tokens.widget_reconcile_policy = self.options.widget_reconcile_policy;
2221
+ tokens.scroll_tree_policy = self.options.scroll_tree_policy;
2222
+ tokens.scroll_mutation_policy = self.options.scroll_mutation_policy;
2223
+ tokens.widget_continuity_policy = self.options.widget_continuity_policy;
2224
+ tokens.staged_rebuild_policy = self.options.staged_rebuild_policy;
2225
+ tokens.widget_paint_policy = self.options.widget_paint_policy;
2226
+ tokens.widget_presentation_policy = self.options.widget_presentation_policy;
2227
+ tokens.widget_paint_walk_policy = self.options.widget_paint_walk_policy;
2228
+ tokens.terminal_paint_policy = self.options.terminal_paint_policy;
2229
+ tokens.control_geometry_policy = self.options.control_geometry_policy;
2230
+ tokens.code_content_policy = self.options.code_content_policy;
2231
+ tokens.paragraph_policy = self.options.paragraph_policy;
2232
+ tokens.text_run_policy = self.options.text_run_policy;
1949
2233
  return tokens;
1950
2234
  }
1951
2235
 
@@ -1957,13 +2241,14 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1957
2241
  /// Re-derive once per rebuild and reject malformed adapter input at
1958
2242
  /// the declaration boundary. A valid retained state contains no
1959
2243
  /// borrowed accent text, so it remains safe between dispatches.
1960
- fn refreshThemeState(self: *Self) error{InvalidThemeAccent}!void {
2244
+ fn refreshThemeState(self: *Self, runtime: *Runtime) anyerror!void {
1961
2245
  // Complete-token paths outrank the stock-theme helper entirely.
1962
2246
  // Do not even validate an unused model accent: the app has
1963
2247
  // explicitly claimed the whole DesignTokens register.
1964
- if (self.options.tokens_fn != null or self.options.tokens != null) {
2248
+ if (self.themeControl(.system).mode != 0) {
1965
2249
  self.theme_state = .{};
1966
2250
  self.theme_state_known = true;
2251
+ try self.applyWindowColorSchemes(runtime);
1967
2252
  return;
1968
2253
  }
1969
2254
  const next = if (self.options.theme_state_fn) |theme_state_fn| theme_state_fn(&self.model) else ThemeState{};
@@ -1978,6 +2263,24 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1978
2263
  self.theme_state = next;
1979
2264
  self.theme_state_known = true;
1980
2265
  }
2266
+ try self.applyWindowColorSchemes(runtime);
2267
+ }
2268
+
2269
+ fn windowColorScheme(self: *const Self) platform.WindowColorScheme {
2270
+ return switch (self.theme_state.color_scheme) {
2271
+ .system => .system,
2272
+ .light => .light,
2273
+ .dark => .dark,
2274
+ };
2275
+ }
2276
+
2277
+ /// Forward the model-owned declaration, not the resolved OS scheme:
2278
+ /// `system` must remove the native override. Hidden and not-yet-rendered
2279
+ /// windows participate too; no canvas installation is required.
2280
+ fn applyWindowColorSchemes(self: *const Self, runtime: *Runtime) anyerror!void {
2281
+ for (runtime.windows[0..runtime.window_count]) |window| {
2282
+ if (window.info.open) try runtime.options.platform.services.setWindowColorScheme(window.info.id, self.windowColorScheme());
2283
+ }
1981
2284
  }
1982
2285
 
1983
2286
  /// The design tokens for a secondary window's rebuild: the same
@@ -1995,15 +2298,18 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1995
2298
  /// true only when the app claims neither token override, so an
1996
2299
  /// appearance flip must re-derive and re-render.
1997
2300
  fn followsSystemAppearance(self: *const Self) bool {
1998
- if (self.options.tokens_fn != null or self.options.tokens != null) return false;
1999
- if (self.options.theme_state_fn == null) return true;
2000
- return self.currentThemeState().color_scheme == .system;
2301
+ // Preserve the reference helper's lazy evaluation and call count.
2302
+ const scheme = if (self.options.tokens_fn == null and self.options.tokens == null and self.options.theme_state_fn != null)
2303
+ self.currentThemeState().color_scheme
2304
+ else
2305
+ ThemeColorScheme.system;
2306
+ return self.themeControl(scheme).follows_system;
2001
2307
  }
2002
2308
 
2003
2309
  /// Whether tokens are derived per rebuild (model-owned or
2004
2310
  /// system-followed) rather than a fixed set.
2005
2311
  fn derivesTokens(self: *const Self) bool {
2006
- return self.options.tokens_fn != null or self.options.theme_state_fn != null or self.followsSystemAppearance();
2312
+ return self.themeControl(.system).derives;
2007
2313
  }
2008
2314
 
2009
2315
  /// Whether a rebuild must push its tokens into the runtime's
@@ -2053,8 +2359,22 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2053
2359
  /// window converges within the same rebuild instead of waiting
2054
2360
  /// for the next Msg.
2055
2361
  pub fn rebuild(self: *Self, runtime: *Runtime, window_id: platform.WindowId) anyerror!void {
2362
+ for (runtime.windows[0..runtime.window_count]) |window| {
2363
+ if (window.info.id == window_id and !window.info.open) {
2364
+ // The app and secondary windows survive a closed primary
2365
+ // canvas. Continue declaration reconciliation without
2366
+ // installing a tree into the removed native surface.
2367
+ self.tree = null;
2368
+ self.main_tree_current = false;
2369
+ self.releaseContextMenuSnapshotForWindow(window_id);
2370
+ try self.refreshThemeState(runtime);
2371
+ self.applyStatusItem(runtime);
2372
+ self.applyWindows(runtime);
2373
+ return;
2374
+ }
2375
+ }
2056
2376
  self.syncModel(runtime, window_id);
2057
- try self.refreshThemeState();
2377
+ try self.refreshThemeState(runtime);
2058
2378
  if (comptime features.runtime_markup) {
2059
2379
  // Under automation, drive the interpreter from the first
2060
2380
  // frame even when a compiled view is present: provenance
@@ -2107,7 +2427,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2107
2427
  // Apps whose headers already pad through the chrome
2108
2428
  // channel's insets never collide, never retry, and keep a
2109
2429
  // byte-identical layout.
2110
- if (windowControlsReservation(runtime, window_id, self.options.canvas_label, built.layout, tokens)) |controls| {
2430
+ if (try windowControlsReservation(runtime, window_id, self.options.canvas_label, built.layout, tokens)) |controls| {
2111
2431
  tokens.window_controls = controls;
2112
2432
  built = try self.buildLayoutPass(runtime, window_id, bounds, tokens, next_index);
2113
2433
  }
@@ -2155,7 +2475,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2155
2475
  // The fallback menu's target vanished from this build (the
2156
2476
  // model dropped the row, or its menu emptied): the open state
2157
2477
  // has nothing to present, so it closes.
2158
- if (self.contextMenuFallbackTargetForLabel(self.options.canvas_label) != 0 and tree.context_menu_fallback == null) {
2478
+ if (self.componentDecision(.fallback_vanished, self.contextMenuFallbackTargetForLabel(self.options.canvas_label) != 0, tree.context_menu_fallback != null, false) != 0) {
2159
2479
  self.clearContextMenuFallback();
2160
2480
  }
2161
2481
  try self.scheduleAnimations(runtime, window_id);
@@ -2220,9 +2540,10 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2220
2540
  const content_height = @max(0, frame.height - inset.top - inset.bottom);
2221
2541
  const metrics = canvas.terminalCellMetrics(tokens);
2222
2542
  if (metrics.width <= 0 or metrics.height <= 0) continue;
2223
- const proposed = canvas.clampTerminalGrid(
2543
+ const proposed = canvas.terminal_grid.clampGridWithPolicy(
2224
2544
  @intFromFloat(@max(2, @floor(content_width / metrics.width))),
2225
2545
  @intFromFloat(@max(2, @floor(content_height / metrics.height))),
2546
+ tokens.terminal_paint_policy,
2226
2547
  );
2227
2548
  const state = self.terminal_sessions.reconcile(
2228
2549
  pty,
@@ -2329,6 +2650,12 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2329
2650
  std.debug.assert(if (self.context_menu_pin) |pin| pin.window_id != null or pin.arena_index != next_index else true);
2330
2651
  _ = self.arenas[next_index].reset(.retain_capacity);
2331
2652
  var ui = Ui.init(self.arenas[next_index].allocator());
2653
+ ui.composition_policy = self.options.composition_policy;
2654
+ ui.code_content_policy = self.options.code_content_policy;
2655
+ ui.chart_content_policy = self.options.chart_content_policy;
2656
+ ui.markdown_content_policy = self.options.markdown_content_policy;
2657
+ ui.construction_policy = self.options.construction_policy;
2658
+ ui.expression_policy = self.options.expression_policy;
2332
2659
  // The house video chrome renders the channel's honest
2333
2660
  // snapshot, stamped before the view fn runs — the model
2334
2661
  // carries none of it.
@@ -2339,10 +2666,12 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2339
2666
  // driving the palette's theme mapping.
2340
2667
  self.terminal_sessions.beginBuild(tokens);
2341
2668
  ui.terminal_lookup = self.terminal_sessions.lookup();
2669
+ ui.pty_key_resolver = self.options.pty_key_resolver;
2342
2670
  ui.virtual_window_context = @ptrCast(&window_source);
2343
2671
  ui.virtual_window_source = VirtualWindowResolver.resolve;
2344
2672
  ui.virtual_extent_context = @ptrCast(self);
2345
2673
  ui.virtual_extent_source = virtualExtentResolve;
2674
+ ui.virtual_extent_policy = self.options.intrinsic_layout_policy;
2346
2675
  ui.context_menu_fallback_target = self.contextMenuFallbackTargetForLabel(self.options.canvas_label);
2347
2676
  if (ui.context_menu_fallback_target != 0) ui.context_menu_fallback_point = self.context_menu_fallback_point;
2348
2677
  self.armUiFragmentHost(&ui);
@@ -2352,6 +2681,13 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2352
2681
  ui.provenance_sink = self.provenance.sink();
2353
2682
  }
2354
2683
  }
2684
+ if (comptime features.view_reload and view_reload_enabled) {
2685
+ if (view_reload.installed != null and runtime.options.automation != null) {
2686
+ self.provenance.resetRecords();
2687
+ view_reload.view_files_len = 0;
2688
+ ui.provenance_sink = self.provenance.sink();
2689
+ }
2690
+ }
2355
2691
  // Frame-profile stamps (no-ops unless profiling is on): the
2356
2692
  // view build fn + tree finalize is the `rebuild` stage, the
2357
2693
  // flex pass below is `layout`; reconcile/emit are stamped at
@@ -2359,6 +2695,12 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2359
2695
  // are attributed too.
2360
2696
  const rebuild_begin = runtime.frame_profile.begin();
2361
2697
  const node = try self.buildViewNode(&ui);
2698
+ // A compiled view names its markup files as it decodes;
2699
+ // they must be in the table before finalize appends the
2700
+ // records that point at them.
2701
+ if (comptime features.view_reload and view_reload_enabled) {
2702
+ if (ui.provenance_sink != null) self.commitViewSourceFiles();
2703
+ }
2362
2704
  tree = try ui.finalizeWithTokens(node, tokens);
2363
2705
  runtime.frame_profile.end(.rebuild, rebuild_begin);
2364
2706
 
@@ -2408,9 +2750,20 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2408
2750
  // coverage miss does, so the installed frame already
2409
2751
  // consumed it; a residual delta rides to the next
2410
2752
  // rebuild, atomically with the geometry either way.
2411
- const corrected = self.measureVirtualWindows(layout);
2753
+ var virtual_plan: ?virtual_window_policy.Layout = null;
2754
+ if (self.virtual_window_count != 0) {
2755
+ if (self.options.virtual_window_policy) |policy| virtual_plan =
2756
+ virtual_window_policy.Layout.init(policy, self.virtual_windows[0..self.virtual_window_count], layout.nodes);
2757
+ }
2758
+ const plan = if (virtual_plan) |*value| value else null;
2759
+ const corrected = self.measureVirtualWindows(layout, plan);
2412
2760
  pass += 1;
2413
- if (pass >= 2 or (!corrected and !self.virtualWindowsUndercovered(layout))) break;
2761
+ if (self.options.virtual_window_policy) |policy| {
2762
+ var decision = virtual_window_policy.retry(policy, pass, corrected, null);
2763
+ if (decision == .probe) decision = virtual_window_policy.retry(policy, pass, corrected, self.virtualWindowsUndercovered(layout, plan));
2764
+ if (decision == .stop) break;
2765
+ if (decision != .rebuild) @panic("nonprogressing virtual window retry");
2766
+ } else if (pass >= 2 or (!corrected and !self.virtualWindowsUndercovered(layout, null))) break;
2414
2767
  window_source.fresh = layout;
2415
2768
  }
2416
2769
  return .{ .tree = tree, .layout = layout };
@@ -2426,7 +2779,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2426
2779
  /// cluster. `tokens` must be the tokens the layout was built
2427
2780
  /// with: the scan re-measures text through the same seam to
2428
2781
  /// judge painted bounds, not frames.
2429
- fn windowControlsReservation(runtime: *Runtime, window_id: platform.WindowId, canvas_label: []const u8, layout: canvas.WidgetLayoutTree, tokens: canvas.DesignTokens) ?geometry.RectF {
2782
+ fn windowControlsReservation(runtime: *Runtime, window_id: platform.WindowId, canvas_label: []const u8, layout: canvas.WidgetLayoutTree, tokens: canvas.DesignTokens) !?geometry.RectF {
2430
2783
  var has_drag_region = false;
2431
2784
  for (layout.nodes) |node| {
2432
2785
  if (canvas.widgetIsWindowDragRegion(node.widget)) {
@@ -2435,7 +2788,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2435
2788
  }
2436
2789
  }
2437
2790
  if (!has_drag_region) return null;
2438
- const controls = runtime.windowControlsForView(window_id, canvas_label);
2791
+ const controls = try runtime.windowControlsForView(window_id, canvas_label);
2439
2792
  if (controls.width <= 0 or controls.height <= 0) return null;
2440
2793
  if (!canvas.windowDragContentUnderWindowControls(layout.nodes, controls, tokens)) return null;
2441
2794
  return controls;
@@ -2538,7 +2891,25 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2538
2891
  /// Whether any declared virtual window fails to cover the visible
2539
2892
  /// range its FRESH geometry implies (first-build viewport guess,
2540
2893
  /// resize growth): the trigger for the one coverage-retry build.
2541
- fn virtualWindowsUndercovered(self: *const Self, layout: canvas.WidgetLayoutTree) bool {
2894
+ fn virtualWindowsUndercovered(self: *const Self, layout: canvas.WidgetLayoutTree, plan: ?*const virtual_window_policy.Layout) bool {
2895
+ if (plan) |program| {
2896
+ for (self.virtual_windows[0..self.virtual_window_count], 0..) |record, i| {
2897
+ const step = program.list(i);
2898
+ if (step.coverage == .skip) continue;
2899
+ const node = layout.nodes[step.node.?];
2900
+ const viewport = node.frame.inset(node.widget.layout.padding).normalized();
2901
+ switch (step.coverage) {
2902
+ .skip => unreachable,
2903
+ .variable => {
2904
+ const table = self.virtualExtentTableForId(record.id) orelse continue;
2905
+ const offset = @max(0, node.widget.value);
2906
+ if (canvas.virtual_extent_policy.undercovered(self.options.virtual_window_policy.?, record.item_count, table.indexAtOffset(offset), table.indexAtOffset(offset + viewport.height), record.overscan, record.start_index, record.end_index)) return true;
2907
+ },
2908
+ .fixed => if (virtual_window_policy.fixedUndercovered(self.options.virtual_window_policy.?, record, node)) return true,
2909
+ }
2910
+ }
2911
+ return false;
2912
+ }
2542
2913
  for (self.virtual_windows[0..self.virtual_window_count]) |record| {
2543
2914
  const node = layout.findById(record.id) orelse continue;
2544
2915
  const viewport = node.frame.inset(node.widget.layout.padding).normalized();
@@ -2548,7 +2919,12 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2548
2919
  if (record.item_count == 0) continue;
2549
2920
  const offset = @max(0, node.widget.value);
2550
2921
  const first_visible = table.indexAtOffset(offset);
2551
- const visible_end = @min(record.item_count, table.indexAtOffset(offset + viewport.height) + 1);
2922
+ const end_probe = table.indexAtOffset(offset + viewport.height);
2923
+ if (self.options.intrinsic_layout_policy) |policy| {
2924
+ if (canvas.virtual_extent_policy.undercovered(policy, record.item_count, first_visible, end_probe, record.overscan, record.start_index, record.end_index)) return true;
2925
+ continue;
2926
+ }
2927
+ const visible_end = @min(record.item_count, end_probe + 1);
2552
2928
  const start = if (first_visible > record.overscan) first_visible - record.overscan else 0;
2553
2929
  const end = @min(record.item_count, visible_end + record.overscan);
2554
2930
  if (start < record.start_index or end > record.end_index) return true;
@@ -2590,6 +2966,17 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2590
2966
  }
2591
2967
 
2592
2968
  fn claimVirtualExtentTable(self: *Self, id: canvas.ObjectId) ?*canvas.VirtualExtentTable {
2969
+ if (self.options.intrinsic_layout_policy) |policy| {
2970
+ const decision = canvas.virtual_extent_policy.slot(policy, id, &self.virtual_extent_tables, self.virtual_windows[0..self.virtual_window_count]);
2971
+ if (decision) |plan| {
2972
+ const table = &self.virtual_extent_tables[plan.index];
2973
+ if (plan.recycle) table.reset();
2974
+ table.policy = policy;
2975
+ return table;
2976
+ }
2977
+ if (id != 0) ui_app_log.warn("variable-extent virtual list table budget exhausted; using estimates without measured corrections", .{});
2978
+ return null;
2979
+ }
2593
2980
  if (id == 0) return null;
2594
2981
  for (&self.virtual_extent_tables) |*table| {
2595
2982
  if (table.id == id) return table;
@@ -2621,7 +3008,27 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2621
3008
  /// the pending offset delta keeps it visually fixed. Returns
2622
3009
  /// whether any table accumulated a correction worth the retry
2623
3010
  /// pass.
2624
- fn measureVirtualWindows(self: *Self, layout: canvas.WidgetLayoutTree) bool {
3011
+ fn measureVirtualWindows(self: *Self, layout: canvas.WidgetLayoutTree, plan: ?*const virtual_window_policy.Layout) bool {
3012
+ if (plan) |program| {
3013
+ var deltas: [canvas.max_virtual_windows]f32 = @splat(0);
3014
+ for (self.virtual_windows[0..self.virtual_window_count], 0..) |record, i| {
3015
+ const step = program.list(i);
3016
+ // Empty measurement batches are significant: the table
3017
+ // refreshes its anchor even when no eligible row exists.
3018
+ if (!step.measure) continue;
3019
+ const table = self.virtualExtentTableForId(record.id) orelse continue;
3020
+ const list_node = layout.nodes[step.node.?];
3021
+ var measurements: std.ArrayList(canvas.VirtualExtentMeasurement) = .empty;
3022
+ defer measurements.deinit(std.heap.page_allocator);
3023
+ for (0..step.rows.len / 4) |j| {
3024
+ const node = layout.nodes[virtual_window_policy.row(step.rows, j)];
3025
+ measurements.append(std.heap.page_allocator, .{ .physical = @intCast(node.widget.semantics.list_item_index.?), .extent = node.frame.normalized().height }) catch @panic("virtual row measurement allocation failed");
3026
+ }
3027
+ table.applyMeasurements(list_node.widget.layout.virtual_anchor_index, null, measurements.items);
3028
+ deltas[i] = table.pending_offset_delta;
3029
+ }
3030
+ return virtual_window_policy.corrected(self.options.virtual_window_policy.?, deltas[0..self.virtual_window_count]);
3031
+ }
2625
3032
  var corrected = false;
2626
3033
  for (self.virtual_windows[0..self.virtual_window_count]) |record| {
2627
3034
  if (!record.variable or record.item_count == 0) continue;
@@ -2646,21 +3053,23 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2646
3053
  // the pending offset by however much the batch moves
2647
3054
  // that edge, and the anchored row stays under the
2648
3055
  // user's eyes.
2649
- table.beginCorrections(list_node.widget.layout.virtual_anchor_index, null);
3056
+ var measurements: std.ArrayList(canvas.VirtualExtentMeasurement) = .empty;
3057
+ defer measurements.deinit(std.heap.page_allocator);
2650
3058
  for (layout.nodes) |node| {
2651
3059
  const parent = node.parent_index orelse continue;
2652
3060
  if (parent != list_index) continue;
2653
3061
  if (node.widget.layout.anchor != null) continue;
2654
3062
  const physical = node.widget.semantics.list_item_index orelse continue;
2655
- table.recordMeasured(@intCast(physical), node.frame.normalized().height);
3063
+ measurements.append(std.heap.page_allocator, .{ .physical = @intCast(physical), .extent = node.frame.normalized().height }) catch @panic("virtual row measurement allocation failed");
2656
3064
  }
2657
- table.endCorrections();
3065
+ table.applyMeasurements(list_node.widget.layout.virtual_anchor_index, null, measurements.items);
2658
3066
  if (@abs(table.pending_offset_delta) > virtual_correction_retry_threshold) corrected = true;
2659
3067
  }
2660
3068
  return corrected;
2661
3069
  }
2662
3070
 
2663
3071
  fn isVirtualWindowId(self: *const Self, id: canvas.ObjectId) bool {
3072
+ if (self.options.virtual_window_policy) |policy| return virtual_window_policy.contains(policy, id, self.virtual_windows[0..self.virtual_window_count]);
2664
3073
  if (id == 0) return false;
2665
3074
  for (self.virtual_windows[0..self.virtual_window_count]) |record| {
2666
3075
  if (record.id == id) return true;
@@ -2679,25 +3088,6 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2679
3088
  axis: canvas.ScrollAxis = .vertical,
2680
3089
  };
2681
3090
 
2682
- const ReachAxis = struct {
2683
- state: canvas.ScrollAxisState,
2684
- axis: canvas.ScrollAxis,
2685
- };
2686
-
2687
- /// The axis reach-end/reach-start measure: the vertical axis
2688
- /// wherever it has scrollable range (every pre-axis region, so
2689
- /// existing apps see identical behavior), otherwise the
2690
- /// horizontal one — a horizontal timeline's `on-reach-end` is
2691
- /// its right edge. One rule for both signals so "the end" and
2692
- /// "the start" always name the same axis.
2693
- fn reachAxisState(scroll_state: canvas.ScrollState) ReachAxis {
2694
- const vertical = scroll_state.axis(.vertical);
2695
- if (vertical.maxOffset() > 0) return .{ .state = vertical, .axis = .vertical };
2696
- const horizontal = scroll_state.axis(.horizontal);
2697
- if (horizontal.maxOffset() > 0) return .{ .state = horizontal, .axis = .horizontal };
2698
- return .{ .state = vertical, .axis = .vertical };
2699
- }
2700
-
2701
3091
  /// Approach-end hysteresis (`on_reach_end`): fire when a scroll
2702
3092
  /// lands within `reach_end_fire_ratio` viewports of the content
2703
3093
  /// end and the region is armed; re-arm once the offset sits more
@@ -2705,22 +3095,24 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2705
3095
  /// appending a batch causes on its own, since the extent grows
2706
3096
  /// under the unchanged offset. One Msg per approach, never a
2707
3097
  /// fetch storm from a user riding the end of the list.
2708
- fn reachEndShouldFire(self: *Self, id: canvas.ObjectId, scroll_state: canvas.ScrollState) bool {
2709
- const reach = reachAxisState(scroll_state);
2710
- const axis_state = reach.state;
2711
- if (id == 0 or axis_state.viewport_extent <= 0) return false;
2712
- const remaining = axis_state.content_extent - axis_state.viewport_extent - axis_state.offset;
2713
- if (remaining > axis_state.viewport_extent * reach_end_rearm_ratio) {
2714
- self.clearReachEndFired(id, reach.axis);
2715
- return false;
3098
+ fn applyReachPlan(self: *Self, start: bool, id: canvas.ObjectId, scroll_state: canvas.ScrollState) bool {
3099
+ const vertical_fired = if (start) self.reachStartFired(id, .vertical) else self.reachEndFired(id, .vertical);
3100
+ const horizontal_fired = if (start) self.reachStartFired(id, .horizontal) else self.reachEndFired(id, .horizontal);
3101
+ const plan = component_policy.reach(self.options.component_policy, start, id != 0, scroll_state, vertical_fired, horizontal_fired);
3102
+ const axis: canvas.ScrollAxis = if (plan.horizontal) .horizontal else .vertical;
3103
+ switch (plan.action) {
3104
+ .none => return false,
3105
+ .clear => {
3106
+ if (start) self.clearReachStartFired(id, axis) else self.clearReachEndFired(id, axis);
3107
+ return false;
3108
+ },
3109
+ // Dispatch only after a native latch slot was actually stored.
3110
+ .store => return if (start) self.markReachStartFired(id, axis) else self.markReachEndFired(id, axis),
2716
3111
  }
2717
- if (remaining > axis_state.viewport_extent * reach_end_fire_ratio) return false;
2718
- if (self.reachEndFired(id, reach.axis)) return false;
2719
- // Fire only when the latch STORES: an unstorable latch
2720
- // (table full — a degenerate tree) would otherwise fire on
2721
- // every observation, the exact storm the hysteresis exists
2722
- // to prevent. Silence is the safer failure.
2723
- return self.markReachEndFired(id, reach.axis);
3112
+ }
3113
+
3114
+ fn reachEndShouldFire(self: *Self, id: canvas.ObjectId, scroll_state: canvas.ScrollState) bool {
3115
+ return self.applyReachPlan(false, id, scroll_state);
2724
3116
  }
2725
3117
 
2726
3118
  fn reachEndFired(self: *const Self, id: canvas.ObjectId, axis: canvas.ScrollAxis) bool {
@@ -2757,18 +3149,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2757
3149
  /// only moves on scroll OBSERVATIONS, so a programmatic jump out
2758
3150
  /// of the band re-arms on the next user scroll, not instantly.
2759
3151
  fn reachStartShouldFire(self: *Self, id: canvas.ObjectId, scroll_state: canvas.ScrollState) bool {
2760
- const reach = reachAxisState(scroll_state);
2761
- const axis_state = reach.state;
2762
- if (id == 0 or axis_state.viewport_extent <= 0) return false;
2763
- const remaining = axis_state.offset;
2764
- if (remaining > axis_state.viewport_extent * reach_start_rearm_ratio) {
2765
- self.clearReachStartFired(id, reach.axis);
2766
- return false;
2767
- }
2768
- if (remaining > axis_state.viewport_extent * reach_start_fire_ratio) return false;
2769
- if (self.reachStartFired(id, reach.axis)) return false;
2770
- // Fire only when the latch stores (the reach-end rule).
2771
- return self.markReachStartFired(id, reach.axis);
3152
+ return self.applyReachPlan(true, id, scroll_state);
2772
3153
  }
2773
3154
 
2774
3155
  fn reachStartFired(self: *const Self, id: canvas.ObjectId, axis: canvas.ScrollAxis) bool {
@@ -2810,6 +3191,13 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2810
3191
  declared = declared[0..max_ui_windows];
2811
3192
  }
2812
3193
 
3194
+ if (self.options.window_policy != null) {
3195
+ self.applyCompiledWindows(runtime, declared) catch |err| {
3196
+ ui_app_log.warn("window reconciliation failed: {s}", .{@errorName(err)});
3197
+ };
3198
+ return;
3199
+ }
3200
+
2813
3201
  // Close first: a label leaving the declared set frees its
2814
3202
  // slot (and its runtime window label) before creations run.
2815
3203
  var index: usize = 0;
@@ -2831,6 +3219,77 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2831
3219
  }
2832
3220
  }
2833
3221
 
3222
+ fn writeWindowPolicyLabel(writer: *std.Io.Writer, label: []const u8) !void {
3223
+ if (label.len > std.math.maxInt(u32)) return error.WindowPolicyLabelTooLong;
3224
+ try writer.writeInt(u32, @intCast(label.len), .little);
3225
+ try writer.writeAll(label);
3226
+ }
3227
+
3228
+ /// Each decision sees the current ordered slots, including the swap
3229
+ /// after a close and only successful OS creates. Copy the complete
3230
+ /// request before entering scriptc; keep all descriptor bytes alive.
3231
+ fn windowPolicyDecision(self: *Self, declared: []const WindowDescriptor, descriptor: ?WindowDescriptor) ![2]u8 {
3232
+ comptime {
3233
+ std.debug.assert(max_ui_windows == 4);
3234
+ std.debug.assert(platform.max_window_label_bytes == 64);
3235
+ std.debug.assert(app_manifest.max_view_label_bytes == 64);
3236
+ }
3237
+ var request = std.Io.Writer.Allocating.init(self.backing);
3238
+ defer request.deinit();
3239
+ const writer = &request.writer;
3240
+ try writer.writeByte(@intFromBool(descriptor != null));
3241
+ if (descriptor) |value| {
3242
+ try writeWindowPolicyLabel(writer, self.options.canvas_label);
3243
+ try writeWindowPolicyLabel(writer, value.label);
3244
+ try writeWindowPolicyLabel(writer, value.canvas_label);
3245
+ } else {
3246
+ try writer.writeByte(@intCast(declared.len));
3247
+ for (declared) |value| try writeWindowPolicyLabel(writer, value.label);
3248
+ }
3249
+ try writer.writeByte(@intCast(self.window_slot_count));
3250
+ for (self.window_slots[0..self.window_slot_count]) |*slot| {
3251
+ try writeWindowPolicyLabel(writer, slot.label());
3252
+ try writeWindowPolicyLabel(writer, slot.canvasLabel());
3253
+ }
3254
+ var result: [2]u8 = undefined;
3255
+ if (self.options.window_policy.?(request.written(), &result) != result.len or
3256
+ result[0] > 4 or (result[1] != 255 and result[1] >= self.window_slot_count))
3257
+ @panic("invalid compiled window policy result");
3258
+ if (descriptor == null) {
3259
+ if (result[0] != 0) @panic("invalid compiled window retirement result");
3260
+ } else if ((result[0] == 1) == (result[1] == 255)) {
3261
+ @panic("invalid compiled window declaration result");
3262
+ }
3263
+ return result;
3264
+ }
3265
+
3266
+ fn applyCompiledWindows(self: *Self, runtime: *Runtime, declared: []const WindowDescriptor) !void {
3267
+ while (true) {
3268
+ const plan = try self.windowPolicyDecision(declared, null);
3269
+ if (plan[1] == 255) break;
3270
+ self.closeWindowSlot(runtime, plan[1]);
3271
+ }
3272
+ for (declared) |descriptor| {
3273
+ const plan = try self.windowPolicyDecision(&.{}, descriptor);
3274
+ switch (plan[0]) {
3275
+ 0 => {
3276
+ // Bound native copies even if a custom callback violates
3277
+ // the ABI. Lookup/collision decisions belong to policy.
3278
+ if (self.window_slot_count >= max_ui_windows or
3279
+ descriptor.label.len == 0 or descriptor.label.len > platform.max_window_label_bytes or
3280
+ descriptor.canvas_label.len == 0 or descriptor.canvas_label.len > app_manifest.max_view_label_bytes)
3281
+ @panic("invalid compiled window creation result");
3282
+ self.openWindowSlot(runtime, descriptor);
3283
+ },
3284
+ 1 => self.setWindowSlotOnClose(&self.window_slots[plan[1]], descriptor.on_close),
3285
+ 2 => ui_app_log.warn("declared window '{s}' ignored: more than {d} secondary windows (canvas_limits.max_ui_app_windows)", .{ descriptor.label, max_ui_windows }),
3286
+ 3 => ui_app_log.warn("declared window '{s}' ignored: window and canvas labels must be non-empty and fit the platform label budgets", .{descriptor.label}),
3287
+ 4 => ui_app_log.warn("declared window '{s}' ignored: canvas label '{s}' is already bound - every window's canvas label must be unique", .{ descriptor.label, descriptor.canvas_label }),
3288
+ else => unreachable,
3289
+ }
3290
+ }
3291
+ }
3292
+
2834
3293
  fn declaredWindowIndex(declared: []const WindowDescriptor, label: []const u8) ?usize {
2835
3294
  for (declared, 0..) |descriptor, index| {
2836
3295
  if (std.mem.eql(u8, descriptor.label, label)) return index;
@@ -2881,6 +3340,12 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2881
3340
  return;
2882
3341
  }
2883
3342
 
3343
+ self.openWindowSlot(runtime, descriptor);
3344
+ }
3345
+
3346
+ /// Native capability boundary: create the shell, then retain its
3347
+ /// labels, close message, tree arenas and GPU state only on success.
3348
+ fn openWindowSlot(self: *Self, runtime: *Runtime, descriptor: WindowDescriptor) void {
2884
3349
  const shell_views = [_]app_manifest.ShellView{self.secondaryShellView(descriptor)};
2885
3350
  const info = runtime.createSourcelessShellWindow(.{
2886
3351
  .label = descriptor.label,
@@ -2926,6 +3391,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2926
3391
  slot.tree = null;
2927
3392
  slot.arena_index = 0;
2928
3393
  self.window_slot_count += 1;
3394
+ // A deferred secondary window has not presented its first canvas
3395
+ // yet. Apply the retained theme before it can become visible.
3396
+ runtime.options.platform.services.setWindowColorScheme(info.id, self.windowColorScheme()) catch |err| {
3397
+ ui_app_log.warn("declared window '{s}' appearance failed: {s}", .{ descriptor.label, @errorName(err) });
3398
+ };
2929
3399
  }
2930
3400
 
2931
3401
  fn setWindowSlotOnClose(self: *Self, slot: *WindowSlot, msg: ?MsgT) void {
@@ -3028,7 +3498,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3028
3498
 
3029
3499
  fn rebuildWindowSlot(self: *Self, runtime: *Runtime, slot: *WindowSlot) anyerror!void {
3030
3500
  if (self.options.window_view == null) return;
3031
- try self.refreshThemeState();
3501
+ try self.refreshThemeState(runtime);
3032
3502
  var tokens = runtime.tokensWithTextMeasure(self.slotEffectiveTokens(slot));
3033
3503
  const next_index = self.contextMenuRebuildIndex(slot.window_id, slot.arena_index);
3034
3504
  const bounds = geometry.RectF.fromSize(slot.canvas_size).deflate(runtime.viewportInsetsForWindow(slot.window_id));
@@ -3047,7 +3517,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3047
3517
  // exactly like the main window's, so a proven collision
3048
3518
  // stamps the cluster into THIS slot's tokens (a local copy —
3049
3519
  // other windows keep their own layout) for one more pass.
3050
- if (windowControlsReservation(runtime, slot.window_id, slot.canvasLabel(), built.layout, tokens)) |controls| {
3520
+ if (try windowControlsReservation(runtime, slot.window_id, slot.canvasLabel(), built.layout, tokens)) |controls| {
3051
3521
  tokens.window_controls = controls;
3052
3522
  built = try self.buildWindowSlotPass(slot, bounds, tokens, next_index);
3053
3523
  }
@@ -3075,7 +3545,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3075
3545
  runtime.recordDispatchError("hover_leave_capture", refresh_err);
3076
3546
  }
3077
3547
  // Same close-on-vanish rule as the main canvas rebuild.
3078
- if (self.contextMenuFallbackTargetForLabel(slot.canvasLabel()) != 0 and tree.context_menu_fallback == null) {
3548
+ if (self.componentDecision(.fallback_vanished, self.contextMenuFallbackTargetForLabel(slot.canvasLabel()) != 0, tree.context_menu_fallback != null, false) != 0) {
3079
3549
  self.clearContextMenuFallback();
3080
3550
  }
3081
3551
  // Reconcile the video declaration THIS build recorded or
@@ -3170,6 +3640,12 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3170
3640
  std.debug.assert(if (self.context_menu_pin) |pin| pin.window_id != slot.window_id or pin.arena_index != next_index else true);
3171
3641
  _ = slot.arenas[next_index].reset(.retain_capacity);
3172
3642
  var ui = Ui.init(slot.arenas[next_index].allocator());
3643
+ ui.composition_policy = self.options.composition_policy;
3644
+ ui.code_content_policy = self.options.code_content_policy;
3645
+ ui.chart_content_policy = self.options.chart_content_policy;
3646
+ ui.markdown_content_policy = self.options.markdown_content_policy;
3647
+ ui.construction_policy = self.options.construction_policy;
3648
+ ui.expression_policy = self.options.expression_policy;
3173
3649
  // Window views render the same honest video chrome state,
3174
3650
  // and their `<video src>` declarations reconcile the channel
3175
3651
  // too — `Ui.video` promises that declaring the element IS
@@ -3182,6 +3658,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3182
3658
  // key, whichever tree binds it.
3183
3659
  self.terminal_sessions.beginBuild(tokens);
3184
3660
  ui.terminal_lookup = self.terminal_sessions.lookup();
3661
+ ui.pty_key_resolver = self.options.pty_key_resolver;
3185
3662
  ui.context_menu_fallback_target = self.contextMenuFallbackTargetForLabel(slot.canvasLabel());
3186
3663
  if (ui.context_menu_fallback_target != 0) ui.context_menu_fallback_point = self.context_menu_fallback_point;
3187
3664
  self.armUiFragmentHost(&ui);
@@ -3218,6 +3695,52 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3218
3695
  }
3219
3696
 
3220
3697
  fn applyWebPane(self: *Self, runtime: *Runtime, window_id: platform.WindowId, layout: canvas.WidgetLayoutTree, pane: WebViewPane) void {
3698
+ if (self.options.web_pane_policy) |policy| return self.applyCompiledWebPane(runtime, window_id, layout, pane, policy);
3699
+ self.applyNativeWebPane(runtime, window_id, layout, pane);
3700
+ }
3701
+
3702
+ fn applyCompiledWebPane(self: *Self, runtime: *Runtime, window_id: platform.WindowId, layout: canvas.WidgetLayoutTree, pane: WebViewPane, policy: web_pane_policy.Policy) void {
3703
+ const planned = web_pane_policy.frame(policy, layout.nodes, pane.frame, pane.anchor);
3704
+ switch (planned.kind) {
3705
+ .missing_anchor => {
3706
+ ui_app_log.warn(
3707
+ "webview pane '{s}': no canvas widget carries semantics label '{s}' - mark the region's widget with .semantics = .{{ .label = \"{s}\" }}",
3708
+ .{ pane.label, pane.anchor.?, pane.anchor.? },
3709
+ );
3710
+ return;
3711
+ },
3712
+ .collapsed => return,
3713
+ .apply => {},
3714
+ }
3715
+ const claimed = web_pane_policy.slot(policy, self.web_pane_states[0..self.web_pane_state_count], pane.label, app_manifest.max_view_label_bytes) orelse {
3716
+ ui_app_log.warn("webview pane '{s}' ignored: more than {d} distinct pane labels", .{ pane.label, max_web_panes });
3717
+ return;
3718
+ };
3719
+ const state = &self.web_pane_states[claimed.index];
3720
+ if (claimed.create) {
3721
+ state.* = .{};
3722
+ @memcpy(state.label_storage[0..claimed.label_bytes], pane.label[0..claimed.label_bytes]);
3723
+ state.label_len = claimed.label_bytes;
3724
+ self.web_pane_state_count += 1;
3725
+ }
3726
+ const actual = runtime.webViewLocalFrame(window_id, pane.label) orelse {
3727
+ ui_app_log.warn("webview pane '{s}': the scene declares no .webview shell view with this label", .{pane.label});
3728
+ return;
3729
+ };
3730
+ const planned_patch = web_pane_policy.patch(policy, actual, planned.value, state.url(), pane.url, state.reload_token, pane.reload_token);
3731
+ if (!planned_patch.frame and !planned_patch.url) return;
3732
+ const patch: platform.ViewPatch = .{ .frame = if (planned_patch.frame) planned.value else null, .url = if (planned_patch.url) pane.url else null };
3733
+ const success = if (runtime.updateView(window_id, pane.label, patch)) |_| true else |err| failed: {
3734
+ ui_app_log.warn("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", .{ pane.label, @errorName(err) });
3735
+ break :failed false;
3736
+ };
3737
+ const bytes = web_pane_policy.commit(policy, success, pane.url.len, state.url_storage.len) orelse return;
3738
+ @memcpy(state.url_storage[0..bytes], pane.url[0..bytes]);
3739
+ state.url_len = bytes;
3740
+ state.reload_token = pane.reload_token;
3741
+ }
3742
+
3743
+ fn applyNativeWebPane(self: *Self, runtime: *Runtime, window_id: platform.WindowId, layout: canvas.WidgetLayoutTree, pane: WebViewPane) void {
3221
3744
  var frame = pane.frame;
3222
3745
  if (pane.anchor) |anchor| {
3223
3746
  frame = webPaneAnchorFrame(layout, anchor) orelse {
@@ -3308,21 +3831,37 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3308
3831
  /// runtime then regenerates the widget span on internal state
3309
3832
  /// changes while preserving the chrome via
3310
3833
  /// `emitCanvasWidgetDisplayListWithChrome`.
3834
+ // Zig-core compatibility for the original combined chrome callback.
3835
+ // Compiled cores always install the TypeScript composition owner.
3836
+ fn nativeChromePlan(chrome: ChromeOptions, count: usize, before: ?usize) error{InvalidChromeCommandCount}!canvas.render_coordination_policy.ChromePlan {
3837
+ const prefix = before orelse blk: {
3838
+ if (count < chrome.suffix_commands) return error.InvalidChromeCommandCount;
3839
+ break :blk count - chrome.suffix_commands;
3840
+ };
3841
+ if (prefix > count or (chrome.variable_prefix and prefix > chrome.prefix_commands) or
3842
+ (!chrome.variable_prefix and prefix != chrome.prefix_commands)) return error.InvalidChromeCommandCount;
3843
+ const suffix = count - prefix;
3844
+ if (before != null and suffix > chrome.suffix_commands) return error.InvalidChromeCommandCount;
3845
+ return .{ .prefix = prefix, .suffix = suffix };
3846
+ }
3847
+
3311
3848
  fn installChromeDisplayList(self: *Self, runtime: *Runtime, window_id: platform.WindowId, chrome: ChromeOptions, layout: canvas.WidgetLayoutTree, tokens: canvas.DesignTokens) anyerror!void {
3312
3849
  var chrome_commands: [canvas_limits.max_canvas_commands_per_view]canvas.CanvasCommand = undefined;
3313
3850
  var chrome_builder = canvas.Builder.init(&chrome_commands);
3314
3851
  try chrome.build(&self.model, &chrome_builder, self.canvas_size, tokens);
3852
+ var before_suffix: ?usize = null;
3853
+ if (chrome.build_suffix) |build_suffix| {
3854
+ before_suffix = chrome_builder.displayList().commands.len;
3855
+ try build_suffix(&self.model, &chrome_builder, self.canvas_size, tokens);
3856
+ }
3857
+ const count = chrome_builder.displayList().commands.len;
3858
+ const plan = if (self.options.render_coordination_policy) |policy|
3859
+ try canvas.render_coordination_policy.ChromePlan.init(policy, chrome.prefix_commands, chrome.suffix_commands, count, before_suffix, chrome.variable_prefix)
3860
+ else
3861
+ try nativeChromePlan(chrome, count, before_suffix);
3862
+ const prefix_len = plan.prefix;
3863
+ const suffix_len = plan.suffix;
3315
3864
  const chrome_list = chrome_builder.displayList();
3316
- if (chrome.variable_prefix) {
3317
- if (chrome_list.commands.len < chrome.suffix_commands or
3318
- chrome_list.commands.len - chrome.suffix_commands > chrome.prefix_commands)
3319
- {
3320
- return error.InvalidChromeCommandCount;
3321
- }
3322
- } else if (chrome_list.commands.len != chrome.prefix_commands + chrome.suffix_commands) {
3323
- return error.InvalidChromeCommandCount;
3324
- }
3325
- const prefix_len = chrome_list.commands.len - chrome.suffix_commands;
3326
3865
 
3327
3866
  var commands: [canvas_limits.max_canvas_commands_per_view]canvas.CanvasCommand = undefined;
3328
3867
  var builder = canvas.Builder.init(&commands);
@@ -3338,7 +3877,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3338
3877
  try self.publishWidgetLayoutTracked(runtime, window_id, self.options.canvas_label, layout, &self.main_tree_current);
3339
3878
  _ = try runtime.emitCanvasWidgetDisplayListWithChrome(window_id, self.options.canvas_label, tokens, .{
3340
3879
  .prefix_command_count = prefix_len,
3341
- .suffix_command_count = chrome.suffix_commands,
3880
+ .suffix_command_count = suffix_len,
3342
3881
  });
3343
3882
  }
3344
3883
 
@@ -3407,6 +3946,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3407
3946
  const sources: []const canvas.ui_markup.SourceFile = if (self.options.markup) |markup_options| markup_options.sources else &.{};
3408
3947
  var set_loader = canvas.ui_markup.SourceSetLoader{ .set = sources };
3409
3948
  var hashing = HashingLoader.init(set_loader.loader(), source, "");
3949
+ hashing.policy = self.options.markup_development_policy;
3410
3950
  if (comptime features.runtime_markup) {
3411
3951
  self.provenance_closure.reset();
3412
3952
  hashing.closure = &self.provenance_closure;
@@ -3416,13 +3956,24 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3416
3956
  const arena = self.markup_arenas[next_index].allocator();
3417
3957
  const owned_source = try arena.dupe(u8, source);
3418
3958
  var diagnostic: canvas.ui_markup.MarkupErrorInfo = .{};
3419
- const document = canvas.ui_markup.resolveImports(arena, "", owned_source, hashing.loader(), &diagnostic) catch |err| {
3420
- if (err == error.MarkupSyntax or err == error.MarkupImport) self.recordMarkupDiagnostic(diagnostic);
3959
+ const document = canvas.ui_markup.resolveImportsWithPolicy(self.options.expression_policy, arena, "", owned_source, hashing.loader(), &diagnostic) catch |err| {
3960
+ if (self.options.markup_development_policy) |callback| {
3961
+ const program = markup_development.reload(callback, 0, true, true, err == error.MarkupSyntax or err == error.MarkupImport, false, self.installed);
3962
+ for (program) |byte| switch (@as(markup_development.Action, @enumFromInt(byte))) {
3963
+ .end => break,
3964
+ .diagnostic => self.recordMarkupDiagnostic(diagnostic),
3965
+ else => unreachable,
3966
+ };
3967
+ } else if (err == error.MarkupSyntax or err == error.MarkupImport) self.recordMarkupDiagnostic(diagnostic);
3421
3968
  return err;
3422
3969
  };
3423
3970
  // The typed-document pass: attribute expressions parse once
3424
3971
  // here instead of on every frame's build.
3425
- const canonical = try canvas.ui_markup.canonicalize(arena, document);
3972
+ if (self.options.markup_development_policy) |callback| {
3973
+ try self.applyRootMarkupProgram(callback, 0, document, arena, next_index, hashing.hasher.final(), "", owned_source, null, 0);
3974
+ return;
3975
+ }
3976
+ const canonical = try canvas.ui_markup.canonicalizeWithPolicy(self.options.expression_policy, arena, document);
3426
3977
  self.adoptMarkupDocument(canonical, next_index, hashing.hasher.final());
3427
3978
  // Embedded resolve: root nodes carry an empty src_path, and
3428
3979
  // imported entries are markup-root-relative (joined onto the
@@ -3430,6 +3981,21 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3430
3981
  self.commitProvenanceFiles("", owned_source, false);
3431
3982
  }
3432
3983
 
3984
+ fn applyRootMarkupProgram(self: *Self, callback: *const fn ([]const u8, []u8) usize, kind: u8, document: canvas.ui_markup.MarkupDocument, arena: std.mem.Allocator, next_index: usize, hash: u64, path: []const u8, source: []const u8, runtime: ?*Runtime, window_id: platform.WindowId) anyerror!void {
3985
+ const program = markup_development.reload(callback, kind, kind == 0 or hash != self.markup_source_hash, false, false, false, self.installed);
3986
+ var canonical = document;
3987
+ for (program) |byte| switch (@as(markup_development.Action, @enumFromInt(byte))) {
3988
+ .end => break,
3989
+ .canonicalize => canonical = if (kind == 0) try canvas.ui_markup.canonicalizeWithPolicy(self.options.expression_policy, arena, document) else canvas.ui_markup.canonicalizeWithPolicy(self.options.expression_policy, arena, document) catch document,
3990
+ .adopt_root => self.adoptMarkupDocument(canonical, next_index, hash),
3991
+ .provenance => self.commitProvenanceFiles(path, source, kind == 1),
3992
+ .rebuild_root => if (runtime) |value| {
3993
+ self.rebuild(value, window_id) catch {};
3994
+ },
3995
+ else => unreachable,
3996
+ };
3997
+ }
3998
+
3433
3999
  /// Activate a resolved document built into `arena_index`'s arena.
3434
4000
  fn adoptMarkupDocument(self: *Self, document: canvas.ui_markup.MarkupDocument, arena_index: usize, closure_hash: u64) void {
3435
4001
  self.markup_view = MarkupView.fromDocument(document);
@@ -3454,6 +4020,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3454
4020
  /// resolver-relative path and content hash is recorded so the
3455
4021
  /// adopt step can commit them as write-back anchors.
3456
4022
  closure: ?*ui_app_provenance.ClosureFiles = null,
4023
+ policy: markup_development.Policy = null,
3457
4024
 
3458
4025
  fn init(inner: canvas.ui_markup.ImportLoader, root_source: []const u8, strip_prefix: []const u8) HashingLoader {
3459
4026
  var hasher = std.hash.Wyhash.init(0);
@@ -3469,7 +4036,9 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3469
4036
  const self: *HashingLoader = @ptrCast(@alignCast(@constCast(context)));
3470
4037
  const source = self.inner.load(self.inner.context, arena, path) orelse return null;
3471
4038
  var hashed_path = path;
3472
- if (self.strip_prefix.len > 0 and path.len > self.strip_prefix.len and
4039
+ if (self.policy) |callback| {
4040
+ hashed_path = markup_development.stripPrefix(callback, self.strip_prefix, path);
4041
+ } else if (self.strip_prefix.len > 0 and path.len > self.strip_prefix.len and
3473
4042
  std.mem.startsWith(u8, path, self.strip_prefix) and path[self.strip_prefix.len] == '/')
3474
4043
  {
3475
4044
  hashed_path = path[self.strip_prefix.len + 1 ..];
@@ -3501,7 +4070,16 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3501
4070
  for (self.provenance_closure.entries[0..self.provenance_closure.len]) |*entry| {
3502
4071
  const stamped = entry.path[0..entry.path_len];
3503
4072
  var disk_buffer: [ui_app_provenance.max_path_bytes]u8 = undefined;
3504
- const disk: []const u8 = if (entries_are_disk_paths)
4073
+ const disk: []const u8 = if (self.options.markup_development_policy) |callback| blk: {
4074
+ var input: [2 * ui_app_provenance.max_path_bytes + 16]u8 = undefined;
4075
+ var writer = std.Io.Writer.fixed(&input);
4076
+ const r = markup_development.Request.begin(&writer, 10) catch unreachable;
4077
+ r.byte(@intFromBool(entries_are_disk_paths)) catch unreachable;
4078
+ r.byte(@intFromBool(watch_path != null)) catch unreachable;
4079
+ r.blob(disk_prefix[0..@min(disk_prefix.len, ui_app_provenance.max_path_bytes + 1)]) catch unreachable;
4080
+ r.blob(stamped) catch unreachable;
4081
+ break :blk markup_development.evaluate(callback, writer.buffered(), &disk_buffer);
4082
+ } else if (entries_are_disk_paths)
3505
4083
  stamped
3506
4084
  else if (watch_path == null)
3507
4085
  ""
@@ -3517,8 +4095,20 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3517
4095
  /// from the retained table and publish the response artifact.
3518
4096
  /// Setting the runtime's handshake flag tells the dispatcher an
3519
4097
  /// answer landed (its fallback teaches when no app responds).
4098
+ /// The markup files the compiled view just decoded, with the hashes
4099
+ /// of the bytes it was compiled from; edits refuse a file that has
4100
+ /// changed since. The watcher reloads every edit, so the table is
4101
+ /// always watching.
4102
+ fn commitViewSourceFiles(self: *Self) void {
4103
+ self.provenance.resetFiles();
4104
+ self.provenance.watching = true;
4105
+ for (view_reload.view_files[0..view_reload.view_files_len]) |file| {
4106
+ self.provenance.addFile(file.stamped, file.disk, file.hash) catch break;
4107
+ }
4108
+ }
4109
+
3520
4110
  fn handleProvenanceQuery(self: *Self, runtime: *Runtime, query: core.AutomationProvenanceEvent) anyerror!void {
3521
- if (comptime !features.runtime_markup) return;
4111
+ if (comptime !provenance_enabled) return;
3522
4112
  if (!std.mem.eql(u8, query.view_label, self.options.canvas_label)) return;
3523
4113
  const server = runtime.options.automation orelse return;
3524
4114
  var buffer: [4096]u8 = undefined;
@@ -3536,25 +4126,52 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3536
4126
  /// sites) and the arena resets on the next reload attempt, so the
3537
4127
  /// stored copy owns its bytes.
3538
4128
  fn recordMarkupDiagnostic(self: *Self, info: canvas.ui_markup.MarkupErrorInfo) void {
3539
- const already_reported = if (self.markup_diagnostic) |current|
3540
- current.line == info.line and current.column == info.column and
3541
- std.mem.eql(u8, current.message, info.message) and std.mem.eql(u8, current.path, info.path)
3542
- else
3543
- false;
3544
- if (!already_reported) {
4129
+ var should_report: bool = undefined;
4130
+ var message_len: usize = @min(info.message.len, self.markup_diagnostic_message_storage.len);
4131
+ var path_len: usize = @min(info.path.len, self.markup_diagnostic_path_storage.len);
4132
+ if (self.options.markup_development_policy) |callback| {
4133
+ var input: [8192]u8 = undefined;
4134
+ var writer = std.Io.Writer.fixed(&input);
4135
+ const r = markup_development.Request.begin(&writer, 2) catch unreachable;
4136
+ const current = self.markup_diagnostic;
4137
+ r.byte(@intFromBool(current != null)) catch unreachable;
4138
+ r.byte(@intFromBool(if (current) |value| value.line == info.line else false)) catch unreachable;
4139
+ r.byte(@intFromBool(if (current) |value| value.column == info.column else false)) catch unreachable;
4140
+ r.blob(if (current) |value| value.message else "") catch unreachable;
4141
+ r.blob(info.message[0..@min(info.message.len, self.markup_diagnostic_message_storage.len + 1)]) catch unreachable;
4142
+ r.blob(if (current) |value| value.path else "") catch unreachable;
4143
+ r.blob(info.path[0..@min(info.path.len, self.markup_diagnostic_path_storage.len + 1)]) catch unreachable;
4144
+ r.word(self.markup_diagnostic_message_storage.len) catch unreachable;
4145
+ r.word(self.markup_diagnostic_path_storage.len) catch unreachable;
4146
+ var output: [12]u8 = undefined;
4147
+ const result = markup_development.evaluate(callback, writer.buffered(), &output);
4148
+ if (result.len != 12 or markup_development.word(result, 0) > 1 or markup_development.word(result, 4) > message_len or markup_development.word(result, 8) > path_len) @panic("invalid markup diagnostic extent");
4149
+ should_report = markup_development.word(result, 0) != 0;
4150
+ message_len = markup_development.word(result, 4);
4151
+ path_len = markup_development.word(result, 8);
4152
+ } else {
4153
+ should_report = if (self.markup_diagnostic) |current|
4154
+ !(current.line == info.line and current.column == info.column and
4155
+ std.mem.eql(u8, current.message, info.message) and std.mem.eql(u8, current.path, info.path))
4156
+ else
4157
+ true;
4158
+ }
4159
+ if (should_report) {
3545
4160
  // std.debug.print, not std.log: the default scaffold app is
3546
4161
  // ReleaseFast (std.log only passes .err there), while
3547
4162
  // logged errors fail test suites that exercise bad markup
3548
4163
  // on purpose. Direct stderr is visible in both.
3549
4164
  if (info.path.len > 0) {
3550
4165
  std.debug.print("markup view failed to build ({s}:{d}:{d}): {s}\n", .{ info.path, info.line, info.column, info.message });
4166
+ } else if (view_reload_enabled and info.line == 0 and info.column == 0) {
4167
+ // A view reload refusal has no source location (a
4168
+ // program for another build, for example).
4169
+ std.debug.print("markup view failed to build: {s}\n", .{info.message});
3551
4170
  } else {
3552
4171
  std.debug.print("markup view failed to build ({d}:{d}): {s}\n", .{ info.line, info.column, info.message });
3553
4172
  }
3554
4173
  }
3555
- const message_len = @min(info.message.len, self.markup_diagnostic_message_storage.len);
3556
4174
  @memcpy(self.markup_diagnostic_message_storage[0..message_len], info.message[0..message_len]);
3557
- const path_len = @min(info.path.len, self.markup_diagnostic_path_storage.len);
3558
4175
  @memcpy(self.markup_diagnostic_path_storage[0..path_len], info.path[0..path_len]);
3559
4176
  self.markup_diagnostic = .{
3560
4177
  .line = info.line,
@@ -3569,12 +4186,21 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3569
4186
  /// once, on first install, and only when something is watchable —
3570
4187
  /// a root watch path with io, or (Debug only) registered fragments.
3571
4188
  fn startMarkupWatch(self: *Self, runtime: *Runtime) void {
4189
+ if (comptime view_reload_enabled) {
4190
+ if (view_reload.installed != null) {
4191
+ runtime.startTimer(markup_watch_timer_id, markup_watch_interval_ns, true) catch {};
4192
+ if (comptime @hasDecl(Runtime, "setMarkupWatchArmed")) runtime.setMarkupWatchArmed(true);
4193
+ return;
4194
+ }
4195
+ }
3572
4196
  if (comptime !features.runtime_markup) return;
3573
4197
  const root_armed = if (self.options.markup) |markup_options|
3574
4198
  markup_options.watch_path != null and markup_options.io != null
3575
4199
  else
3576
4200
  false;
3577
- if (root_armed) {
4201
+ const count = if (comptime fragment_watch_enabled) (if (self.options.fragment_watch) |watch| watch.fragments.len else 0) else 0;
4202
+ const plan = if (self.options.markup_development_policy) |callback| markup_development.watch(callback, root_armed, self.options.view != null, self.markup_source_hash == 0, fragment_watch_enabled and self.options.fragment_watch != null, count, max_watched_fragments) else null;
4203
+ if (if (plan) |value| value[0] != 0 else root_armed and self.options.view != null and self.markup_source_hash == 0) {
3578
4204
  const markup_options = self.options.markup.?;
3579
4205
  // With a compiled `view` also set, the embedded sources are
3580
4206
  // the baseline: the interpreter only takes over once the
@@ -3582,12 +4208,10 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3582
4208
  // be computed the way the poll computes it — over the whole
3583
4209
  // resolved import closure — or the first poll would flag a
3584
4210
  // phantom change.
3585
- if (self.options.view != null and self.markup_source_hash == 0) {
3586
- self.markup_source_hash = self.embeddedMarkupClosureHash(markup_options);
3587
- }
4211
+ self.markup_source_hash = self.embeddedMarkupClosureHash(markup_options);
3588
4212
  }
3589
4213
  const fragments_armed = self.armFragmentWatch();
3590
- if (!root_armed and !fragments_armed) return;
4214
+ if (if (plan) |value| value[1] == 0 else !root_armed and !fragments_armed) return;
3591
4215
  runtime.startTimer(markup_watch_timer_id, markup_watch_interval_ns, true) catch {};
3592
4216
  // Make the armed watch observable: the automation snapshot
3593
4217
  // header reports `markup_watch=armed|off`, so a dev loop can
@@ -3608,19 +4232,20 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3608
4232
  fn armFragmentWatch(self: *Self) bool {
3609
4233
  if (comptime !fragment_watch_enabled) return false;
3610
4234
  const fragment_watch = self.options.fragment_watch orelse return false;
3611
- if (fragment_watch.fragments.len > max_watched_fragments) {
4235
+ const plan = if (self.options.markup_development_policy) |callback| markup_development.watch(callback, false, false, false, true, fragment_watch.fragments.len, max_watched_fragments) else null;
4236
+ if (if (plan) |value| value[3] != 0 else fragment_watch.fragments.len > max_watched_fragments) {
3612
4237
  ui_app_log.warn(
3613
4238
  "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",
3614
4239
  .{ fragment_watch.fragments.len, max_watched_fragments },
3615
4240
  );
3616
4241
  }
3617
- const count = @min(fragment_watch.fragments.len, max_watched_fragments);
4242
+ const count: usize = if (plan) |value| value[2] else @min(fragment_watch.fragments.len, max_watched_fragments);
3618
4243
  for (fragment_watch.fragments[0..count], self.markup_fragment_slots[0..count]) |spec, *slot| {
3619
4244
  // Baseline into the slot's inactive arena — reset on the
3620
4245
  // next reload attempt, so this costs nothing durable.
3621
4246
  const scratch_index = slot.arena_index ^ 1;
3622
4247
  _ = slot.arenas[scratch_index].reset(.retain_capacity);
3623
- slot.baseline_hash = embeddedClosureHash(slot.arenas[scratch_index].allocator(), spec.source, spec.sources);
4248
+ slot.baseline_hash = embeddedClosureHash(slot.arenas[scratch_index].allocator(), spec.source, spec.sources, self.options.markup_development_policy, self.options.expression_policy);
3624
4249
  slot.hash = slot.baseline_hash;
3625
4250
  }
3626
4251
  return count > 0;
@@ -3631,20 +4256,22 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3631
4256
  // hashing side effect; the arena resets on the next reload.
3632
4257
  const scratch_index = self.markup_arena_index ^ 1;
3633
4258
  _ = self.markup_arenas[scratch_index].reset(.retain_capacity);
3634
- return embeddedClosureHash(self.markup_arenas[scratch_index].allocator(), markup_options.source, markup_options.sources);
4259
+ return embeddedClosureHash(self.markup_arenas[scratch_index].allocator(), markup_options.source, markup_options.sources, self.options.markup_development_policy, self.options.expression_policy);
3635
4260
  }
3636
4261
 
3637
4262
  /// Hash an embedded source closure exactly like the disk poll
3638
4263
  /// hashes the on-disk one: root bytes plus every loaded file's
3639
4264
  /// root-relative path and bytes, in resolution order.
3640
- fn embeddedClosureHash(arena: std.mem.Allocator, source: []const u8, sources: []const canvas.ui_markup.SourceFile) u64 {
4265
+ fn embeddedClosureHash(arena: std.mem.Allocator, source: []const u8, sources: []const canvas.ui_markup.SourceFile, policy: markup_development.Policy, parser_policy: ?canvas.ui_markup.expr.Policy) u64 {
3641
4266
  if (sources.len == 0) {
3642
4267
  return std.hash.Wyhash.hash(0, source);
3643
4268
  }
3644
4269
  var set_loader = canvas.ui_markup.SourceSetLoader{ .set = sources };
3645
4270
  var hashing = HashingLoader.init(set_loader.loader(), source, "");
4271
+ hashing.policy = policy;
3646
4272
  var diagnostic: canvas.ui_markup.MarkupErrorInfo = .{};
3647
- _ = canvas.ui_markup.resolveImports(
4273
+ _ = canvas.ui_markup.resolveImportsWithPolicy(
4274
+ parser_policy,
3648
4275
  arena,
3649
4276
  "",
3650
4277
  source,
@@ -3673,13 +4300,24 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3673
4300
  var disk_loader = DiskImportLoader{ .io = io };
3674
4301
  const watch_dir = std.fs.path.dirname(watch_path) orelse "";
3675
4302
  var hashing = HashingLoader.init(disk_loader.loader(), source, watch_dir);
4303
+ hashing.policy = self.options.markup_development_policy;
3676
4304
  if (comptime features.runtime_markup) {
3677
4305
  self.provenance_closure.reset();
3678
4306
  hashing.closure = &self.provenance_closure;
3679
4307
  }
3680
4308
  var diagnostic: canvas.ui_markup.MarkupErrorInfo = .{};
3681
- const document = canvas.ui_markup.resolveImports(arena, watch_path, source, hashing.loader(), &diagnostic) catch |err| {
4309
+ const document = canvas.ui_markup.resolveImportsWithPolicy(self.options.expression_policy, arena, watch_path, source, hashing.loader(), &diagnostic) catch |err| {
3682
4310
  const hash = hashing.hasher.final();
4311
+ if (self.options.markup_development_policy) |callback| {
4312
+ const program = markup_development.reload(callback, 1, hash != self.markup_source_hash, true, err == error.MarkupSyntax or err == error.MarkupImport, false, self.installed);
4313
+ for (program) |byte| switch (@as(markup_development.Action, @enumFromInt(byte))) {
4314
+ .end => break,
4315
+ .observed_hash => self.markup_source_hash = hash,
4316
+ .diagnostic => self.recordMarkupDiagnostic(diagnostic),
4317
+ else => unreachable,
4318
+ };
4319
+ return;
4320
+ }
3683
4321
  if (hash == self.markup_source_hash) return;
3684
4322
  self.markup_source_hash = hash;
3685
4323
  if (err == error.MarkupSyntax or err == error.MarkupImport) {
@@ -3688,10 +4326,14 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3688
4326
  return;
3689
4327
  };
3690
4328
  const hash = hashing.hasher.final();
4329
+ if (self.options.markup_development_policy) |callback| {
4330
+ self.applyRootMarkupProgram(callback, 1, document, arena, next_index, hash, watch_path, source, runtime, window_id) catch {};
4331
+ return;
4332
+ }
3691
4333
  if (hash == self.markup_source_hash) return;
3692
4334
  // Canonicalize for per-frame cost only; on OOM the raw
3693
4335
  // document builds identically through attrTyped's fallback.
3694
- const canonical = canvas.ui_markup.canonicalize(arena, document) catch document;
4336
+ const canonical = canvas.ui_markup.canonicalizeWithPolicy(self.options.expression_policy, arena, document) catch document;
3695
4337
  self.adoptMarkupDocument(canonical, next_index, hash);
3696
4338
  // Disk resolve: root nodes carry the watch path, and imported
3697
4339
  // entries are already cwd-relative disk paths.
@@ -3699,6 +4341,24 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3699
4341
  if (self.installed) self.rebuild(runtime, window_id) catch {};
3700
4342
  }
3701
4343
 
4344
+ fn pollViewReload(self: *Self, runtime: *Runtime, reload: view_reload.Hook) anyerror!void {
4345
+ var diagnostic: canvas.ui_markup.MarkupErrorInfo = .{};
4346
+ switch (reload.poll(reload.context, &diagnostic)) {
4347
+ .unchanged => {},
4348
+ .failed => self.recordMarkupDiagnostic(diagnostic),
4349
+ .reloaded => {
4350
+ self.markup_diagnostic = null;
4351
+ // A sealed replay starts from the markup the session
4352
+ // launched with, so a session that changed its view
4353
+ // can no longer replay faithfully.
4354
+ if (runtime.options.session_recorder) |recorder| recorder.abandon("the view's markup was reloaded during the session; record again without editing markup to replay it");
4355
+ if (!self.installed) return;
4356
+ try self.rebuild(runtime, self.canvas_window_id);
4357
+ try self.rebuildWindowSlots(runtime);
4358
+ },
4359
+ }
4360
+ }
4361
+
3702
4362
  /// Timer-driven poll of every registered fragment (Debug dev runs
3703
4363
  /// only), riding the same reserved timer as the root watch. Each
3704
4364
  /// fragment's whole import closure is re-resolved and hashed per
@@ -3721,9 +4381,20 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3721
4381
  var disk_loader = DiskImportLoader{ .io = fragment_watch.io };
3722
4382
  const watch_dir = std.fs.path.dirname(spec.path) orelse "";
3723
4383
  var hashing = HashingLoader.init(disk_loader.loader(), source, watch_dir);
4384
+ hashing.policy = self.options.markup_development_policy;
3724
4385
  var diagnostic: canvas.ui_markup.MarkupErrorInfo = .{};
3725
- const document = canvas.ui_markup.resolveImports(arena, spec.path, source, hashing.loader(), &diagnostic) catch |err| {
4386
+ const document = canvas.ui_markup.resolveImportsWithPolicy(self.options.expression_policy, arena, spec.path, source, hashing.loader(), &diagnostic) catch |err| {
3726
4387
  const hash = hashing.hasher.final();
4388
+ if (self.options.markup_development_policy) |callback| {
4389
+ const program = markup_development.reload(callback, 2, hash != slot.hash, true, err == error.MarkupSyntax or err == error.MarkupImport, false, self.installed);
4390
+ for (program) |byte| switch (@as(markup_development.Action, @enumFromInt(byte))) {
4391
+ .end => break,
4392
+ .observed_hash => slot.hash = hash,
4393
+ .diagnostic => self.recordMarkupDiagnostic(diagnostic),
4394
+ else => unreachable,
4395
+ };
4396
+ continue;
4397
+ }
3727
4398
  if (hash == slot.hash) continue;
3728
4399
  slot.hash = hash;
3729
4400
  if (err == error.MarkupSyntax or err == error.MarkupImport) {
@@ -3732,6 +4403,22 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3732
4403
  continue;
3733
4404
  };
3734
4405
  const hash = hashing.hasher.final();
4406
+ if (self.options.markup_development_policy) |callback| {
4407
+ const program = markup_development.reload(callback, 2, hash != slot.hash, false, false, hash == slot.baseline_hash, self.installed);
4408
+ var canonical = document;
4409
+ for (program) |byte| switch (@as(markup_development.Action, @enumFromInt(byte))) {
4410
+ .end => break,
4411
+ .observed_hash => slot.hash = hash,
4412
+ .canonicalize => canonical = canvas.ui_markup.canonicalizeWithPolicy(self.options.expression_policy, arena, document) catch document,
4413
+ .restore_fragment => slot.document = null,
4414
+ .adopt_fragment => slot.document = canonical,
4415
+ .switch_arena => slot.arena_index = next_index,
4416
+ .clear_diagnostic => self.markup_diagnostic = null,
4417
+ .adopted_fragment => any_adopted = true,
4418
+ else => unreachable,
4419
+ };
4420
+ continue;
4421
+ }
3735
4422
  if (hash == slot.hash) continue;
3736
4423
  slot.hash = hash;
3737
4424
  if (hash == slot.baseline_hash) {
@@ -3742,7 +4429,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3742
4429
  // Canonicalize for per-frame cost only; on OOM the raw
3743
4430
  // document builds identically through attrTyped's
3744
4431
  // fallback.
3745
- slot.document = canvas.ui_markup.canonicalize(arena, document) catch document;
4432
+ slot.document = canvas.ui_markup.canonicalizeWithPolicy(self.options.expression_policy, arena, document) catch document;
3746
4433
  }
3747
4434
  slot.arena_index = next_index;
3748
4435
  // One diagnostic channel, adopt clears it — the root
@@ -3755,7 +4442,14 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3755
4442
  // Fragments build wherever the app's views embed them — the
3756
4443
  // main canvas and declared windows — so a reload re-derives
3757
4444
  // every open view.
3758
- if (any_adopted and self.installed) self.rebuildAllViews(runtime) catch {};
4445
+ const should_rebuild = if (self.options.markup_development_policy) |callback| blk: {
4446
+ const input = [_]u8{ 32, 1, 11, 0, @intFromBool(any_adopted), @intFromBool(self.installed) };
4447
+ var output: [4]u8 = undefined;
4448
+ const result = markup_development.evaluate(callback, &input, &output);
4449
+ if (result.len != 4 or markup_development.word(result, 0) > 1) @panic("invalid markup rebuild result");
4450
+ break :blk markup_development.word(result, 0) != 0;
4451
+ } else any_adopted and self.installed;
4452
+ if (should_rebuild) self.rebuildAllViews(runtime) catch {};
3759
4453
  }
3760
4454
 
3761
4455
  /// The `override` half of the fragment hot-reload seam (see
@@ -3902,14 +4596,50 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3902
4596
  return self.status_items_scratch.status_items[0..1];
3903
4597
  }
3904
4598
 
4599
+ fn statusItemPolicyDecision(self: *Self, desired: []const StatusItemDescriptor, index: ?usize) [2]u8 {
4600
+ comptime std.debug.assert(platform.max_status_items == 8);
4601
+ var request: [4 + 8 * 4 + 8 * 5]u8 = undefined;
4602
+ request[0] = @intFromBool(index != null);
4603
+ request[1] = if (index) |i| @intCast(i) else 255;
4604
+ request[2] = @intCast(desired.len);
4605
+ request[3] = @intCast(self.applied_status_item_count);
4606
+ var at: usize = 4;
4607
+ for (desired) |descriptor| {
4608
+ std.mem.writeInt(u32, request[at..][0..4], descriptor.id, .little);
4609
+ at += 4;
4610
+ }
4611
+ for (self.applied_status_items) |applied| {
4612
+ request[at] = @intFromBool(applied.active);
4613
+ std.mem.writeInt(u32, request[at + 1 ..][0..4], applied.id, .little);
4614
+ at += 5;
4615
+ }
4616
+ var result: [2]u8 = undefined;
4617
+ if (self.options.status_policy.?(request[0..at], &result) != result.len) @panic("invalid compiled status policy result");
4618
+ if (index != null and (result[0] > 3 or (result[0] >= 2 and result[1] >= platform.max_status_items))) @panic("invalid compiled status admission");
4619
+ return result;
4620
+ }
4621
+
4622
+ fn statusItemPatchDecision(self: *Self, applied: *const AppliedStatusItem, shell: u64, presentation: u64, menu: u64) u8 {
4623
+ var request: [49]u8 = undefined;
4624
+ request[0] = 2;
4625
+ const hashes = [_]u64{ shell, presentation, menu, applied.shell_hash, applied.presentation_hash, applied.menu_hash };
4626
+ for (hashes, 0..) |hash, index| std.mem.writeInt(u64, request[1 + index * 8 ..][0..8], hash, .little);
4627
+ var result: [2]u8 = undefined;
4628
+ if (self.options.status_policy.?(&request, &result) != result.len or result[0] > 7) @panic("invalid compiled status patch result");
4629
+ return result[0];
4630
+ }
4631
+
3905
4632
  fn reconcileStatusItems(self: *Self, runtime: *Runtime, declared: []const StatusItemDescriptor) void {
3906
4633
  if (declared.len > platform.max_status_items) {
3907
4634
  ui_app_log.warn("status item collection has {d} entries; at most {d} are supported", .{ declared.len, platform.max_status_items });
3908
4635
  }
3909
4636
  const desired = declared[0..@min(declared.len, platform.max_status_items)];
3910
4637
 
3911
- for (&self.applied_status_items) |*applied| {
3912
- if (!applied.active or statusItemDeclared(desired, applied.id)) continue;
4638
+ const compiled = self.options.status_policy != null;
4639
+ const retirement = if (compiled) self.statusItemPolicyDecision(desired, null)[0] else 0;
4640
+ for (&self.applied_status_items, 0..) |*applied, slot| {
4641
+ const remove = if (compiled) retirement & (@as(u8, 1) << @intCast(slot)) != 0 else applied.active and !statusItemDeclared(desired, applied.id);
4642
+ if (!remove) continue;
3913
4643
  runtime.removeStatusItem(applied.id) catch |err| {
3914
4644
  ui_app_log.warn("status item #{d} remove failed: {s}", .{ applied.id, @errorName(err) });
3915
4645
  continue;
@@ -3919,10 +4649,18 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3919
4649
  }
3920
4650
 
3921
4651
  for (desired, 0..) |raw_descriptor, index| {
3922
- if (raw_descriptor.id == 0 or statusItemIdAppearedEarlier(desired, index, raw_descriptor.id)) {
4652
+ // Requery the owned table after every successful or failed OS
4653
+ // operation. Failed removals retain slots; failed creates do not.
4654
+ const plan = if (compiled) self.statusItemPolicyDecision(desired, index) else [2]u8{ 0, 255 };
4655
+ const invalid = if (compiled) plan[0] == 0 else raw_descriptor.id == 0 or statusItemIdAppearedEarlier(desired, index, raw_descriptor.id);
4656
+ if (invalid) {
3923
4657
  ui_app_log.warn("status item declaration ignored: identifiers must be unique and non-zero (got {d})", .{raw_descriptor.id});
3924
4658
  continue;
3925
4659
  }
4660
+ if (compiled and plan[0] == 1) {
4661
+ ui_app_log.warn("status item #{d} ignored: status-item capacity is full", .{raw_descriptor.id});
4662
+ continue;
4663
+ }
3926
4664
  var descriptor = raw_descriptor;
3927
4665
  if (descriptor.state.presentation.title.len == 0) descriptor.state.presentation.title = descriptor.state.title;
3928
4666
  const shell = platform.TrayShell{
@@ -3937,11 +4675,12 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3937
4675
  const presentation_hash = hashTrayPresentation(descriptor.state.presentation);
3938
4676
  const menu_hash = hashTrayMenu(descriptor.state.items);
3939
4677
 
3940
- const applied = self.findAppliedStatusItem(descriptor.id) orelse self.emptyAppliedStatusItem() orelse {
4678
+ const applied = if (compiled) &self.applied_status_items[plan[1]] else self.findAppliedStatusItem(descriptor.id) orelse self.emptyAppliedStatusItem() orelse {
3941
4679
  ui_app_log.warn("status item #{d} ignored: status-item capacity is full", .{descriptor.id});
3942
4680
  continue;
3943
4681
  };
3944
- if (!applied.active) {
4682
+ const creating = if (compiled) plan[0] == 2 else !applied.active;
4683
+ if (creating) {
3945
4684
  runtime.createStatusItem(descriptor.id, .{
3946
4685
  .title = descriptor.state.presentation.title,
3947
4686
  .icon_path = shell.icon_path,
@@ -3967,7 +4706,10 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3967
4706
  continue;
3968
4707
  }
3969
4708
 
3970
- if (shell_hash != applied.shell_hash) {
4709
+ const changes = if (compiled) self.statusItemPatchDecision(applied, shell_hash, presentation_hash, menu_hash) else @as(u8, @intFromBool(shell_hash != applied.shell_hash)) |
4710
+ (@as(u8, @intFromBool(presentation_hash != applied.presentation_hash)) << 1) |
4711
+ (@as(u8, @intFromBool(menu_hash != applied.menu_hash)) << 2);
4712
+ if (changes & 1 != 0) {
3971
4713
  applied.shell_hash = shell_hash;
3972
4714
  if (!applied.shell_unsupported) {
3973
4715
  runtime.updateStatusItemShell(descriptor.id, shell) catch |err| {
@@ -3976,7 +4718,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3976
4718
  };
3977
4719
  }
3978
4720
  }
3979
- if (presentation_hash != applied.presentation_hash) {
4721
+ if (changes & 2 != 0) {
3980
4722
  applied.presentation_hash = presentation_hash;
3981
4723
  if (!applied.presentation_unsupported) {
3982
4724
  runtime.updateStatusItemPresentation(descriptor.id, descriptor.state.presentation) catch |err| {
@@ -3985,7 +4727,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3985
4727
  };
3986
4728
  }
3987
4729
  }
3988
- if (menu_hash != applied.menu_hash) {
4730
+ if (changes & 4 != 0) {
3989
4731
  applied.menu_hash = menu_hash;
3990
4732
  runtime.updateStatusItemMenu(descriptor.id, descriptor.state.items) catch |err| {
3991
4733
  ui_app_log.warn("status item #{d} menu update failed: {s}", .{ descriptor.id, @errorName(err) });
@@ -4247,65 +4989,45 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4247
4989
 
4248
4990
  fn eventFn(context: *anyopaque, runtime: *Runtime, event_value: Event) anyerror!void {
4249
4991
  const self: *Self = @ptrCast(@alignCast(context));
4992
+ if (self.options.on_window_context) |map| {
4993
+ const source_id: ?platform.WindowId = switch (event_value) {
4994
+ inline .command, .shortcut, .canvas_widget_pointer, .canvas_widget_keyboard, .canvas_widget_scroll, .canvas_widget_file_drop, .canvas_widget_drag, .canvas_widget_context_menu, .canvas_widget_context_menu_shown, .canvas_widget_context_menu_dismissed, .canvas_widget_context_menu_request, .canvas_widget_dismiss, .canvas_widget_context_press, .canvas_widget_resize, .canvas_widget_change, .window_closed, .automation_provenance => |event| event.window_id,
4995
+ else => null,
4996
+ };
4997
+ if (source_id) |id| {
4998
+ var storage: [platform.max_windows]platform.WindowInfo = undefined;
4999
+ for (runtime.listWindows(&storage)) |window| {
5000
+ if (window.id != id) continue;
5001
+ if (map(&self.model, window.label)) |msg| self.applyMsg(msg);
5002
+ break;
5003
+ }
5004
+ }
5005
+ }
4250
5006
  self.hover_msg_event_depth += 1;
4251
5007
  defer self.hover_msg_event_depth -= 1;
4252
- // Hover enter/leave delivery rides the tail of runtime
4253
- // events: the standing chain moves during pointer routing,
4254
- // scroll reconciles (wheel, kinetic, drivers, keyboard),
4255
- // dismissals, and any rebuild the dispatches above
4256
- // performed — the drain seam catches them all, and replay
4257
- // re-runs the same events through the same seam. The drain
4258
- // runs on the handler's ERROR path too (the degraded-error
4259
- // doctrine): a failing handler must not strand edges the
4260
- // event already produced — a closed window's leave, a
4261
- // failed rebuild's prune — until some later event happens
4262
- // by. Mid-cycle DERIVED widget events skip the drain (see
4263
- // `hoverDrainsAfterEvent`): their input cycle's terminal
4264
- // `gpu_surface_input` dispatch drains after the cycle's
4265
- // pending scroll/resize/change observations were delivered,
4266
- // so a hover Msg's rebuild can never unmount a view whose
4267
- // promised observation is still queued.
5008
+ var first_error: ?anyerror = null;
4268
5009
  handleRuntimeEvent(self, runtime, event_value) catch |err| {
4269
- if (hoverDrainsAfterEvent(event_value)) self.drainHoverMsgs(runtime) catch {};
4270
- return err;
5010
+ first_error = err;
5011
+ };
5012
+ // Event classification describes the native input envelope; the
5013
+ // portable policy chooses settlement, including error paths.
5014
+ const kind: u8 = switch (event_value) {
5015
+ .canvas_widget_keyboard => 2,
5016
+ .canvas_widget_pointer, .canvas_widget_drag, .canvas_widget_file_drop, .canvas_widget_context_press, .canvas_widget_context_menu_request, .canvas_widget_context_menu_shown, .canvas_widget_scroll, .canvas_widget_resize, .canvas_widget_change => 1,
5017
+ else => 0,
4271
5018
  };
4272
- if (hoverDrainsAfterEvent(event_value)) try self.drainHoverMsgs(runtime);
4273
- }
4274
-
4275
- /// Whether the hover drain runs at this event's tail. Derived
4276
- /// widget events that only occur INSIDE a gpu-surface input
4277
- /// cycle defer to the cycle's terminal `gpu_surface_input`
4278
- /// dispatch — which always follows them, after the pending
4279
- /// scroll/resize/change drains. Scroll/resize/change events also
4280
- /// arrive standalone from the native-driver and kinetic paths;
4281
- /// those defer at most one frame (both paths run under an
4282
- /// actively pumping frame channel), which is the price of never
4283
- /// rebuilding mid-cycle. Dismiss events DO drain: the
4284
- /// automation/accessibility dismiss verb dispatches one
4285
- /// standalone, and a dismissal's own Msg rebuild already runs
4286
- /// before the cycle's pending drains, so draining here adds no
4287
- /// new hazard class. Everything else — commands, timers, wakes,
4288
- /// frames, the terminal input dispatch, native menu selections —
4289
- /// drains immediately.
4290
- fn hoverDrainsAfterEvent(event_value: Event) bool {
4291
- return switch (event_value) {
4292
- // Keyboard events usually ride an input cycle (their
4293
- // terminal dispatch drains); the standalone ones —
4294
- // accessibility selection edits, context-menu
4295
- // cut/paste/select-all — have no cycle and drain here.
4296
- .canvas_widget_keyboard => |keyboard_event| keyboard_event.standalone,
4297
- .canvas_widget_pointer,
4298
- .canvas_widget_drag,
4299
- .canvas_widget_file_drop,
4300
- .canvas_widget_context_press,
4301
- .canvas_widget_context_menu_request,
4302
- .canvas_widget_context_menu_shown,
4303
- .canvas_widget_scroll,
4304
- .canvas_widget_resize,
4305
- .canvas_widget_change,
4306
- => false,
4307
- else => true,
5019
+ const standalone = switch (event_value) {
5020
+ .canvas_widget_keyboard => |keyboard| keyboard.standalone,
5021
+ else => false,
4308
5022
  };
5023
+ const tail = dispatch_policy.plan(self.options.app_dispatch_policy, .event_tail, kind, @intFromBool(standalone));
5024
+ for (tail) |byte| switch (@as(dispatch_policy.Action, @enumFromInt(byte))) {
5025
+ .end => break,
5026
+ .hover => self.drainHoverMsgs(runtime) catch |err| self.selectDispatchError(&first_error, err),
5027
+ else => @panic("unexpected event tail action"),
5028
+ };
5029
+ if (self.hover_msg_event_depth == 1) self.effects.flushDesktopCapabilities();
5030
+ if (first_error) |err| return err;
4309
5031
  }
4310
5032
 
4311
5033
  fn handleRuntimeEvent(self: *Self, runtime: *Runtime, event_value: Event) anyerror!void {
@@ -4449,6 +5171,9 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4449
5171
 
4450
5172
  fn handleTimer(self: *Self, runtime: *Runtime, timer_event: platform.TimerEvent) anyerror!void {
4451
5173
  if (timer_event.id == markup_watch_timer_id) {
5174
+ if (comptime view_reload_enabled) {
5175
+ if (view_reload.installed) |reload| return self.pollViewReload(runtime, reload);
5176
+ }
4452
5177
  self.pollMarkupWatch(runtime, self.canvas_window_id);
4453
5178
  self.pollFragmentWatch(runtime);
4454
5179
  return;
@@ -4524,15 +5249,19 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4524
5249
  }
4525
5250
 
4526
5251
  fn handleFrame(self: *Self, runtime: *Runtime, frame_event: platform.GpuSurfaceFrameEvent) anyerror!void {
5252
+ // A secondary surface can be the only surviving frame source.
5253
+ try self.drainEffects(runtime);
5254
+ for (runtime.windows[0..runtime.window_count]) |window| {
5255
+ if (window.info.id == frame_event.window_id and !window.info.open) return;
5256
+ }
4527
5257
  if (!std.mem.eql(u8, frame_event.label, self.options.canvas_label)) {
4528
5258
  return self.handleWindowSlotFrame(runtime, frame_event);
4529
5259
  }
4530
5260
  // Host-pumped embeds deliver no `.wake`; drain pending effect
4531
5261
  // results with the frame tick so this frame presents them.
4532
- try self.drainEffects(runtime);
4533
5262
  self.canvas_window_id = frame_event.window_id;
4534
5263
  self.frame_timestamp_ns = frame_event.timestamp_ns;
4535
- const scale = normalizedSurfaceScale(frame_event.scale_factor);
5264
+ const scale = self.normalizedSurfaceScale(frame_event.scale_factor);
4536
5265
  var installing = false;
4537
5266
  if (!self.installed) {
4538
5267
  installing = true;
@@ -4568,7 +5297,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4568
5297
  // rebuild below is the one that renders it), so a
4569
5298
  // hidden-titlebar header is padded in the very first
4570
5299
  // paint.
4571
- if (self.chromeInsetsMsg(runtime, frame_event.window_id)) |msg| {
5300
+ if (try self.chromeInsetsMsg(runtime, frame_event.window_id)) |msg| {
4572
5301
  self.applyMsg(msg);
4573
5302
  }
4574
5303
  try self.rebuild(runtime, frame_event.window_id);
@@ -4610,7 +5339,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4610
5339
  // job.
4611
5340
  self.canvas_size = frame_event.size;
4612
5341
  try self.rebuild(runtime, frame_event.window_id);
4613
- } else if (runtime.registeredCanvasFontCount() != self.fonts_built_count) {
5342
+ } else if (if (self.options.font_registry_policy) |policy|
5343
+ @import("font_registry_policy.zig").plan(policy, .refresh, &.{}, runtime.registeredCanvasFontCount(), .{ .built_count = self.fonts_built_count }).action != 0
5344
+ else
5345
+ runtime.registeredCanvasFontCount() != self.fonts_built_count)
5346
+ {
4614
5347
  // A face joined the registry after install (late
4615
5348
  // registration through the runtime seam). The runtime
4616
5349
  // already invalidated measurement caches and requested
@@ -4621,14 +5354,6 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4621
5354
  // rebuilding so layout and the re-emitted display lists
4622
5355
  // charge the registered face's advances.
4623
5356
  try self.rebuildForRegisteredFonts(runtime);
4624
- } else if (self.options.web_panes != null) {
4625
- // Re-snap the webview panes each presented frame: a shell
4626
- // relayout that stomped a pane frame also invalidated the
4627
- // canvas, so the reconciliation ride-along here converges
4628
- // without a dedicated event.
4629
- if (runtime.canvasWidgetLayout(frame_event.window_id, self.options.canvas_label)) |layout| {
4630
- self.applyWebPanes(runtime, frame_event.window_id, layout);
4631
- } else |_| {}
4632
5357
  }
4633
5358
  // Terminal outbound pacing: a child that read without
4634
5359
  // echoing freed stdin-FIFO room no output event announces,
@@ -4646,6 +5371,16 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4646
5371
  installing,
4647
5372
  self.effectiveTokens().colors.background,
4648
5373
  );
5374
+ // The first native present can show the window and synchronously
5375
+ // report its frame. Shell relayout then resets child WebViews to
5376
+ // their manifest frames after rebuild applied the model's panes.
5377
+ // Restore pane ownership before this event commits, so recording
5378
+ // and flat replay observe the same anchored first-frame state.
5379
+ if (self.options.web_panes != null) {
5380
+ if (runtime.canvasWidgetLayout(frame_event.window_id, self.options.canvas_label)) |layout| {
5381
+ self.applyWebPanes(runtime, frame_event.window_id, layout);
5382
+ } else |_| {}
5383
+ }
4649
5384
  if (installing) return;
4650
5385
  const on_frame = self.options.on_frame orelse return;
4651
5386
  const gpu_frame = runtime.gpuSurfaceFrame(frame_event.window_id, self.options.canvas_label) catch return;
@@ -4662,7 +5397,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4662
5397
  fn handleWindowSlotFrame(self: *Self, runtime: *Runtime, frame_event: platform.GpuSurfaceFrameEvent) anyerror!void {
4663
5398
  const slot = self.windowSlotByCanvasLabel(frame_event.label) orelse return;
4664
5399
  slot.window_id = frame_event.window_id;
4665
- const scale = normalizedSurfaceScale(frame_event.scale_factor);
5400
+ const scale = self.normalizedSurfaceScale(frame_event.scale_factor);
4666
5401
  var installing = false;
4667
5402
  if (!slot.installed) {
4668
5403
  installing = true;
@@ -4690,7 +5425,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4690
5425
  // stale bounds.
4691
5426
  slot.canvas_size = frame_event.size;
4692
5427
  try self.rebuildWindowSlot(runtime, slot);
4693
- } else if (runtime.registeredCanvasFontCount() != self.fonts_built_count) {
5428
+ } else if (if (self.options.font_registry_policy) |policy|
5429
+ @import("font_registry_policy.zig").plan(policy, .refresh, &.{}, runtime.registeredCanvasFontCount(), .{ .built_count = self.fonts_built_count }).action != 0
5430
+ else
5431
+ runtime.registeredCanvasFontCount() != self.fonts_built_count)
5432
+ {
4694
5433
  // Late registration, first observed on a secondary
4695
5434
  // window's frame (registration requests frames for every
4696
5435
  // open surface, and arrival order is the platform's):
@@ -4803,7 +5542,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4803
5542
  /// Grow the heap pixel buffers to hold the surface at the given
4804
5543
  /// scale. No-op when they are already large enough.
4805
5544
  fn ensurePixelBuffers(self: *Self, surface_size: geometry.SizeF, scale_factor: f32) anyerror!void {
4806
- const pixel_size = try canvas_frame.canvasSurfacePixelSize(surface_size, scale_factor);
5545
+ const pixel_size = try canvas_frame.canvasSurfacePixelSizeWithPolicy(surface_size, scale_factor, self.options.render_cache_policy);
4807
5546
  if (self.pixel_buffer.len < pixel_size.byte_len) {
4808
5547
  self.pixel_buffer_window_id = null;
4809
5548
  if (self.pixel_buffer.len > 0) self.backing.free(self.pixel_buffer);
@@ -4817,9 +5556,8 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4817
5556
  }
4818
5557
  }
4819
5558
 
4820
- fn normalizedSurfaceScale(scale_factor: f32) f32 {
4821
- if (!std.math.isFinite(scale_factor) or scale_factor <= 0) return 1;
4822
- return scale_factor;
5559
+ fn normalizedSurfaceScale(self: *Self, scale_factor: f32) f32 {
5560
+ return canvas_frame.normalizedCanvasPresentationScaleWithPolicy(scale_factor, 1, self.options.render_cache_policy);
4823
5561
  }
4824
5562
 
4825
5563
  /// Change-detection hashes for the model-derived tray state:
@@ -4917,19 +5655,19 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4917
5655
  if (!std.mem.eql(u8, resize_event.label, self.options.canvas_label)) {
4918
5656
  const slot = self.windowSlotByCanvasLabel(resize_event.label) orelse return;
4919
5657
  slot.canvas_size = .{ .width = resize_event.frame.width, .height = resize_event.frame.height };
4920
- slot.pixel_snap_scale = normalizedSurfaceScale(resize_event.scale_factor);
5658
+ slot.pixel_snap_scale = self.normalizedSurfaceScale(resize_event.scale_factor);
4921
5659
  if (slot.installed) try self.rebuildWindowSlot(runtime, slot);
4922
5660
  return;
4923
5661
  }
4924
5662
  self.canvas_size = .{ .width = resize_event.frame.width, .height = resize_event.frame.height };
4925
- self.pixel_snap_scale = normalizedSurfaceScale(resize_event.scale_factor);
5663
+ self.pixel_snap_scale = self.normalizedSurfaceScale(resize_event.scale_factor);
4926
5664
  if (!self.installed) return;
4927
5665
  // Fullscreen transitions resize the canvas AND flip the
4928
5666
  // chrome overlay insets (macOS hides the titlebar band and
4929
5667
  // traffic lights); re-query on every resize and dispatch
4930
5668
  // only on change — `dispatch` already rebuilds, so the
4931
5669
  // plain-resize rebuild is the else arm.
4932
- if (self.chromeInsetsMsg(runtime, resize_event.window_id)) |msg| {
5670
+ if (try self.chromeInsetsMsg(runtime, resize_event.window_id)) |msg| {
4933
5671
  try self.dispatch(runtime, resize_event.window_id, msg);
4934
5672
  return;
4935
5673
  }
@@ -4961,9 +5699,9 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4961
5699
  /// The `on_chrome` delivery gate: query the platform's chrome
4962
5700
  /// overlay geometry for the canvas window and map it to a Msg
4963
5701
  /// when the app subscribed AND the geometry actually changed.
4964
- fn chromeInsetsMsg(self: *Self, runtime: *Runtime, window_id: platform.WindowId) ?MsgT {
5702
+ fn chromeInsetsMsg(self: *Self, runtime: *Runtime, window_id: platform.WindowId) !?MsgT {
4965
5703
  const map = self.options.on_chrome orelse return null;
4966
- const chrome = runtime.options.platform.services.windowChrome(window_id);
5704
+ const chrome = try runtime.windowChrome(window_id);
4967
5705
  if (self.window_chrome_known and std.meta.eql(chrome, self.window_chrome)) return null;
4968
5706
  self.window_chrome = chrome;
4969
5707
  self.window_chrome_known = true;
@@ -5032,9 +5770,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5032
5770
  const terminal_selected = try self.handleTerminalPointer(runtime, pointer_event);
5033
5771
  switch (pointer_event.pointer.phase) {
5034
5772
  .down => {
5035
- self.disarmHold(runtime);
5773
+ const has_hold = if (pointer_event.press_target) |target| tree.hasHoldHandler(target.id) else false;
5774
+ const plan = self.pressHoldPlan(0, has_hold, true);
5775
+ self.applyHoldReset(runtime, plan);
5036
5776
  if (pointer_event.press_target) |target| {
5037
- if (tree.hasHoldHandler(target.id)) {
5777
+ if (plan & 4 != 0) {
5038
5778
  self.hold_armed_id = target.id;
5039
5779
  self.hold_fired = false;
5040
5780
  // One pointer, one gesture — but it can be
@@ -5050,9 +5790,9 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5050
5790
  }
5051
5791
  },
5052
5792
  .up, .cancel => {
5053
- const suppressed = self.hold_fired;
5054
- self.disarmHold(runtime);
5055
- if (suppressed) return;
5793
+ const plan = self.pressHoldPlan(1, false, true);
5794
+ self.applyHoldReset(runtime, plan);
5795
+ if (plan & 8 != 0) return;
5056
5796
  },
5057
5797
  else => {},
5058
5798
  }
@@ -5100,19 +5840,6 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5100
5840
  }
5101
5841
  }
5102
5842
 
5103
- /// Cap on hover-Msg drain passes per runtime event: each pass
5104
- /// delivers one coalesced containment transition, and the Msgs
5105
- /// it dispatches can rebuild the tree and move the standing
5106
- /// chain again (an enter handler that unmounts the hovered
5107
- /// element owes an immediate leave — the second pass delivers
5108
- /// it). The cap exists ONLY as a flap guard (an app whose enter
5109
- /// mounts and whose leave unmounts, forever), sized far past
5110
- /// any honest cascade — even one where every enter replaces the
5111
- /// listener under a stationary pointer — so a finite sequence
5112
- /// always settles within one drain; residue past the cap
5113
- /// delivers on the next event's drain.
5114
- const hover_msg_drain_passes: usize = 64;
5115
-
5116
5843
  /// Refresh every standing capture from the mirror view's live
5117
5844
  /// tree when the trees moved underneath: called at EVERY
5118
5845
  /// rebuild commit — two dispatches in one cycle (payload A to
@@ -5123,66 +5850,56 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5123
5850
  /// (allocation) after attempting every entry, leaving the
5124
5851
  /// generation behind so the next commit or drain retries.
5125
5852
  fn refreshHoverLeaveCaptures(self: *Self) ?anyerror {
5126
- if (self.hover_msg_chain_len == 0) return null;
5127
- if (self.hover_msg_captured_generation == self.build_generation) return null;
5128
- if (!self.hoverTreeCurrentFor(self.hover_msg_window_id, self.hoverMsgViewLabel())) return null;
5129
- const mirror_tree = self.hoverTreeFor(self.hover_msg_window_id, self.hoverMsgViewLabel()) orelse return null;
5853
+ const mirror_tree = self.hoverTreeFor(self.hover_msg_window_id, self.hoverMsgViewLabel());
5854
+ if (hover_policy.decide(self.options.surface_scope_policy, .{ .stage = .refresh, .facts = @as(u8, if (self.hover_msg_chain_len != 0) 1 else 0) | @as(u8, if (self.hover_msg_captured_generation == self.build_generation) 2 else 0) |
5855
+ @as(u8, if (self.hoverTreeCurrentFor(self.hover_msg_window_id, self.hoverMsgViewLabel())) 4 else 0) | @as(u8, if (mirror_tree != null) 8 else 0) }) == 0) return null;
5130
5856
  var first_error: ?anyerror = null;
5131
5857
  var refreshed = true;
5132
5858
  for (0..self.hover_msg_chain_len) |position| {
5133
5859
  // A refused entry's pair is disabled (its enter never
5134
5860
  // dispatched); a rebind only takes effect on re-entry.
5135
- if (self.hover_msg_slots[position] == hover_msg_slot_refused) continue;
5136
- const leave_msg = mirror_tree.msgFor(self.hover_msg_chain[position], .hover_leave) orelse continue;
5861
+ const leave_msg = if (mirror_tree) |tree| tree.msgFor(self.hover_msg_chain[position], .hover_leave) else null;
5862
+ if (hover_policy.decide(self.options.surface_scope_policy, .{ .stage = .refresh_entry, .facts = @as(u8, if (self.hover_msg_slots[position] == hover_msg_slot_refused) 1 else 0) | @as(u8, if (leave_msg != null) 2 else 0) }) == 0) continue;
5137
5863
  // Copy-then-swap: the replacement lands in a FRESH slot
5138
5864
  // (the pool sizing guarantees one is free) and the old
5139
5865
  // capture releases only after it succeeded — a failed
5140
5866
  // allocation must never destroy the still-valid capture
5141
5867
  // it was refreshing.
5142
5868
  const fresh = self.claimHoverSlot() orelse {
5143
- refreshed = false;
5144
- ui_app_log.warn("hover-leave capture refresh failed: no free capture slot - retrying at the next rebuild or drain", .{});
5145
- if (first_error == null) first_error = error.OutOfMemory;
5869
+ if (self.hoverCaptureDecision(0, 0, self.hover_msg_slots[position]) == 1) {
5870
+ refreshed = false;
5871
+ ui_app_log.warn("hover-leave capture refresh failed: no free capture slot - retrying at the next rebuild or drain", .{});
5872
+ if (first_error == null) first_error = error.OutOfMemory;
5873
+ }
5146
5874
  continue;
5147
5875
  };
5148
- self.captureHoverLeave(fresh, leave_msg) catch |err| {
5876
+ self.captureHoverLeave(fresh, leave_msg.?) catch |err| {
5149
5877
  self.releaseHoverSlot(fresh);
5150
- switch (err) {
5151
- error.OutOfMemory => {
5152
- // Transient: keep the old capture, retry at
5153
- // the next commit or drain — the generation
5154
- // stays behind — and surface the failure
5155
- // LOUD: if the element unmounts before a
5156
- // retry lands, its refreshed leave is lost,
5157
- // and that must never be silent.
5158
- refreshed = false;
5159
- ui_app_log.warn("hover-leave capture refresh failed: {t} - retrying at the next rebuild or drain; an unmount before a successful retry loses the newly bound leave", .{err});
5160
- if (first_error == null) first_error = err;
5161
- },
5162
- error.HoverCapturePayloadUnsupported => {
5163
- // A rebind to an unownable payload. An
5164
- // entry with a standing capture keeps it
5165
- // quietly (the promise the enter earned);
5166
- // an entry that never had one — entered
5167
- // with no leave bound, then given one no
5168
- // copy can own — is marked so the
5169
- // degradation is WARNED once, not silent,
5170
- // and not re-warned every generation.
5171
- if (self.hover_msg_slots[position] == hover_msg_slot_none) {
5172
- self.hover_msg_slots[position] = hover_msg_slot_unowned;
5173
- ui_app_log.warn("on_hover_leave rebind cannot be owned (a single-item pointer): the standing element's leave degrades to live-tree resolution, and an unmount loses it - bind a slice or scalar payload instead", .{});
5174
- }
5175
- },
5878
+ const action = self.hoverCaptureDecision(0, if (err == error.OutOfMemory) 0 else 1, self.hover_msg_slots[position]);
5879
+ if (action == 1) {
5880
+ refreshed = false;
5881
+ ui_app_log.warn("hover-leave capture refresh failed: {t} - retrying at the next rebuild or drain; an unmount before a successful retry loses the newly bound leave", .{err});
5882
+ if (first_error == null) first_error = err;
5883
+ } else if (action == 3) {
5884
+ self.hover_msg_slots[position] = hover_msg_slot_unowned;
5885
+ ui_app_log.warn("on_hover_leave rebind cannot be owned (a single-item pointer): the standing element's leave degrades to live-tree resolution, and an unmount loses it - bind a slice or scalar payload instead", .{});
5176
5886
  }
5177
5887
  continue;
5178
5888
  };
5179
- self.releaseHoverSlot(self.hover_msg_slots[position]);
5180
- self.hover_msg_slots[position] = fresh;
5889
+ if (self.hoverCaptureDecision(0, 2, self.hover_msg_slots[position]) == 4) {
5890
+ self.releaseHoverSlot(self.hover_msg_slots[position]);
5891
+ self.hover_msg_slots[position] = fresh;
5892
+ } else self.releaseHoverSlot(fresh);
5181
5893
  }
5182
5894
  if (refreshed) self.hover_msg_captured_generation = self.build_generation;
5183
5895
  return first_error;
5184
5896
  }
5185
5897
 
5898
+ fn hoverCaptureDecision(self: *const Self, context: u8, outcome: u8, slot: u8) u8 {
5899
+ const kind: u8 = if (slot == hover_msg_slot_none) 0 else if (slot == hover_msg_slot_refused) 1 else if (slot == hover_msg_slot_unowned) 2 else 3;
5900
+ return hover_policy.decide(self.options.surface_scope_policy, .{ .stage = .capture, .a = context, .b = outcome, .facts = kind });
5901
+ }
5902
+
5186
5903
  /// The mirror-view adoption count for the tracked publication
5187
5904
  /// below (0 when the view is not found — then no adoption can
5188
5905
  /// have happened either).
@@ -5201,8 +5918,23 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5201
5918
  /// still mark the pair stale, while a pre-adoption rejection
5202
5919
  /// must not. The view's adoption counter is the witness.
5203
5920
  fn publishWidgetLayoutTracked(self: *Self, runtime: *Runtime, window_id: platform.WindowId, label: []const u8, layout: canvas.WidgetLayoutTree, current_flag: *bool) anyerror!void {
5204
- _ = self;
5205
5921
  const adoptions_before = canvasWidgetLayoutAdoptions(runtime, window_id, label);
5922
+ defer {
5923
+ // Adoption precedes fallible host synchronization. Stamp
5924
+ // the policy even when those later operations fail, while
5925
+ // leaving a rejected publication's retained policy intact.
5926
+ if (canvasWidgetLayoutAdoptions(runtime, window_id, label) != adoptions_before) {
5927
+ for (runtime.views[0..runtime.view_count]) |*view| {
5928
+ if (view.window_id == window_id and std.mem.eql(u8, view.label, label)) {
5929
+ view.canvas_widget_tab_focus_policy = self.options.tab_focus_policy;
5930
+ view.canvas_widget_surface_scope_policy = self.options.surface_scope_policy;
5931
+ view.canvas_widget_focus_return_policy = self.options.focus_return_policy;
5932
+ view.canvas_widget_tooltip_policy = self.options.tooltip_policy;
5933
+ break;
5934
+ }
5935
+ }
5936
+ }
5937
+ }
5206
5938
  _ = runtime.setCanvasWidgetLayout(window_id, label, layout) catch |err| {
5207
5939
  if (canvasWidgetLayoutAdoptions(runtime, window_id, label) != adoptions_before) current_flag.* = false;
5208
5940
  return err;
@@ -5397,8 +6129,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5397
6129
  /// dispatches, which is what "discrete edges, never per-move"
5398
6130
  /// means under a fast pointer.
5399
6131
  fn drainHoverMsgs(self: *Self, runtime: *Runtime) anyerror!void {
5400
- if (!self.installed) return;
5401
- if (self.hover_msg_draining) return;
6132
+ if (hover_policy.decide(self.options.surface_scope_policy, .{ .stage = .drain, .facts = @as(u8, if (self.installed) 1 else 0) | @as(u8, if (self.hover_msg_draining) 2 else 0) }) == 0) return;
5402
6133
  self.hover_msg_draining = true;
5403
6134
  defer self.hover_msg_draining = false;
5404
6135
  // A pass's error degrades WITHOUT aborting the drain: its
@@ -5409,12 +6140,12 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5409
6140
  // degraded handling every event handler gets.
5410
6141
  var first_error: ?anyerror = null;
5411
6142
  var passes: usize = 0;
5412
- while (passes < hover_msg_drain_passes) : (passes += 1) {
6143
+ while (hover_policy.decide(self.options.surface_scope_policy, .{ .stage = .continuation, .a = @intCast(passes), .facts = 1 }) != 0) : (passes += 1) {
5413
6144
  const progressed = self.stepHoverMsgs(runtime) catch |err| blk: {
5414
6145
  if (first_error == null) first_error = err;
5415
6146
  break :blk true;
5416
6147
  };
5417
- if (!progressed) break;
6148
+ if (hover_policy.decide(self.options.surface_scope_policy, .{ .stage = .continuation, .a = @intCast(passes + 1), .facts = @intFromBool(progressed) }) == 0) break;
5418
6149
  }
5419
6150
  if (first_error) |err| return err;
5420
6151
  }
@@ -5432,15 +6163,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5432
6163
  fn stepHoverMsgs(self: *Self, runtime: *Runtime) anyerror!bool {
5433
6164
  var standing_index: ?usize = null;
5434
6165
  for (runtime.views[0..runtime.view_count], 0..) |*view, index| {
5435
- if (view.kind != .gpu_surface) continue;
5436
- if (view.canvas_widget_hover_msg_chain_len == 0) continue;
5437
- const is_mirror = view.window_id == self.hover_msg_window_id and
5438
- std.mem.eql(u8, view.label, self.hoverMsgViewLabel());
5439
- if (is_mirror) {
5440
- standing_index = index;
5441
- break;
5442
- }
5443
- if (standing_index == null) standing_index = index;
6166
+ const is_mirror = view.window_id == self.hover_msg_window_id and std.mem.eql(u8, view.label, self.hoverMsgViewLabel());
6167
+ const action = hover_policy.decide(self.options.surface_scope_policy, .{ .stage = .view, .facts = @as(u8, if (view.kind == .gpu_surface) 1 else 0) | @as(u8, if (view.canvas_widget_hover_msg_chain_len != 0) 2 else 0) |
6168
+ @as(u8, if (is_mirror) 4 else 0) | @as(u8, if (standing_index != null) 8 else 0) });
6169
+ if (action != 0) standing_index = index;
6170
+ if (action == 2) break;
5444
6171
  }
5445
6172
 
5446
6173
  // The standing chain and the view identity it belongs to
@@ -5491,28 +6218,13 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5491
6218
  // A view change retains nothing (one pointer, one view).
5492
6219
  var retained_slots: [canvas.max_widget_depth]u8 = undefined;
5493
6220
  var entering_at: [canvas.max_widget_depth]bool = undefined;
5494
- var entering_any = false;
5495
- var identical = same_view and standing_len == mirror_len;
5496
- for (standing_chain[0..standing_len], 0..) |id, position| {
5497
- var slot: u8 = hover_msg_slot_none;
5498
- var retained = false;
5499
- if (same_view) {
5500
- for (self.hover_msg_chain[0..mirror_len], 0..) |mirror_id, mirror_position| {
5501
- if (mirror_id != id) continue;
5502
- slot = self.hover_msg_slots[mirror_position];
5503
- retained = true;
5504
- if (mirror_position != position) identical = false;
5505
- break;
5506
- }
5507
- }
5508
- retained_slots[position] = slot;
5509
- entering_at[position] = !retained;
5510
- if (!retained) {
5511
- entering_any = true;
5512
- identical = false;
5513
- }
6221
+ const plan = hover_policy.plan(self.options.surface_scope_policy, same_view, self.hover_msg_chain[0..mirror_len], standing_chain[0..standing_len]);
6222
+ for (0..standing_len) |position| {
6223
+ const retained = plan.retained[position];
6224
+ retained_slots[position] = if (retained == 255) hover_msg_slot_none else self.hover_msg_slots[retained];
6225
+ entering_at[position] = retained == 255;
5514
6226
  }
5515
- if (identical) {
6227
+ if (plan.identical) {
5516
6228
  if (first_error) |err| return err;
5517
6229
  return false;
5518
6230
  }
@@ -5528,26 +6240,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5528
6240
  // while the leaves this transition owes still dispatch
5529
6241
  // below — their Msgs are owned captures, not tree lookups,
5530
6242
  // and a broken destination must never withhold them.
5531
- const destination_ready = !entering_any or
5532
- (self.hoverTreeCurrentFor(standing_window, standing_label) and self.hoverTreeFor(standing_window, standing_label) != null);
5533
- if (!destination_ready) {
5534
- var any_leaving = false;
5535
- for (self.hover_msg_chain[0..mirror_len]) |id| {
5536
- const still_standing = same_view and blk: {
5537
- for (standing_chain[0..standing_len]) |candidate| {
5538
- if (candidate == id) break :blk true;
5539
- }
5540
- break :blk false;
5541
- };
5542
- if (!still_standing) {
5543
- any_leaving = true;
5544
- break;
5545
- }
5546
- }
5547
- // Nothing deliverable now: enters wait for a current
5548
- // tree, retained entries stay put.
5549
- if (!any_leaving) return false;
5550
- }
6243
+ const destination_ready = hover_policy.decide(self.options.surface_scope_policy, .{ .stage = .enter, .facts = 1 |
6244
+ @as(u8, if (plan.entering) 2 else 0) | @as(u8, if (self.hoverTreeCurrentFor(standing_window, standing_label)) 4 else 0) |
6245
+ @as(u8, if (self.hoverTreeFor(standing_window, standing_label) != null) 8 else 0) }) != 2;
6246
+ // Deferred enters stay outside the mirror, but owned leaves still deliver.
6247
+ if (!destination_ready and plan.leave_count == 0) return false;
5551
6248
 
5552
6249
  // The leaves this pass owes — mirror ids absent from the
5553
6250
  // standing chain — innermost-first. Their captured Msgs own
@@ -5562,21 +6259,10 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5562
6259
  @memcpy(leave_label_storage[0..leave_label_len], self.hover_msg_view_label_storage[0..leave_label_len]);
5563
6260
  var leave_ids: [canvas.max_widget_depth]canvas.ObjectId = undefined;
5564
6261
  var leave_slots: [canvas.max_widget_depth]u8 = undefined;
5565
- var leave_count: usize = 0;
5566
- var index = mirror_len;
5567
- while (index > 0) {
5568
- index -= 1;
5569
- const id = self.hover_msg_chain[index];
5570
- const still_standing = same_view and blk: {
5571
- for (standing_chain[0..standing_len]) |candidate| {
5572
- if (candidate == id) break :blk true;
5573
- }
5574
- break :blk false;
5575
- };
5576
- if (still_standing) continue;
5577
- leave_ids[leave_count] = id;
5578
- leave_slots[leave_count] = self.hover_msg_slots[index];
5579
- leave_count += 1;
6262
+ const leave_count = plan.leave_count;
6263
+ for (plan.leaving[0..leave_count], 0..) |index, position| {
6264
+ leave_ids[position] = self.hover_msg_chain[index];
6265
+ leave_slots[position] = self.hover_msg_slots[index];
5580
6266
  }
5581
6267
 
5582
6268
  // Commit the mirror before dispatching so a mid-dispatch
@@ -5610,18 +6296,12 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5610
6296
  // — and the first error propagates after the batch, into
5611
6297
  // the same degraded handling every event handler gets.
5612
6298
  for (leave_ids[0..leave_count], leave_slots[0..leave_count]) |id, slot| {
5613
- // A refused entry never entered: it owes nothing on
5614
- // exit.
5615
- if (slot == hover_msg_slot_refused) continue;
5616
- // The capture wins (leave answers what enter announced);
5617
- // an unowned capture falls back to the live tree while
5618
- // its element still stands there.
5619
6299
  const captured: ?MsgT = if (slot >= hover_msg_slot_count) null else self.hover_msg_leave_msgs[slot];
5620
- const msg = captured orelse blk: {
5621
- if (!self.hoverTreeCurrentFor(leave_window, leave_label_storage[0..leave_label_len])) break :blk null;
5622
- const live = self.hoverTreeFor(leave_window, leave_label_storage[0..leave_label_len]) orelse break :blk null;
5623
- break :blk live.msgFor(id, .hover_leave);
5624
- } orelse {
6300
+ const live = self.hoverTreeFor(leave_window, leave_label_storage[0..leave_label_len]);
6301
+ const resolution = hover_policy.decide(self.options.surface_scope_policy, .{ .stage = .leave, .facts = @as(u8, if (slot == hover_msg_slot_refused) 1 else 0) | @as(u8, if (captured != null) 2 else 0) |
6302
+ @as(u8, if (self.hoverTreeCurrentFor(leave_window, leave_label_storage[0..leave_label_len])) 4 else 0) | @as(u8, if (live != null) 8 else 0) });
6303
+ if (resolution == 0) continue;
6304
+ const msg = (if (resolution == 1) captured else if (resolution == 2) live.?.msgFor(id, .hover_leave) else null) orelse {
5625
6305
  self.releaseHoverSlot(slot);
5626
6306
  continue;
5627
6307
  };
@@ -5634,69 +6314,47 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5634
6314
  self.releaseHoverSlot(slot);
5635
6315
  }
5636
6316
  for (standing_chain[0..standing_len], 0..) |id, position| {
5637
- if (!destination_ready) break;
5638
- if (!entering_at[position]) continue;
5639
- if (!self.hoverTreeCurrentFor(standing_window, standing_label)) {
5640
- // An earlier edge's failed rebuild left this tree
5641
- // stale mid-batch: the same deferral as above — drop
5642
- // the unentered tail from the mirror and retry after
5643
- // a rebuild lands.
6317
+ const live = self.hoverTreeFor(standing_window, standing_label);
6318
+ const admission = hover_policy.decide(self.options.surface_scope_policy, .{ .stage = .enter, .facts = @as(u8, if (destination_ready) 1 else 0) | @as(u8, if (entering_at[position]) 2 else 0) |
6319
+ @as(u8, if (self.hoverTreeCurrentFor(standing_window, standing_label)) 4 else 0) | @as(u8, if (live != null) 8 else 0) });
6320
+ if (admission == 0) break;
6321
+ if (admission == 1) continue;
6322
+ if (admission == 2) {
5644
6323
  self.unwindHoverEnters(&entering_at, position);
5645
6324
  break;
5646
6325
  }
5647
- // Resolve from the LIVE tree per edge: an earlier edge
5648
- // in this batch may have rebuilt the view (payload
5649
- // bytes are only promised for their own dispatch), and
5650
- // its update may even have unmounted this element — a
5651
- // vanished handler then dispatches no enter and owes no
5652
- // leave. The paired leave is captured BEFORE the enter
5653
- // dispatches, from the same tree that resolved it, so
5654
- // an enter whose own handler unmounts the element still
5655
- // has its leave to deliver.
5656
- const live = self.hoverTreeFor(standing_window, standing_label) orelse {
5657
- // A failed rebuild cleared the tree mid-batch: drop
5658
- // the not-yet-entered ids from the mirror so the
5659
- // next drain retries them once the tree returns (the
5660
- // entering-with-no-tree deferral above then holds
5661
- // the line instead of consuming enters as silence).
5662
- self.unwindHoverEnters(&entering_at, position);
5663
- break;
5664
- };
5665
- const enter_msg = live.msgFor(id, .hover_enter);
5666
- if (live.msgFor(id, .hover_leave)) |leave_msg| {
6326
+ // Resolve each edge from the current tree; own its paired leave before dispatch.
6327
+ const enter_msg = live.?.msgFor(id, .hover_enter);
6328
+ if (live.?.msgFor(id, .hover_leave)) |leave_msg| {
5667
6329
  const slot = self.claimHoverSlot() orelse {
5668
6330
  // Pool pressure degrades like allocation
5669
6331
  // pressure: defer this id and the entering tail
5670
6332
  // to the next drain.
5671
- self.unwindHoverEnters(&entering_at, position);
5672
- if (first_error == null) first_error = error.OutOfMemory;
6333
+ if (self.hoverCaptureDecision(1, 0, self.hover_msg_slots[position]) == 1) {
6334
+ self.unwindHoverEnters(&entering_at, position);
6335
+ if (first_error == null) first_error = error.OutOfMemory;
6336
+ }
5673
6337
  break;
5674
6338
  };
5675
- self.captureHoverLeave(slot, leave_msg) catch |err| switch (err) {
5676
- error.OutOfMemory => {
5677
- // Transient: an enter whose paired leave
5678
- // cannot be owned must not dispatch — defer
5679
- // this id and the rest of the entering tail
5680
- // to the next drain instead of breaking the
5681
- // pairing guarantee.
5682
- self.releaseHoverSlot(slot);
6339
+ self.captureHoverLeave(slot, leave_msg) catch |err| {
6340
+ self.releaseHoverSlot(slot);
6341
+ const action = self.hoverCaptureDecision(1, if (err == error.OutOfMemory) 0 else 1, self.hover_msg_slots[position]);
6342
+ if (action == 1) {
5683
6343
  self.unwindHoverEnters(&entering_at, position);
5684
6344
  if (first_error == null) first_error = error.OutOfMemory;
5685
6345
  break;
5686
- },
5687
- error.HoverCapturePayloadUnsupported => {
5688
- // Permanent: no copy can own this payload
5689
- // (a single-item pointer), so the PAIR is
5690
- // disabled — the enter is refused too,
5691
- // once, loudly, and the entry settles as
5692
- // refused instead of retrying every drain.
5693
- self.releaseHoverSlot(slot);
6346
+ }
6347
+ if (action == 2) {
5694
6348
  self.releaseHoverSlot(self.hover_msg_slots[position]);
5695
6349
  self.hover_msg_slots[position] = hover_msg_slot_refused;
5696
6350
  ui_app_log.warn("on_hover_leave payload cannot be owned (a single-item pointer): the hover pair is disabled for this element - bind a slice or scalar payload instead", .{});
5697
- continue;
5698
- },
6351
+ }
6352
+ continue;
5699
6353
  };
6354
+ if (self.hoverCaptureDecision(1, 2, self.hover_msg_slots[position]) != 4) {
6355
+ self.releaseHoverSlot(slot);
6356
+ continue;
6357
+ }
5700
6358
  // A mid-batch rebuild's capture refresh can have
5701
6359
  // filled this position's slot already (an earlier
5702
6360
  // edge's dispatch rebuilt): release it before the
@@ -5724,20 +6382,17 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5724
6382
  /// sees them as entering again and retries. Their positions hold
5725
6383
  /// no capture slots yet, so nothing needs releasing.
5726
6384
  fn unwindHoverEnters(self: *Self, entering_at: *const [canvas.max_widget_depth]bool, from: usize) void {
5727
- var kept: usize = 0;
6385
+ const compaction = hover_policy.unwind(self.options.surface_scope_policy, entering_at[0..self.hover_msg_chain_len], from);
6386
+ // Release discarded claims before compacting the native id/slot storage.
6387
+ var kept_position: usize = 0;
5728
6388
  for (0..self.hover_msg_chain_len) |position| {
5729
- if (position >= from and entering_at[position]) {
5730
- // A mid-batch capture refresh can have filled this
5731
- // never-entered position's slot: release it so an
5732
- // unwound enter never leaks its claim.
5733
- self.releaseHoverSlot(self.hover_msg_slots[position]);
5734
- continue;
5735
- }
6389
+ if (kept_position < compaction.len and compaction.kept[kept_position] == position) kept_position += 1 else self.releaseHoverSlot(self.hover_msg_slots[position]);
6390
+ }
6391
+ for (compaction.kept[0..compaction.len], 0..) |position, kept| {
5736
6392
  self.hover_msg_chain[kept] = self.hover_msg_chain[position];
5737
6393
  self.hover_msg_slots[kept] = self.hover_msg_slots[position];
5738
- kept += 1;
5739
6394
  }
5740
- self.hover_msg_chain_len = kept;
6395
+ self.hover_msg_chain_len = compaction.len;
5741
6396
  }
5742
6397
 
5743
6398
  /// Re-render the house video chrome from the moved channel
@@ -5782,10 +6437,44 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5782
6437
  try self.rebuildVideoChrome(runtime);
5783
6438
  }
5784
6439
 
6440
+ fn pressHoldPlan(self: *const Self, operation: u8, has_hold: bool, tree_available: bool) u8 {
6441
+ const armed = self.hold_armed_id != 0;
6442
+ if (self.options.press_hold_policy) |policy| {
6443
+ const facts = @as(u8, @intFromBool(armed)) |
6444
+ (@as(u8, @intFromBool(self.hold_fired)) << 1) |
6445
+ (@as(u8, @intFromBool(has_hold)) << 2) |
6446
+ (@as(u8, @intFromBool(tree_available)) << 3);
6447
+ const request = [_]u8{ 19, operation, facts };
6448
+ var result: [1]u8 = undefined;
6449
+ const allowed: u8 = switch (operation) {
6450
+ 0 => 7,
6451
+ 1 => 11,
6452
+ 2 => 16,
6453
+ 3 => 3,
6454
+ else => unreachable,
6455
+ };
6456
+ if (policy(&request, &result) != result.len or result[0] & ~allowed != 0 or
6457
+ (result[0] & 4 != 0 and !has_hold) or
6458
+ (result[0] & 16 != 0 and (!armed or self.hold_fired or !tree_available)))
6459
+ @panic("invalid compiled press hold result");
6460
+ return result[0];
6461
+ }
6462
+ if (operation == 2) return if (armed and !self.hold_fired and tree_available) 16 else 0;
6463
+ const reset: u8 = 2 | @as(u8, @intFromBool(armed and !self.hold_fired));
6464
+ return reset | (if (operation == 0 and has_hold) @as(u8, 4) else 0) |
6465
+ (if (operation == 1 and self.hold_fired) @as(u8, 8) else 0);
6466
+ }
6467
+
6468
+ fn applyHoldReset(self: *Self, runtime: *Runtime, plan: u8) void {
6469
+ if (plan & 1 != 0) runtime.cancelTimer(press_hold_timer_id) catch {};
6470
+ if (plan & 2 != 0) {
6471
+ self.hold_armed_id = 0;
6472
+ self.hold_fired = false;
6473
+ }
6474
+ }
6475
+
5785
6476
  fn disarmHold(self: *Self, runtime: *Runtime) void {
5786
- if (self.hold_armed_id != 0 and !self.hold_fired) runtime.cancelTimer(press_hold_timer_id) catch {};
5787
- self.hold_armed_id = 0;
5788
- self.hold_fired = false;
6477
+ self.applyHoldReset(runtime, self.pressHoldPlan(3, false, false));
5789
6478
  }
5790
6479
 
5791
6480
  /// The hold timer fired while the press is still down: dispatch
@@ -5794,11 +6483,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5794
6483
  /// that this gesture consumed its press.
5795
6484
  fn firePressHold(self: *Self, runtime: *Runtime) anyerror!void {
5796
6485
  const armed_id = self.hold_armed_id;
5797
- if (armed_id == 0 or self.hold_fired) return;
5798
6486
  const hold_label = self.hold_view_label_storage[0..self.hold_view_label_len];
5799
- const tree = self.treeForViewLabel(hold_label) orelse return;
6487
+ const tree = if (armed_id != 0 and !self.hold_fired) self.treeForViewLabel(hold_label) else null;
6488
+ if (self.pressHoldPlan(2, false, tree != null) & 16 == 0) return;
5800
6489
  self.hold_fired = true;
5801
- if (tree.msgForHold(armed_id)) |msg| {
6490
+ if (tree.?.msgForHold(armed_id)) |msg| {
5802
6491
  try self.dispatch(runtime, self.hold_window_id, msg);
5803
6492
  }
5804
6493
  }
@@ -5815,14 +6504,12 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5815
6504
  // on_dismiss (its open state lives here, not in the model):
5816
6505
  // close the state and rebuild, agreeing with the engine's
5817
6506
  // optimistic hide.
5818
- if (self.context_menu_fallback_target != 0) {
5819
- if (tree.context_menu_fallback) |fallback| {
5820
- if (fallback.surface_id == dismiss_event.id) {
5821
- self.clearContextMenuFallback();
5822
- try self.rebuildAllViews(runtime);
5823
- return;
5824
- }
5825
- }
6507
+ const fallback = tree.context_menu_fallback;
6508
+ const matches = if (fallback) |value| value.surface_id == dismiss_event.id else false;
6509
+ if (self.componentDecision(.fallback_dismiss, self.context_menu_fallback_target != 0, fallback != null, matches) != 0) {
6510
+ self.clearContextMenuFallback();
6511
+ try self.rebuildAllViews(runtime);
6512
+ return;
5826
6513
  }
5827
6514
  if (tree.msgForDismiss(dismiss_event.id)) |msg| {
5828
6515
  try self.dispatch(runtime, dismiss_event.window_id, msg);
@@ -6124,19 +6811,12 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6124
6811
  /// point, and view dimensions so it can preview a semantic insertion
6125
6812
  /// during motion, commit it on release, or restore it on cancel.
6126
6813
  fn handleWidgetDrag(self: *Self, runtime: *Runtime, drag_event: core.CanvasWidgetDragEvent) anyerror!void {
6127
- // The runtime promotes a source only after this slop, so terminal
6128
- // phases are always real drags and must dispatch even when the
6129
- // pointer returned near its origin before release. Change events
6130
- // below slop remain on the low-level channel to own text motion,
6131
- // but declarative apps do not hear them.
6132
- if (drag_event.drag.phase == .change and
6133
- !canvas_widget_events.canvasWidgetDragCrossedSlop(drag_event.drag.delta)) return;
6134
- const source = drag_event.source orelse return;
6135
- // Once drag wins the pointer gesture it also owns its delayed
6136
- // interpretation. An element may declare both on-hold and on-drag;
6137
- // leaving the down-armed timer live would dispatch the hold Msg in
6138
- // the middle of a stationary drag and then dispatch drag end too.
6139
- if (drag_event.drag.phase == .change) self.disarmHold(runtime);
6814
+ const policy = self.options.surface_scope_policy;
6815
+ const phase = drag_policy.dragPhase(drag_event.drag.phase);
6816
+ const admission = drag_policy.decide(policy, .{ .stage = .delivery, .phase = phase, .facts = @intFromBool(drag_event.source != null), .delta = drag_event.drag.delta });
6817
+ if (admission == 0) return;
6818
+ const source = drag_event.source.?;
6819
+ if (admission == 1) self.disarmHold(runtime);
6140
6820
  const tree = self.treeForViewLabel(drag_event.view_label);
6141
6821
  const live_template = if (tree) |value| value.msgFor(source.id, .drag) else null;
6142
6822
  const layout: ?canvas.WidgetLayoutTree = runtime.canvasWidgetLayout(drag_event.window_id, drag_event.view_label) catch null;
@@ -6144,31 +6824,23 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6144
6824
  const root = root_value.normalized();
6145
6825
  break :blk geometry.SizeF.init(root.width, root.height);
6146
6826
  } else null else null;
6147
-
6148
- if (drag_event.drag.phase == .change) {
6149
- const template = live_template orelse return;
6150
- const view_size = live_view_size orelse return;
6151
- const msg = Ui.Tree.msgForDragTemplate(template, drag_event.drag, view_size) orelse return;
6152
- // Capture before dispatch: this very Msg may rebuild the tree
6153
- // without its source or handler.
6154
- try self.captureWidgetDragMsg(drag_event, template, view_size);
6155
- try self.dispatch(runtime, drag_event.window_id, msg);
6827
+ const captured = if (admission == 2) self.widgetDragCaptureMatches(drag_event.window_id, drag_event.view_label, source.id) else false;
6828
+ const resolve = drag_policy.decide(policy, .{ .stage = .resolve, .phase = phase, .facts = @as(u8, if (live_template != null) 1 else 0) | @as(u8, if (live_view_size != null) 2 else 0) |
6829
+ @as(u8, if (captured) 4 else 0) | @as(u8, if (self.drag_msg_template != null) 8 else 0) });
6830
+ if (resolve == 32) {
6831
+ self.clearWidgetDragMsgCapture();
6156
6832
  return;
6157
6833
  }
6158
-
6159
- const captured = self.widgetDragCaptureMatches(drag_event.window_id, drag_event.view_label, source.id);
6160
- const maybe_template: ?MsgT = live_template orelse if (captured) self.drag_msg_template else null;
6161
- const template = maybe_template orelse {
6162
- if (captured) self.clearWidgetDragMsgCapture();
6163
- return;
6164
- };
6165
- const view_size = live_view_size orelse if (captured) self.drag_msg_view_size else return;
6166
- const msg = Ui.Tree.msgForDragTemplate(template, drag_event.drag, view_size) orelse {
6167
- if (captured) self.clearWidgetDragMsgCapture();
6168
- return;
6169
- };
6170
- defer if (captured) self.clearWidgetDragMsgCapture();
6171
- try self.dispatch(runtime, drag_event.window_id, msg);
6834
+ if (resolve == 0) return;
6835
+ const template = if (resolve & 1 != 0) live_template.? else self.drag_msg_template.?;
6836
+ const view_size = if (resolve & 4 != 0) live_view_size.? else self.drag_msg_view_size;
6837
+ const msg = Ui.Tree.msgForDragTemplate(template, drag_event.drag, view_size);
6838
+ const action = drag_policy.decide(policy, .{ .stage = .message, .phase = phase, .facts = @as(u8, if (msg != null) 1 else 0) | @as(u8, if (captured) 2 else 0) });
6839
+ defer if (action & 4 != 0) self.clearWidgetDragMsgCapture();
6840
+ if (action & 1 == 0) return;
6841
+ // Copy before dispatch: the resulting Msg may remove its source.
6842
+ if (action & 2 != 0) try self.captureWidgetDragMsg(drag_event, template, view_size);
6843
+ try self.dispatch(runtime, drag_event.window_id, msg.?);
6172
6844
  }
6173
6845
 
6174
6846
  fn captureWidgetDragMsg(self: *Self, drag_event: core.CanvasWidgetDragEvent, template: MsgT, view_size: geometry.SizeF) anyerror!void {
@@ -6189,10 +6861,9 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6189
6861
  }
6190
6862
 
6191
6863
  fn widgetDragCaptureMatches(self: *const Self, window_id: platform.WindowId, view_label: []const u8, source_id: canvas.ObjectId) bool {
6192
- return self.drag_msg_template != null and
6193
- self.drag_msg_window_id == window_id and
6194
- self.drag_msg_source_id == source_id and
6195
- std.mem.eql(u8, self.drag_msg_view_label_storage[0..self.drag_msg_view_label_len], view_label);
6864
+ return drag_policy.decide(self.options.surface_scope_policy, .{ .stage = .capture_match, .facts = @as(u8, if (self.drag_msg_template != null) 1 else 0) | @as(u8, if (self.drag_msg_window_id == window_id) 2 else 0) |
6865
+ @as(u8, if (self.drag_msg_source_id == source_id) 4 else 0) |
6866
+ @as(u8, if (std.mem.eql(u8, self.drag_msg_view_label_storage[0..self.drag_msg_view_label_len], view_label)) 8 else 0) }) != 0;
6196
6867
  }
6197
6868
 
6198
6869
  fn clearWidgetDragMsgCapture(self: *Self) void {
@@ -6264,10 +6935,8 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6264
6935
  rebuilt = true;
6265
6936
  }
6266
6937
  }
6267
- if (!rebuilt and self.installed and
6268
- std.mem.eql(u8, scroll_event.view_label, self.options.canvas_label) and
6269
- self.isVirtualWindowId(scroll_event.id))
6270
- {
6938
+ const rebuild_plan = component_policy.plan(self.options.component_policy, .scroll_rebuild, rebuilt, self.installed, std.mem.eql(u8, scroll_event.view_label, self.options.canvas_label), @intFromBool(self.isVirtualWindowId(scroll_event.id)), 0);
6939
+ if (rebuild_plan[0] != 0) {
6271
6940
  try self.rebuild(runtime, scroll_event.window_id);
6272
6941
  }
6273
6942
  }
@@ -6288,20 +6957,26 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6288
6957
  // the tree first — silently arming nothing would leave the
6289
6958
  // presented menu's selection to fall through a null tree
6290
6959
  // and dispatch no message.
6291
- if (self.treeForViewLabel(shown_event.view_label) == null) try self.restoreMissingTree(runtime);
6960
+ if (self.componentDecision(.missing_tree, self.treeForViewLabel(shown_event.view_label) == null, false, false) != 0) try self.restoreMissingTree(runtime);
6292
6961
  const tree = self.treeForViewLabel(shown_event.view_label) orelse return;
6293
- const count = @min(shown_event.item_count, self.context_menu_shown_msgs.len);
6962
+ const count_plan = component_policy.plan(self.options.component_policy, .shown_count, false, false, false, shown_event.item_count, self.context_menu_shown_msgs.len);
6963
+ const count: usize = @intCast(std.mem.readInt(u64, count_plan[8..16], .little));
6294
6964
  for (0..count) |item_index| {
6295
6965
  self.context_menu_shown_msgs[item_index] = tree.msgForContextMenu(shown_event.target_id, item_index);
6296
6966
  }
6297
6967
  self.context_menu_shown_token = shown_event.token;
6298
6968
  self.context_menu_shown_count = count;
6299
- self.context_menu_pin = if (std.mem.eql(u8, shown_event.view_label, self.options.canvas_label))
6300
- .{ .window_id = null, .arena_index = self.arena_index }
6301
- else if (self.windowSlotByCanvasLabel(shown_event.view_label)) |slot|
6302
- .{ .window_id = slot.window_id, .arena_index = slot.arena_index }
6303
- else
6304
- null;
6969
+ const slot = self.windowSlotByCanvasLabel(shown_event.view_label);
6970
+ const owner = self.componentDecision(.pin_owner, std.mem.eql(u8, shown_event.view_label, self.options.canvas_label), slot != null, false);
6971
+ self.context_menu_pin = switch (owner) {
6972
+ 1 => .{ .window_id = null, .arena_index = self.arena_index },
6973
+ 2 => .{ .window_id = slot.?.window_id, .arena_index = slot.?.arena_index },
6974
+ else => null,
6975
+ };
6976
+ }
6977
+
6978
+ fn componentDecision(self: *const Self, stage: component_policy.Stage, a: bool, b: bool, c: bool) u8 {
6979
+ return component_policy.plan(self.options.component_policy, stage, a, b, c, 0, 0)[0];
6305
6980
  }
6306
6981
 
6307
6982
  /// The arena index this canvas's next rebuild must use:
@@ -6315,13 +6990,10 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6315
6990
  /// therefore bounded at two trees, however many rebuilds occur.
6316
6991
  fn contextMenuRebuildIndex(self: *const Self, window_id: ?platform.WindowId, current_index: usize) usize {
6317
6992
  const natural = current_index ^ 1;
6318
- const pin = self.context_menu_pin orelse return natural;
6319
- if (pin.arena_index != natural) return natural;
6320
- const matches = if (pin.window_id) |pin_window|
6321
- (window_id orelse return natural) == pin_window
6322
- else
6323
- window_id == null;
6324
- return if (matches) natural ^ 1 else natural;
6993
+ const pin = self.context_menu_pin;
6994
+ const matches = if (pin) |value| value.window_id == window_id else false;
6995
+ const pinned = if (pin) |value| value.arena_index == natural else false;
6996
+ return natural ^ self.componentDecision(.rebuild_arena, pin != null, pinned, matches);
6325
6997
  }
6326
6998
 
6327
6999
  /// Window teardown for the pin's owner: the slot's arenas are
@@ -6330,9 +7002,10 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6330
7002
  /// a stale pin would otherwise keep steering the reused slot's
6331
7003
  /// rebuild cadence around a generation that no longer exists.
6332
7004
  fn releaseContextMenuSnapshotForWindow(self: *Self, window_id: platform.WindowId) void {
6333
- const pin = self.context_menu_pin orelse return;
6334
- const pin_window = pin.window_id orelse return;
6335
- if (pin_window == window_id) self.releaseContextMenuSnapshot();
7005
+ const pin = self.context_menu_pin;
7006
+ const has_window = if (pin) |value| value.window_id != null else false;
7007
+ const matches = if (pin) |value| value.window_id == window_id else false;
7008
+ if (self.componentDecision(.release_window, pin != null, has_window, matches) != 0) self.releaseContextMenuSnapshot();
6336
7009
  }
6337
7010
 
6338
7011
  /// Disarm the presented-menu snapshot and release the pinned
@@ -6350,7 +7023,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6350
7023
  /// token's notice is ignored (a superseding presentation
6351
7024
  /// already replaced the snapshot and the pin).
6352
7025
  fn handleContextMenuDismissed(self: *Self, runtime: *Runtime, dismissed_event: core.CanvasWidgetContextMenuDismissedEvent) anyerror!void {
6353
- if (dismissed_event.token == 0 or dismissed_event.token != self.context_menu_shown_token) return;
7026
+ if (self.componentDecision(.dismiss_token, dismissed_event.token != 0, dismissed_event.token == self.context_menu_shown_token, false) == 0) return;
6354
7027
  self.releaseContextMenuSnapshot();
6355
7028
  try self.restoreMissingTree(runtime);
6356
7029
  }
@@ -6364,12 +7037,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6364
7037
  /// no-ops until an unrelated resize, timer, or effect happens
6365
7038
  /// to rebuild.
6366
7039
  fn restoreMissingTree(self: *Self, runtime: *Runtime) anyerror!void {
6367
- if (!self.installed) return;
6368
- var missing = self.tree == null;
7040
+ var secondary_missing = false;
6369
7041
  for (self.window_slots[0..self.window_slot_count]) |*slot| {
6370
- if (slot.installed and slot.tree == null) missing = true;
7042
+ if (slot.installed and slot.tree == null) secondary_missing = true;
6371
7043
  }
6372
- if (missing) try self.rebuildAllViews(runtime);
7044
+ if (self.componentDecision(.restore_tree, self.installed, self.tree == null, secondary_missing) != 0) try self.rebuildAllViews(runtime);
6373
7045
  }
6374
7046
 
6375
7047
  /// A native context-menu selection: resolve the selected item's
@@ -6382,32 +7054,30 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6382
7054
  // A selection on this menu closes it whatever the source: an
6383
7055
  // automation-invoked selection while the fallback surface is
6384
7056
  // open must not leave the surface mounted.
6385
- if (self.context_menu_fallback_target == menu_event.target_id) {
6386
- self.clearContextMenuFallback();
6387
- }
6388
- if (menu_event.token != 0 and menu_event.token == self.context_menu_shown_token) {
7057
+ const begin = self.componentDecision(.selection_begin, self.context_menu_fallback_target == menu_event.target_id, menu_event.token != 0, menu_event.token == self.context_menu_shown_token);
7058
+ if (begin & 1 != 0) self.clearContextMenuFallback();
7059
+ if (begin & 2 != 0) {
6389
7060
  const count = self.context_menu_shown_count;
6390
7061
  // The request is consumed on every path out of this
6391
7062
  // block — resolved, out-of-range, or a failed dispatch.
6392
7063
  defer self.releaseContextMenuSnapshot();
6393
- if (menu_event.item_index < count) {
6394
- if (self.context_menu_shown_msgs[menu_event.item_index]) |msg| {
6395
- // The Msg is stored by value and its pinned-arena
6396
- // payload slices are consumed by `update` itself;
6397
- // the rebuild that follows reads only the model.
6398
- // Release the pin BEFORE the dispatch: nothing
6399
- // resets the pinned arena until the rebuild, and
6400
- // the rebuild then routes into the partner arena
6401
- // naturally — so a Msg whose update pushes the
6402
- // model past a build budget fails the rebuild
6403
- // WITHOUT resetting the live arena underneath it.
6404
- // Input keeps working on the previous tree, and
6405
- // the app's controls can recover the model —
6406
- // production's degraded-error contract.
6407
- self.releaseContextMenuSnapshot();
6408
- try self.dispatch(runtime, menu_event.window_id, msg);
6409
- return;
6410
- }
7064
+ const msg = if (menu_event.item_index < count) self.context_menu_shown_msgs[menu_event.item_index] else null;
7065
+ if (self.componentDecision(.selection_item, menu_event.item_index < count, msg != null, false) == 1) {
7066
+ // The Msg is stored by value and its pinned-arena
7067
+ // payload slices are consumed by `update` itself;
7068
+ // the rebuild that follows reads only the model.
7069
+ // Release the pin BEFORE the dispatch: nothing
7070
+ // resets the pinned arena until the rebuild, and
7071
+ // the rebuild then routes into the partner arena
7072
+ // naturally — so a Msg whose update pushes the
7073
+ // model past a build budget fails the rebuild
7074
+ // WITHOUT resetting the live arena underneath it.
7075
+ // Input keeps working on the previous tree, and
7076
+ // the app's controls can recover the model —
7077
+ // production's degraded-error contract.
7078
+ self.releaseContextMenuSnapshot();
7079
+ try self.dispatch(runtime, menu_event.window_id, msg.?);
7080
+ return;
6411
7081
  }
6412
7082
  // Swallowed without a Msg (out of range, or an item the
6413
7083
  // presented tree never mapped): no dispatch rebuilds, so
@@ -6420,7 +7090,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6420
7090
  // failed while the model was unbuildable): the model may
6421
7091
  // have recovered since, so restore a dropped tree before
6422
7092
  // resolving rather than silently dispatching nothing.
6423
- if (self.treeForViewLabel(menu_event.view_label) == null) try self.restoreMissingTree(runtime);
7093
+ if (self.componentDecision(.missing_tree, self.treeForViewLabel(menu_event.view_label) == null, false, false) != 0) try self.restoreMissingTree(runtime);
6424
7094
  const tree = self.treeForViewLabel(menu_event.view_label) orelse return;
6425
7095
  if (tree.msgForContextMenu(menu_event.target_id, menu_event.item_index)) |msg| {
6426
7096
  try self.dispatch(runtime, menu_event.window_id, msg);
@@ -6450,9 +7120,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6450
7120
  /// being rebuilt, or 0 when the open fallback (if any) belongs to
6451
7121
  /// a different view.
6452
7122
  fn contextMenuFallbackTargetForLabel(self: *const Self, view_label: []const u8) canvas.ObjectId {
6453
- if (self.context_menu_fallback_target == 0) return 0;
6454
- if (!std.mem.eql(u8, view_label, self.contextMenuFallbackLabel())) return 0;
6455
- return self.context_menu_fallback_target;
7123
+ return if (self.componentDecision(.fallback_label, self.context_menu_fallback_target != 0, std.mem.eql(u8, view_label, self.contextMenuFallbackLabel()), false) != 0) self.context_menu_fallback_target else 0;
6456
7124
  }
6457
7125
 
6458
7126
  fn clearContextMenuFallback(self: *Self) void {
@@ -6464,7 +7132,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6464
7132
  /// menu's open state lives here, not in the model, so opening and
6465
7133
  /// closing it re-derives the views directly.
6466
7134
  fn rebuildAllViews(self: *Self, runtime: *Runtime) anyerror!void {
6467
- if (!self.installed) return;
7135
+ if (self.componentDecision(.rebuild_views, self.installed, false, false) == 0) return;
6468
7136
  try self.rebuild(runtime, self.canvas_window_id);
6469
7137
  try self.rebuildWindowSlots(runtime);
6470
7138
  }
@@ -6475,12 +7143,13 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6475
7143
  /// a native selection resolves. Returns true when the id was a
6476
7144
  /// fallback item (consumed either way).
6477
7145
  fn dispatchContextMenuFallbackItem(self: *Self, runtime: *Runtime, tree: *const Ui.Tree, window_id: platform.WindowId, id: canvas.ObjectId) anyerror!bool {
6478
- if (self.context_menu_fallback_target == 0) return false;
6479
- const fallback = tree.context_menu_fallback orelse return false;
6480
- const item_index = fallback.itemIndex(id) orelse return false;
7146
+ const fallback = tree.context_menu_fallback;
7147
+ const item_index = if (fallback) |value| value.itemIndex(id) else null;
7148
+ if (self.componentDecision(.fallback_item, self.context_menu_fallback_target != 0, fallback != null, item_index != null) == 0) return false;
6481
7149
  self.clearContextMenuFallback();
6482
- if (tree.msgForContextMenu(fallback.target_id, item_index)) |msg| {
6483
- try self.dispatch(runtime, window_id, msg);
7150
+ const msg = tree.msgForContextMenu(fallback.?.target_id, item_index.?);
7151
+ if (self.componentDecision(.fallback_dispatch, msg != null, false, false) == 1) {
7152
+ try self.dispatch(runtime, window_id, msg.?);
6484
7153
  } else {
6485
7154
  try self.rebuildAllViews(runtime);
6486
7155
  }
@@ -6535,6 +7204,11 @@ fn effectsShowWindowByLabel(context: *anyopaque, window_label: []const u8) bool
6535
7204
  return true;
6536
7205
  }
6537
7206
 
7207
+ fn effectsReplayShowWindowByLabel(context: *anyopaque, window_label: []const u8) void {
7208
+ const runtime: *Runtime = @ptrCast(@alignCast(context));
7209
+ runtime.restoreWindowShow(window_label);
7210
+ }
7211
+
6538
7212
  fn effectsSetDockPresence(context: *anyopaque, visible: bool) bool {
6539
7213
  const runtime: *Runtime = @ptrCast(@alignCast(context));
6540
7214
  runtime.options.platform.services.setDockPresence(visible) catch return false;
@@ -6562,6 +7236,16 @@ fn effectsFormatLocalTime(context: *anyopaque, timestamp_ms: i64, style: platfor
6562
7236
  return runtime.formatLocalTime(timestamp_ms, style, buffer);
6563
7237
  }
6564
7238
 
7239
+ fn effectsSendKeyChord(context: *anyopaque, chord: platform.KeyChord) anyerror!void {
7240
+ const runtime: *Runtime = @ptrCast(@alignCast(context));
7241
+ return runtime.sendKeyChord(chord);
7242
+ }
7243
+
7244
+ fn effectsKeyboardInputAccess(context: *anyopaque, prompt: bool) anyerror!platform.KeyboardInputAccess {
7245
+ const runtime: *Runtime = @ptrCast(@alignCast(context));
7246
+ return runtime.keyboardInputAccess(prompt);
7247
+ }
7248
+
6565
7249
  /// The build storage pinned under a presented native context menu:
6566
7250
  /// which canvas's arena pair and which generation (index) of that pair
6567
7251
  /// built the presented tree. The canvas is named by STABLE window
@@ -6578,3 +7262,50 @@ const ContextMenuPin = struct {
6578
7262
  window_id: ?platform.WindowId,
6579
7263
  arena_index: usize,
6580
7264
  };
7265
+
7266
+ fn effectsRestoreWindowResult(context: *anyopaque, label: []const u8, closed: bool) void {
7267
+ const runtime: *Runtime = @ptrCast(@alignCast(context));
7268
+ runtime.restoreWindowCapabilityResult(label, closed);
7269
+ }
7270
+
7271
+ fn effectsExecuteCapability(context: *anyopaque, name: []const u8, payload: []const u8, output: []u8) anyerror![]const u8 {
7272
+ const runtime: *Runtime = @ptrCast(@alignCast(context));
7273
+ const desktop_files = @import("desktop_files.zig");
7274
+ var reader = try desktop_files.request(payload);
7275
+ if (std.mem.eql(u8, name, "native-sdk.window.focusResult") or std.mem.eql(u8, name, "native-sdk.window.closeResult")) {
7276
+ const label = try reader.field();
7277
+ try reader.finish();
7278
+ if (label.len == 0 or label.len > 255 or std.mem.indexOfScalar(u8, label, 0) != null) return error.InvalidRequest;
7279
+ const window_id = effectsWindowIdByLabel(runtime, label) orelse
7280
+ return output[0..try desktop_files.replyHeaderFor(output, payload, "WindowNotFound")];
7281
+ if (std.mem.eql(u8, name, "native-sdk.window.focusResult")) {
7282
+ runtime.focusWindow(window_id) catch |err| return output[0..try desktop_files.replyHeaderFor(output, payload, @errorName(err))];
7283
+ } else {
7284
+ runtime.closeWindow(window_id) catch |err| return output[0..try desktop_files.replyHeaderFor(output, payload, @errorName(err))];
7285
+ }
7286
+ return output[0..try desktop_files.replyHeaderFor(output, payload, "")];
7287
+ }
7288
+ if (std.mem.eql(u8, name, "native-sdk.dialog.openDirectory")) {
7289
+ if (!authorization.hasPermission(runtime.authorization_policy, runtime.options.security.permissions, security.permission_dialog)) return error.PermissionDenied;
7290
+ const title = try reader.field();
7291
+ const path = try reader.field();
7292
+ try reader.finish();
7293
+ if (title.len > 255 or path.len > desktop_files.max_path_bytes or std.mem.indexOfScalar(u8, path, 0) != null) return error.InvalidRequest;
7294
+ var storage: [platform.max_dialog_paths_bytes]u8 = undefined;
7295
+ const result = runtime.showOpenDialog(.{ .title = title, .default_path = path, .allow_directories = true, .allow_multiple = false }, &storage) catch |err| {
7296
+ return output[0..try desktop_files.replyHeaderFor(output, payload, @errorName(err))];
7297
+ };
7298
+ const selected = if (result.count == 0) "" else result.paths;
7299
+ const header = try desktop_files.replyHeaderFor(output, payload, "");
7300
+ if (selected.len > 65535 or output.len - header < 2 or selected.len > output.len - header - 2) return error.OverBound;
7301
+ std.mem.writeInt(u16, output[header..][0..2], @intCast(selected.len), .little);
7302
+ @memcpy(output[header + 2 ..][0..selected.len], selected);
7303
+ return output[0 .. header + 2 + selected.len];
7304
+ }
7305
+ if (!authorization.hasPermission(runtime.authorization_policy, runtime.options.security.permissions, security.permission_filesystem)) return error.PermissionDenied;
7306
+ if (comptime builtin.os.tag == .macos or builtin.os.tag == .linux or builtin.os.tag == .windows) {
7307
+ var threaded = std.Io.Threaded.init(runtime.owned_allocator, .{});
7308
+ defer threaded.deinit();
7309
+ return desktop_files.execute(threaded.io(), name, payload, output);
7310
+ } else return error.Unsupported;
7311
+ }