@native-sdk/cli 0.0.0 → 0.4.0

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 (367) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +50 -1
  3. package/app.zon +30 -0
  4. package/bin/native.js +156 -0
  5. package/build/app.zig +716 -0
  6. package/build.zig +2593 -0
  7. package/build.zig.zon +24 -0
  8. package/native-sdk.d.ts +615 -0
  9. package/package.json +44 -8
  10. package/skill-data/automation/SKILL.md +248 -0
  11. package/skill-data/core/SKILL.md +249 -0
  12. package/skill-data/core/references/app-model-runtime.md +141 -0
  13. package/skill-data/core/references/bridge-security-native-capabilities.md +230 -0
  14. package/skill-data/core/references/frontend-assets.md +124 -0
  15. package/skill-data/core/references/project-anatomy.md +108 -0
  16. package/skill-data/core/references/web-engines-packaging-debugging.md +199 -0
  17. package/skill-data/native-ui/SKILL.md +1080 -0
  18. package/skills/native-sdk/SKILL.md +33 -0
  19. package/src/app_runner/root.zig +740 -0
  20. package/src/assets/root.zig +20 -0
  21. package/src/automation/protocol.zig +285 -0
  22. package/src/automation/root.zig +13 -0
  23. package/src/automation/server.zig +506 -0
  24. package/src/automation/snapshot.zig +1202 -0
  25. package/src/automation/watcher.zig +165 -0
  26. package/src/bridge/root.zig +507 -0
  27. package/src/debug/root.zig +246 -0
  28. package/src/embed/app_exports.zig +11 -0
  29. package/src/embed/c_api.zig +793 -0
  30. package/src/embed/c_exports.zig +10 -0
  31. package/src/embed/chrome.zig +168 -0
  32. package/src/embed/conversions.zig +359 -0
  33. package/src/embed/host.zig +960 -0
  34. package/src/embed/root.zig +81 -0
  35. package/src/embed/tests.zig +2552 -0
  36. package/src/embed/types.zig +382 -0
  37. package/src/embed/ui_host.zig +289 -0
  38. package/src/extensions/root.zig +197 -0
  39. package/src/frontend/root.zig +48 -0
  40. package/src/js/root.zig +65 -0
  41. package/src/platform/android/NativeSdkActivity.java +1370 -0
  42. package/src/platform/android/android_host.c +696 -0
  43. package/src/platform/android/files.zig +9 -0
  44. package/src/platform/android/native_sdk_app.h +237 -0
  45. package/src/platform/ios/files.zig +8 -0
  46. package/src/platform/ios/native_sdk_app.h +289 -0
  47. package/src/platform/ios/uikit_host.m +2739 -0
  48. package/src/platform/linux/cef_host.cpp +599 -0
  49. package/src/platform/linux/gtk_host.c +5362 -0
  50. package/src/platform/linux/gtk_host.h +265 -0
  51. package/src/platform/linux/root.zig +1519 -0
  52. package/src/platform/macos/appkit_host.h +604 -0
  53. package/src/platform/macos/appkit_host.m +10392 -0
  54. package/src/platform/macos/automation_host.h +14 -0
  55. package/src/platform/macos/automation_host.m +12 -0
  56. package/src/platform/macos/cef_host.mm +3028 -0
  57. package/src/platform/macos/root.zig +2260 -0
  58. package/src/platform/null_platform.zig +2232 -0
  59. package/src/platform/null_platform_tests.zig +670 -0
  60. package/src/platform/policy_values.zig +14 -0
  61. package/src/platform/root.zig +181 -0
  62. package/src/platform/types.zig +2681 -0
  63. package/src/platform/windows/cef_host.cpp +3 -0
  64. package/src/platform/windows/root.zig +1521 -0
  65. package/src/platform/windows/webview2_host.cpp +6230 -0
  66. package/src/primitives/app_dirs/root.zig +440 -0
  67. package/src/primitives/app_manifest/root.zig +109 -0
  68. package/src/primitives/app_manifest/tests.zig +758 -0
  69. package/src/primitives/app_manifest/types.zig +587 -0
  70. package/src/primitives/app_manifest/validation.zig +828 -0
  71. package/src/primitives/assets/root.zig +520 -0
  72. package/src/primitives/canvas/a11y_audit.zig +390 -0
  73. package/src/primitives/canvas/a11y_audit_tests.zig +225 -0
  74. package/src/primitives/canvas/app_icon.zig +1590 -0
  75. package/src/primitives/canvas/chart.zig +392 -0
  76. package/src/primitives/canvas/chart_tests.zig +751 -0
  77. package/src/primitives/canvas/commands.zig +446 -0
  78. package/src/primitives/canvas/drawing.zig +309 -0
  79. package/src/primitives/canvas/equality.zig +316 -0
  80. package/src/primitives/canvas/events.zig +696 -0
  81. package/src/primitives/canvas/font_coverage.zig +118 -0
  82. package/src/primitives/canvas/font_ttf.zig +510 -0
  83. package/src/primitives/canvas/font_ttf_tests.zig +280 -0
  84. package/src/primitives/canvas/fonts/Geist-Regular.ttf +0 -0
  85. package/src/primitives/canvas/fonts/GeistMono-Regular.ttf +0 -0
  86. package/src/primitives/canvas/frame.zig +679 -0
  87. package/src/primitives/canvas/frame_metrics.zig +462 -0
  88. package/src/primitives/canvas/gpu.zig +639 -0
  89. package/src/primitives/canvas/hash.zig +112 -0
  90. package/src/primitives/canvas/icons/alert.svg +1 -0
  91. package/src/primitives/canvas/icons/archive.svg +1 -0
  92. package/src/primitives/canvas/icons/arrow-down.svg +1 -0
  93. package/src/primitives/canvas/icons/arrow-right.svg +1 -0
  94. package/src/primitives/canvas/icons/arrow-up.svg +1 -0
  95. package/src/primitives/canvas/icons/check-circle.svg +1 -0
  96. package/src/primitives/canvas/icons/check.svg +1 -0
  97. package/src/primitives/canvas/icons/chevron-down.svg +1 -0
  98. package/src/primitives/canvas/icons/chevron-left.svg +1 -0
  99. package/src/primitives/canvas/icons/chevron-right.svg +1 -0
  100. package/src/primitives/canvas/icons/chevron-up.svg +1 -0
  101. package/src/primitives/canvas/icons/circle-dot.svg +1 -0
  102. package/src/primitives/canvas/icons/clock.svg +1 -0
  103. package/src/primitives/canvas/icons/copy.svg +1 -0
  104. package/src/primitives/canvas/icons/download.svg +1 -0
  105. package/src/primitives/canvas/icons/edit.svg +1 -0
  106. package/src/primitives/canvas/icons/ellipsis.svg +1 -0
  107. package/src/primitives/canvas/icons/external-link.svg +1 -0
  108. package/src/primitives/canvas/icons/eye.svg +1 -0
  109. package/src/primitives/canvas/icons/file-text.svg +1 -0
  110. package/src/primitives/canvas/icons/folder-open.svg +1 -0
  111. package/src/primitives/canvas/icons/folder.svg +1 -0
  112. package/src/primitives/canvas/icons/git-branch.svg +1 -0
  113. package/src/primitives/canvas/icons/git-merge.svg +1 -0
  114. package/src/primitives/canvas/icons/git-pull-request.svg +1 -0
  115. package/src/primitives/canvas/icons/info.svg +1 -0
  116. package/src/primitives/canvas/icons/menu.svg +1 -0
  117. package/src/primitives/canvas/icons/missing.svg +1 -0
  118. package/src/primitives/canvas/icons/moon.svg +1 -0
  119. package/src/primitives/canvas/icons/music.svg +1 -0
  120. package/src/primitives/canvas/icons/panel-left.svg +1 -0
  121. package/src/primitives/canvas/icons/panel-right.svg +1 -0
  122. package/src/primitives/canvas/icons/pause.svg +1 -0
  123. package/src/primitives/canvas/icons/play.svg +1 -0
  124. package/src/primitives/canvas/icons/plus.svg +1 -0
  125. package/src/primitives/canvas/icons/refresh-cw.svg +1 -0
  126. package/src/primitives/canvas/icons/repeat.svg +1 -0
  127. package/src/primitives/canvas/icons/save.svg +1 -0
  128. package/src/primitives/canvas/icons/search.svg +1 -0
  129. package/src/primitives/canvas/icons/send.svg +1 -0
  130. package/src/primitives/canvas/icons/settings.svg +1 -0
  131. package/src/primitives/canvas/icons/shuffle.svg +1 -0
  132. package/src/primitives/canvas/icons/skip-back.svg +1 -0
  133. package/src/primitives/canvas/icons/skip-forward.svg +1 -0
  134. package/src/primitives/canvas/icons/sun.svg +1 -0
  135. package/src/primitives/canvas/icons/terminal.svg +1 -0
  136. package/src/primitives/canvas/icons/trash.svg +1 -0
  137. package/src/primitives/canvas/icons/volume.svg +1 -0
  138. package/src/primitives/canvas/icons/wrench.svg +1 -0
  139. package/src/primitives/canvas/icons/x-circle.svg +1 -0
  140. package/src/primitives/canvas/icons/x.svg +1 -0
  141. package/src/primitives/canvas/icons.zig +249 -0
  142. package/src/primitives/canvas/layout_audit.zig +744 -0
  143. package/src/primitives/canvas/layout_audit_tests.zig +426 -0
  144. package/src/primitives/canvas/markdown.zig +1031 -0
  145. package/src/primitives/canvas/markdown_hostile_tests.zig +471 -0
  146. package/src/primitives/canvas/markdown_tests.zig +538 -0
  147. package/src/primitives/canvas/plan_key_index.zig +120 -0
  148. package/src/primitives/canvas/png.zig +355 -0
  149. package/src/primitives/canvas/reference.zig +1457 -0
  150. package/src/primitives/canvas/reference_blur.zig +104 -0
  151. package/src/primitives/canvas/reference_memo.zig +322 -0
  152. package/src/primitives/canvas/reference_paths.zig +184 -0
  153. package/src/primitives/canvas/reference_tests.zig +1650 -0
  154. package/src/primitives/canvas/render.zig +747 -0
  155. package/src/primitives/canvas/render_effects.zig +255 -0
  156. package/src/primitives/canvas/render_fingerprints.zig +256 -0
  157. package/src/primitives/canvas/render_generic_resources.zig +376 -0
  158. package/src/primitives/canvas/render_images.zig +247 -0
  159. package/src/primitives/canvas/render_layers.zig +260 -0
  160. package/src/primitives/canvas/render_paths.zig +347 -0
  161. package/src/primitives/canvas/render_resources.zig +51 -0
  162. package/src/primitives/canvas/render_tests.zig +3186 -0
  163. package/src/primitives/canvas/root.zig +744 -0
  164. package/src/primitives/canvas/serialization.zig +1528 -0
  165. package/src/primitives/canvas/svg_icon.zig +636 -0
  166. package/src/primitives/canvas/svg_icon_tests.zig +312 -0
  167. package/src/primitives/canvas/test_support.zig +422 -0
  168. package/src/primitives/canvas/testdata/markdown_document.md +83 -0
  169. package/src/primitives/canvas/tests.zig +30 -0
  170. package/src/primitives/canvas/text.zig +82 -0
  171. package/src/primitives/canvas/text_atlas.zig +408 -0
  172. package/src/primitives/canvas/text_batch_tests.zig +431 -0
  173. package/src/primitives/canvas/text_interaction.zig +615 -0
  174. package/src/primitives/canvas/text_layout.zig +1069 -0
  175. package/src/primitives/canvas/text_layout_cache.zig +281 -0
  176. package/src/primitives/canvas/text_layout_hash.zig +113 -0
  177. package/src/primitives/canvas/text_layout_types.zig +128 -0
  178. package/src/primitives/canvas/text_measure_cache.zig +279 -0
  179. package/src/primitives/canvas/text_metrics.zig +309 -0
  180. package/src/primitives/canvas/text_metrics_tests.zig +262 -0
  181. package/src/primitives/canvas/text_span_tests.zig +608 -0
  182. package/src/primitives/canvas/text_spans.zig +1010 -0
  183. package/src/primitives/canvas/text_tests.zig +1949 -0
  184. package/src/primitives/canvas/themes/geist.zig +470 -0
  185. package/src/primitives/canvas/tokens.zig +1522 -0
  186. package/src/primitives/canvas/ui.zig +2686 -0
  187. package/src/primitives/canvas/ui_markup.zig +3791 -0
  188. package/src/primitives/canvas/ui_markup_binary.zig +522 -0
  189. package/src/primitives/canvas/ui_markup_binary_tests.zig +591 -0
  190. package/src/primitives/canvas/ui_markup_compiled.zig +2565 -0
  191. package/src/primitives/canvas/ui_markup_compiled_tests.zig +1669 -0
  192. package/src/primitives/canvas/ui_markup_contract.zig +1620 -0
  193. package/src/primitives/canvas/ui_markup_contract_tests.zig +953 -0
  194. package/src/primitives/canvas/ui_markup_edit.zig +416 -0
  195. package/src/primitives/canvas/ui_markup_edit_tests.zig +341 -0
  196. package/src/primitives/canvas/ui_markup_expr.zig +1152 -0
  197. package/src/primitives/canvas/ui_markup_expr_tests.zig +779 -0
  198. package/src/primitives/canvas/ui_markup_huge_model_tests.zig +505 -0
  199. package/src/primitives/canvas/ui_markup_reflect.zig +127 -0
  200. package/src/primitives/canvas/ui_markup_tests.zig +1545 -0
  201. package/src/primitives/canvas/ui_markup_view.zig +2352 -0
  202. package/src/primitives/canvas/ui_markup_view_tests.zig +3709 -0
  203. package/src/primitives/canvas/ui_provenance.zig +96 -0
  204. package/src/primitives/canvas/ui_provenance_tests.zig +186 -0
  205. package/src/primitives/canvas/ui_schema.zig +825 -0
  206. package/src/primitives/canvas/ui_schema_tests.zig +128 -0
  207. package/src/primitives/canvas/ui_tests.zig +1432 -0
  208. package/src/primitives/canvas/vector.zig +919 -0
  209. package/src/primitives/canvas/vector_tests.zig +547 -0
  210. package/src/primitives/canvas/virtual_extent_tests.zig +317 -0
  211. package/src/primitives/canvas/virtual_extents.zig +540 -0
  212. package/src/primitives/canvas/widget_access.zig +208 -0
  213. package/src/primitives/canvas/widget_anchored_tests.zig +264 -0
  214. package/src/primitives/canvas/widget_builtin_tests.zig +3160 -0
  215. package/src/primitives/canvas/widget_invalidation.zig +748 -0
  216. package/src/primitives/canvas/widget_layout.zig +2055 -0
  217. package/src/primitives/canvas/widget_layout_tests.zig +2691 -0
  218. package/src/primitives/canvas/widget_metrics.zig +228 -0
  219. package/src/primitives/canvas/widget_render.zig +2534 -0
  220. package/src/primitives/canvas/widget_render_controls.zig +1563 -0
  221. package/src/primitives/canvas/widget_render_scroll.zig +136 -0
  222. package/src/primitives/canvas/widget_render_style.zig +626 -0
  223. package/src/primitives/canvas/widget_render_surfaces.zig +794 -0
  224. package/src/primitives/canvas/widget_routing.zig +475 -0
  225. package/src/primitives/canvas/widget_runtime.zig +307 -0
  226. package/src/primitives/canvas/widget_runtime_tests.zig +3015 -0
  227. package/src/primitives/canvas/widget_semantics.zig +480 -0
  228. package/src/primitives/canvas/widget_semantics_tests.zig +2129 -0
  229. package/src/primitives/canvas/widget_tests.zig +8 -0
  230. package/src/primitives/canvas/widget_text_input.zig +351 -0
  231. package/src/primitives/canvas/widget_text_select.zig +147 -0
  232. package/src/primitives/canvas/widget_tree.zig +232 -0
  233. package/src/primitives/canvas/widgets.zig +1319 -0
  234. package/src/primitives/diagnostics/root.zig +445 -0
  235. package/src/primitives/geometry/root.zig +889 -0
  236. package/src/primitives/json/root.zig +272 -0
  237. package/src/primitives/platform_info/root.zig +450 -0
  238. package/src/primitives/trace/root.zig +569 -0
  239. package/src/root.zig +165 -0
  240. package/src/runtime/api.zig +431 -0
  241. package/src/runtime/async_bridge.zig +49 -0
  242. package/src/runtime/automation_commands.zig +686 -0
  243. package/src/runtime/automation_liveness_tests.zig +140 -0
  244. package/src/runtime/automation_snapshot.zig +246 -0
  245. package/src/runtime/automation_widget_dispatch.zig +617 -0
  246. package/src/runtime/bridge_dispatch_tests.zig +202 -0
  247. package/src/runtime/bridge_payload.zig +194 -0
  248. package/src/runtime/bridge_permission_tests.zig +551 -0
  249. package/src/runtime/bridge_responses.zig +414 -0
  250. package/src/runtime/builtin_bridge.zig +554 -0
  251. package/src/runtime/canvas_budget_edge_tests.zig +415 -0
  252. package/src/runtime/canvas_font_tests.zig +410 -0
  253. package/src/runtime/canvas_fonts.zig +229 -0
  254. package/src/runtime/canvas_frame.zig +1734 -0
  255. package/src/runtime/canvas_frame_animation_tests.zig +609 -0
  256. package/src/runtime/canvas_frame_cache_tests.zig +333 -0
  257. package/src/runtime/canvas_frame_helpers.zig +414 -0
  258. package/src/runtime/canvas_frame_invalidation_tests.zig +544 -0
  259. package/src/runtime/canvas_frame_packet_tests.zig +1353 -0
  260. package/src/runtime/canvas_frame_patch_tests.zig +1051 -0
  261. package/src/runtime/canvas_frame_retained_tests.zig +753 -0
  262. package/src/runtime/canvas_frame_tests.zig +9 -0
  263. package/src/runtime/canvas_frame_text_layout_budget_tests.zig +149 -0
  264. package/src/runtime/canvas_image_tests.zig +362 -0
  265. package/src/runtime/canvas_images.zig +224 -0
  266. package/src/runtime/canvas_limits.zig +317 -0
  267. package/src/runtime/canvas_screenshot_tests.zig +289 -0
  268. package/src/runtime/canvas_widget_accessibility_tests.zig +1494 -0
  269. package/src/runtime/canvas_widget_anchored_tests.zig +678 -0
  270. package/src/runtime/canvas_widget_chart_tests.zig +249 -0
  271. package/src/runtime/canvas_widget_clipboard_tests.zig +399 -0
  272. package/src/runtime/canvas_widget_context_menu.zig +318 -0
  273. package/src/runtime/canvas_widget_context_menu_tests.zig +462 -0
  274. package/src/runtime/canvas_widget_control_tests.zig +2164 -0
  275. package/src/runtime/canvas_widget_disclosure_tests.zig +440 -0
  276. package/src/runtime/canvas_widget_display.zig +677 -0
  277. package/src/runtime/canvas_widget_event_tests.zig +1779 -0
  278. package/src/runtime/canvas_widget_events.zig +1098 -0
  279. package/src/runtime/canvas_widget_floating_tests.zig +695 -0
  280. package/src/runtime/canvas_widget_layout_tests.zig +26 -0
  281. package/src/runtime/canvas_widget_runtime.zig +1335 -0
  282. package/src/runtime/canvas_widget_scroll_driver_tests.zig +582 -0
  283. package/src/runtime/canvas_widget_scroll_drivers.zig +202 -0
  284. package/src/runtime/canvas_widget_scroll_tests.zig +1549 -0
  285. package/src/runtime/canvas_widget_semantics_tests.zig +810 -0
  286. package/src/runtime/canvas_widget_split_tree_tests.zig +1031 -0
  287. package/src/runtime/canvas_widget_state.zig +798 -0
  288. package/src/runtime/canvas_widget_text_tests.zig +2104 -0
  289. package/src/runtime/canvas_widget_window_drag_tests.zig +284 -0
  290. package/src/runtime/clock.zig +231 -0
  291. package/src/runtime/core.zig +927 -0
  292. package/src/runtime/effects.zig +4197 -0
  293. package/src/runtime/effects_audio_tests.zig +690 -0
  294. package/src/runtime/effects_clipboard_tests.zig +317 -0
  295. package/src/runtime/effects_fetch_tests.zig +1031 -0
  296. package/src/runtime/effects_file_tests.zig +407 -0
  297. package/src/runtime/effects_tests.zig +1251 -0
  298. package/src/runtime/flow.zig +1175 -0
  299. package/src/runtime/frame_profile.zig +221 -0
  300. package/src/runtime/gpu_surface_events.zig +639 -0
  301. package/src/runtime/launch_timing.zig +59 -0
  302. package/src/runtime/markdown_app_tests.zig +224 -0
  303. package/src/runtime/native_command_event_tests.zig +431 -0
  304. package/src/runtime/platform_bridge_tests.zig +8 -0
  305. package/src/runtime/platform_config_tests.zig +392 -0
  306. package/src/runtime/root.zig +150 -0
  307. package/src/runtime/runtime_event_tests.zig +1079 -0
  308. package/src/runtime/session_journal.zig +1522 -0
  309. package/src/runtime/session_record.zig +332 -0
  310. package/src/runtime/session_replay.zig +274 -0
  311. package/src/runtime/session_state.zig +30 -0
  312. package/src/runtime/session_tests.zig +399 -0
  313. package/src/runtime/shell_layout.zig +472 -0
  314. package/src/runtime/shell_layout_tests.zig +1246 -0
  315. package/src/runtime/shell_view_tests.zig +604 -0
  316. package/src/runtime/state.zig +110 -0
  317. package/src/runtime/system_services.zig +392 -0
  318. package/src/runtime/test_support.zig +79 -0
  319. package/src/runtime/tests.zig +30 -0
  320. package/src/runtime/ui_app.zig +3290 -0
  321. package/src/runtime/ui_app_huge_model_tests.zig +351 -0
  322. package/src/runtime/ui_app_provenance.zig +370 -0
  323. package/src/runtime/ui_app_tests.zig +3254 -0
  324. package/src/runtime/ui_app_virtual_variable_tests.zig +485 -0
  325. package/src/runtime/ui_app_window_tests.zig +442 -0
  326. package/src/runtime/validation.zig +206 -0
  327. package/src/runtime/view.zig +908 -0
  328. package/src/runtime/view_canvas.zig +850 -0
  329. package/src/runtime/view_widget_control.zig +433 -0
  330. package/src/runtime/view_widget_scroll.zig +360 -0
  331. package/src/runtime/view_widget_text.zig +275 -0
  332. package/src/runtime/view_widget_tree.zig +843 -0
  333. package/src/runtime/webview_view_bridge_tests.zig +664 -0
  334. package/src/runtime/widget_bridge.zig +231 -0
  335. package/src/runtime/window_command_bridge_tests.zig +403 -0
  336. package/src/runtime/window_storage.zig +255 -0
  337. package/src/runtime/window_view_runtime.zig +727 -0
  338. package/src/runtime/window_views.zig +334 -0
  339. package/src/security/root.zig +118 -0
  340. package/src/tooling/android.zig +1172 -0
  341. package/src/tooling/assets.zig +128 -0
  342. package/src/tooling/buildgraph.zig +379 -0
  343. package/src/tooling/cef.zig +671 -0
  344. package/src/tooling/codesign.zig +172 -0
  345. package/src/tooling/components/identity_tests.zig +185 -0
  346. package/src/tooling/components/stepper.zig +113 -0
  347. package/src/tooling/components/timeline.native +27 -0
  348. package/src/tooling/components/timeline_item.zig +131 -0
  349. package/src/tooling/default_icon.icns +0 -0
  350. package/src/tooling/default_icon.png +0 -0
  351. package/src/tooling/dev.zig +172 -0
  352. package/src/tooling/doctor.zig +349 -0
  353. package/src/tooling/eject_components.zig +170 -0
  354. package/src/tooling/embedlib.zig +290 -0
  355. package/src/tooling/ios.zig +528 -0
  356. package/src/tooling/manifest.zig +1939 -0
  357. package/src/tooling/package.zig +2388 -0
  358. package/src/tooling/process_tree.zig +114 -0
  359. package/src/tooling/raw_manifest.zig +193 -0
  360. package/src/tooling/root.zig +22 -0
  361. package/src/tooling/templates.zig +3191 -0
  362. package/src/tooling/toolchain.zig +371 -0
  363. package/src/tooling/verbs.zig +204 -0
  364. package/src/tooling/web_engine.zig +135 -0
  365. package/src/tooling/xcodeproj.zig +462 -0
  366. package/src/window_state/root.zig +507 -0
  367. package/index.js +0 -2
