@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,1370 @@
1
+ // The toolkit-owned Android host: a complete Android application around
2
+ // the embed C ABI, in plain Java so `native dev --target android` and
3
+ // `native package --target android` compile it with nothing but the JDK
4
+ // and the Android SDK's build tools — an app project carries zero host
5
+ // code, and everything app-specific (application id, names, icons)
6
+ // arrives through the generated manifest and resources. The native half
7
+ // lives in android_host.c; the pair is the Android mirror of the iOS
8
+ // host (src/platform/ios/uikit_host.m).
9
+ //
10
+ // Presentation: a SurfaceView shows the CPU reference renderer's pixels,
11
+ // copied into the surface's window buffer by the native bridge. A
12
+ // Choreographer callback pumps `native_sdk_app_frame` and the canvas
13
+ // revision gates re-presents, so unchanged frames cost one JNI call.
14
+ //
15
+ // Input: single-pointer touch sequences forward through the embed
16
+ // touch/scroll exports in density-independent points. The touch-slop
17
+ // state machine mirrors the iOS host (and UIScrollView's delayed content
18
+ // touches): an under-slop touch is a tap, an over-slop move over a
19
+ // scrollable widget pans it through wheel-style scroll deltas, and an
20
+ // over-slop move elsewhere becomes a pointer drag so sliders and text
21
+ // selection keep desktop semantics.
22
+ //
23
+ // The soft keyboard keys off the embed focus/IME-intent state: while an
24
+ // editable text widget owns focus the canvas view holds Android input
25
+ // focus and InputMethodManager shows the keyboard; when focus leaves it
26
+ // hides. Committed text flows through `native_sdk_app_text` and IME
27
+ // composition (setComposingText / finishComposingText) maps onto the
28
+ // same `native_sdk_app_ime` set/commit/cancel path the desktop hosts
29
+ // drive. Keyboard overlap reports through the viewport's keyboard
30
+ // insets: the window stays edge-to-edge (the decor never resizes), the
31
+ // IME inset arrives via WindowInsets, and the runtime insets layout by
32
+ // the keyboard's residual overlap beyond the safe area.
33
+ //
34
+ // Layout: display cutout and system-bar insets report as the viewport's
35
+ // safe area, which the embed host republishes over the window-chrome
36
+ // channel — apps pad via `on_chrome` exactly as they do for the macOS
37
+ // titlebar band, and apps without the hook keep the automatic runtime
38
+ // inset. Rotation keeps the activity (the manifest claims configChanges)
39
+ // so the embedded runtime survives with a resize instead of a restart.
40
+ //
41
+ // Text metrics: the host registers a Paint-backed measure callback
42
+ // before start — the Android mirror of the iOS host's CoreText callback —
43
+ // so layout uses real typographic widths instead of the deterministic
44
+ // estimator. Launch with the `estimator-text-metrics` boolean extra to
45
+ // keep the estimator (before/after comparisons, deterministic goldens).
46
+ //
47
+ // Audio: the host registers the platform audio service (through the
48
+ // native bridge's nativeSetAudioService) before start, mirroring the iOS
49
+ // host's player: one android.media.MediaPlayer for local files, verified
50
+ // cache entries, and progressive HTTP(S) URL streams, with a parallel
51
+ // HttpURLConnection download filling the track cache (part file,
52
+ // size-verified, atomic rename), ~500ms position ticks only while
53
+ // playing, and one completion at natural end — all reported back through
54
+ // nativeAudioEvent. Android additionally owns audio focus: requested on
55
+ // play, and a focus loss pauses the player and reports the paused state
56
+ // honestly through an immediate position event. See the audio section
57
+ // below for the backend rationale and its constraints.
58
+ //
59
+ // Images: the host registers the platform image decoder (through the
60
+ // native bridge's nativeSetImageService) before start, mirroring the iOS
61
+ // host's CGImageSource callback: BitmapFactory decodes encoded bytes
62
+ // (PNG, JPEG, ...) into straight-alpha RGBA8 written directly into the
63
+ // runtime's decode buffer, so `fx.registerImageBytes` registers real
64
+ // pixels (album covers, fetched avatars) instead of declining. Decoding
65
+ // runs once per registration; frames reference the runtime's registered
66
+ // copy afterwards.
67
+
68
+ package dev.native_sdk.host;
69
+
70
+ import android.app.Activity;
71
+ import android.content.res.AssetManager;
72
+ import android.graphics.Bitmap;
73
+ import android.graphics.BitmapFactory;
74
+ import android.graphics.Paint;
75
+ import android.graphics.Typeface;
76
+ import android.media.AudioAttributes;
77
+ import android.media.AudioFocusRequest;
78
+ import android.media.AudioManager;
79
+ import android.media.MediaPlayer;
80
+ import android.os.Bundle;
81
+ import android.os.Handler;
82
+ import android.os.Looper;
83
+ import android.text.InputType;
84
+ import android.util.LruCache;
85
+ import android.view.Choreographer;
86
+ import android.view.KeyEvent;
87
+ import android.view.MotionEvent;
88
+ import android.view.SurfaceHolder;
89
+ import android.view.SurfaceView;
90
+ import android.view.ViewConfiguration;
91
+ import android.view.WindowInsets;
92
+ import android.view.WindowManager;
93
+ import android.view.inputmethod.BaseInputConnection;
94
+ import android.view.inputmethod.EditorInfo;
95
+ import android.view.inputmethod.InputConnection;
96
+ import android.view.inputmethod.InputMethodManager;
97
+ import java.io.File;
98
+ import java.io.FileOutputStream;
99
+ import java.io.InputStream;
100
+ import java.io.OutputStream;
101
+ import java.nio.ByteBuffer;
102
+ import java.nio.charset.CharacterCodingException;
103
+ import java.nio.charset.CodingErrorAction;
104
+ import java.nio.charset.StandardCharsets;
105
+
106
+ public final class NativeSdkActivity extends Activity implements SurfaceHolder.Callback, Choreographer.FrameCallback {
107
+ private static final int TOUCH_MODE_IDLE = 0;
108
+ // Touch down seen, under slop: undecided between tap / drag / scroll.
109
+ private static final int TOUCH_MODE_PENDING = 1;
110
+ // Over slop on a scrollable widget: forwarding wheel scroll deltas.
111
+ private static final int TOUCH_MODE_SCROLLING = 2;
112
+ // Over slop elsewhere: forwarded pointer down, forwarding drags.
113
+ private static final int TOUCH_MODE_DRAGGING = 3;
114
+
115
+ private static final int TOUCH_PHASE_DOWN = 0;
116
+ private static final int TOUCH_PHASE_UP = 1;
117
+ private static final int TOUCH_PHASE_DRAG = 2;
118
+ private static final int TOUCH_PHASE_CANCEL = 3;
119
+
120
+ private static final int KEY_PHASE_DOWN = 0;
121
+ private static final int KEY_PHASE_UP = 1;
122
+
123
+ private static final int IME_SET_COMPOSITION = 0;
124
+ private static final int IME_COMMIT_COMPOSITION = 1;
125
+ private static final int IME_CANCEL_COMPOSITION = 2;
126
+
127
+ // Audio event kinds for nativeAudioEvent (ordinals match the embed
128
+ // ABI's audio event enum in native_sdk_app.h).
129
+ private static final int AUDIO_EVENT_LOADED = 0;
130
+ private static final int AUDIO_EVENT_POSITION = 1;
131
+ private static final int AUDIO_EVENT_COMPLETED = 2;
132
+ private static final int AUDIO_EVENT_FAILED = 3;
133
+
134
+ private long nativeApp;
135
+ private CanvasSurfaceView canvasView;
136
+ private boolean surfaceReady;
137
+ private float density = 1f;
138
+ private float safeTop, safeRight, safeBottom, safeLeft;
139
+ private float keyboardBottom;
140
+ private int surfaceWidthPx, surfaceHeightPx;
141
+ private long lastCanvasRevision = -1;
142
+ private boolean hasPresentedRevision;
143
+ private boolean needsPresent;
144
+ private boolean keyboardShown;
145
+ private long focusedTextWidget;
146
+ private final LruCache<String, Double> measureCache = new LruCache<>(16384);
147
+ private final Paint measurePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
148
+
149
+ // ------------------------------------------------------- audio state
150
+ // The single platform player behind the embed audio service (see the
151
+ // audio section below). All fields are main-thread only.
152
+ private MediaPlayer audioPlayer;
153
+ private boolean audioPrepared;
154
+ private boolean audioBuffering;
155
+ private boolean audioPendingPlay;
156
+ private long audioPendingSeekMs = -1;
157
+ private java.util.Timer audioTickTimer;
158
+ private java.util.concurrent.atomic.AtomicBoolean audioCacheCancel;
159
+ private AudioFocusRequest audioFocusRequest;
160
+ private boolean audioFocusHeld;
161
+ private final Handler audioMainHandler = new Handler(Looper.getMainLooper());
162
+
163
+ @Override
164
+ protected void onCreate(Bundle savedInstanceState) {
165
+ super.onCreate(savedInstanceState);
166
+
167
+ // Export the per-app directory namespace into the process
168
+ // environment before any app code runs: Android gives app
169
+ // processes no per-app HOME of their own, so the host publishes
170
+ // the data directory as HOME and its cache child as TMPDIR — the
171
+ // same env-based convention iOS processes get from the OS — and
172
+ // env-driven directory resolution (the app_dirs primitive's
173
+ // Android mapping) stays honest. `.cache` under that HOME is
174
+ // exactly getCacheDir(), where the audio track cache belongs.
175
+ try {
176
+ android.system.Os.setenv("HOME", getDataDir().getAbsolutePath(), true);
177
+ android.system.Os.setenv("TMPDIR", getCacheDir().getAbsolutePath(), true);
178
+ } catch (Exception e) {
179
+ android.util.Log.e("native-sdk", "env export failed: " + e);
180
+ }
181
+
182
+ System.loadLibrary("native_sdk_host");
183
+
184
+ // Edge-to-edge: the decor never resizes for system bars, cutouts,
185
+ // or the keyboard — those bands arrive as viewport insets instead,
186
+ // so the embedded runtime owns clearance the same way it does on
187
+ // iOS.
188
+ getWindow().setDecorFitsSystemWindows(false);
189
+ getWindow().getAttributes().layoutInDisplayCutoutMode =
190
+ WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
191
+ getWindow().setStatusBarColor(android.graphics.Color.TRANSPARENT);
192
+ getWindow().setNavigationBarColor(android.graphics.Color.TRANSPARENT);
193
+
194
+ density = getResources().getDisplayMetrics().density;
195
+ canvasView = new CanvasSurfaceView();
196
+ canvasView.getHolder().addCallback(this);
197
+ setContentView(canvasView);
198
+
199
+ canvasView.setOnApplyWindowInsetsListener((view, insets) -> {
200
+ android.graphics.Insets bars = insets.getInsets(
201
+ WindowInsets.Type.systemBars() | WindowInsets.Type.displayCutout());
202
+ android.graphics.Insets ime = insets.getInsets(WindowInsets.Type.ime());
203
+ safeTop = bars.top / density;
204
+ safeRight = bars.right / density;
205
+ safeBottom = bars.bottom / density;
206
+ safeLeft = bars.left / density;
207
+ keyboardBottom = ime.bottom / density;
208
+ pushViewport();
209
+ return insets;
210
+ });
211
+
212
+ nativeApp = nativeCreate();
213
+ if (nativeApp == 0) {
214
+ android.util.Log.e("native-sdk", "nativeCreate failed");
215
+ finish();
216
+ return;
217
+ }
218
+
219
+ // Real text metrics: register the Paint measure callback before
220
+ // start so the installing layout already measures with the fonts
221
+ // presentation would draw with.
222
+ if (getIntent().getBooleanExtra("estimator-text-metrics", false)) {
223
+ android.util.Log.i("native-sdk", "text measure disabled (estimator metrics)");
224
+ } else {
225
+ nativeSetTextMeasure(nativeApp);
226
+ }
227
+
228
+ // The platform audio service (registered before start, like the
229
+ // text measure, so the first effect dispatch already sees it):
230
+ // one real player behind the embed audio seam — see the audio
231
+ // section below.
232
+ nativeSetAudioService(nativeApp);
233
+
234
+ // The platform image decoder (registered before start, so a
235
+ // boot-effect fx.registerImageBytes already decodes): the
236
+ // BitmapFactory codec behind the embed image seam — see the image
237
+ // section below.
238
+ nativeSetImageService(nativeApp);
239
+
240
+ // Verification harness: `am start --ez native-sdk-automation true`
241
+ // publishes snapshot.txt into the app's files dir, same protocol
242
+ // as the desktop -Dautomation=true runners (readable over
243
+ // `adb shell run-as <application id>` for this debuggable host).
244
+ if (getIntent().getBooleanExtra("native-sdk-automation", false)) {
245
+ File dir = new File(getFilesDir(), "native-sdk-automation");
246
+ dir.mkdirs();
247
+ nativeSetAutomationDir(nativeApp, dir.getAbsolutePath());
248
+ }
249
+
250
+ // Packaged assets: the APK carries the app's assets under
251
+ // assets/native-sdk; the embed asset root needs a real directory,
252
+ // so mirror them into the files dir once and point the host there.
253
+ String assetRoot = mirrorPackagedAssets();
254
+ if (assetRoot != null) {
255
+ nativeSetAssetRoot(nativeApp, assetRoot);
256
+ }
257
+
258
+ nativeStart(nativeApp);
259
+ nativeActivate(nativeApp);
260
+ Choreographer.getInstance().postFrameCallback(this);
261
+ }
262
+
263
+ @Override
264
+ protected void onResume() {
265
+ super.onResume();
266
+ if (nativeApp != 0) nativeActivate(nativeApp);
267
+ }
268
+
269
+ @Override
270
+ protected void onPause() {
271
+ if (nativeApp != 0) nativeDeactivate(nativeApp);
272
+ super.onPause();
273
+ }
274
+
275
+ @Override
276
+ protected void onDestroy() {
277
+ Choreographer.getInstance().removeFrameCallback(this);
278
+ if (nativeApp != 0) {
279
+ // Stop first: the runtime's shutdown path releases the audio
280
+ // channel through the still-registered service. Zeroing
281
+ // nativeApp afterwards cuts the event path, so a stray
282
+ // asynchronous report cannot reach a dead runtime; then the
283
+ // belt-and-braces teardown below retires whatever survived.
284
+ nativeStop(nativeApp);
285
+ nativeDestroy(nativeApp);
286
+ nativeApp = 0;
287
+ }
288
+ audioReleasePlayer(true);
289
+ super.onDestroy();
290
+ }
291
+
292
+ // ------------------------------------------------------------ surface
293
+
294
+ @Override
295
+ public void surfaceCreated(SurfaceHolder holder) {
296
+ }
297
+
298
+ @Override
299
+ public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
300
+ if (nativeApp == 0) return;
301
+ nativeSurfaceChanged(nativeApp, holder.getSurface());
302
+ surfaceReady = true;
303
+ surfaceWidthPx = width;
304
+ surfaceHeightPx = height;
305
+ pushViewport();
306
+ }
307
+
308
+ @Override
309
+ public void surfaceDestroyed(SurfaceHolder holder) {
310
+ surfaceReady = false;
311
+ if (nativeApp != 0) nativeSurfaceDestroyed(nativeApp);
312
+ }
313
+
314
+ // Report the surface size in density-independent points plus the
315
+ // safe-area and keyboard insets; the embed host republishes the safe
316
+ // area over the window-chrome channel and keeps insetting layout by
317
+ // the keyboard's residual overlap beyond it.
318
+ private void pushViewport() {
319
+ if (nativeApp == 0 || !surfaceReady || surfaceWidthPx <= 0 || surfaceHeightPx <= 0) return;
320
+ nativeViewport(nativeApp,
321
+ surfaceWidthPx / density, surfaceHeightPx / density, density,
322
+ safeTop, safeRight, safeBottom, safeLeft,
323
+ 0f, 0f, keyboardBottom, 0f);
324
+ needsPresent = true;
325
+ }
326
+
327
+ // ------------------------------------------------------------- frames
328
+
329
+ @Override
330
+ public void doFrame(long frameTimeNanos) {
331
+ if (nativeApp == 0) return;
332
+ Choreographer.getInstance().postFrameCallback(this);
333
+
334
+ // Host-pumped frame: synthesizes the gpu_surface_frame event
335
+ // (first tick installs the widget tree, later ticks re-present).
336
+ nativeFrame(nativeApp);
337
+
338
+ // Keyboard show/hide follows the runtime's focus state each tick,
339
+ // not only after forwarded input: focus can also move from key
340
+ // handling or model updates.
341
+ syncTextInput();
342
+
343
+ if (!surfaceReady) return;
344
+ long revision = nativeCanvasRevision(nativeApp);
345
+ if (!needsPresent && revision >= 0 && hasPresentedRevision && revision == lastCanvasRevision) return;
346
+ // nativePresent returns the revision the glass now REFLECTS (-1
347
+ // on failure) - a change whose frame has not presented yet
348
+ // reports the old revision, keeping the gate open so the next
349
+ // tick delivers its damage instead of stranding it.
350
+ long delivered = nativePresent(nativeApp, density);
351
+ if (delivered >= 0) {
352
+ lastCanvasRevision = delivered;
353
+ hasPresentedRevision = true;
354
+ needsPresent = false;
355
+ }
356
+ }
357
+
358
+ // ------------------------------------------- keyboard <-> focus sync
359
+
360
+ // Reconcile the platform soft keyboard with the runtime's
361
+ // focus/IME-intent state: keyboard up while an editable text widget
362
+ // owns focus, down when focus leaves — the Android mirror of the iOS
363
+ // host's first-responder sync.
364
+ private void syncTextInput() {
365
+ if (nativeApp == 0 || canvasView == null) return;
366
+ long[] widgetId = new long[1];
367
+ float[] frame = new float[4];
368
+ boolean active = nativeTextInputState(nativeApp, widgetId, frame);
369
+ InputMethodManager input = getSystemService(InputMethodManager.class);
370
+ if (active) {
371
+ boolean widgetChanged = widgetId[0] != focusedTextWidget;
372
+ focusedTextWidget = widgetId[0];
373
+ if (widgetChanged) {
374
+ canvasView.clearComposingState();
375
+ if (keyboardShown) input.restartInput(canvasView);
376
+ }
377
+ if (!keyboardShown) {
378
+ canvasView.requestFocus();
379
+ input.showSoftInput(canvasView, 0);
380
+ keyboardShown = true;
381
+ }
382
+ } else {
383
+ focusedTextWidget = 0;
384
+ if (keyboardShown) {
385
+ canvasView.clearComposingState();
386
+ input.hideSoftInputFromWindow(canvasView.getWindowToken(), 0);
387
+ keyboardShown = false;
388
+ }
389
+ }
390
+ }
391
+
392
+ // ------------------------------------------------------- text metrics
393
+
394
+ // Paint-backed measure upcall from android_host.c: the typographic
395
+ // width of a single-line run, measured with the same font resolution
396
+ // presentation draws with. Returns a negative value when the bytes
397
+ // are not valid UTF-8 so layout falls back to its estimator.
398
+ @SuppressWarnings("unused") // called from android_host.c
399
+ double measureText(long fontId, double size, byte[] utf8) {
400
+ if (utf8 == null || utf8.length == 0) return 0;
401
+ String text;
402
+ try {
403
+ text = StandardCharsets.UTF_8.newDecoder()
404
+ .onMalformedInput(CodingErrorAction.REPORT)
405
+ .onUnmappableCharacter(CodingErrorAction.REPORT)
406
+ .decode(ByteBuffer.wrap(utf8))
407
+ .toString();
408
+ } catch (CharacterCodingException e) {
409
+ return -1;
410
+ }
411
+ double clamped = Math.max(1, size);
412
+ String key = fontId + "/" + clamped + "/" + text;
413
+ Double cached = measureCache.get(key);
414
+ if (cached != null) return cached;
415
+ measurePaint.setTypeface(typefaceForFontId(fontId));
416
+ measurePaint.setTextSize((float) clamped);
417
+ double width = measurePaint.measureText(text);
418
+ measureCache.put(key, width);
419
+ return width;
420
+ }
421
+
422
+ // Resolves a canvas font id to the Typeface measurement uses. Ids 3-6
423
+ // are the reserved sans span variants (medium, bold, italic, bold
424
+ // italic); 2 is mono; everything else keeps the regular sans.
425
+ private static Typeface typefaceForFontId(long fontId) {
426
+ if (fontId == 2) return Typeface.MONOSPACE;
427
+ if (fontId == 3) return Typeface.create(Typeface.DEFAULT, 500, false);
428
+ if (fontId == 4) return Typeface.create(Typeface.DEFAULT, Typeface.BOLD);
429
+ if (fontId == 5) return Typeface.create(Typeface.DEFAULT, Typeface.ITALIC);
430
+ if (fontId == 6) return Typeface.create(Typeface.DEFAULT, Typeface.BOLD_ITALIC);
431
+ return Typeface.DEFAULT;
432
+ }
433
+
434
+ // -------------------------------------------------------------- images
435
+ //
436
+ // The platform image decoder behind the embed image service — the
437
+ // Android mirror of the iOS host's CGImageSource callback. Backend:
438
+ // android.graphics.BitmapFactory, the platform's in-box codec stack
439
+ // (PNG, JPEG, WebP, ...), decoding to a non-premultiplied ARGB_8888
440
+ // bitmap whose copyPixelsToBuffer byte order is exactly the tightly
441
+ // packed straight-alpha RGBA8 the canvas image pipeline expects. The
442
+ // upcall writes into the runtime's decode scratch through a direct
443
+ // ByteBuffer, so the decoded pixels cross the JNI seam without a
444
+ // second copy; the bitmap is recycled before returning — decode is
445
+ // one-shot per registration, and frames reference the runtime's
446
+ // registered copy afterwards.
447
+
448
+ // Decode upcall from android_host.c. Returns 1 decoded (dimensions in
449
+ // size[0]/size[1]), -1 when the decoded pixels do not fit the buffer,
450
+ // 0 undecodable — the embed image service contract.
451
+ @SuppressWarnings("unused") // called from android_host.c
452
+ int imageDecode(byte[] encoded, ByteBuffer pixels, long[] size) {
453
+ if (encoded == null || encoded.length == 0 || pixels == null || size == null || size.length < 2) return 0;
454
+ BitmapFactory.Options options = new BitmapFactory.Options();
455
+ options.inPreferredConfig = Bitmap.Config.ARGB_8888;
456
+ // Straight alpha, matching the desktop decoders: the canvas
457
+ // pipeline un-premultiplies nothing downstream.
458
+ options.inPremultiplied = false;
459
+ Bitmap bitmap;
460
+ try {
461
+ bitmap = BitmapFactory.decodeByteArray(encoded, 0, encoded.length, options);
462
+ } catch (Exception e) {
463
+ return 0;
464
+ }
465
+ if (bitmap == null) return 0;
466
+ try {
467
+ if (bitmap.getConfig() != Bitmap.Config.ARGB_8888) {
468
+ // A codec that ignored the preferred config (rare): one
469
+ // conversion pass; copy(...) preserves isPremultiplied.
470
+ Bitmap converted = bitmap.copy(Bitmap.Config.ARGB_8888, false);
471
+ bitmap.recycle();
472
+ if (converted == null) return 0;
473
+ bitmap = converted;
474
+ }
475
+ long width = bitmap.getWidth();
476
+ long height = bitmap.getHeight();
477
+ // The dimension ceiling mirrors the iOS/macOS decode callback.
478
+ if (width <= 0 || height <= 0 || width > 8192 || height > 8192) return 0;
479
+ size[0] = width;
480
+ size[1] = height;
481
+ long byteLen = width * height * 4;
482
+ if (byteLen > pixels.capacity()) return -1;
483
+ pixels.position(0);
484
+ bitmap.copyPixelsToBuffer(pixels);
485
+ return 1;
486
+ } catch (Exception e) {
487
+ return 0;
488
+ } finally {
489
+ if (!bitmap.isRecycled()) bitmap.recycle();
490
+ }
491
+ }
492
+
493
+ // -------------------------------------------------------------- audio
494
+ //
495
+ // The platform audio player behind the embed audio service. Backend
496
+ // choice, made deliberately: android.media.MediaPlayer, the platform's
497
+ // in-box media stack, driven from this activity. It covers the whole
498
+ // contract with no dependencies — local files and verified cache
499
+ // entries (synchronous prepare with the real decoded duration),
500
+ // progressive HTTP(S) streaming (playback starts while bytes arrive,
501
+ // never download-then-play), pause/seek/volume mid-stream, one
502
+ // completion listener, and honest buffering reports via the info
503
+ // callbacks. The plausible alternatives lose on this host's terms: a
504
+ // third-party player library is out of the question for the toolkit's
505
+ // in-box host, and a hand-rolled NDK pipeline (a decoder feeding a raw
506
+ // output stream) is an order of magnitude more code to reimplement
507
+ // seeking, buffering, and format coverage the platform already ships.
508
+ // MediaPlayer's honest constraints, all handled below: it cannot seek
509
+ // or pause before prepareAsync completes (a pre-prepared seek is
510
+ // stored and applied on the prepared callback; play before prepared
511
+ // records intent and starts on readiness, mirroring how a stream's
512
+ // play "applies" on every other platform), a released player object is
513
+ // never reusable (each load builds a fresh one), and its callbacks
514
+ // must be consumed on this thread's looper (they are — the player is
515
+ // created on the main thread).
516
+ //
517
+ // Contract mirror of the macOS/iOS hosts: exactly one player at a
518
+ // time, every asynchronous report — the loaded acknowledgment with the
519
+ // real duration, ~500ms position ticks only while playing, buffering
520
+ // flips, exactly one completion, explicit failures — arrives through
521
+ // nativeAudioEvent on the main thread, and the service entry points
522
+ // (called from native code inside runtime dispatch) never emit
523
+ // synchronously: the local-file LOADED acknowledgment defers one
524
+ // main-loop turn, exactly like the macOS host's.
525
+ //
526
+ // The cache fill is a PARALLEL download, not a tee off the player's
527
+ // own connection: a partially buffered stream must never masquerade as
528
+ // a cache entry. One extra request on a track's first (uncached) play
529
+ // buys a stock streaming path and a cache whose entries are whole
530
+ // files by construction: downloaded beside the final name,
531
+ // size-verified against the manifest, and renamed into place — a
532
+ // same-directory rename, so a partial file never occupies the cache
533
+ // name even across a crash.
534
+ //
535
+ // Android divergence, all focus-related: the host requests audio focus
536
+ // on play, and a focus loss (another app took the output route) pauses
537
+ // the player and reports the paused state honestly through one
538
+ // immediate position event with playing=0 — a platform-initiated pause
539
+ // the app did NOT command, so unlike app-driven pause it must echo.
540
+ // Focus regain never auto-resumes: the app (or the person holding the
541
+ // phone) decides. Media-session and notification integration (lock
542
+ // screen controls, background playback beyond the cached process) are
543
+ // out of scope for this host today.
544
+
545
+ private AudioAttributes audioAttributes() {
546
+ return new AudioAttributes.Builder()
547
+ .setUsage(AudioAttributes.USAGE_MEDIA)
548
+ .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
549
+ .build();
550
+ }
551
+
552
+ private static String audioUtf8(byte[] bytes) {
553
+ if (bytes == null || bytes.length == 0) return null;
554
+ try {
555
+ return StandardCharsets.UTF_8.newDecoder()
556
+ .onMalformedInput(CodingErrorAction.REPORT)
557
+ .onUnmappableCharacter(CodingErrorAction.REPORT)
558
+ .decode(ByteBuffer.wrap(bytes))
559
+ .toString();
560
+ } catch (CharacterCodingException e) {
561
+ return null;
562
+ }
563
+ }
564
+
565
+ // Emit one audio report carrying the live position/duration readout of
566
+ // the active player. Main thread only, between runtime entry points.
567
+ private void emitAudioEvent(int kind) {
568
+ if (nativeApp == 0) return;
569
+ long position = 0;
570
+ long duration = 0;
571
+ int playing = 0;
572
+ int buffering = 0;
573
+ MediaPlayer player = audioPlayer;
574
+ if (player != null) {
575
+ if (audioPrepared) {
576
+ try {
577
+ int current = player.getCurrentPosition();
578
+ if (current > 0) position = current;
579
+ int total = player.getDuration();
580
+ if (total > 0) duration = total;
581
+ playing = player.isPlaying() ? 1 : 0;
582
+ } catch (IllegalStateException ignored) {
583
+ }
584
+ } else {
585
+ // A stream still preparing: the transport intent is the
586
+ // honest playing flag (un-paused, silent until bytes
587
+ // arrive), with buffering set beside it.
588
+ playing = audioPendingPlay ? 1 : 0;
589
+ }
590
+ buffering = audioBuffering ? 1 : 0;
591
+ }
592
+ if (kind == AUDIO_EVENT_COMPLETED) {
593
+ // A finished player rewinds itself; report the honest
594
+ // terminal position instead.
595
+ position = duration;
596
+ playing = 0;
597
+ buffering = 0;
598
+ }
599
+ nativeAudioEvent(nativeApp, kind, position, duration, playing, buffering);
600
+ }
601
+
602
+ // ~500ms position ticks while playing only. java.util.Timer runs on
603
+ // its own thread, deliberately independent of the Choreographer frame
604
+ // pump and any UI Handler cadence (a busy frame loop must not starve
605
+ // or skew the readout); each tick marshals onto the main thread — the
606
+ // runtime's thread — like every other host event.
607
+ private void startAudioTicks() {
608
+ if (audioTickTimer != null) return;
609
+ java.util.Timer timer = new java.util.Timer("native-sdk-audio-ticks", true);
610
+ timer.scheduleAtFixedRate(new java.util.TimerTask() {
611
+ @Override
612
+ public void run() {
613
+ runOnUiThread(() -> {
614
+ if (audioPlayer == null) {
615
+ stopAudioTicks();
616
+ return;
617
+ }
618
+ emitAudioEvent(AUDIO_EVENT_POSITION);
619
+ });
620
+ }
621
+ }, 500, 500);
622
+ audioTickTimer = timer;
623
+ }
624
+
625
+ private void stopAudioTicks() {
626
+ if (audioTickTimer == null) return;
627
+ audioTickTimer.cancel();
628
+ audioTickTimer = null;
629
+ }
630
+
631
+ // Retire the player and its bookkeeping. The cache download is
632
+ // cancelled when a new load replaces the stream mid-flight or the
633
+ // transport stops or fails (a skipped track should not keep burning
634
+ // bandwidth) but ORPHANED on natural completion — it is usually
635
+ // already done, and letting a straggler finish installs the cache
636
+ // entry the completed play earned.
637
+ private void audioReleasePlayer(boolean cancelDownload) {
638
+ stopAudioTicks();
639
+ abandonAudioFocus();
640
+ if (cancelDownload) {
641
+ if (audioCacheCancel != null) audioCacheCancel.set(true);
642
+ audioCacheCancel = null;
643
+ } else {
644
+ audioCacheCancel = null;
645
+ }
646
+ audioPendingPlay = false;
647
+ audioPendingSeekMs = -1;
648
+ audioBuffering = false;
649
+ audioPrepared = false;
650
+ MediaPlayer player = audioPlayer;
651
+ audioPlayer = null;
652
+ if (player == null) return;
653
+ try {
654
+ player.release();
655
+ } catch (Exception ignored) {
656
+ }
657
+ }
658
+
659
+ // Natural end of the track (exactly once). Retire-before-emit
660
+ // discipline: the completion Msg routinely starts the NEXT track from
661
+ // inside its own dispatch (a music app auto-advancing), and retiring
662
+ // afterwards would destroy the player that load just installed. The
663
+ // duration is captured first so the event carries the honest terminal
664
+ // position.
665
+ private void audioPlayerCompleted(MediaPlayer player) {
666
+ if (audioPlayer != player) return;
667
+ long duration = 0;
668
+ try {
669
+ int total = player.getDuration();
670
+ if (total > 0) duration = total;
671
+ } catch (IllegalStateException ignored) {
672
+ }
673
+ audioReleasePlayer(false);
674
+ if (nativeApp != 0) {
675
+ nativeAudioEvent(nativeApp, AUDIO_EVENT_COMPLETED, duration, duration, 0, 0);
676
+ }
677
+ }
678
+
679
+ // The player died (unreachable host, undecodable payload, mid-stream
680
+ // network loss): one FAILED event, player retired first, cache
681
+ // download cancelled — bytes from a failing source are not
682
+ // trustworthy.
683
+ private void audioPlayerFailed(MediaPlayer player) {
684
+ if (audioPlayer != player) return;
685
+ audioReleasePlayer(true);
686
+ if (nativeApp != 0) {
687
+ nativeAudioEvent(nativeApp, AUDIO_EVENT_FAILED, 0, 0, 0, 0);
688
+ }
689
+ }
690
+
691
+ private void installAudioCallbacks(MediaPlayer player) {
692
+ player.setOnCompletionListener(this::audioPlayerCompleted);
693
+ player.setOnErrorListener((mp, what, extra) -> {
694
+ audioPlayerFailed(mp);
695
+ // Consumed: without this the platform follows an error with
696
+ // its own completion callback, and a failure must never
697
+ // masquerade as a finished track.
698
+ return true;
699
+ });
700
+ player.setOnInfoListener((mp, what, extra) -> {
701
+ if (audioPlayer != mp) return false;
702
+ // A stream stalled waiting for bytes (or recovered): flip the
703
+ // honest buffering flag and report the transition NOW as a
704
+ // position event, not at the next 500ms tick.
705
+ if (what == MediaPlayer.MEDIA_INFO_BUFFERING_START) {
706
+ audioBuffering = true;
707
+ emitAudioEvent(AUDIO_EVENT_POSITION);
708
+ return true;
709
+ }
710
+ if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END) {
711
+ audioBuffering = false;
712
+ emitAudioEvent(AUDIO_EVENT_POSITION);
713
+ return true;
714
+ }
715
+ return false;
716
+ });
717
+ }
718
+
719
+ // Synchronous local-file load (also the verified-cache-entry path).
720
+ // Returns 0 loaded / 1 missing / 2 decode failure — the macOS host's
721
+ // contract. The LOADED acknowledgment is asynchronous by contract:
722
+ // emitting it inside this service call would re-enter the runtime
723
+ // while it is still dispatching the command that asked for the load,
724
+ // so it posts to the next main-loop turn, guarded on this player
725
+ // still being the loaded one.
726
+ private int audioLoadFile(String path) {
727
+ audioReleasePlayer(true);
728
+ if (path == null) return 1;
729
+ if (!new File(path).isFile()) return 1;
730
+ MediaPlayer player = new MediaPlayer();
731
+ try {
732
+ player.setAudioAttributes(audioAttributes());
733
+ player.setDataSource(path);
734
+ player.prepare();
735
+ } catch (Exception e) {
736
+ player.release();
737
+ return 2;
738
+ }
739
+ installAudioCallbacks(player);
740
+ audioPlayer = player;
741
+ audioPrepared = true;
742
+ audioBuffering = false;
743
+ audioMainHandler.post(() -> {
744
+ if (audioPlayer != player) return;
745
+ emitAudioEvent(AUDIO_EVENT_LOADED);
746
+ });
747
+ return 0;
748
+ }
749
+
750
+ @SuppressWarnings("unused") // called from android_host.c
751
+ int audioLoad(byte[] pathUtf8) {
752
+ String path = audioUtf8(pathUtf8);
753
+ return path == null ? 1 : audioLoadFile(path);
754
+ }
755
+
756
+ // URL source resolution: verified cache entry first (plays as a plain
757
+ // local file, no network), then a progressive MediaPlayer stream with
758
+ // a parallel cache-filling download. Returns 1 for the cache hit, 0
759
+ // for a started stream, 2 when the URL is unusable; everything
760
+ // asynchronous — readiness, stalls, natural end, network death —
761
+ // arrives as audio events.
762
+ @SuppressWarnings("unused") // called from android_host.c
763
+ int audioLoadUrl(byte[] urlUtf8, byte[] cacheUtf8, long expectedBytes) {
764
+ audioReleasePlayer(true);
765
+ String url = audioUtf8(urlUtf8);
766
+ if (url == null) return 2;
767
+ android.net.Uri uri = android.net.Uri.parse(url);
768
+ if (uri.getScheme() == null) return 2;
769
+ String cachePath = audioUtf8(cacheUtf8);
770
+ if (cachePath != null) {
771
+ File entry = new File(cachePath);
772
+ if (entry.isFile()) {
773
+ if ((expectedBytes == 0 || entry.length() == expectedBytes)
774
+ && audioLoadFile(cachePath) == 0) {
775
+ return 1;
776
+ }
777
+ // Partial, stale, or corrupt (right size but undecodable):
778
+ // a bad cache entry never plays, and never survives to
779
+ // fool the next lookup.
780
+ entry.delete();
781
+ }
782
+ }
783
+ MediaPlayer player = new MediaPlayer();
784
+ try {
785
+ player.setAudioAttributes(audioAttributes());
786
+ player.setDataSource(url);
787
+ } catch (Exception e) {
788
+ player.release();
789
+ return 2;
790
+ }
791
+ installAudioCallbacks(player);
792
+ player.setOnPreparedListener(mp -> {
793
+ if (audioPlayer != mp) return;
794
+ // The stream's LOADED acknowledgment: the duration is decoded
795
+ // and playback can roll. Apply what the app commanded while
796
+ // the player could not act on it yet.
797
+ audioPrepared = true;
798
+ audioBuffering = false;
799
+ if (audioPendingSeekMs >= 0) {
800
+ try {
801
+ mp.seekTo(audioPendingSeekMs, MediaPlayer.SEEK_CLOSEST);
802
+ } catch (IllegalStateException ignored) {
803
+ }
804
+ audioPendingSeekMs = -1;
805
+ }
806
+ if (audioPendingPlay) {
807
+ audioPendingPlay = false;
808
+ try {
809
+ mp.start();
810
+ startAudioTicks();
811
+ } catch (IllegalStateException ignored) {
812
+ }
813
+ }
814
+ emitAudioEvent(AUDIO_EVENT_LOADED);
815
+ });
816
+ audioPlayer = player;
817
+ audioPrepared = false;
818
+ // Honest buffering from stream start until playback actually
819
+ // rolls; the info callbacks track stalls afterwards.
820
+ audioBuffering = true;
821
+ player.prepareAsync();
822
+ if (cachePath != null) {
823
+ startAudioCacheDownload(url, cachePath, expectedBytes);
824
+ }
825
+ return 0;
826
+ }
827
+
828
+ // Background cache fill: file and network bytes only, no player state,
829
+ // no events. A failed or cancelled download simply leaves no cache
830
+ // entry — the next play streams again.
831
+ private void startAudioCacheDownload(String url, String cachePath, long expectedBytes) {
832
+ final java.util.concurrent.atomic.AtomicBoolean cancelled =
833
+ new java.util.concurrent.atomic.AtomicBoolean(false);
834
+ audioCacheCancel = cancelled;
835
+ Thread thread = new Thread(() -> {
836
+ java.net.HttpURLConnection connection = null;
837
+ File part = new File(cachePath + ".part");
838
+ boolean installed = false;
839
+ try {
840
+ connection = (java.net.HttpURLConnection) new java.net.URL(url).openConnection();
841
+ connection.setConnectTimeout(15000);
842
+ connection.setReadTimeout(30000);
843
+ if (connection.getResponseCode() != 200) return;
844
+ File parent = part.getParentFile();
845
+ if (parent != null) parent.mkdirs();
846
+ try (InputStream in = connection.getInputStream();
847
+ OutputStream out = new FileOutputStream(part)) {
848
+ byte[] buffer = new byte[65536];
849
+ int count;
850
+ while ((count = in.read(buffer)) > 0) {
851
+ if (cancelled.get()) return;
852
+ out.write(buffer, 0, count);
853
+ }
854
+ }
855
+ if (cancelled.get()) return;
856
+ // Truncated or wrong content: never installed.
857
+ if (expectedBytes != 0 && part.length() != expectedBytes) return;
858
+ File entry = new File(cachePath);
859
+ entry.delete();
860
+ installed = part.renameTo(entry);
861
+ } catch (Exception ignored) {
862
+ // No cache entry; playback is unaffected.
863
+ } finally {
864
+ if (!installed) part.delete();
865
+ if (connection != null) connection.disconnect();
866
+ }
867
+ }, "native-sdk-audio-cache");
868
+ thread.setDaemon(true);
869
+ thread.start();
870
+ }
871
+
872
+ // First play claims audio focus (deferred from load so a silent app
873
+ // never takes the route). A rejected request is not fatal — playback
874
+ // proceeds and the platform arbitrates, matching the iOS session
875
+ // posture.
876
+ private void requestAudioFocus() {
877
+ if (audioFocusHeld) return;
878
+ AudioManager manager = getSystemService(AudioManager.class);
879
+ if (manager == null) return;
880
+ if (audioFocusRequest == null) {
881
+ audioFocusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
882
+ .setAudioAttributes(audioAttributes())
883
+ .setOnAudioFocusChangeListener(this::onAudioFocusChange, audioMainHandler)
884
+ .build();
885
+ }
886
+ audioFocusHeld =
887
+ manager.requestAudioFocus(audioFocusRequest) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
888
+ }
889
+
890
+ private void abandonAudioFocus() {
891
+ if (!audioFocusHeld || audioFocusRequest == null) return;
892
+ AudioManager manager = getSystemService(AudioManager.class);
893
+ if (manager != null) manager.abandonAudioFocusRequest(audioFocusRequest);
894
+ audioFocusHeld = false;
895
+ }
896
+
897
+ // The system moved the output route to someone else (a call, another
898
+ // media app): the platform is about to silence this player anyway, so
899
+ // make the transport state match — pause explicitly, stop the ticks,
900
+ // and report the paused state NOW through one position event. This is
901
+ // the one pause that must echo: the app did not command it. A
902
+ // transient duck (short notification blip) keeps playing, and focus
903
+ // regain deliberately does not auto-resume.
904
+ private void onAudioFocusChange(int change) {
905
+ if (change != AudioManager.AUDIOFOCUS_LOSS
906
+ && change != AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
907
+ return;
908
+ }
909
+ audioFocusHeld = false;
910
+ if (audioPlayer == null) return;
911
+ audioPendingPlay = false;
912
+ if (audioPrepared) {
913
+ try {
914
+ audioPlayer.pause();
915
+ } catch (IllegalStateException ignored) {
916
+ }
917
+ }
918
+ stopAudioTicks();
919
+ emitAudioEvent(AUDIO_EVENT_POSITION);
920
+ }
921
+
922
+ // Transport entry points, called from android_host.c inside runtime
923
+ // dispatch on the main thread. Results follow the desktop contract:
924
+ // play and seek return nonzero when they applied, pause/stop/volume
925
+ // results are advisory.
926
+
927
+ @SuppressWarnings("unused") // called from android_host.c
928
+ int audioPlay() {
929
+ if (audioPlayer == null) return 0;
930
+ requestAudioFocus();
931
+ if (!audioPrepared) {
932
+ // Stream still preparing: play applies when readiness lands
933
+ // (the prepared callback starts it) — a stream's play is
934
+ // asynchronous by nature on every platform. The ticks start
935
+ // NOW so the un-paused-but-silent state reports honestly
936
+ // (playing=1, buffering=1) while the network catches up.
937
+ audioPendingPlay = true;
938
+ startAudioTicks();
939
+ return 1;
940
+ }
941
+ try {
942
+ audioPlayer.start();
943
+ } catch (IllegalStateException e) {
944
+ return 0;
945
+ }
946
+ startAudioTicks();
947
+ return 1;
948
+ }
949
+
950
+ @SuppressWarnings("unused") // called from android_host.c
951
+ int audioPause() {
952
+ if (audioPlayer == null) return 0;
953
+ audioPendingPlay = false;
954
+ if (audioPrepared) {
955
+ try {
956
+ audioPlayer.pause();
957
+ } catch (IllegalStateException ignored) {
958
+ }
959
+ }
960
+ stopAudioTicks();
961
+ return 1;
962
+ }
963
+
964
+ @SuppressWarnings("unused") // called from android_host.c
965
+ int audioStop() {
966
+ boolean had = audioPlayer != null;
967
+ audioReleasePlayer(true);
968
+ return had ? 1 : 0;
969
+ }
970
+
971
+ @SuppressWarnings("unused") // called from android_host.c
972
+ int audioSeek(long positionMs) {
973
+ if (audioPlayer == null) return 0;
974
+ if (!audioPrepared) {
975
+ // MediaPlayer cannot seek before prepareAsync completes;
976
+ // store the target and apply it on the prepared callback so
977
+ // the seek still lands where the app asked.
978
+ audioPendingSeekMs = positionMs;
979
+ return 1;
980
+ }
981
+ long target = positionMs;
982
+ try {
983
+ int duration = audioPlayer.getDuration();
984
+ if (duration > 0 && target > duration) target = duration;
985
+ audioPlayer.seekTo(target, MediaPlayer.SEEK_CLOSEST);
986
+ } catch (IllegalStateException e) {
987
+ return 0;
988
+ }
989
+ return 1;
990
+ }
991
+
992
+ @SuppressWarnings("unused") // called from android_host.c
993
+ int audioSetVolume(double volume) {
994
+ if (audioPlayer == null) return 0;
995
+ float level = (float) volume;
996
+ try {
997
+ audioPlayer.setVolume(level, level);
998
+ } catch (IllegalStateException ignored) {
999
+ }
1000
+ return 1;
1001
+ }
1002
+
1003
+ // ------------------------------------------------------------- assets
1004
+
1005
+ // Copy the APK's assets/native-sdk tree into files/native-sdk-assets
1006
+ // so asset-relative loads resolve against a real directory. Returns
1007
+ // null when the app ships no assets.
1008
+ private String mirrorPackagedAssets() {
1009
+ AssetManager assets = getAssets();
1010
+ try {
1011
+ String[] entries = assets.list("native-sdk");
1012
+ if (entries == null || entries.length == 0) return null;
1013
+ File root = new File(getFilesDir(), "native-sdk-assets");
1014
+ copyAssetDir(assets, "native-sdk", root);
1015
+ return root.getAbsolutePath();
1016
+ } catch (Exception e) {
1017
+ android.util.Log.e("native-sdk", "asset mirror failed: " + e);
1018
+ return null;
1019
+ }
1020
+ }
1021
+
1022
+ private static void copyAssetDir(AssetManager assets, String path, File dest) throws Exception {
1023
+ String[] entries = assets.list(path);
1024
+ if (entries == null || entries.length == 0) {
1025
+ // A leaf: copy the file bytes.
1026
+ File parent = dest.getParentFile();
1027
+ if (parent != null) parent.mkdirs();
1028
+ try (InputStream in = assets.open(path); OutputStream out = new FileOutputStream(dest)) {
1029
+ byte[] buffer = new byte[65536];
1030
+ int count;
1031
+ while ((count = in.read(buffer)) > 0) out.write(buffer, 0, count);
1032
+ }
1033
+ return;
1034
+ }
1035
+ dest.mkdirs();
1036
+ for (String entry : entries) {
1037
+ copyAssetDir(assets, path + "/" + entry, new File(dest, entry));
1038
+ }
1039
+ }
1040
+
1041
+ // -------------------------------------------------------- canvas view
1042
+
1043
+ private final class CanvasSurfaceView extends SurfaceView {
1044
+ private int touchMode = TOUCH_MODE_IDLE;
1045
+ private long touchSequence;
1046
+ private float startXPx, startYPx;
1047
+ private float lastXPx, lastYPx;
1048
+ private final int touchSlopPx;
1049
+ private String composingText = "";
1050
+
1051
+ CanvasSurfaceView() {
1052
+ super(NativeSdkActivity.this);
1053
+ setFocusable(true);
1054
+ setFocusableInTouchMode(true);
1055
+ touchSlopPx = ViewConfiguration.get(NativeSdkActivity.this).getScaledTouchSlop();
1056
+ }
1057
+
1058
+ void clearComposingState() {
1059
+ composingText = "";
1060
+ }
1061
+
1062
+ private void forwardTouchPhase(int phase, float xPx, float yPx, float pressure) {
1063
+ if (nativeApp == 0) return;
1064
+ nativeTouch(nativeApp, touchSequence, phase, xPx / density, yPx / density, pressure);
1065
+ }
1066
+
1067
+ @Override
1068
+ public boolean onTouchEvent(MotionEvent event) {
1069
+ if (nativeApp == 0) return false;
1070
+ float x = event.getX();
1071
+ float y = event.getY();
1072
+ switch (event.getActionMasked()) {
1073
+ case MotionEvent.ACTION_DOWN:
1074
+ touchSequence += 1;
1075
+ touchMode = TOUCH_MODE_PENDING;
1076
+ startXPx = x;
1077
+ startYPx = y;
1078
+ lastXPx = x;
1079
+ lastYPx = y;
1080
+ return true;
1081
+ case MotionEvent.ACTION_MOVE: {
1082
+ if (touchMode == TOUCH_MODE_IDLE) return true;
1083
+ if (touchMode == TOUCH_MODE_PENDING) {
1084
+ float dx = x - startXPx;
1085
+ float dy = y - startYPx;
1086
+ if (dx * dx + dy * dy < (float) touchSlopPx * touchSlopPx) return true;
1087
+ if (nativeScrollableWidgetAt(nativeApp, startXPx / density, startYPx / density)) {
1088
+ touchMode = TOUCH_MODE_SCROLLING;
1089
+ } else {
1090
+ touchMode = TOUCH_MODE_DRAGGING;
1091
+ forwardTouchPhase(TOUCH_PHASE_DOWN, startXPx, startYPx, 1f);
1092
+ }
1093
+ }
1094
+ if (touchMode == TOUCH_MODE_SCROLLING) {
1095
+ // Natural scrolling: finger up moves content up =
1096
+ // offset grows, so the wheel delta is the negated
1097
+ // finger delta.
1098
+ float deltaX = (lastXPx - x) / density;
1099
+ float deltaY = (lastYPx - y) / density;
1100
+ if (deltaX != 0 || deltaY != 0) {
1101
+ nativeScroll(nativeApp, touchSequence, x / density, y / density, deltaX, deltaY);
1102
+ }
1103
+ } else if (touchMode == TOUCH_MODE_DRAGGING) {
1104
+ forwardTouchPhase(TOUCH_PHASE_DRAG, x, y, event.getPressure());
1105
+ }
1106
+ lastXPx = x;
1107
+ lastYPx = y;
1108
+ return true;
1109
+ }
1110
+ case MotionEvent.ACTION_UP:
1111
+ switch (touchMode) {
1112
+ case TOUCH_MODE_PENDING:
1113
+ // Under-slop touch: a tap at the start point.
1114
+ forwardTouchPhase(TOUCH_PHASE_DOWN, startXPx, startYPx, 1f);
1115
+ forwardTouchPhase(TOUCH_PHASE_UP, startXPx, startYPx, 0f);
1116
+ break;
1117
+ case TOUCH_MODE_DRAGGING:
1118
+ forwardTouchPhase(TOUCH_PHASE_UP, x, y, 0f);
1119
+ break;
1120
+ default:
1121
+ break;
1122
+ }
1123
+ touchMode = TOUCH_MODE_IDLE;
1124
+ syncTextInput();
1125
+ return true;
1126
+ case MotionEvent.ACTION_CANCEL:
1127
+ if (touchMode == TOUCH_MODE_DRAGGING) {
1128
+ forwardTouchPhase(TOUCH_PHASE_CANCEL, lastXPx, lastYPx, 0f);
1129
+ }
1130
+ touchMode = TOUCH_MODE_IDLE;
1131
+ syncTextInput();
1132
+ return true;
1133
+ default:
1134
+ return super.onTouchEvent(event);
1135
+ }
1136
+ }
1137
+
1138
+ // --------------------------------------------------- hardware keys
1139
+
1140
+ // Hardware keys (and `adb shell input` injections) arrive here:
1141
+ // named control keys forward by name, printable characters commit
1142
+ // as text — the split the desktop key/text seam expects.
1143
+ @Override
1144
+ public boolean onKeyDown(int keyCode, KeyEvent event) {
1145
+ if (nativeApp == 0) return super.onKeyDown(keyCode, event);
1146
+ String name = keyNameForCode(keyCode);
1147
+ if (name != null) {
1148
+ emitKeyDownUp(name, modifiersMask(event));
1149
+ syncTextInput();
1150
+ return true;
1151
+ }
1152
+ int unicode = event.getUnicodeChar();
1153
+ if (unicode != 0 && !event.isCtrlPressed() && !event.isAltPressed()) {
1154
+ commitTextToApp(new String(Character.toChars(unicode)));
1155
+ syncTextInput();
1156
+ return true;
1157
+ }
1158
+ return super.onKeyDown(keyCode, event);
1159
+ }
1160
+
1161
+ private void emitKeyDownUp(String key, int modifiers) {
1162
+ nativeKey(nativeApp, KEY_PHASE_DOWN, key, modifiers);
1163
+ nativeKey(nativeApp, KEY_PHASE_UP, key, modifiers);
1164
+ }
1165
+
1166
+ // ------------------------------------------------ input connection
1167
+
1168
+ @Override
1169
+ public boolean onCheckIsTextEditor() {
1170
+ return true;
1171
+ }
1172
+
1173
+ @Override
1174
+ public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
1175
+ // Deterministic input for tests and desktop-parity text
1176
+ // handling: the runtime owns editing behavior, so system
1177
+ // rewriting stays off.
1178
+ outAttrs.inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
1179
+ outAttrs.imeOptions = EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_FULLSCREEN;
1180
+ return new BaseInputConnection(this, true) {
1181
+ // Mirrors the iOS host's insertText: committing identical
1182
+ // composed text maps to commit_composition; divergent
1183
+ // text cancels before the plain insert so the runtime
1184
+ // never double-applies the composition.
1185
+ @Override
1186
+ public boolean commitText(CharSequence text, int newCursorPosition) {
1187
+ String value = text == null ? "" : text.toString();
1188
+ if (value.isEmpty()) return true;
1189
+ if ("\n".equals(value)) {
1190
+ boolean hadComposition = !composingText.isEmpty();
1191
+ clearComposingState();
1192
+ if (hadComposition) emitIme(IME_COMMIT_COMPOSITION, "", -1);
1193
+ emitKeyDownUp("enter", 0);
1194
+ syncTextInput();
1195
+ return true;
1196
+ }
1197
+ boolean hadComposition = !composingText.isEmpty();
1198
+ String previous = composingText;
1199
+ clearComposingState();
1200
+ if (hadComposition && previous.equals(value)) {
1201
+ emitIme(IME_COMMIT_COMPOSITION, "", -1);
1202
+ return true;
1203
+ }
1204
+ if (hadComposition) emitIme(IME_CANCEL_COMPOSITION, "", -1);
1205
+ commitTextToApp(value);
1206
+ return true;
1207
+ }
1208
+
1209
+ // The live composition forwards (with the caret as a
1210
+ // UTF-8 byte offset) through the same set_composition
1211
+ // path the desktop hosts use, so multi-stage IMEs stay
1212
+ // correct.
1213
+ @Override
1214
+ public boolean setComposingText(CharSequence text, int newCursorPosition) {
1215
+ String value = text == null ? "" : text.toString();
1216
+ if (value.isEmpty()) {
1217
+ boolean hadComposition = !composingText.isEmpty();
1218
+ clearComposingState();
1219
+ if (hadComposition) emitIme(IME_CANCEL_COMPOSITION, "", -1);
1220
+ return true;
1221
+ }
1222
+ composingText = value;
1223
+ long cursorBytes = value.getBytes(StandardCharsets.UTF_8).length;
1224
+ emitIme(IME_SET_COMPOSITION, value, cursorBytes);
1225
+ return true;
1226
+ }
1227
+
1228
+ @Override
1229
+ public boolean finishComposingText() {
1230
+ boolean hadComposition = !composingText.isEmpty();
1231
+ clearComposingState();
1232
+ if (hadComposition) emitIme(IME_COMMIT_COMPOSITION, "", -1);
1233
+ return true;
1234
+ }
1235
+
1236
+ @Override
1237
+ public boolean deleteSurroundingText(int beforeLength, int afterLength) {
1238
+ if (!composingText.isEmpty()) {
1239
+ clearComposingState();
1240
+ emitIme(IME_CANCEL_COMPOSITION, "", -1);
1241
+ return true;
1242
+ }
1243
+ if (beforeLength > 0 && afterLength == 0) {
1244
+ for (int i = 0; i < beforeLength; i++) emitKeyDownUp("backspace", 0);
1245
+ return true;
1246
+ }
1247
+ if (afterLength > 0 && beforeLength == 0) {
1248
+ for (int i = 0; i < afterLength; i++) emitKeyDownUp("delete", 0);
1249
+ return true;
1250
+ }
1251
+ return super.deleteSurroundingText(beforeLength, afterLength);
1252
+ }
1253
+
1254
+ @Override
1255
+ public boolean performEditorAction(int actionCode) {
1256
+ emitKeyDownUp("enter", 0);
1257
+ syncTextInput();
1258
+ return true;
1259
+ }
1260
+
1261
+ @Override
1262
+ public boolean sendKeyEvent(KeyEvent event) {
1263
+ if (event.getAction() == KeyEvent.ACTION_DOWN) {
1264
+ if (event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
1265
+ if (!composingText.isEmpty()) {
1266
+ clearComposingState();
1267
+ emitIme(IME_CANCEL_COMPOSITION, "", -1);
1268
+ return true;
1269
+ }
1270
+ emitKeyDownUp("backspace", 0);
1271
+ return true;
1272
+ }
1273
+ if (event.getKeyCode() == KeyEvent.KEYCODE_FORWARD_DEL) {
1274
+ emitKeyDownUp("delete", 0);
1275
+ return true;
1276
+ }
1277
+ }
1278
+ return super.sendKeyEvent(event);
1279
+ }
1280
+ };
1281
+ }
1282
+
1283
+ private void emitIme(int kind, String text, long cursor) {
1284
+ if (nativeApp == 0) return;
1285
+ nativeIme(nativeApp, kind, text.getBytes(StandardCharsets.UTF_8), cursor);
1286
+ }
1287
+
1288
+ private void commitTextToApp(String text) {
1289
+ if (nativeApp == 0 || text.isEmpty()) return;
1290
+ nativeText(nativeApp, text.getBytes(StandardCharsets.UTF_8));
1291
+ }
1292
+ }
1293
+
1294
+ // Named control keys the runtime's key vocabulary understands; other
1295
+ // key codes fall through to their unicode character (as committed
1296
+ // text) or the platform default.
1297
+ private static String keyNameForCode(int keyCode) {
1298
+ switch (keyCode) {
1299
+ case KeyEvent.KEYCODE_ENTER:
1300
+ case KeyEvent.KEYCODE_NUMPAD_ENTER:
1301
+ return "enter";
1302
+ case KeyEvent.KEYCODE_DEL:
1303
+ return "backspace";
1304
+ case KeyEvent.KEYCODE_FORWARD_DEL:
1305
+ return "delete";
1306
+ case KeyEvent.KEYCODE_ESCAPE:
1307
+ return "escape";
1308
+ case KeyEvent.KEYCODE_TAB:
1309
+ return "tab";
1310
+ case KeyEvent.KEYCODE_DPAD_LEFT:
1311
+ return "arrowleft";
1312
+ case KeyEvent.KEYCODE_DPAD_RIGHT:
1313
+ return "arrowright";
1314
+ case KeyEvent.KEYCODE_DPAD_UP:
1315
+ return "arrowup";
1316
+ case KeyEvent.KEYCODE_DPAD_DOWN:
1317
+ return "arrowdown";
1318
+ case KeyEvent.KEYCODE_MOVE_HOME:
1319
+ return "home";
1320
+ case KeyEvent.KEYCODE_MOVE_END:
1321
+ return "end";
1322
+ case KeyEvent.KEYCODE_PAGE_UP:
1323
+ return "pageup";
1324
+ case KeyEvent.KEYCODE_PAGE_DOWN:
1325
+ return "pagedown";
1326
+ default:
1327
+ return null;
1328
+ }
1329
+ }
1330
+
1331
+ // The embed modifiers mask (1 primary, 2 command, 4 control, 8
1332
+ // option, 16 shift); Android's ctrl doubles as primary, matching the
1333
+ // Linux and Windows hosts.
1334
+ private static int modifiersMask(KeyEvent event) {
1335
+ int mask = 0;
1336
+ if (event.isCtrlPressed()) mask |= 1 | 4;
1337
+ if (event.isAltPressed()) mask |= 8;
1338
+ if (event.isShiftPressed()) mask |= 16;
1339
+ return mask;
1340
+ }
1341
+
1342
+ // ------------------------------------------------------- JNI bridge
1343
+
1344
+ private native long nativeCreate();
1345
+ private native void nativeDestroy(long app);
1346
+ private native void nativeStart(long app);
1347
+ private native void nativeActivate(long app);
1348
+ private native void nativeDeactivate(long app);
1349
+ private native void nativeStop(long app);
1350
+ private native void nativeSurfaceChanged(long app, android.view.Surface surface);
1351
+ private native void nativeSurfaceDestroyed(long app);
1352
+ private native void nativeViewport(long app, float width, float height, float scale, float safeTop, float safeRight, float safeBottom, float safeLeft, float keyboardTop, float keyboardRight, float keyboardBottom, float keyboardLeft);
1353
+ private native void nativeFrame(long app);
1354
+ private native long nativeCanvasRevision(long app);
1355
+ private native long nativePresent(long app, float scale);
1356
+ private native void nativeTouch(long app, long id, int phase, float x, float y, float pressure);
1357
+ private native void nativeScroll(long app, long id, float x, float y, float deltaX, float deltaY);
1358
+ private native void nativeKey(long app, int phase, String key, int modifiers);
1359
+ private native void nativeText(long app, byte[] utf8);
1360
+ private native void nativeIme(long app, int kind, byte[] utf8, long cursor);
1361
+ private native boolean nativeTextInputState(long app, long[] widgetId, float[] frame);
1362
+ private native boolean nativeScrollableWidgetAt(long app, float x, float y);
1363
+ private native void nativeSetAssetRoot(long app, String path);
1364
+ private native void nativeSetAutomationDir(long app, String path);
1365
+ private native void nativeSetTextMeasure(long app);
1366
+ private native void nativeSetAudioService(long app);
1367
+ private native void nativeSetImageService(long app);
1368
+ private native void nativeAudioEvent(long app, int kind, long positionMs, long durationMs, int playing, int buffering);
1369
+ private native String nativeLastError(long app);
1370
+ }