@@ -0,0 +1,1734 @@
1
+ const std = @import("std");
2
+ const geometry = @import("geometry");
3
+ const canvas = @import("canvas");
4
+ const canvas_frame_helpers = @import("canvas_frame_helpers.zig");
5
+ const launch_timing = @import("launch_timing.zig");
6
+ const platform = @import("../platform/root.zig");
7
+
8
+ pub const CanvasPixelSize = canvas_frame_helpers.CanvasPixelSize;
9
+ pub const appendCanvasSummaryChange = canvas_frame_helpers.appendCanvasSummaryChange;
10
+ pub const canvasDirtyBoundsFromChanges = canvas_frame_helpers.canvasDirtyBoundsFromChanges;
11
+ pub const canvasFrameBudgetIsUnset = canvas_frame_helpers.canvasFrameBudgetIsUnset;
12
+ pub const canvasFullRepaintBounds = canvas_frame_helpers.canvasFullRepaintBounds;
13
+ pub const sizesEqual = canvas_frame_helpers.sizesEqual;
14
+ pub const canvasSurfacePixelSize = canvas_frame_helpers.canvasSurfacePixelSize;
15
+ pub const normalizedCanvasPresentationScale = canvas_frame_helpers.normalizedCanvasPresentationScale;
16
+ pub const canvasFramePixelSize = canvas_frame_helpers.canvasFramePixelSize;
17
+ pub const canvasColorToRgba8 = canvas_frame_helpers.canvasColorToRgba8;
18
+ pub const clippedCanvasDirtyBounds = canvas_frame_helpers.clippedCanvasDirtyBounds;
19
+ pub const unionRects = canvas_frame_helpers.unionRects;
20
+ pub const canvasWidgetPointerEventFromGpuInput = canvas_frame_helpers.canvasWidgetPointerEventFromGpuInput;
21
+ pub const canvasWidgetInputBatchesDisplayListRefresh = canvas_frame_helpers.canvasWidgetInputBatchesDisplayListRefresh;
22
+ pub const canvasWidgetKeyboardEventFromGpuInput = canvas_frame_helpers.canvasWidgetKeyboardEventFromGpuInput;
23
+ pub const canvasWidgetTextInputEventFromGpuInput = canvas_frame_helpers.canvasWidgetTextInputEventFromGpuInput;
24
+ pub const canvasWidgetEscapeKey = canvas_frame_helpers.canvasWidgetEscapeKey;
25
+ pub const canvasWidgetKeyboardModifiers = canvas_frame_helpers.canvasWidgetKeyboardModifiers;
26
+ pub const mergeCanvasRenderOverrides = canvas_frame_helpers.mergeCanvasRenderOverrides;
27
+ pub const findCanvasRenderOverrideIndex = canvas_frame_helpers.findCanvasRenderOverrideIndex;
28
+ pub const canvasRenderOverrideNoop = canvas_frame_helpers.canvasRenderOverrideNoop;
29
+ pub const canvasRenderAnimationFinalOverrideNoop = canvas_frame_helpers.canvasRenderAnimationFinalOverrideNoop;
30
+ pub const canvasRenderAnimationActive = canvas_frame_helpers.canvasRenderAnimationActive;
31
+ pub const platformCanvasFrameProfileRisk = canvas_frame_helpers.platformCanvasFrameProfileRisk;
32
+ pub const gpuSurfaceFrameEventFromGpuFrame = canvas_frame_helpers.gpuSurfaceFrameEventFromGpuFrame;
33
+
34
+ const runtime_api = @import("api.zig");
35
+ const runtime_clock = @import("clock.zig");
36
+ const validation = @import("validation.zig");
37
+ const canvas_limits = @import("canvas_limits.zig");
38
+ const runtime_view = @import("view.zig");
39
+
40
+ const CanvasPresentationResult = runtime_api.CanvasPresentationResult;
41
+ const max_canvas_diff_changes_per_view = canvas_limits.max_canvas_diff_changes_per_view;
42
+ const max_canvas_render_animations_per_view = canvas_limits.max_canvas_render_animations_per_view;
43
+ const max_canvas_text_layouts_per_view = canvas_limits.max_canvas_text_layouts_per_view;
44
+ const max_canvas_text_layout_lines_per_view = canvas_limits.max_canvas_text_layout_lines_per_view;
45
+ const max_canvas_retained_packet_commands_per_view = canvas_limits.max_canvas_retained_packet_commands_per_view;
46
+ threadlocal var canvas_frame_text_layout_plans_scratch: [max_canvas_text_layouts_per_view]canvas.TextLayoutPlan = undefined;
47
+ threadlocal var canvas_frame_text_layout_lines_scratch: [max_canvas_text_layout_lines_per_view]canvas.TextLine = undefined;
48
+ threadlocal var canvas_frame_text_layout_cache_entries_scratch: [max_canvas_text_layouts_per_view]canvas.TextLayoutCacheEntry = undefined;
49
+ threadlocal var canvas_frame_text_layout_cache_actions_scratch: [max_canvas_text_layouts_per_view * 2]canvas.TextLayoutCacheAction = undefined;
50
+
51
+ /// One entry of the frame's CURRENT keyed command list — the full draw
52
+ /// order the retained packet protocol works on (never the scissor
53
+ /// subset). `render_index` points back into the frame's render plan so
54
+ /// upserts re-encode only the commands that changed; `bounds` is the
55
+ /// resolved render bounds, mirrored into the retained baseline so the
56
+ /// next frame's patch-derived dirty rect can name the pixels an upsert
57
+ /// or evict vacates.
58
+ const CanvasPacketCurrentCommand = struct {
59
+ key: u64,
60
+ fingerprint: u64,
61
+ render_index: u32,
62
+ bounds: geometry.RectF,
63
+ };
64
+
65
+ // Patch-derivation scratch (threadlocal, same pattern as the text-layout
66
+ // scratch above): the current keyed list, a key-sorted index over it for
67
+ // duplicate detection, a key-sorted index over the view's retained
68
+ // baseline for O(log n) lookups, per-baseline matched flags (unmatched =
69
+ // evict), and per-current upsert flags. ~64 KiB per thread total.
70
+ threadlocal var canvas_packet_current_scratch: [max_canvas_retained_packet_commands_per_view]CanvasPacketCurrentCommand = undefined;
71
+ threadlocal var canvas_packet_current_sort_scratch: [max_canvas_retained_packet_commands_per_view]u32 = undefined;
72
+ threadlocal var canvas_packet_baseline_sort_scratch: [max_canvas_retained_packet_commands_per_view]u32 = undefined;
73
+ threadlocal var canvas_packet_baseline_matched_scratch: [max_canvas_retained_packet_commands_per_view]bool = undefined;
74
+ threadlocal var canvas_packet_baseline_stable_scratch: [max_canvas_retained_packet_commands_per_view]bool = undefined;
75
+ threadlocal var canvas_packet_upsert_scratch: [max_canvas_retained_packet_commands_per_view]bool = undefined;
76
+
77
+ const validateViewLabel = validation.validateViewLabel;
78
+ const canvasRenderAnimationStartNsForView = runtime_view.canvasRenderAnimationStartNsForView;
79
+ const canvas_frame_log = std.log.scoped(.zero_canvas_frame);
80
+
81
+ /// Result of `renderCanvasScreenshot`: tightly packed RGBA8 pixels sliced
82
+ /// from the caller's buffer.
83
+ pub const CanvasScreenshot = struct {
84
+ width: usize,
85
+ height: usize,
86
+ rgba8: []const u8,
87
+ };
88
+
89
+ pub fn RuntimeCanvasFrames(comptime Runtime: type) type {
90
+ return struct {
91
+ pub fn setCanvasDisplayList(self: *Runtime, window_id: platform.WindowId, label: []const u8, display_list: canvas.DisplayList) anyerror!platform.ViewInfo {
92
+ try validateRuntimeViewParent(self, window_id);
93
+ try validateViewLabel(label);
94
+ const index = runtimeFindViewIndex(self, window_id, label) orelse return error.ViewNotFound;
95
+ if (self.views[index].kind != .gpu_surface) return error.InvalidViewOptions;
96
+ var canvas_changes: [max_canvas_diff_changes_per_view]canvas.DiffChange = undefined;
97
+ const changes = try canvas.DisplayList.diff(self.views[index].canvasDisplayList(), display_list, &canvas_changes);
98
+ try self.views[index].copyCanvasDisplayList(display_list);
99
+ self.views[index].canvas_display_list_widget_owned = false;
100
+ self.views[index].canvas_widget_display_list_prefix_count = 0;
101
+ self.views[index].canvas_widget_display_list_suffix_count = 0;
102
+ self.views[index].canvas_widget_display_list_reserved_count = 0;
103
+ invalidateForCanvasChanges(self, self.views[index].frame, changes);
104
+ if (changes.len > 0) try requestCanvasFrameForView(self, index);
105
+ return self.views[index].info();
106
+ }
107
+
108
+ pub fn canvasDisplayList(self: *const Runtime, window_id: platform.WindowId, label: []const u8) anyerror!canvas.DisplayList {
109
+ try validateRuntimeViewParent(self, window_id);
110
+ try validateViewLabel(label);
111
+ const index = runtimeFindViewIndex(self, window_id, label) orelse return error.ViewNotFound;
112
+ if (self.views[index].kind != .gpu_surface) return error.InvalidViewOptions;
113
+ return self.views[index].canvasDisplayList();
114
+ }
115
+
116
+ pub fn setCanvasRenderAnimations(self: *Runtime, window_id: platform.WindowId, label: []const u8, animations: []const canvas.CanvasRenderAnimation) anyerror!platform.ViewInfo {
117
+ try validateRuntimeViewParent(self, window_id);
118
+ try validateViewLabel(label);
119
+ const index = runtimeFindViewIndex(self, window_id, label) orelse return error.ViewNotFound;
120
+ if (self.views[index].kind != .gpu_surface) return error.InvalidViewOptions;
121
+ try validateCanvasRenderAnimations(animations);
122
+ // Replacing NOTHING with NOTHING is a no-op: a rebuild that
123
+ // never declared animations must not schedule work.
124
+ if (animations.len == 0 and
125
+ self.views[index].canvas_render_animation_count == 0 and
126
+ self.views[index].canvas_frame_render_override_count == 0)
127
+ {
128
+ return self.views[index].info();
129
+ }
130
+ // Invalidate the AFFECTED commands, not the whole view: the
131
+ // union of the display-list bounds of every command a
132
+ // previously APPLIED override or a new animation targets,
133
+ // widened by the animations' from/to transforms. The next
134
+ // planned frame recomputes exact override dirt; this region
135
+ // only schedules the repaint — but a UiApp rebuild re-bases
136
+ // its animations on EVERY update, and a full-frame region
137
+ // here silently defeated incremental presentation.
138
+ const dirty = canvasRenderAnimationScheduleDirtyBounds(&self.views[index], animations);
139
+ try self.views[index].copyCanvasRenderAnimations(animations);
140
+ if (dirty) |local_dirty| {
141
+ if (canvasDirtyRegionForView(self.views[index].frame, local_dirty)) |region| {
142
+ self.invalidateFor(.state, region);
143
+ } else {
144
+ self.invalidateFor(.state, self.views[index].frame);
145
+ }
146
+ } else if (animations.len == 0 and self.views[index].canvas_frame_render_override_count == 0) {
147
+ // Cleared an inert set (no applied overrides on screen):
148
+ // nothing painted from it, nothing to repaint.
149
+ self.invalidateFor(.state, null);
150
+ } else {
151
+ // Targets not in the current display list (or bounds
152
+ // unknown): stay loud with the full view.
153
+ self.invalidateFor(.state, self.views[index].frame);
154
+ }
155
+ try requestCanvasFrameForView(self, index);
156
+ return self.views[index].info();
157
+ }
158
+
159
+ pub fn clearCanvasRenderAnimations(self: *Runtime, window_id: platform.WindowId, label: []const u8) anyerror!platform.ViewInfo {
160
+ try validateRuntimeViewParent(self, window_id);
161
+ try validateViewLabel(label);
162
+ const index = runtimeFindViewIndex(self, window_id, label) orelse return error.ViewNotFound;
163
+ if (self.views[index].kind != .gpu_surface) return error.InvalidViewOptions;
164
+ if (self.views[index].canvas_render_animation_count == 0 and self.views[index].canvas_frame_render_override_count == 0) return self.views[index].info();
165
+ self.views[index].canvas_render_animation_count = 0;
166
+ self.invalidateFor(.state, self.views[index].frame);
167
+ try requestCanvasFrameForView(self, index);
168
+ return self.views[index].info();
169
+ }
170
+
171
+ pub fn canvasRenderAnimations(self: *const Runtime, window_id: platform.WindowId, label: []const u8) anyerror![]const canvas.CanvasRenderAnimation {
172
+ try validateRuntimeViewParent(self, window_id);
173
+ try validateViewLabel(label);
174
+ const index = runtimeFindViewIndex(self, window_id, label) orelse return error.ViewNotFound;
175
+ if (self.views[index].kind != .gpu_surface) return error.InvalidViewOptions;
176
+ return self.views[index].canvasRenderAnimations();
177
+ }
178
+
179
+ pub fn canvasRenderAnimationStartNs(self: *const Runtime, window_id: platform.WindowId, label: []const u8) anyerror!u64 {
180
+ try validateRuntimeViewParent(self, window_id);
181
+ try validateViewLabel(label);
182
+ const index = runtimeFindViewIndex(self, window_id, label) orelse return error.ViewNotFound;
183
+ if (self.views[index].kind != .gpu_surface) return error.InvalidViewOptions;
184
+ return canvasRenderAnimationStartNsForView(&self.views[index]);
185
+ }
186
+
187
+ pub fn canvasFramePlan(self: *const Runtime, window_id: platform.WindowId, label: []const u8, previous: ?canvas.DisplayList, options: canvas.CanvasFrameOptions, storage: canvas.CanvasFrameStorage) anyerror!canvas.CanvasFrame {
188
+ try validateRuntimeViewParent(self, window_id);
189
+ try validateViewLabel(label);
190
+ const index = runtimeFindViewIndex(self, window_id, label) orelse return error.ViewNotFound;
191
+ if (self.views[index].kind != .gpu_surface) return error.InvalidViewOptions;
192
+
193
+ var frame_options = options;
194
+ if (frame_options.surface_size.isEmpty()) frame_options.surface_size = self.views[index].frame.size();
195
+ return self.views[index].canvasDisplayList().framePlan(previous, frame_options, storage);
196
+ }
197
+
198
+ pub fn nextCanvasFrame(self: *Runtime, window_id: platform.WindowId, label: []const u8, options: canvas.CanvasFrameOptions, storage: canvas.CanvasFrameStorage) anyerror!canvas.CanvasFrame {
199
+ try validateRuntimeViewParent(self, window_id);
200
+ try validateViewLabel(label);
201
+ const index = runtimeFindViewIndex(self, window_id, label) orelse return error.ViewNotFound;
202
+ if (self.views[index].kind != .gpu_surface) return error.InvalidViewOptions;
203
+ return try planCanvasFrameForView(self, index, options, storage, true);
204
+ }
205
+
206
+ pub fn nextCanvasGpuPacket(self: *Runtime, window_id: platform.WindowId, label: []const u8, options: canvas.CanvasFrameOptions, storage: canvas.CanvasFrameStorage, output: []canvas.CanvasGpuCommand) anyerror!canvas.CanvasGpuPacket {
207
+ try validateRuntimeViewParent(self, window_id);
208
+ try validateViewLabel(label);
209
+ const index = runtimeFindViewIndex(self, window_id, label) orelse return error.ViewNotFound;
210
+ if (self.views[index].kind != .gpu_surface) return error.InvalidViewOptions;
211
+ const canvas_frame = try planCanvasFrameForView(self, index, options, storage, true);
212
+ return try canvas_frame.gpuPacket(output);
213
+ }
214
+
215
+ pub fn presentNextCanvasGpuPacket(
216
+ self: *Runtime,
217
+ window_id: platform.WindowId,
218
+ label: []const u8,
219
+ options: canvas.CanvasFrameOptions,
220
+ storage: canvas.CanvasFrameStorage,
221
+ clear_color: canvas.Color,
222
+ output: []canvas.CanvasGpuCommand,
223
+ packet_json_buffer: []u8,
224
+ ) anyerror!canvas.CanvasGpuPacket {
225
+ return try self.presentNextCanvasGpuPacketWithScale(window_id, label, options, storage, clear_color, output, packet_json_buffer, null);
226
+ }
227
+
228
+ pub fn presentNextCanvasGpuPacketWithScale(
229
+ self: *Runtime,
230
+ window_id: platform.WindowId,
231
+ label: []const u8,
232
+ options: canvas.CanvasFrameOptions,
233
+ storage: canvas.CanvasFrameStorage,
234
+ clear_color: canvas.Color,
235
+ output: []canvas.CanvasGpuCommand,
236
+ packet_json_buffer: []u8,
237
+ packet_scale: ?f32,
238
+ ) anyerror!canvas.CanvasGpuPacket {
239
+ const canvas_frame = try self.nextCanvasFrame(window_id, label, options, storage);
240
+ recordCanvasClearColor(self, window_id, label, clear_color);
241
+ var packet = try canvas_frame.gpuPacket(output);
242
+ packet.scale = normalizedCanvasPresentationScale(packet_scale, canvas_frame.scale);
243
+ if (!packet.requiresRender()) return packet;
244
+ uploadCanvasPacketImages(self, packet) catch |err| {
245
+ if (err == error.UnsupportedService) {
246
+ recordCanvasPacketFallback(self, window_id, label, .{ .reason = .missing_service });
247
+ }
248
+ return err;
249
+ };
250
+ // A refused present surfaces as error.UnsupportedService so
251
+ // callers (UiApp's frame loop) take their existing pixel
252
+ // fallback; the refusal reason was already recorded on the
253
+ // view. Packets with unrepresentable commands are still
254
+ // offered — the null platform accepts them for inspection —
255
+ // but a real host's refusal is attributed to the command,
256
+ // not to a missing service.
257
+ const refusal: CanvasPacketRefusal = if (packet.fullyRepresentable())
258
+ .{ .reason = .missing_service }
259
+ else
260
+ .{ .reason = .unsupported_command, .command_kind = firstUnsupportedCommandName(canvas_frame, packet) };
261
+ const presented = try presentCanvasPacketEncoded(self, window_id, label, canvas_frame, packet, clear_color, packet_json_buffer, refusal);
262
+ if (!presented) return error.UnsupportedService;
263
+ if (runtimeFindViewIndex(self, window_id, label)) |index| {
264
+ self.views[index].recordCanvasFramePresentationComplete(canvas_frame);
265
+ // The platform present call succeeded: this frame painted
266
+ // through the packet path. A failed attempt never stamps.
267
+ self.views[index].gpu_present_path = .packet;
268
+ clearCanvasPacketFallback(&self.views[index]);
269
+ recordCanvasPresentInputLatency(&self.views[index]);
270
+ }
271
+ return packet;
272
+ }
273
+
274
+ pub fn presentNextCanvasFrame(
275
+ self: *Runtime,
276
+ window_id: platform.WindowId,
277
+ label: []const u8,
278
+ options: canvas.CanvasFrameOptions,
279
+ storage: canvas.CanvasFrameStorage,
280
+ gpu_commands: []canvas.CanvasGpuCommand,
281
+ packet_json_buffer: []u8,
282
+ pixels: []u8,
283
+ scratch: []u8,
284
+ clear_color: canvas.Color,
285
+ pixel_scale: ?f32,
286
+ ) anyerror!CanvasPresentationResult {
287
+ const canvas_frame = try self.nextCanvasFrame(window_id, label, options, storage);
288
+ recordCanvasClearColor(self, window_id, label, clear_color);
289
+ if (!canvas_frame.requiresRender()) {
290
+ return .{ .frame = canvas_frame, .mode = .skipped };
291
+ }
292
+
293
+ const services = self.options.platform.services;
294
+ const packet_service_available = services.present_gpu_surface_packet_fn != null or
295
+ services.present_gpu_surface_packet_binary_fn != null;
296
+ if (gpu_commands.len > 0 and packet_json_buffer.len > 0) {
297
+ if (packet_service_available) {
298
+ var packet = try canvas_frame.gpuPacket(gpu_commands);
299
+ packet.scale = normalizedCanvasPresentationScale(pixel_scale, canvas_frame.scale);
300
+ const result = CanvasPresentationResult{
301
+ .frame = canvas_frame,
302
+ .mode = .gpu_packet,
303
+ .packet_command_count = packet.commandCount(),
304
+ .packet_cache_action_count = packet.cacheActionCount(),
305
+ .packet_cached_resource_command_count = packet.cachedResourceCommandCount(),
306
+ .packet_unsupported_command_count = packet.unsupported_command_count,
307
+ .packet_representable = packet.fullyRepresentable(),
308
+ };
309
+ if (packet.fullyRepresentable()) {
310
+ const packet_presented = blk: {
311
+ uploadCanvasPacketImages(self, packet) catch |err| switch (err) {
312
+ error.UnsupportedService => {
313
+ recordCanvasPacketFallback(self, window_id, label, .{ .reason = .missing_service });
314
+ break :blk false;
315
+ },
316
+ else => return err,
317
+ };
318
+ break :blk try presentCanvasPacketEncoded(self, window_id, label, canvas_frame, packet, clear_color, packet_json_buffer, .{ .reason = .missing_service });
319
+ };
320
+ if (packet_presented) {
321
+ if (runtimeFindViewIndex(self, window_id, label)) |index| {
322
+ self.views[index].recordCanvasFramePresentationComplete(canvas_frame);
323
+ self.views[index].gpu_present_path = .packet;
324
+ clearCanvasPacketFallback(&self.views[index]);
325
+ recordCanvasPresentInputLatency(&self.views[index]);
326
+ }
327
+ return result;
328
+ }
329
+ } else {
330
+ recordCanvasPacketFallback(self, window_id, label, .{
331
+ .reason = .unsupported_command,
332
+ .command_kind = firstUnsupportedCommandName(canvas_frame, packet),
333
+ });
334
+ }
335
+ } else {
336
+ // The caller offered packet transport buffers, so a
337
+ // packet was wanted; the platform simply has no
338
+ // packet presenter.
339
+ recordCanvasPacketFallback(self, window_id, label, .{ .reason = .missing_service });
340
+ }
341
+ }
342
+
343
+ var pixel_frame = canvas_frame;
344
+ if (pixel_scale) |scale| pixel_frame.scale = scale;
345
+ try presentCanvasFramePixelsWithRecord(self, window_id, label, pixel_frame, canvas_frame, pixels, scratch, clear_color);
346
+ return .{
347
+ .frame = canvas_frame,
348
+ .mode = .pixels,
349
+ .packet_representable = false,
350
+ };
351
+ }
352
+
353
+ pub fn presentCanvasFramePixels(
354
+ self: *Runtime,
355
+ window_id: platform.WindowId,
356
+ label: []const u8,
357
+ canvas_frame: canvas.CanvasFrame,
358
+ pixels: []u8,
359
+ scratch: []u8,
360
+ clear_color: canvas.Color,
361
+ ) anyerror!void {
362
+ try presentCanvasFramePixelsWithRecord(self, window_id, label, canvas_frame, canvas_frame, pixels, scratch, clear_color);
363
+ }
364
+
365
+ fn presentCanvasFramePixelsWithRecord(
366
+ self: *Runtime,
367
+ window_id: platform.WindowId,
368
+ label: []const u8,
369
+ canvas_frame: canvas.CanvasFrame,
370
+ record_frame: canvas.CanvasFrame,
371
+ pixels: []u8,
372
+ scratch: []u8,
373
+ clear_color: canvas.Color,
374
+ ) anyerror!void {
375
+ recordCanvasClearColor(self, window_id, label, clear_color);
376
+ if (!canvas_frame.requiresRender()) return;
377
+ const pixel_size = try canvasFramePixelSize(canvas_frame);
378
+ var surface = if (scratch.len >= pixel_size.byte_len)
379
+ try canvas.ReferenceRenderSurface.initWithScratch(pixel_size.width, pixel_size.height, pixels, scratch)
380
+ else
381
+ try canvas.ReferenceRenderSurface.init(pixel_size.width, pixel_size.height, pixels);
382
+ surface = surface.withImages(canvas_frame.image_resources).withFonts(canvas_frame.font_resources).withRenderMemo(self.options.pixel_present_render_memo);
383
+ // Frame-profile `present` stage for the CPU pixel path: the
384
+ // reference raster + the host present call (the software
385
+ // equivalent of the packet host's decode+draw).
386
+ const present_begin = self.frame_profile.begin();
387
+ defer self.frame_profile.end(.present, present_begin);
388
+ try surface.renderPass(canvas_frame.renderPass(), clear_color);
389
+ try self.options.platform.services.presentGpuSurfacePixels(.{
390
+ .window_id = window_id,
391
+ .label = label,
392
+ .width = pixel_size.width,
393
+ .height = pixel_size.height,
394
+ .scale_factor = canvas_frame.scale,
395
+ .dirty_bounds = canvas_frame.dirty_bounds,
396
+ .rgba8 = surface.pixels,
397
+ });
398
+ if (runtimeFindViewIndex(self, window_id, label)) |index| {
399
+ self.views[index].recordCanvasFramePresentationComplete(record_frame);
400
+ // The platform present call succeeded: this frame painted
401
+ // through the pixel path (covers the direct pixel entry
402
+ // points and the packet-fallback route alike).
403
+ self.views[index].gpu_present_path = .pixels;
404
+ recordCanvasPresentInputLatency(&self.views[index]);
405
+ // Pixels-only hosts that opted in keep the keyed mirror
406
+ // ALIVE across pixel presents: the buffer now shows this
407
+ // frame's keyed list, so the next plan refines its dirty
408
+ // bounds from the key+fingerprint edit script instead of
409
+ // the summary union (which marks every keyed command
410
+ // changed on a Msg rebuild). The pixel adoption is marked
411
+ // so the packet patch gate can never encode against it.
412
+ var baseline_adopted = false;
413
+ if (self.options.pixel_present_retained_baseline) {
414
+ if (gatherCanvasPacketCurrentCommands(record_frame)) |current| {
415
+ adoptCanvasPixelPresentBaseline(&self.views[index], current, record_frame.surface_size, record_frame.scale);
416
+ baseline_adopted = true;
417
+ }
418
+ }
419
+ // Otherwise: pixels on the glass no longer match the
420
+ // retained command dictionary (the host drops its copy on
421
+ // pixel presents too) — the next packet present must be
422
+ // FULL.
423
+ if (!baseline_adopted) self.views[index].canvas_packet_baseline_valid = false;
424
+ self.views[index].gpu_present_packet_mode = .none;
425
+ self.views[index].gpu_present_patch_bytes = 0;
426
+ self.views[index].gpu_present_patch_upsert_count = 0;
427
+ self.views[index].gpu_present_patch_evict_count = 0;
428
+ }
429
+ }
430
+
431
+ pub fn presentNextCanvasFramePixels(
432
+ self: *Runtime,
433
+ window_id: platform.WindowId,
434
+ label: []const u8,
435
+ options: canvas.CanvasFrameOptions,
436
+ storage: canvas.CanvasFrameStorage,
437
+ pixels: []u8,
438
+ scratch: []u8,
439
+ clear_color: canvas.Color,
440
+ ) anyerror!canvas.CanvasFrame {
441
+ const canvas_frame = try self.nextCanvasFrame(window_id, label, options, storage);
442
+ try self.presentCanvasFramePixels(window_id, label, canvas_frame, pixels, scratch, clear_color);
443
+ return canvas_frame;
444
+ }
445
+
446
+ /// Push the pixel bytes behind every `upload` image cache action
447
+ /// in `packet` through the platform's binary side-channel
448
+ /// (`uploadGpuSurfaceImage`) BEFORE the packet is presented, so
449
+ /// the host holds the texture when it applies the action. Packet
450
+ /// JSON carries only id + fingerprint references — pixel payloads
451
+ /// never ride it, so frames with registered images stay under the
452
+ /// packet JSON bound instead of falling back to the software
453
+ /// pixel path. Absent resources (a draw referencing an id that is
454
+ /// not registered — a legitimate transient state) upload nothing;
455
+ /// the host skips those draws exactly like the reference
456
+ /// renderer. `error.UnsupportedService` (platform without the
457
+ /// seam) propagates so callers take their existing pixel
458
+ /// fallback.
459
+ fn uploadCanvasPacketImages(self: *Runtime, packet: canvas.CanvasGpuPacket) anyerror!void {
460
+ for (packet.image_actions) |action| {
461
+ if (action.kind != .upload) continue;
462
+ const image_index = action.image_index orelse continue;
463
+ if (image_index >= packet.images.len) continue;
464
+ const image = packet.images[image_index];
465
+ if (image.width == 0 or image.height == 0 or image.pixels.len == 0) continue;
466
+ try self.options.platform.services.uploadGpuSurfaceImage(.{
467
+ .id = image.image_id,
468
+ .width = image.width,
469
+ .height = image.height,
470
+ .rgba8 = image.pixels,
471
+ });
472
+ }
473
+ }
474
+
475
+ /// Encode `packet` and push it through the platform's packet
476
+ /// presenter. The compact binary encoding is preferred whenever
477
+ /// the platform wires the binary presenter; a platform that
478
+ /// wires it but refuses the call itself
479
+ /// (`error.UnsupportedService`) gets the JSON attempt in the
480
+ /// same frame, so capability negotiation is a per-present
481
+ /// conversation rather than a boot-time contract and the JSON
482
+ /// path stays alive for compatibility and wire debugging.
483
+ ///
484
+ /// On the binary path, presentation is INCREMENTAL whenever the
485
+ /// view holds a valid retained baseline: the frame's full keyed
486
+ /// command list is diffed against the baseline's key+fingerprint
487
+ /// mirror and only the edits (upserts + evicts + the draw-order
488
+ /// vector) ride the wire as a `patch` present. Everything else —
489
+ /// no baseline, resized surface, unrepresentable or over-budget
490
+ /// command lists, duplicate keys, host refusal, patch overflow —
491
+ /// resolves to a FULL keyed present in the same frame that
492
+ /// rebuilds both sides' retained state under a fresh generation.
493
+ /// Drift can therefore cost one full present, never wrong pixels.
494
+ ///
495
+ /// Returns true when a present succeeded. Every refusal records
496
+ /// its fallback reason on the view BEFORE returning, so
497
+ /// automation snapshots explain WHY a frame left the packet
498
+ /// path; `refusal` names the reason to record when a presenter
499
+ /// exists but declines (the caller knows whether the packet was
500
+ /// representable — this helper does not).
501
+ fn presentCanvasPacketEncoded(
502
+ self: *Runtime,
503
+ window_id: platform.WindowId,
504
+ label: []const u8,
505
+ canvas_frame: canvas.CanvasFrame,
506
+ packet: canvas.CanvasGpuPacket,
507
+ clear_color: canvas.Color,
508
+ packet_bytes_buffer: []u8,
509
+ refusal: CanvasPacketRefusal,
510
+ ) anyerror!bool {
511
+ const services = self.options.platform.services;
512
+ var base = platform.GpuSurfacePacket{
513
+ .window_id = window_id,
514
+ .label = label,
515
+ .frame_index = packet.frame_index,
516
+ .timestamp_ns = packet.timestamp_ns,
517
+ .surface_size = packet.surface_size,
518
+ .scale_factor = packet.scale,
519
+ .clear_color_rgba8 = canvasColorToRgba8(clear_color),
520
+ .requires_render = packet.requiresRender(),
521
+ .command_count = packet.commandCount(),
522
+ .cache_action_count = packet.cacheActionCount(),
523
+ .cached_resource_command_count = packet.cachedResourceCommandCount(),
524
+ .unsupported_command_count = packet.unsupported_command_count,
525
+ .representable = packet.fullyRepresentable(),
526
+ };
527
+ if (services.present_gpu_surface_packet_binary_fn != null) binary: {
528
+ const binary_buffer = packet_bytes_buffer[0..@min(packet_bytes_buffer.len, platform.max_gpu_surface_packet_binary_bytes)];
529
+ const view_index = runtimeFindViewIndex(self, window_id, label);
530
+ // Frame-profile `patch` stage: gathering the keyed list +
531
+ // diffing it against the retained baseline. Stamps no-op
532
+ // unless profiling is on.
533
+ const patch_begin = self.frame_profile.begin();
534
+ // The retained protocol works on the frame's FULL keyed
535
+ // draw order (never the scissor subset); null when the
536
+ // full list is unrepresentable, over the retained budget,
537
+ // or carries duplicate keys — those frames present
538
+ // through the non-retained encoding below.
539
+ const current = if (view_index != null) gatherCanvasPacketCurrentCommands(canvas_frame) else null;
540
+ // Patch derivation runs eagerly with the gather (one
541
+ // profile stage, one scratch fill the encoder below
542
+ // reads); null when the view holds no usable baseline.
543
+ const patch_stats: ?CanvasPacketPatchStats = stats: {
544
+ const current_commands = current orelse break :stats null;
545
+ const view = &self.views[view_index.?];
546
+ if (!view.canvas_packet_baseline_valid) break :stats null;
547
+ // A baseline a PIXEL present adopted refines dirty
548
+ // bounds only — no host retains a dictionary for it,
549
+ // so a patch encoded against it would edit nothing.
550
+ if (view.canvas_packet_baseline_pixels) break :stats null;
551
+ if (!sizesEqual(view.canvas_packet_baseline_surface_size, packet.surface_size) or
552
+ view.canvas_packet_baseline_scale != packet.scale) break :stats null;
553
+ break :stats computeCanvasPacketPatchStats(view, current_commands);
554
+ };
555
+ self.frame_profile.end(.patch, patch_begin);
556
+
557
+ // ---- incremental attempt: patch the host's retained list.
558
+ if (current) |current_commands| patch: {
559
+ const view = &self.views[view_index.?];
560
+ const stats = patch_stats orelse break :patch;
561
+ // A patch that re-encodes EVERY command is strictly
562
+ // larger than the keyed full present (same upserts
563
+ // plus the order vector), so frames where everything
564
+ // changed — a scroll step shifting the whole view —
565
+ // present full, which also refreshes the baseline
566
+ // generation.
567
+ if (stats.upsert_count >= current_commands.len) break :patch;
568
+ var writer = std.Io.Writer.fixed(binary_buffer);
569
+ // A patch that outgrows the transport is not a
570
+ // failure — the full present below is the compact
571
+ // form.
572
+ const encode_begin = self.frame_profile.begin();
573
+ writeCanvasPacketPatchBinary(view, canvas_frame, packet, current_commands, stats, &writer) catch break :patch;
574
+ self.frame_profile.end(.encode, encode_begin);
575
+ base.binary = writer.buffered();
576
+ base.json = "";
577
+ base.command_count = current_commands.len;
578
+ const present_begin = self.frame_profile.begin();
579
+ services.presentGpuSurfacePacketBinary(base) catch |err| switch (err) {
580
+ error.UnsupportedService => {
581
+ // Host refused the patch (retained state
582
+ // lost, generation drift, budget, decode).
583
+ // Record the reason, then resync via the
584
+ // full present below in this same frame.
585
+ recordCanvasPacketFallback(self, window_id, label, .{ .reason = .patch_refused });
586
+ view.canvas_packet_baseline_valid = false;
587
+ break :patch;
588
+ },
589
+ else => return err,
590
+ };
591
+ self.frame_profile.end(.present, present_begin);
592
+ adoptCanvasPacketBaseline(view, current_commands, packet);
593
+ view.gpu_present_packet_mode = .patch;
594
+ view.gpu_present_patch_bytes = base.binary.len;
595
+ view.gpu_present_patch_upsert_count = stats.upsert_count;
596
+ view.gpu_present_patch_evict_count = stats.evict_count;
597
+ return true;
598
+ }
599
+
600
+ // ---- full keyed present: (re)build both sides' retained
601
+ // state under a fresh generation.
602
+ if (current) |current_commands| {
603
+ const view = &self.views[view_index.?];
604
+ const generation = if (view.canvas_packet_generation == std.math.maxInt(u64)) 1 else view.canvas_packet_generation + 1;
605
+ var writer = std.Io.Writer.fixed(binary_buffer);
606
+ const encode_begin = self.frame_profile.begin();
607
+ writeCanvasPacketFullBinary(canvas_frame, packet, current_commands, generation, &writer) catch {
608
+ view.canvas_packet_baseline_valid = false;
609
+ if (services.present_gpu_surface_packet_fn == null) {
610
+ recordCanvasPacketFallback(self, window_id, label, .{
611
+ .reason = .binary_overflow,
612
+ .needed_bytes = canvasPacketFullBinaryByteSize(canvas_frame, packet, current_commands, generation),
613
+ .limit_bytes = binary_buffer.len,
614
+ });
615
+ return false;
616
+ }
617
+ break :binary;
618
+ };
619
+ self.frame_profile.end(.encode, encode_begin);
620
+ base.binary = writer.buffered();
621
+ base.json = "";
622
+ base.command_count = current_commands.len;
623
+ const present_begin = self.frame_profile.begin();
624
+ services.presentGpuSurfacePacketBinary(base) catch |err| switch (err) {
625
+ // A host that refuses the keyed full present is
626
+ // refusing this binary encoding, not the retained
627
+ // protocol: negotiate down to JSON.
628
+ error.UnsupportedService => {
629
+ view.canvas_packet_baseline_valid = false;
630
+ break :binary;
631
+ },
632
+ else => return err,
633
+ };
634
+ self.frame_profile.end(.present, present_begin);
635
+ view.canvas_packet_generation = generation;
636
+ adoptCanvasPacketBaseline(view, current_commands, packet);
637
+ view.gpu_present_packet_mode = .full;
638
+ view.gpu_present_patch_bytes = 0;
639
+ view.gpu_present_patch_upsert_count = 0;
640
+ view.gpu_present_patch_evict_count = 0;
641
+ return true;
642
+ }
643
+
644
+ // ---- non-retained binary present (no view, duplicate
645
+ // keys, over-budget or unrepresentable full list): the
646
+ // scissor-subset packet under generation 0, which the
647
+ // host draws but never retains.
648
+ if (view_index) |index| self.views[index].canvas_packet_baseline_valid = false;
649
+ var writer = std.Io.Writer.fixed(binary_buffer);
650
+ const encode_begin = self.frame_profile.begin();
651
+ packet.writeBinary(&writer) catch {
652
+ // A frame too big for the binary encoding might
653
+ // still matter to a JSON-only host (whose binary
654
+ // presenter would have refused anyway), so the JSON
655
+ // attempt below delivers the single per-frame
656
+ // verdict — unless there is no JSON presenter at
657
+ // all, in which case this overflow IS the verdict.
658
+ if (services.present_gpu_surface_packet_fn == null) {
659
+ recordCanvasPacketFallback(self, window_id, label, .{
660
+ .reason = .binary_overflow,
661
+ .needed_bytes = canvasPacketEncodedByteSize(packet, .binary),
662
+ .limit_bytes = binary_buffer.len,
663
+ });
664
+ return false;
665
+ }
666
+ break :binary;
667
+ };
668
+ self.frame_profile.end(.encode, encode_begin);
669
+ base.binary = writer.buffered();
670
+ base.json = "";
671
+ base.command_count = packet.commandCount();
672
+ const present_begin = self.frame_profile.begin();
673
+ services.presentGpuSurfacePacketBinary(base) catch |err| switch (err) {
674
+ // The platform wires the binary seam but declines at
675
+ // call time: negotiate down to JSON.
676
+ error.UnsupportedService => break :binary,
677
+ else => return err,
678
+ };
679
+ self.frame_profile.end(.present, present_begin);
680
+ if (view_index) |index| recordCanvasPacketFullPresent(&self.views[index]);
681
+ return true;
682
+ }
683
+ if (services.present_gpu_surface_packet_fn == null) {
684
+ recordCanvasPacketFallback(self, window_id, label, .{ .reason = .missing_service });
685
+ return false;
686
+ }
687
+ // The transport buffer may exceed the JSON wire bound (it is
688
+ // sized for the larger binary encoding); clamp so an
689
+ // oversized encode fails HERE as a recorded overflow instead
690
+ // of tripping the service wrapper's validation.
691
+ const json_buffer = packet_bytes_buffer[0..@min(packet_bytes_buffer.len, platform.max_gpu_surface_packet_json_bytes)];
692
+ var writer = std.Io.Writer.fixed(json_buffer);
693
+ const encode_begin = self.frame_profile.begin();
694
+ packet.writeJson(&writer) catch {
695
+ recordCanvasPacketFallback(self, window_id, label, .{
696
+ .reason = .json_overflow,
697
+ .needed_bytes = canvasPacketEncodedByteSize(packet, .json),
698
+ .limit_bytes = json_buffer.len,
699
+ });
700
+ return false;
701
+ };
702
+ self.frame_profile.end(.encode, encode_begin);
703
+ base.json = writer.buffered();
704
+ base.binary = "";
705
+ base.command_count = packet.commandCount();
706
+ const present_begin = self.frame_profile.begin();
707
+ services.presentGpuSurfacePacket(base) catch |err| switch (err) {
708
+ error.UnsupportedService => {
709
+ recordCanvasPacketFallback(self, window_id, label, refusal);
710
+ return false;
711
+ },
712
+ else => return err,
713
+ };
714
+ self.frame_profile.end(.present, present_begin);
715
+ // JSON presents bypass the retained protocol entirely (the
716
+ // host invalidates its retained state on them too).
717
+ if (runtimeFindViewIndex(self, window_id, label)) |index| {
718
+ self.views[index].canvas_packet_baseline_valid = false;
719
+ recordCanvasPacketFullPresent(&self.views[index]);
720
+ }
721
+ return true;
722
+ }
723
+
724
+ fn recordCanvasClearColor(self: *Runtime, window_id: platform.WindowId, label: []const u8, clear_color: canvas.Color) void {
725
+ if (runtimeFindViewIndex(self, window_id, label)) |index| {
726
+ self.views[index].canvas_clear_color = clear_color;
727
+ }
728
+ }
729
+
730
+ /// Render the view's current retained canvas scene through the
731
+ /// deterministic CPU reference renderer — the same pixel path the
732
+ /// software presentation uses (`presentCanvasFramePixels`) — without
733
+ /// presenting or mutating presentation state. The frame is planned
734
+ /// as a full repaint at the view's last frame timestamp, cleared
735
+ /// with the view's declared clear color — recorded by presents AND
736
+ /// by widget display-list emissions (from live tokens), so a theme
737
+ /// change screenshots correctly without an intervening present.
738
+ /// `pixels` (and optionally
739
+ /// `scratch`, for layer effects) must hold
740
+ /// `canvasScreenshotPixelSize(...).byte_len` bytes.
741
+ pub fn renderCanvasScreenshot(
742
+ self: *Runtime,
743
+ window_id: platform.WindowId,
744
+ label: []const u8,
745
+ scale: ?f32,
746
+ pixels: []u8,
747
+ scratch: []u8,
748
+ ) anyerror!CanvasScreenshot {
749
+ return renderCanvasScreenshotWithMemo(self, window_id, label, scale, pixels, scratch, null);
750
+ }
751
+
752
+ /// `renderCanvasScreenshot` with a caller-owned render memo for
753
+ /// hosts that re-render the same retained scene every frame (the
754
+ /// docs live previews): heavyweight per-pixel commands (backdrop
755
+ /// blur, drop shadow, big fills) whose inputs are byte-identical
756
+ /// to the previous render replay their stored pixels instead of
757
+ /// re-running their loops. Output bytes are identical with or
758
+ /// without the memo — it only moves time, never pixels.
759
+ pub fn renderCanvasScreenshotWithMemo(
760
+ self: *Runtime,
761
+ window_id: platform.WindowId,
762
+ label: []const u8,
763
+ scale: ?f32,
764
+ pixels: []u8,
765
+ scratch: []u8,
766
+ render_memo: ?*canvas.ReferenceRenderMemo,
767
+ ) anyerror!CanvasScreenshot {
768
+ try validateRuntimeViewParent(self, window_id);
769
+ try validateViewLabel(label);
770
+ const index = runtimeFindViewIndex(self, window_id, label) orelse return error.ViewNotFound;
771
+ if (self.views[index].kind != .gpu_surface) return error.InvalidViewOptions;
772
+
773
+ const canvas_frame = try planCanvasFrameForView(self, index, .{
774
+ .frame_index = self.views[index].gpu_frame_index,
775
+ .timestamp_ns = self.views[index].gpu_timestamp_ns,
776
+ .surface_size = canvasScreenshotSurfaceSize(&self.views[index]),
777
+ .scale = normalizedCanvasPresentationScale(scale, 1),
778
+ .full_repaint = true,
779
+ }, canvasFrameScratchStorage(self), false);
780
+ const pixel_size = try canvasFramePixelSize(canvas_frame);
781
+ var surface = if (scratch.len >= pixel_size.byte_len)
782
+ try canvas.ReferenceRenderSurface.initWithScratch(pixel_size.width, pixel_size.height, pixels, scratch)
783
+ else
784
+ try canvas.ReferenceRenderSurface.init(pixel_size.width, pixel_size.height, pixels);
785
+ surface = surface.withImages(canvas_frame.image_resources).withFonts(canvas_frame.font_resources).withRenderMemo(render_memo);
786
+ try surface.renderPass(canvas_frame.renderPass(), self.views[index].canvas_clear_color);
787
+ return .{
788
+ .width = pixel_size.width,
789
+ .height = pixel_size.height,
790
+ .rgba8 = surface.pixels,
791
+ };
792
+ }
793
+
794
+ /// Pixel dimensions `renderCanvasScreenshot` will produce for the
795
+ /// view at the given scale (default 1).
796
+ pub fn canvasScreenshotPixelSize(
797
+ self: *const Runtime,
798
+ window_id: platform.WindowId,
799
+ label: []const u8,
800
+ scale: ?f32,
801
+ ) anyerror!CanvasPixelSize {
802
+ try validateRuntimeViewParent(self, window_id);
803
+ try validateViewLabel(label);
804
+ const index = runtimeFindViewIndex(self, window_id, label) orelse return error.ViewNotFound;
805
+ if (self.views[index].kind != .gpu_surface) return error.InvalidViewOptions;
806
+ return canvasSurfacePixelSize(canvasScreenshotSurfaceSize(&self.views[index]), normalizedCanvasPresentationScale(scale, 1));
807
+ }
808
+
809
+ fn canvasScreenshotSurfaceSize(view: anytype) geometry.SizeF {
810
+ return if (view.gpu_size.isEmpty()) view.frame.size() else view.gpu_size;
811
+ }
812
+
813
+ pub fn planCanvasFrameForView(self: *Runtime, index: usize, options: canvas.CanvasFrameOptions, storage: canvas.CanvasFrameStorage, record: bool) anyerror!canvas.CanvasFrame {
814
+ // Frame-profile `plan` stage: the whole render-plan cascade
815
+ // (batches, caches, text layout, diff). Recording plans only —
816
+ // diagnostic previews and screenshots re-plan without
817
+ // presenting and would double-count. No-op unless profiling
818
+ // is on.
819
+ const plan_begin = if (record) self.frame_profile.begin() else 0;
820
+ defer if (record) self.frame_profile.end(.plan, plan_begin);
821
+ // Launch laps (env-gated, once per process): bracket the
822
+ // startup frame's render-plan cascade so the launch timeline
823
+ // splits plan cost (text layout, caches, diff) from the
824
+ // reconcile/emit segment before it and the encode/present
825
+ // segment after it.
826
+ launch_timing.lapOnce("first_plan_begin");
827
+ defer launch_timing.lapOnce("first_plan_done");
828
+ var frame_options = options;
829
+ if (frame_options.surface_size.isEmpty()) {
830
+ frame_options.surface_size = if (self.views[index].gpu_size.isEmpty()) self.views[index].frame.size() else self.views[index].gpu_size;
831
+ }
832
+ // Runtime-registered images feed every view unless the caller
833
+ // supplied its own resource set: the CPU pixel paths
834
+ // (presentation, screenshots) and the GPU packet plan both
835
+ // read `image_resources` from the planned frame.
836
+ if (frame_options.image_resources.len == 0) {
837
+ frame_options.image_resources = self.registeredCanvasImages();
838
+ }
839
+ // Runtime-registered fonts feed every view the same way: the
840
+ // CPU pixel paths resolve registered font ids from the
841
+ // planned frame's `font_resources`.
842
+ if (frame_options.font_resources.len == 0) {
843
+ frame_options.font_resources = self.registeredCanvasFonts();
844
+ }
845
+ if (canvasFrameBudgetIsUnset(frame_options.budget)) {
846
+ frame_options.budget = self.views[index].canvas_frame_budget;
847
+ }
848
+ frame_options.previous_resource_cache = self.views[index].canvasFrameResourceCache();
849
+ frame_options.previous_pipeline_cache = self.views[index].canvasFramePipelineCache();
850
+ frame_options.previous_path_geometry_cache = self.views[index].canvasFramePathGeometryCache();
851
+ frame_options.previous_image_cache = self.views[index].canvasFrameImageCache();
852
+ frame_options.previous_layer_cache = self.views[index].canvasFrameLayerCache();
853
+ frame_options.previous_visual_effect_cache = self.views[index].canvasFrameVisualEffectCache();
854
+ frame_options.previous_glyph_atlas_cache = self.views[index].canvasFrameGlyphAtlasCache();
855
+ frame_options.previous_text_layout_cache = self.views[index].canvasFrameTextLayoutCache();
856
+ const scheduled_render_overrides = try self.views[index].sampleCanvasRenderAnimations(
857
+ frame_options.timestamp_ns,
858
+ &self.canvas_frame_render_override_samples,
859
+ );
860
+ const render_overrides = try mergeCanvasRenderOverrides(
861
+ scheduled_render_overrides,
862
+ frame_options.render_overrides,
863
+ &self.canvas_frame_render_override_combined,
864
+ );
865
+ if (frame_options.previous_render_overrides.len == 0) {
866
+ frame_options.previous_render_overrides = self.views[index].canvasFrameRenderOverrides();
867
+ }
868
+ frame_options.render_overrides = render_overrides;
869
+
870
+ const display_list = self.views[index].canvasDisplayList();
871
+ const canvas_changed = self.views[index].canvas_revision != self.views[index].presented_canvas_revision;
872
+ const canvas_surface_changed = !sizesEqual(self.views[index].presented_canvas_surface_size, frame_options.surface_size) or
873
+ self.views[index].presented_canvas_scale != frame_options.scale;
874
+ if (!frame_options.full_repaint and
875
+ self.views[index].presented_canvas_valid and
876
+ !canvas_changed and
877
+ !canvas_surface_changed and
878
+ frame_options.previous_render_overrides.len == 0 and
879
+ frame_options.render_overrides.len == 0)
880
+ {
881
+ const canvas_frame = canvas.CanvasFrame{
882
+ .frame_index = frame_options.frame_index,
883
+ .timestamp_ns = frame_options.timestamp_ns,
884
+ .surface_size = frame_options.surface_size,
885
+ .scale = frame_options.scale,
886
+ .display_list = display_list,
887
+ .image_resources = frame_options.image_resources,
888
+ .font_resources = frame_options.font_resources,
889
+ .changes = storage.changes[0..0],
890
+ .budget = frame_options.budget,
891
+ };
892
+ self.views[index].recordCanvasFrame(canvas_frame);
893
+ return canvas_frame;
894
+ }
895
+
896
+ var render_plan = try display_list.renderPlan(storage.render_commands);
897
+ const render_override_dirty_bounds = canvas.renderOverrideDirtyBounds(render_plan.commands, frame_options.previous_render_overrides, frame_options.render_overrides);
898
+ const render_animation_dirty_bounds = self.views[index].canvasRenderAnimationDirtyBoundsForOverrides(frame_options.previous_render_overrides, frame_options.render_overrides);
899
+ render_plan.bounds = canvas.applyRenderOverrides(storage.render_commands[0..render_plan.commandCount()], frame_options.render_overrides);
900
+ const batch_plan = try render_plan.batchPlan(storage.render_batches);
901
+ const pipeline_cache_plan = if (storage.pipeline_cache_entries.len == 0 and storage.pipeline_cache_actions.len == 0)
902
+ canvas.RenderPipelineCachePlan{}
903
+ else
904
+ try batch_plan.cachePlan(
905
+ frame_options.previous_pipeline_cache,
906
+ frame_options.frame_index,
907
+ storage.pipeline_cache_entries,
908
+ storage.pipeline_cache_actions,
909
+ );
910
+ const path_geometry_plan = if (storage.path_geometries.len == 0)
911
+ canvas.RenderPathGeometryPlan{}
912
+ else
913
+ try render_plan.pathGeometryPlan(storage.path_geometries);
914
+ const path_geometry_cache_plan = if (storage.path_geometry_cache_entries.len == 0 and storage.path_geometry_cache_actions.len == 0)
915
+ canvas.RenderPathGeometryCachePlan{}
916
+ else
917
+ try path_geometry_plan.cachePlan(
918
+ frame_options.previous_path_geometry_cache,
919
+ frame_options.frame_index,
920
+ storage.path_geometry_cache_entries,
921
+ storage.path_geometry_cache_actions,
922
+ );
923
+ const image_plan = if (storage.images.len == 0)
924
+ canvas.RenderImagePlan{}
925
+ else
926
+ try render_plan.imagePlanWithResources(frame_options.image_resources, storage.images);
927
+ const image_cache_plan = if (storage.image_cache_entries.len == 0 and storage.image_cache_actions.len == 0)
928
+ canvas.RenderImageCachePlan{}
929
+ else
930
+ try image_plan.cachePlan(
931
+ frame_options.previous_image_cache,
932
+ frame_options.frame_index,
933
+ storage.image_cache_entries,
934
+ storage.image_cache_actions,
935
+ );
936
+ const layer_plan = if (storage.layers.len == 0)
937
+ canvas.RenderLayerPlan{}
938
+ else
939
+ try render_plan.layerPlan(storage.layers);
940
+ const layer_cache_plan = if (storage.layer_cache_entries.len == 0 and storage.layer_cache_actions.len == 0)
941
+ canvas.RenderLayerCachePlan{}
942
+ else
943
+ try layer_plan.cachePlan(
944
+ frame_options.previous_layer_cache,
945
+ frame_options.frame_index,
946
+ storage.layer_cache_entries,
947
+ storage.layer_cache_actions,
948
+ );
949
+ const resource_plan = try display_list.resourcePlan(storage.resources);
950
+ const resource_cache_plan = try resource_plan.cachePlan(
951
+ frame_options.previous_resource_cache,
952
+ frame_options.frame_index,
953
+ storage.resource_cache_entries,
954
+ storage.resource_cache_actions,
955
+ );
956
+ const visual_effect_plan = if (storage.visual_effects.len == 0)
957
+ canvas.VisualEffectPlan{}
958
+ else
959
+ try display_list.visualEffectPlan(storage.visual_effects);
960
+ const visual_effect_cache_plan = if (storage.visual_effect_cache_entries.len == 0 and storage.visual_effect_cache_actions.len == 0)
961
+ canvas.VisualEffectCachePlan{}
962
+ else
963
+ try visual_effect_plan.cachePlan(
964
+ frame_options.previous_visual_effect_cache,
965
+ frame_options.frame_index,
966
+ storage.visual_effect_cache_entries,
967
+ storage.visual_effect_cache_actions,
968
+ );
969
+ const glyph_atlas_plan = try display_list.glyphAtlasPlan(storage.glyph_atlas_entries);
970
+ const glyph_atlas_cache_plan = try glyph_atlas_plan.cachePlanWithRetention(
971
+ frame_options.previous_glyph_atlas_cache,
972
+ frame_options.frame_index,
973
+ frame_options.glyph_atlas_cache_retention_frames,
974
+ storage.glyph_atlas_cache_entries,
975
+ storage.glyph_atlas_cache_actions,
976
+ );
977
+ const text_layout_plan = display_list.textLayoutPlan(frame_options.text_layout_options, storage.text_layout_plans, storage.text_layout_lines) catch |err| {
978
+ // Teach the fix at the failure site: the bare error
979
+ // name kills the frame without saying which budget bound
980
+ // it or where the headroom telemetry lives.
981
+ switch (err) {
982
+ error.TextLayoutPlanListFull => canvas_frame_log.warn(
983
+ "text layout plan capacity exceeded: the per-frame budget is {d} text runs (canvas_limits.max_canvas_text_layouts_per_view) - reduce visible draw_text commands or virtualize long text; snapshots report headroom as text_layout_plans=N/{d}",
984
+ .{ canvas_limits.max_canvas_text_layouts_per_view, canvas_limits.max_canvas_text_layouts_per_view },
985
+ ),
986
+ error.TextLayoutLineListFull => canvas_frame_log.warn(
987
+ "text layout line capacity exceeded: the per-frame budget is {d} wrapped lines across all text runs (canvas_limits.max_canvas_text_layout_lines_per_view) - clip or window long wrapped text; snapshots report headroom as text_layout_lines=N/{d}",
988
+ .{ canvas_limits.max_canvas_text_layout_lines_per_view, canvas_limits.max_canvas_text_layout_lines_per_view },
989
+ ),
990
+ else => {},
991
+ }
992
+ return err;
993
+ };
994
+ const text_layout_cache_plan = if (storage.text_layout_cache_entries.len == 0 and storage.text_layout_cache_actions.len == 0)
995
+ canvas.TextLayoutCachePlan{}
996
+ else
997
+ try text_layout_plan.cachePlanWithRetention(
998
+ frame_options.previous_text_layout_cache,
999
+ frame_options.frame_index,
1000
+ frame_options.text_layout_cache_retention_frames,
1001
+ storage.text_layout_cache_entries,
1002
+ storage.text_layout_cache_actions,
1003
+ );
1004
+
1005
+ const full_repaint = frame_options.full_repaint or
1006
+ !self.views[index].presented_canvas_valid or
1007
+ canvas_surface_changed or
1008
+ (canvas_changed and (self.views[index].presented_canvas_has_unkeyed or self.views[index].currentCanvasHasUnkeyed()));
1009
+ const changes = if (full_repaint)
1010
+ storage.changes[0..0]
1011
+ else
1012
+ try self.views[index].diffPresentedCanvasSummary(storage.changes);
1013
+ var dirty_rects: [canvas.max_canvas_frame_dirty_rects]geometry.RectF = undefined;
1014
+ var dirty_rect_count: usize = 0;
1015
+ const dirty_bounds = if (full_repaint)
1016
+ canvasFullRepaintBounds(frame_options.surface_size, render_plan.bounds)
1017
+ else dirty: {
1018
+ const overrides_dirty = unionRects(render_override_dirty_bounds, render_animation_dirty_bounds);
1019
+ // Msg rebuilds: the presented summary records ids and
1020
+ // bounds but not content, so a rebuild marks every keyed
1021
+ // command changed and the dirty rect degrades to the
1022
+ // window even when only a handful of commands differ.
1023
+ // When the view holds a valid retained baseline for this
1024
+ // exact surface, derive the dirty rect from the SAME
1025
+ // key+fingerprint edit script the patch present ships —
1026
+ // the changed commands' union (old and new extents), not
1027
+ // the view — and keep the per-change rect clusters so
1028
+ // far-apart changes present as a dirty rect LIST instead
1029
+ // of their bounding union. Refused refinements (no
1030
+ // baseline, unkeyable list, z-order shuffle of unchanged
1031
+ // commands) keep the conservative summary union below.
1032
+ // Deliberately NO small-list floor: every other
1033
+ // min_entries_for_index gate picks index vs linear scan
1034
+ // with byte-identical results, but skipping refinement
1035
+ // here changes the dirty AREA — a scene one command
1036
+ // under a floor would repaint the full window per click
1037
+ // (a measured ~17 ms of direct-command re-raster on a
1038
+ // 68-command dashboard) where the derived rect costs a
1039
+ // sub-millisecond sort over at most the retained-packet
1040
+ // command budget. Pixel-adopted baselines raise the
1041
+ // stakes further: a full-window repaint there means a
1042
+ // full-surface CPU raster AND a full-surface upload, so
1043
+ // refinement must run at any command count.
1044
+ if (canvas_changed and
1045
+ self.views[index].canvas_packet_baseline_valid and
1046
+ sizesEqual(self.views[index].canvas_packet_baseline_surface_size, frame_options.surface_size) and
1047
+ self.views[index].canvas_packet_baseline_scale == frame_options.scale)
1048
+ {
1049
+ if (gatherCanvasPacketCurrentCommandsFromPlan(render_plan.commands, frame_options.surface_size, render_plan.bounds)) |current| {
1050
+ if (canvasPacketPatchDirtyBounds(&self.views[index], current)) |patch_dirty| {
1051
+ var refined = patch_dirty;
1052
+ if (overrides_dirty) |overrides_rect| refined.add(overrides_rect);
1053
+ const clipped = clippedCanvasDirtyBounds(refined.bounds, frame_options.surface_size);
1054
+ // A list of one rect adds nothing over the
1055
+ // scissor; ship it only when it splits.
1056
+ if (clipped != null and refined.rect_count > 1) {
1057
+ for (refined.rects[0..refined.rect_count]) |rect| {
1058
+ const clipped_rect = clippedCanvasDirtyBounds(rect, frame_options.surface_size) orelse continue;
1059
+ dirty_rects[dirty_rect_count] = clipped_rect;
1060
+ dirty_rect_count += 1;
1061
+ }
1062
+ if (dirty_rect_count < 2) dirty_rect_count = 0;
1063
+ }
1064
+ break :dirty clipped;
1065
+ }
1066
+ }
1067
+ }
1068
+ break :dirty clippedCanvasDirtyBounds(unionRects(canvasDirtyBoundsFromChanges(changes), overrides_dirty), frame_options.surface_size);
1069
+ };
1070
+
1071
+ const canvas_frame = canvas.CanvasFrame{
1072
+ .frame_index = frame_options.frame_index,
1073
+ .timestamp_ns = frame_options.timestamp_ns,
1074
+ .surface_size = frame_options.surface_size,
1075
+ .scale = frame_options.scale,
1076
+ .full_repaint = full_repaint,
1077
+ .display_list = display_list,
1078
+ .render_plan = render_plan,
1079
+ .batch_plan = batch_plan,
1080
+ .pipeline_cache_plan = pipeline_cache_plan,
1081
+ .path_geometry_plan = path_geometry_plan,
1082
+ .path_geometry_cache_plan = path_geometry_cache_plan,
1083
+ .image_plan = image_plan,
1084
+ .image_cache_plan = image_cache_plan,
1085
+ .layer_plan = layer_plan,
1086
+ .layer_cache_plan = layer_cache_plan,
1087
+ .resource_plan = resource_plan,
1088
+ .resource_cache_plan = resource_cache_plan,
1089
+ .visual_effect_plan = visual_effect_plan,
1090
+ .visual_effect_cache_plan = visual_effect_cache_plan,
1091
+ .glyph_atlas_plan = glyph_atlas_plan,
1092
+ .glyph_atlas_cache_plan = glyph_atlas_cache_plan,
1093
+ .text_layout_plan = text_layout_plan,
1094
+ .text_layout_cache_plan = text_layout_cache_plan,
1095
+ .image_resources = frame_options.image_resources,
1096
+ .font_resources = frame_options.font_resources,
1097
+ .changes = changes,
1098
+ .dirty_bounds = dirty_bounds,
1099
+ .dirty_rects = dirty_rects,
1100
+ .dirty_rect_count = dirty_rect_count,
1101
+ .budget = frame_options.budget,
1102
+ };
1103
+ if (record) {
1104
+ try self.views[index].copyCanvasFramePipelineCache(canvas_frame.pipeline_cache_plan.entries);
1105
+ try self.views[index].copyCanvasFramePathGeometryCache(canvas_frame.path_geometry_cache_plan.entries);
1106
+ try self.views[index].copyCanvasFrameImageCache(canvas_frame.image_cache_plan.entries);
1107
+ try self.views[index].copyCanvasFrameLayerCache(canvas_frame.layer_cache_plan.entries);
1108
+ try self.views[index].copyCanvasFrameResourceCache(canvas_frame.resource_cache_plan.entries);
1109
+ try self.views[index].copyCanvasFrameVisualEffectCache(canvas_frame.visual_effect_cache_plan.entries);
1110
+ try self.views[index].copyCanvasFrameGlyphAtlasCache(canvas_frame.glyph_atlas_cache_plan.entries);
1111
+ try self.views[index].copyCanvasFrameTextLayoutCache(canvas_frame.text_layout_cache_plan.entries);
1112
+ try self.views[index].copyPresentedCanvasSummary(display_list, canvas_frame.surface_size, canvas_frame.scale);
1113
+ self.views[index].recordCanvasFrame(canvas_frame);
1114
+ try self.views[index].copyCanvasFrameRenderOverrides(frame_options.render_overrides);
1115
+ if (self.views[index].pruneCompletedNoopCanvasRenderAnimations(frame_options.timestamp_ns)) {
1116
+ self.views[index].compactCanvasFrameRenderOverrideNoops();
1117
+ }
1118
+ if (self.views[index].canvasRenderAnimationsActive(frame_options.timestamp_ns)) {
1119
+ self.invalidateFor(.state, self.views[index].frame);
1120
+ }
1121
+ } else {
1122
+ self.views[index].recordCanvasFrame(canvas_frame);
1123
+ }
1124
+ return canvas_frame;
1125
+ }
1126
+
1127
+ pub fn canvasFrameScratchStorage(self: *Runtime) canvas.CanvasFrameStorage {
1128
+ return .{
1129
+ .render_commands = &self.canvas_frame_render_commands,
1130
+ .render_batches = &self.canvas_frame_render_batches,
1131
+ .pipeline_cache_entries = &self.canvas_frame_pipeline_cache_entries,
1132
+ .pipeline_cache_actions = &self.canvas_frame_pipeline_cache_actions,
1133
+ .path_geometries = &self.canvas_frame_path_geometries,
1134
+ .path_geometry_cache_entries = &self.canvas_frame_path_geometry_cache_entries,
1135
+ .path_geometry_cache_actions = &self.canvas_frame_path_geometry_cache_actions,
1136
+ .images = &self.canvas_frame_images,
1137
+ .image_cache_entries = &self.canvas_frame_image_cache_entries,
1138
+ .image_cache_actions = &self.canvas_frame_image_cache_actions,
1139
+ .layers = &self.canvas_frame_layers,
1140
+ .layer_cache_entries = &self.canvas_frame_layer_cache_entries,
1141
+ .layer_cache_actions = &self.canvas_frame_layer_cache_actions,
1142
+ .resources = &self.canvas_frame_resources,
1143
+ .resource_cache_entries = &self.canvas_frame_resource_cache_entries,
1144
+ .resource_cache_actions = &self.canvas_frame_resource_cache_actions,
1145
+ .visual_effects = &self.canvas_frame_visual_effects,
1146
+ .visual_effect_cache_entries = &self.canvas_frame_visual_effect_cache_entries,
1147
+ .visual_effect_cache_actions = &self.canvas_frame_visual_effect_cache_actions,
1148
+ .glyph_atlas_entries = &self.canvas_frame_glyph_atlas_entries,
1149
+ .glyph_atlas_cache_entries = &self.canvas_frame_glyph_atlas_cache_entries,
1150
+ .glyph_atlas_cache_actions = &self.canvas_frame_glyph_atlas_cache_actions,
1151
+ .text_layout_plans = &canvas_frame_text_layout_plans_scratch,
1152
+ .text_layout_lines = &canvas_frame_text_layout_lines_scratch,
1153
+ .text_layout_cache_entries = &canvas_frame_text_layout_cache_entries_scratch,
1154
+ .text_layout_cache_actions = &canvas_frame_text_layout_cache_actions_scratch,
1155
+ .changes = &self.canvas_frame_changes,
1156
+ };
1157
+ }
1158
+
1159
+ pub fn gpuSurfaceFrame(self: *const Runtime, window_id: platform.WindowId, label: []const u8) anyerror!platform.GpuFrame {
1160
+ try validateRuntimeViewParent(self, window_id);
1161
+ try validateViewLabel(label);
1162
+ const index = runtimeFindViewIndex(self, window_id, label) orelse return error.ViewNotFound;
1163
+ return self.views[index].info().gpuFrame() orelse error.InvalidViewOptions;
1164
+ }
1165
+
1166
+ pub fn setCanvasFrameBudget(self: *Runtime, window_id: platform.WindowId, label: []const u8, budget: canvas.CanvasFrameBudget) anyerror!platform.ViewInfo {
1167
+ try validateRuntimeViewParent(self, window_id);
1168
+ try validateViewLabel(label);
1169
+ const index = runtimeFindViewIndex(self, window_id, label) orelse return error.ViewNotFound;
1170
+ if (self.views[index].kind != .gpu_surface) return error.InvalidViewOptions;
1171
+ self.views[index].canvas_frame_budget = budget;
1172
+ self.views[index].refreshCanvasFrameBudgetStatus();
1173
+ return self.views[index].info();
1174
+ }
1175
+
1176
+ pub fn setGpuSurfaceInputLatencyBudget(self: *Runtime, window_id: platform.WindowId, label: []const u8, budget_ns: u64) anyerror!platform.ViewInfo {
1177
+ try validateRuntimeViewParent(self, window_id);
1178
+ try validateViewLabel(label);
1179
+ const index = runtimeFindViewIndex(self, window_id, label) orelse return error.ViewNotFound;
1180
+ if (self.views[index].kind != .gpu_surface) return error.InvalidViewOptions;
1181
+ self.views[index].gpu_input_latency_budget_ns = budget_ns;
1182
+ self.views[index].gpu_input_latency_budget_custom = true;
1183
+ self.views[index].refreshGpuSurfaceInputLatencyBudgetStatus();
1184
+ return self.views[index].info();
1185
+ }
1186
+
1187
+ pub fn requestCanvasFrameForView(self: *Runtime, view_index: usize) anyerror!void {
1188
+ if (view_index >= self.view_count) return;
1189
+ if (self.views[view_index].kind != .gpu_surface) return;
1190
+ self.options.platform.services.requestGpuSurfaceFrame(
1191
+ self.views[view_index].window_id,
1192
+ self.views[view_index].label,
1193
+ ) catch |err| switch (err) {
1194
+ error.UnsupportedService => return,
1195
+ else => return err,
1196
+ };
1197
+ // A frame event is now coming for this view — the deferred
1198
+ // accessibility settle logic keys off this.
1199
+ self.views[view_index].gpu_canvas_frame_requested = true;
1200
+ }
1201
+
1202
+ pub fn invalidateForCanvasChanges(self: *Runtime, view_frame: geometry.RectF, changes: []const canvas.DiffChange) void {
1203
+ var emitted_dirty_region = false;
1204
+ for (changes) |change| {
1205
+ const local_dirty = change.dirty_bounds orelse continue;
1206
+ if (canvasDirtyRegionForView(view_frame, local_dirty)) |dirty_region| {
1207
+ self.invalidateFor(.state, dirty_region);
1208
+ emitted_dirty_region = true;
1209
+ }
1210
+ }
1211
+ if (!emitted_dirty_region and changes.len > 0) self.invalidateFor(.state, view_frame);
1212
+ }
1213
+ };
1214
+ }
1215
+
1216
+ /// What to record when a packet attempt fails: the reason plus the
1217
+ /// overflow byte math or the offending command kind, whichever applies.
1218
+ const CanvasPacketRefusal = struct {
1219
+ reason: platform.GpuPresentFallbackReason,
1220
+ needed_bytes: usize = 0,
1221
+ limit_bytes: usize = 0,
1222
+ command_kind: []const u8 = "",
1223
+ };
1224
+
1225
+ /// Edit-script size of the last patch encode, for telemetry.
1226
+ const CanvasPacketPatchStats = struct {
1227
+ upsert_count: usize = 0,
1228
+ evict_count: usize = 0,
1229
+ };
1230
+
1231
+ /// Stamp `gpu_input_latency` at the RESPONDING present's completion:
1232
+ /// the present call above just returned synchronously, so the wall
1233
+ /// clock NOW (the domain every host and automation input timestamp
1234
+ /// uses) is the moment the input's pixels reached the swapchain. The
1235
+ /// paced completion event that used to stamp this arrives up to a
1236
+ /// frame interval later and measured the pacing channel, not the
1237
+ /// glass; it remains the fallback for inputs that present nothing.
1238
+ fn recordCanvasPresentInputLatency(view: anytype) void {
1239
+ if (view.gpu_pending_input_timestamp_ns == 0) return;
1240
+ view.recordGpuSurfaceInputLatencyForFrame(runtime_clock.timestampToU64(runtime_clock.nowNanoseconds()));
1241
+ }
1242
+
1243
+ /// Build the frame's CURRENT keyed command list — every supported render
1244
+ /// command intersecting the full-repaint bounds, in draw order, with its
1245
+ /// retain key and content fingerprint. This is the exact set a full
1246
+ /// keyed present ships (and the host retains), so patches derived from
1247
+ /// it can never disagree with a full re-present. Returns null when the
1248
+ /// frame cannot ride the retained protocol: an unsupported command
1249
+ /// anywhere in the FULL list (a scissor subset might hide it), more
1250
+ /// commands than the retained budget
1251
+ /// (`canvas_limits.max_canvas_retained_packet_commands_per_view`), or
1252
+ /// duplicate retain keys (which would corrupt a keyed dictionary) — those
1253
+ /// frames present through the non-retained encoding instead.
1254
+ fn gatherCanvasPacketCurrentCommands(canvas_frame: canvas.CanvasFrame) ?[]const CanvasPacketCurrentCommand {
1255
+ return gatherCanvasPacketCurrentCommandsFromPlan(canvas_frame.render_plan.commands, canvas_frame.surface_size, canvas_frame.render_plan.bounds);
1256
+ }
1257
+
1258
+ /// Plan-time twin of `gatherCanvasPacketCurrentCommands`: the frame
1259
+ /// planner derives Msg-rebuild dirty bounds from the same keyed list
1260
+ /// before the `CanvasFrame` value exists. Same inputs, same scratch,
1261
+ /// byte-identical output.
1262
+ fn gatherCanvasPacketCurrentCommandsFromPlan(render_commands: []const canvas.RenderCommand, surface_size: geometry.SizeF, render_bounds: ?geometry.RectF) ?[]const CanvasPacketCurrentCommand {
1263
+ const full_bounds = canvasFullRepaintBounds(surface_size, render_bounds) orelse return null;
1264
+ var count: usize = 0;
1265
+ for (render_commands, 0..) |command, index| {
1266
+ if (!canvas.renderCommandIntersectsDirtyBounds(command, full_bounds)) continue;
1267
+ const gpu_command = canvas.canvasGpuCommandFromRenderCommand(command, index);
1268
+ if (!gpu_command.supported()) return null;
1269
+ if (count >= canvas_packet_current_scratch.len) return null;
1270
+ const fingerprint = canvas.canvasGpuCommandFingerprint(gpu_command);
1271
+ canvas_packet_current_scratch[count] = .{
1272
+ .key = canvas.canvasGpuPacketCommandKey(gpu_command, fingerprint),
1273
+ .fingerprint = fingerprint,
1274
+ .render_index = @intCast(index),
1275
+ .bounds = command.bounds,
1276
+ };
1277
+ count += 1;
1278
+ }
1279
+ const sorted = canvas_packet_current_sort_scratch[0..count];
1280
+ for (sorted, 0..) |*slot, index| slot.* = @intCast(index);
1281
+ std.sort.pdq(u32, sorted, @as([]const CanvasPacketCurrentCommand, canvas_packet_current_scratch[0..count]), canvasPacketCurrentKeyLessThan);
1282
+ var index: usize = 1;
1283
+ while (index < count) : (index += 1) {
1284
+ if (canvas_packet_current_scratch[sorted[index - 1]].key == canvas_packet_current_scratch[sorted[index]].key) return null;
1285
+ }
1286
+ return canvas_packet_current_scratch[0..count];
1287
+ }
1288
+
1289
+ fn canvasPacketCurrentKeyLessThan(current: []const CanvasPacketCurrentCommand, a: u32, b: u32) bool {
1290
+ return current[a].key < current[b].key;
1291
+ }
1292
+
1293
+ fn canvasPacketBaselineKeyLessThan(keys: []const u64, a: u32, b: u32) bool {
1294
+ return keys[a] < keys[b];
1295
+ }
1296
+
1297
+ /// Binary search over `sorted` (an index array ordered by key) for `key`;
1298
+ /// returns the baseline index holding it.
1299
+ fn findCanvasPacketBaselineIndex(keys: []const u64, sorted: []const u32, key: u64) ?usize {
1300
+ var low: usize = 0;
1301
+ var high: usize = sorted.len;
1302
+ while (low < high) {
1303
+ const mid = low + (high - low) / 2;
1304
+ const candidate = keys[sorted[mid]];
1305
+ if (candidate == key) return sorted[mid];
1306
+ if (candidate < key) low = mid + 1 else high = mid;
1307
+ }
1308
+ return null;
1309
+ }
1310
+
1311
+ /// Diff the frame's current keyed list against the view's retained
1312
+ /// baseline: fills the matched/upsert scratch flags (which the patch
1313
+ /// encoder reads) and returns the edit counts, so callers can decide
1314
+ /// patch-vs-full BEFORE paying for the encode.
1315
+ fn computeCanvasPacketPatchStats(view: anytype, current: []const CanvasPacketCurrentCommand) CanvasPacketPatchStats {
1316
+ const baseline_count = view.canvas_packet_baseline_count;
1317
+ const baseline_keys = view.canvas_packet_baseline_keys[0..baseline_count];
1318
+ const baseline_fingerprints = view.canvas_packet_baseline_fingerprints[0..baseline_count];
1319
+
1320
+ const baseline_sorted = canvas_packet_baseline_sort_scratch[0..baseline_count];
1321
+ for (baseline_sorted, 0..) |*slot, index| slot.* = @intCast(index);
1322
+ std.sort.pdq(u32, baseline_sorted, @as([]const u64, baseline_keys), canvasPacketBaselineKeyLessThan);
1323
+ const matched = canvas_packet_baseline_matched_scratch[0..baseline_count];
1324
+ @memset(matched, false);
1325
+ const upserts = canvas_packet_upsert_scratch[0..current.len];
1326
+
1327
+ var stats = CanvasPacketPatchStats{};
1328
+ for (current, 0..) |entry, index| {
1329
+ upserts[index] = true;
1330
+ if (findCanvasPacketBaselineIndex(baseline_keys, baseline_sorted, entry.key)) |baseline_index| {
1331
+ matched[baseline_index] = true;
1332
+ if (baseline_fingerprints[baseline_index] == entry.fingerprint) upserts[index] = false;
1333
+ }
1334
+ if (upserts[index]) stats.upsert_count += 1;
1335
+ }
1336
+ for (matched) |flag| {
1337
+ if (!flag) stats.evict_count += 1;
1338
+ }
1339
+ return stats;
1340
+ }
1341
+
1342
+ /// The pixels the retained-patch edit script can touch, derived from
1343
+ /// the SAME key+fingerprint diff the patch present ships: the union of
1344
+ /// every upserted command's current bounds, the baseline bounds of the
1345
+ /// key it replaces (content changed — the OLD pixels repaint too), and
1346
+ /// every evicted baseline entry's bounds (vacated pixels). `.{ .bounds
1347
+ /// = null }` means the edit script is empty — nothing visual changed.
1348
+ /// `rects` refines the union into up to `max_canvas_frame_dirty_rects`
1349
+ /// clusters so far-apart small changes (a switch plus a status line)
1350
+ /// stay two small repaints instead of a window-sized one. Returns null
1351
+ /// (refinement refused, caller keeps its conservative dirty) when
1352
+ /// unchanged commands moved relative to each other in draw order: a
1353
+ /// z-order shuffle changes pixels only where commands overlap, which a
1354
+ /// bounds union of the CHANGED set cannot name.
1355
+ const CanvasPacketPatchDirty = struct {
1356
+ bounds: ?geometry.RectF = null,
1357
+ rects: [canvas.max_canvas_frame_dirty_rects]geometry.RectF = undefined,
1358
+ rect_count: usize = 0,
1359
+
1360
+ /// Fold `rect` in: union with the first intersecting cluster, a new
1361
+ /// cluster while slots remain, else the cluster whose union grows
1362
+ /// the least. `bounds` stays the union of everything added.
1363
+ fn add(self: *CanvasPacketPatchDirty, rect: geometry.RectF) void {
1364
+ const normalized = rect.normalized();
1365
+ if (normalized.isEmpty()) return;
1366
+ self.bounds = unionRects(self.bounds, normalized);
1367
+ for (self.rects[0..self.rect_count]) |*cluster| {
1368
+ if (cluster.intersects(normalized)) {
1369
+ cluster.* = geometry.RectF.unionWith(cluster.*, normalized);
1370
+ return;
1371
+ }
1372
+ }
1373
+ if (self.rect_count < self.rects.len) {
1374
+ self.rects[self.rect_count] = normalized;
1375
+ self.rect_count += 1;
1376
+ return;
1377
+ }
1378
+ var best_index: usize = 0;
1379
+ var best_cost: f32 = std.math.floatMax(f32);
1380
+ for (self.rects[0..self.rect_count], 0..) |cluster, index| {
1381
+ const merged = geometry.RectF.unionWith(cluster, normalized);
1382
+ const cost = merged.width * merged.height - cluster.width * cluster.height;
1383
+ if (cost < best_cost) {
1384
+ best_cost = cost;
1385
+ best_index = index;
1386
+ }
1387
+ }
1388
+ self.rects[best_index] = geometry.RectF.unionWith(self.rects[best_index], normalized);
1389
+ }
1390
+ };
1391
+
1392
+ fn canvasPacketPatchDirtyBounds(view: anytype, current: []const CanvasPacketCurrentCommand) ?CanvasPacketPatchDirty {
1393
+ const baseline_count = view.canvas_packet_baseline_count;
1394
+ const baseline_keys = view.canvas_packet_baseline_keys[0..baseline_count];
1395
+ const baseline_fingerprints = view.canvas_packet_baseline_fingerprints[0..baseline_count];
1396
+ const baseline_bounds = view.canvas_packet_baseline_bounds[0..baseline_count];
1397
+
1398
+ const baseline_sorted = canvas_packet_baseline_sort_scratch[0..baseline_count];
1399
+ for (baseline_sorted, 0..) |*slot, index| slot.* = @intCast(index);
1400
+ std.sort.pdq(u32, baseline_sorted, @as([]const u64, baseline_keys), canvasPacketBaselineKeyLessThan);
1401
+ const matched = canvas_packet_baseline_matched_scratch[0..baseline_count];
1402
+ const stable = canvas_packet_baseline_stable_scratch[0..baseline_count];
1403
+ @memset(matched, false);
1404
+ @memset(stable, false);
1405
+
1406
+ var dirty = CanvasPacketPatchDirty{};
1407
+ for (current, 0..) |entry, index| {
1408
+ canvas_packet_upsert_scratch[index] = true;
1409
+ if (findCanvasPacketBaselineIndex(baseline_keys, baseline_sorted, entry.key)) |baseline_index| {
1410
+ matched[baseline_index] = true;
1411
+ if (baseline_fingerprints[baseline_index] == entry.fingerprint) {
1412
+ stable[baseline_index] = true;
1413
+ canvas_packet_upsert_scratch[index] = false;
1414
+ continue;
1415
+ }
1416
+ dirty.add(baseline_bounds[baseline_index]);
1417
+ }
1418
+ dirty.add(entry.bounds);
1419
+ }
1420
+ for (matched, 0..) |flag, index| {
1421
+ if (!flag) dirty.add(baseline_bounds[index]);
1422
+ }
1423
+
1424
+ // Order guard: the unchanged (stable) keys must appear in the same
1425
+ // relative draw order on both sides, or overlap-dependent pixels
1426
+ // outside the union may change.
1427
+ var baseline_walk: usize = 0;
1428
+ for (current, 0..) |entry, index| {
1429
+ if (canvas_packet_upsert_scratch[index]) continue;
1430
+ while (baseline_walk < baseline_count and !stable[baseline_walk]) baseline_walk += 1;
1431
+ if (baseline_walk >= baseline_count or baseline_keys[baseline_walk] != entry.key) return null;
1432
+ baseline_walk += 1;
1433
+ }
1434
+
1435
+ return dirty;
1436
+ }
1437
+
1438
+ /// Encode the incremental `patch` present: evicts (baseline keys gone
1439
+ /// from the current list), keyed upserts (new or fingerprint-changed
1440
+ /// commands, re-encoded), and the full draw-order vector. Unchanged
1441
+ /// commands are never re-encoded — for text runs that skips
1442
+ /// `layoutTextRun` entirely, which is most of what a transcript frame
1443
+ /// used to pay. Reads the scratch flags `computeCanvasPacketPatchStats`
1444
+ /// filled for the same `current` list. Errors are overflow of the
1445
+ /// caller's transport buffer.
1446
+ fn writeCanvasPacketPatchBinary(
1447
+ view: anytype,
1448
+ canvas_frame: canvas.CanvasFrame,
1449
+ packet: canvas.CanvasGpuPacket,
1450
+ current: []const CanvasPacketCurrentCommand,
1451
+ stats: CanvasPacketPatchStats,
1452
+ writer: *std.Io.Writer,
1453
+ ) !void {
1454
+ const baseline_count = view.canvas_packet_baseline_count;
1455
+ const baseline_keys = view.canvas_packet_baseline_keys[0..baseline_count];
1456
+ const matched = canvas_packet_baseline_matched_scratch[0..baseline_count];
1457
+ const upserts = canvas_packet_upsert_scratch[0..current.len];
1458
+
1459
+ try canvas.writeCanvasGpuPacketBinaryHeader(
1460
+ canvas.binary_packet_load_action_patch,
1461
+ view.canvas_packet_generation,
1462
+ packet.scissor,
1463
+ canvas_frame.dirtyRects(),
1464
+ packet.images,
1465
+ packet.image_actions,
1466
+ writer,
1467
+ );
1468
+ try writer.writeInt(u32, @intCast(stats.evict_count), .little);
1469
+ for (matched, 0..) |flag, index| {
1470
+ if (!flag) try writer.writeInt(u64, baseline_keys[index], .little);
1471
+ }
1472
+ try writer.writeInt(u32, @intCast(stats.upsert_count), .little);
1473
+ const render_commands = canvas_frame.render_plan.commands;
1474
+ for (current, 0..) |entry, index| {
1475
+ if (!upserts[index]) continue;
1476
+ const command = canvas.canvasGpuCommandFromRenderCommand(render_commands[entry.render_index], entry.render_index);
1477
+ try canvas.writeCanvasGpuCommandBinaryKeyed(entry.key, command, writer);
1478
+ }
1479
+ try writer.writeInt(u32, @intCast(current.len), .little);
1480
+ for (current) |entry| try writer.writeInt(u64, entry.key, .little);
1481
+ }
1482
+
1483
+ /// Encode the FULL keyed present that (re)builds the host's retained
1484
+ /// command dictionary: a `clear` over the full-repaint bounds carrying
1485
+ /// the whole keyed command list under `generation`. Byte-identical
1486
+ /// content whether it is a first baseline or a resync, which is what the
1487
+ /// golden patch-vs-full equivalence test compares against.
1488
+ fn writeCanvasPacketFullBinary(
1489
+ canvas_frame: canvas.CanvasFrame,
1490
+ packet: canvas.CanvasGpuPacket,
1491
+ current: []const CanvasPacketCurrentCommand,
1492
+ generation: u64,
1493
+ writer: *std.Io.Writer,
1494
+ ) !void {
1495
+ const scissor = canvasFullRepaintBounds(canvas_frame.surface_size, canvas_frame.render_plan.bounds);
1496
+ // Load-action wire code 2 = clear (see serialization.zig's layout).
1497
+ try canvas.writeCanvasGpuPacketBinaryHeader(2, generation, scissor, &.{}, packet.images, packet.image_actions, writer);
1498
+ try writer.writeInt(u32, @intCast(current.len), .little);
1499
+ const render_commands = canvas_frame.render_plan.commands;
1500
+ for (current) |entry| {
1501
+ const command = canvas.canvasGpuCommandFromRenderCommand(render_commands[entry.render_index], entry.render_index);
1502
+ try canvas.writeCanvasGpuCommandBinaryKeyed(entry.key, command, writer);
1503
+ }
1504
+ }
1505
+
1506
+ /// Byte size the overflowing full keyed encode actually needed, measured
1507
+ /// with a discarding writer — overflow-path diagnostics only.
1508
+ fn canvasPacketFullBinaryByteSize(
1509
+ canvas_frame: canvas.CanvasFrame,
1510
+ packet: canvas.CanvasGpuPacket,
1511
+ current: []const CanvasPacketCurrentCommand,
1512
+ generation: u64,
1513
+ ) usize {
1514
+ var trailing: [128]u8 = undefined;
1515
+ var discarding = std.Io.Writer.Discarding.init(&trailing);
1516
+ writeCanvasPacketFullBinary(canvas_frame, packet, current, generation, &discarding.writer) catch return 0;
1517
+ return @intCast(discarding.fullCount());
1518
+ }
1519
+
1520
+ /// A successful retained present (full or patch) makes `current` the
1521
+ /// view's baseline: the engine-side mirror of what the host now retains.
1522
+ fn adoptCanvasPacketBaseline(view: anytype, current: []const CanvasPacketCurrentCommand, packet: canvas.CanvasGpuPacket) void {
1523
+ adoptCanvasBaselineEntries(view, current, packet.surface_size, packet.scale);
1524
+ view.canvas_packet_baseline_pixels = false;
1525
+ }
1526
+
1527
+ /// The pixel-present twin of `adoptCanvasPacketBaseline`
1528
+ /// (`Options.pixel_present_retained_baseline` hosts): the mirror now
1529
+ /// describes what the presented PIXEL buffer shows. Marked so the packet
1530
+ /// patch gate refuses it — only the frame planner's dirty-bounds
1531
+ /// refinement may consume a pixel-adopted baseline.
1532
+ fn adoptCanvasPixelPresentBaseline(view: anytype, current: []const CanvasPacketCurrentCommand, surface_size: geometry.SizeF, scale: f32) void {
1533
+ adoptCanvasBaselineEntries(view, current, surface_size, scale);
1534
+ view.canvas_packet_baseline_pixels = true;
1535
+ }
1536
+
1537
+ fn adoptCanvasBaselineEntries(view: anytype, current: []const CanvasPacketCurrentCommand, surface_size: geometry.SizeF, scale: f32) void {
1538
+ for (current, 0..) |entry, index| {
1539
+ view.canvas_packet_baseline_keys[index] = entry.key;
1540
+ view.canvas_packet_baseline_fingerprints[index] = entry.fingerprint;
1541
+ view.canvas_packet_baseline_bounds[index] = entry.bounds;
1542
+ }
1543
+ view.canvas_packet_baseline_count = current.len;
1544
+ view.canvas_packet_baseline_surface_size = surface_size;
1545
+ view.canvas_packet_baseline_scale = scale;
1546
+ view.canvas_packet_baseline_valid = true;
1547
+ }
1548
+
1549
+ /// Telemetry for packet presents that moved the whole frame (non-retained
1550
+ /// binary and JSON): mode `full`, no patch bytes.
1551
+ fn recordCanvasPacketFullPresent(view: anytype) void {
1552
+ view.gpu_present_packet_mode = .full;
1553
+ view.gpu_present_patch_bytes = 0;
1554
+ view.gpu_present_patch_upsert_count = 0;
1555
+ view.gpu_present_patch_evict_count = 0;
1556
+ }
1557
+
1558
+ /// Emit the rate-limited fallback diagnostic on the first fallback, on
1559
+ /// every reason change, and every this-many fallback frames while the
1560
+ /// reason holds — loud enough to notice a steady oscillation in a debug
1561
+ /// build, quiet enough that a 60 fps fallback loop cannot flood stderr
1562
+ /// (one line every ~2 s).
1563
+ const canvas_packet_fallback_log_interval_frames: usize = 120;
1564
+
1565
+ const CanvasPacketEncoding = enum { json, binary };
1566
+
1567
+ /// Full encoded size of `packet` in the given encoding, measured with a
1568
+ /// discarding writer — used only on the overflow path to report how many
1569
+ /// bytes the frame actually needed against the transport limit.
1570
+ fn canvasPacketEncodedByteSize(packet: canvas.CanvasGpuPacket, encoding: CanvasPacketEncoding) usize {
1571
+ var trailing: [128]u8 = undefined;
1572
+ var discarding = std.Io.Writer.Discarding.init(&trailing);
1573
+ switch (encoding) {
1574
+ .json => packet.writeJson(&discarding.writer) catch return 0,
1575
+ .binary => packet.writeBinary(&discarding.writer) catch return 0,
1576
+ }
1577
+ return @intCast(discarding.fullCount());
1578
+ }
1579
+
1580
+ /// Name of the first display-list command the packet planner could not
1581
+ /// represent — the plan keeps the source command at `command_index`, so
1582
+ /// the diagnostic names the author-facing kind (`draw_text`, ...), not
1583
+ /// the packet's opaque `unsupported` tag.
1584
+ fn firstUnsupportedCommandName(canvas_frame: canvas.CanvasFrame, packet: canvas.CanvasGpuPacket) []const u8 {
1585
+ for (packet.commands) |command| {
1586
+ if (command.supported()) continue;
1587
+ const render_commands = canvas_frame.render_plan.commands;
1588
+ if (command.command_index < render_commands.len) {
1589
+ return @tagName(render_commands[command.command_index].command);
1590
+ }
1591
+ return @tagName(command.kind);
1592
+ }
1593
+ return "";
1594
+ }
1595
+
1596
+ /// Record WHY a packet attempt failed on the view (reason, overflow byte
1597
+ /// math, offending command kind, and a running fallback-frame counter
1598
+ /// that never resets while the view is open), then emit the rate-limited
1599
+ /// debug diagnostic. Every packet-attempt failure funnels through here so
1600
+ /// no fallback is ever silent again: automation snapshots surface the
1601
+ /// fields as `present_fallback=...` on the view line.
1602
+ fn recordCanvasPacketFallback(self: anytype, window_id: platform.WindowId, label: []const u8, refusal: CanvasPacketRefusal) void {
1603
+ const index = runtimeFindViewIndex(self, window_id, label) orelse return;
1604
+ const view = &self.views[index];
1605
+ const reason_changed = view.gpu_present_fallback_reason != refusal.reason;
1606
+ view.gpu_present_fallback_reason = refusal.reason;
1607
+ view.gpu_present_fallback_needed_bytes = refusal.needed_bytes;
1608
+ view.gpu_present_fallback_limit_bytes = refusal.limit_bytes;
1609
+ const kind_len = @min(refusal.command_kind.len, view.gpu_present_fallback_command_kind_storage.len);
1610
+ @memcpy(view.gpu_present_fallback_command_kind_storage[0..kind_len], refusal.command_kind[0..kind_len]);
1611
+ view.gpu_present_fallback_command_kind_len = kind_len;
1612
+ view.gpu_present_fallback_frame_count += 1;
1613
+
1614
+ const should_log = view.gpu_present_fallback_frame_count == 1 or
1615
+ reason_changed or
1616
+ view.gpu_present_fallback_frame_count - view.gpu_present_fallback_logged_count >= canvas_packet_fallback_log_interval_frames;
1617
+ if (!should_log) return;
1618
+ view.gpu_present_fallback_logged_count = view.gpu_present_fallback_frame_count;
1619
+ canvas_frame_log.debug(
1620
+ "gpu packet present fell back to the CPU pixel path for view \"{s}\": reason={s} needed={d}B limit={d}B command={s} fallback_frames={d} - the pixel path rasterizes text and shapes differently, so a steady fallback reads as flickering glyphs; snapshots carry the same fields as present_fallback= on the view line",
1621
+ .{
1622
+ label,
1623
+ @tagName(refusal.reason),
1624
+ refusal.needed_bytes,
1625
+ refusal.limit_bytes,
1626
+ refusal.command_kind,
1627
+ view.gpu_present_fallback_frame_count,
1628
+ },
1629
+ );
1630
+ }
1631
+
1632
+ /// A successful packet present clears the sticky reason and details; the
1633
+ /// cumulative fallback-frame counter deliberately survives, so snapshots
1634
+ /// taken on a healthy frame still expose that the view has been
1635
+ /// oscillating.
1636
+ fn clearCanvasPacketFallback(view: anytype) void {
1637
+ view.gpu_present_fallback_reason = .none;
1638
+ view.gpu_present_fallback_needed_bytes = 0;
1639
+ view.gpu_present_fallback_limit_bytes = 0;
1640
+ view.gpu_present_fallback_command_kind_len = 0;
1641
+ }
1642
+
1643
+ fn validateCanvasRenderAnimations(animations: []const canvas.CanvasRenderAnimation) !void {
1644
+ if (animations.len > max_canvas_render_animations_per_view) return error.RenderAnimationListFull;
1645
+ for (animations) |animation| {
1646
+ if (animation.id == 0) return error.InvalidViewOptions;
1647
+ }
1648
+ }
1649
+
1650
+ fn validateRuntimeViewParent(self: anytype, window_id: platform.WindowId) !void {
1651
+ const index = runtimeFindWindowIndexById(self, window_id) orelse return error.WindowNotFound;
1652
+ if (!self.windows[index].info.open) return error.WindowNotFound;
1653
+ }
1654
+
1655
+ fn runtimeFindWindowIndexById(self: anytype, id: platform.WindowId) ?usize {
1656
+ for (self.windows[0..self.window_count], 0..) |window, index| {
1657
+ if (window.info.id == id) return index;
1658
+ }
1659
+ return null;
1660
+ }
1661
+
1662
+ fn runtimeFindViewIndex(self: anytype, window_id: platform.WindowId, label: []const u8) ?usize {
1663
+ for (self.views[0..self.view_count], 0..) |*view, index| {
1664
+ if (view.open and view.window_id == window_id and std.mem.eql(u8, view.label, label)) return index;
1665
+ }
1666
+ return null;
1667
+ }
1668
+
1669
+ fn canvasDirtyRegionForView(view_frame: geometry.RectF, local_dirty: geometry.RectF) ?geometry.RectF {
1670
+ const normalized_view = view_frame.normalized();
1671
+ const surface_bounds = geometry.RectF.init(0, 0, normalized_view.width, normalized_view.height);
1672
+ const clipped = geometry.RectF.intersection(surface_bounds, local_dirty.normalized());
1673
+ if (clipped.isEmpty()) return null;
1674
+ return clipped.translate(.{ .dx = normalized_view.x, .dy = normalized_view.y });
1675
+ }
1676
+
1677
+ /// The view-local dirty bounds replacing the animation set can touch NOW:
1678
+ /// every command a previously APPLIED override moved (it may snap back)
1679
+ /// plus every command a new animation targets, each widened by the
1680
+ /// animation's from/to transforms (and the circumscribed square of a
1681
+ /// rotation about its center). Null when no targeted command exists in
1682
+ /// the current display list — the caller stays loud with the full view.
1683
+ fn canvasRenderAnimationScheduleDirtyBounds(view: anytype, animations: []const canvas.CanvasRenderAnimation) ?geometry.RectF {
1684
+ const display_list = view.canvasDisplayList();
1685
+ var bounds: ?geometry.RectF = null;
1686
+ var found_any = false;
1687
+
1688
+ for (view.canvas_frame_render_overrides[0..view.canvas_frame_render_override_count]) |override| {
1689
+ const rect = canvasCommandBoundsById(display_list, override.id) orelse continue;
1690
+ found_any = true;
1691
+ bounds = unionRects(bounds, rect);
1692
+ if (override.transform) |transform| bounds = unionRects(bounds, transform.transformRect(rect));
1693
+ }
1694
+
1695
+ for (animations) |animation| {
1696
+ const rect = canvasCommandBoundsById(display_list, animation.id) orelse continue;
1697
+ found_any = true;
1698
+ bounds = unionRects(bounds, rect);
1699
+ if (animation.from_transform) |transform| bounds = unionRects(bounds, transform.transformRect(rect));
1700
+ if (animation.to_transform) |transform| bounds = unionRects(bounds, transform.transformRect(rect));
1701
+ if (animation.from_rotation != null or animation.to_rotation != null) {
1702
+ bounds = unionRects(bounds, canvasRotationCircumscribedBounds(rect, animation.rotation_center));
1703
+ }
1704
+ }
1705
+
1706
+ if (!found_any) return null;
1707
+ return bounds;
1708
+ }
1709
+
1710
+ fn canvasCommandBoundsById(display_list: canvas.DisplayList, id: canvas.ObjectId) ?geometry.RectF {
1711
+ if (id == 0) return null;
1712
+ const command_ref = display_list.findCommandById(id) orelse return null;
1713
+ return command_ref.command.bounds();
1714
+ }
1715
+
1716
+ /// Every pose of `rect` rotating about `center` stays inside the square
1717
+ /// circumscribing the farthest corner — the conservative dirty extent of
1718
+ /// a rotation animation.
1719
+ fn canvasRotationCircumscribedBounds(rect: geometry.RectF, center: geometry.PointF) geometry.RectF {
1720
+ const normalized = rect.normalized();
1721
+ const corners = [_]geometry.PointF{
1722
+ normalized.topLeft(),
1723
+ normalized.topRight(),
1724
+ normalized.bottomLeft(),
1725
+ normalized.bottomRight(),
1726
+ };
1727
+ var radius: f32 = 0;
1728
+ for (corners) |corner| {
1729
+ const dx = corner.x - center.x;
1730
+ const dy = corner.y - center.y;
1731
+ radius = @max(radius, @sqrt(dx * dx + dy * dy));
1732
+ }
1733
+ return geometry.RectF.init(center.x - radius, center.y - radius, radius * 2, radius * 2);
1734
+ }