@native-sdk/cli 0.0.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +176 -0
- package/README.md +50 -1
- package/app.zon +30 -0
- package/assets/icon.icns +0 -0
- package/assets/icon.ico +0 -0
- package/assets/icon.png +0 -0
- package/assets/icon.svg +15 -0
- package/assets/native-sdk.entitlements +10 -0
- package/assets/native-sdk.manifest +12 -0
- package/bin/native.js +156 -0
- package/build/app.zig +716 -0
- package/build.zig +2593 -0
- package/build.zig.zon +24 -0
- package/native-sdk.d.ts +615 -0
- package/package.json +45 -8
- package/skill-data/automation/SKILL.md +248 -0
- package/skill-data/core/SKILL.md +249 -0
- package/skill-data/core/references/app-model-runtime.md +141 -0
- package/skill-data/core/references/bridge-security-native-capabilities.md +230 -0
- package/skill-data/core/references/frontend-assets.md +124 -0
- package/skill-data/core/references/project-anatomy.md +108 -0
- package/skill-data/core/references/web-engines-packaging-debugging.md +199 -0
- package/skill-data/native-ui/SKILL.md +1080 -0
- package/skills/native-sdk/SKILL.md +33 -0
- package/src/app_runner/root.zig +740 -0
- package/src/assets/root.zig +20 -0
- package/src/automation/protocol.zig +285 -0
- package/src/automation/root.zig +13 -0
- package/src/automation/server.zig +506 -0
- package/src/automation/snapshot.zig +1202 -0
- package/src/automation/watcher.zig +165 -0
- package/src/bridge/root.zig +507 -0
- package/src/debug/root.zig +246 -0
- package/src/embed/app_exports.zig +11 -0
- package/src/embed/c_api.zig +793 -0
- package/src/embed/c_exports.zig +10 -0
- package/src/embed/chrome.zig +168 -0
- package/src/embed/conversions.zig +359 -0
- package/src/embed/host.zig +960 -0
- package/src/embed/root.zig +81 -0
- package/src/embed/tests.zig +2552 -0
- package/src/embed/types.zig +382 -0
- package/src/embed/ui_host.zig +289 -0
- package/src/extensions/root.zig +197 -0
- package/src/frontend/root.zig +48 -0
- package/src/js/root.zig +65 -0
- package/src/platform/android/NativeSdkActivity.java +1370 -0
- package/src/platform/android/android_host.c +696 -0
- package/src/platform/android/files.zig +9 -0
- package/src/platform/android/native_sdk_app.h +237 -0
- package/src/platform/ios/files.zig +8 -0
- package/src/platform/ios/native_sdk_app.h +289 -0
- package/src/platform/ios/uikit_host.m +2739 -0
- package/src/platform/linux/cef_host.cpp +599 -0
- package/src/platform/linux/gtk_host.c +5362 -0
- package/src/platform/linux/gtk_host.h +265 -0
- package/src/platform/linux/root.zig +1519 -0
- package/src/platform/macos/appkit_host.h +604 -0
- package/src/platform/macos/appkit_host.m +10392 -0
- package/src/platform/macos/automation_host.h +14 -0
- package/src/platform/macos/automation_host.m +12 -0
- package/src/platform/macos/cef_host.mm +3028 -0
- package/src/platform/macos/root.zig +2260 -0
- package/src/platform/null_platform.zig +2232 -0
- package/src/platform/null_platform_tests.zig +670 -0
- package/src/platform/policy_values.zig +14 -0
- package/src/platform/root.zig +181 -0
- package/src/platform/types.zig +2681 -0
- package/src/platform/windows/cef_host.cpp +3 -0
- package/src/platform/windows/root.zig +1521 -0
- package/src/platform/windows/webview2_host.cpp +6230 -0
- package/src/primitives/app_dirs/root.zig +440 -0
- package/src/primitives/app_manifest/root.zig +109 -0
- package/src/primitives/app_manifest/tests.zig +758 -0
- package/src/primitives/app_manifest/types.zig +587 -0
- package/src/primitives/app_manifest/validation.zig +828 -0
- package/src/primitives/assets/root.zig +520 -0
- package/src/primitives/canvas/a11y_audit.zig +390 -0
- package/src/primitives/canvas/a11y_audit_tests.zig +225 -0
- package/src/primitives/canvas/app_icon.zig +1590 -0
- package/src/primitives/canvas/chart.zig +392 -0
- package/src/primitives/canvas/chart_tests.zig +751 -0
- package/src/primitives/canvas/commands.zig +446 -0
- package/src/primitives/canvas/drawing.zig +309 -0
- package/src/primitives/canvas/equality.zig +316 -0
- package/src/primitives/canvas/events.zig +696 -0
- package/src/primitives/canvas/font_coverage.zig +118 -0
- package/src/primitives/canvas/font_ttf.zig +510 -0
- package/src/primitives/canvas/font_ttf_tests.zig +280 -0
- package/src/primitives/canvas/fonts/Geist-Regular.ttf +0 -0
- package/src/primitives/canvas/fonts/GeistMono-Regular.ttf +0 -0
- package/src/primitives/canvas/frame.zig +679 -0
- package/src/primitives/canvas/frame_metrics.zig +462 -0
- package/src/primitives/canvas/gpu.zig +639 -0
- package/src/primitives/canvas/hash.zig +112 -0
- package/src/primitives/canvas/icons/alert.svg +1 -0
- package/src/primitives/canvas/icons/archive.svg +1 -0
- package/src/primitives/canvas/icons/arrow-down.svg +1 -0
- package/src/primitives/canvas/icons/arrow-right.svg +1 -0
- package/src/primitives/canvas/icons/arrow-up.svg +1 -0
- package/src/primitives/canvas/icons/check-circle.svg +1 -0
- package/src/primitives/canvas/icons/check.svg +1 -0
- package/src/primitives/canvas/icons/chevron-down.svg +1 -0
- package/src/primitives/canvas/icons/chevron-left.svg +1 -0
- package/src/primitives/canvas/icons/chevron-right.svg +1 -0
- package/src/primitives/canvas/icons/chevron-up.svg +1 -0
- package/src/primitives/canvas/icons/circle-dot.svg +1 -0
- package/src/primitives/canvas/icons/clock.svg +1 -0
- package/src/primitives/canvas/icons/copy.svg +1 -0
- package/src/primitives/canvas/icons/download.svg +1 -0
- package/src/primitives/canvas/icons/edit.svg +1 -0
- package/src/primitives/canvas/icons/ellipsis.svg +1 -0
- package/src/primitives/canvas/icons/external-link.svg +1 -0
- package/src/primitives/canvas/icons/eye.svg +1 -0
- package/src/primitives/canvas/icons/file-text.svg +1 -0
- package/src/primitives/canvas/icons/folder-open.svg +1 -0
- package/src/primitives/canvas/icons/folder.svg +1 -0
- package/src/primitives/canvas/icons/git-branch.svg +1 -0
- package/src/primitives/canvas/icons/git-merge.svg +1 -0
- package/src/primitives/canvas/icons/git-pull-request.svg +1 -0
- package/src/primitives/canvas/icons/info.svg +1 -0
- package/src/primitives/canvas/icons/menu.svg +1 -0
- package/src/primitives/canvas/icons/missing.svg +1 -0
- package/src/primitives/canvas/icons/moon.svg +1 -0
- package/src/primitives/canvas/icons/music.svg +1 -0
- package/src/primitives/canvas/icons/panel-left.svg +1 -0
- package/src/primitives/canvas/icons/panel-right.svg +1 -0
- package/src/primitives/canvas/icons/pause.svg +1 -0
- package/src/primitives/canvas/icons/play.svg +1 -0
- package/src/primitives/canvas/icons/plus.svg +1 -0
- package/src/primitives/canvas/icons/refresh-cw.svg +1 -0
- package/src/primitives/canvas/icons/repeat.svg +1 -0
- package/src/primitives/canvas/icons/save.svg +1 -0
- package/src/primitives/canvas/icons/search.svg +1 -0
- package/src/primitives/canvas/icons/send.svg +1 -0
- package/src/primitives/canvas/icons/settings.svg +1 -0
- package/src/primitives/canvas/icons/shuffle.svg +1 -0
- package/src/primitives/canvas/icons/skip-back.svg +1 -0
- package/src/primitives/canvas/icons/skip-forward.svg +1 -0
- package/src/primitives/canvas/icons/sun.svg +1 -0
- package/src/primitives/canvas/icons/terminal.svg +1 -0
- package/src/primitives/canvas/icons/trash.svg +1 -0
- package/src/primitives/canvas/icons/volume.svg +1 -0
- package/src/primitives/canvas/icons/wrench.svg +1 -0
- package/src/primitives/canvas/icons/x-circle.svg +1 -0
- package/src/primitives/canvas/icons/x.svg +1 -0
- package/src/primitives/canvas/icons.zig +249 -0
- package/src/primitives/canvas/layout_audit.zig +744 -0
- package/src/primitives/canvas/layout_audit_tests.zig +426 -0
- package/src/primitives/canvas/markdown.zig +1031 -0
- package/src/primitives/canvas/markdown_hostile_tests.zig +471 -0
- package/src/primitives/canvas/markdown_tests.zig +538 -0
- package/src/primitives/canvas/plan_key_index.zig +120 -0
- package/src/primitives/canvas/png.zig +355 -0
- package/src/primitives/canvas/reference.zig +1457 -0
- package/src/primitives/canvas/reference_blur.zig +104 -0
- package/src/primitives/canvas/reference_memo.zig +322 -0
- package/src/primitives/canvas/reference_paths.zig +184 -0
- package/src/primitives/canvas/reference_tests.zig +1650 -0
- package/src/primitives/canvas/render.zig +747 -0
- package/src/primitives/canvas/render_effects.zig +255 -0
- package/src/primitives/canvas/render_fingerprints.zig +256 -0
- package/src/primitives/canvas/render_generic_resources.zig +376 -0
- package/src/primitives/canvas/render_images.zig +247 -0
- package/src/primitives/canvas/render_layers.zig +260 -0
- package/src/primitives/canvas/render_paths.zig +347 -0
- package/src/primitives/canvas/render_resources.zig +51 -0
- package/src/primitives/canvas/render_tests.zig +3186 -0
- package/src/primitives/canvas/root.zig +744 -0
- package/src/primitives/canvas/serialization.zig +1528 -0
- package/src/primitives/canvas/svg_icon.zig +636 -0
- package/src/primitives/canvas/svg_icon_tests.zig +312 -0
- package/src/primitives/canvas/test_support.zig +422 -0
- package/src/primitives/canvas/testdata/markdown_document.md +83 -0
- package/src/primitives/canvas/tests.zig +30 -0
- package/src/primitives/canvas/text.zig +82 -0
- package/src/primitives/canvas/text_atlas.zig +408 -0
- package/src/primitives/canvas/text_batch_tests.zig +431 -0
- package/src/primitives/canvas/text_interaction.zig +615 -0
- package/src/primitives/canvas/text_layout.zig +1069 -0
- package/src/primitives/canvas/text_layout_cache.zig +281 -0
- package/src/primitives/canvas/text_layout_hash.zig +113 -0
- package/src/primitives/canvas/text_layout_types.zig +128 -0
- package/src/primitives/canvas/text_measure_cache.zig +279 -0
- package/src/primitives/canvas/text_metrics.zig +309 -0
- package/src/primitives/canvas/text_metrics_tests.zig +262 -0
- package/src/primitives/canvas/text_span_tests.zig +608 -0
- package/src/primitives/canvas/text_spans.zig +1010 -0
- package/src/primitives/canvas/text_tests.zig +1949 -0
- package/src/primitives/canvas/themes/geist.zig +470 -0
- package/src/primitives/canvas/tokens.zig +1522 -0
- package/src/primitives/canvas/ui.zig +2686 -0
- package/src/primitives/canvas/ui_markup.zig +3791 -0
- package/src/primitives/canvas/ui_markup_binary.zig +522 -0
- package/src/primitives/canvas/ui_markup_binary_tests.zig +591 -0
- package/src/primitives/canvas/ui_markup_compiled.zig +2565 -0
- package/src/primitives/canvas/ui_markup_compiled_tests.zig +1669 -0
- package/src/primitives/canvas/ui_markup_contract.zig +1620 -0
- package/src/primitives/canvas/ui_markup_contract_tests.zig +953 -0
- package/src/primitives/canvas/ui_markup_edit.zig +416 -0
- package/src/primitives/canvas/ui_markup_edit_tests.zig +341 -0
- package/src/primitives/canvas/ui_markup_expr.zig +1152 -0
- package/src/primitives/canvas/ui_markup_expr_tests.zig +779 -0
- package/src/primitives/canvas/ui_markup_huge_model_tests.zig +505 -0
- package/src/primitives/canvas/ui_markup_reflect.zig +127 -0
- package/src/primitives/canvas/ui_markup_tests.zig +1545 -0
- package/src/primitives/canvas/ui_markup_view.zig +2352 -0
- package/src/primitives/canvas/ui_markup_view_tests.zig +3709 -0
- package/src/primitives/canvas/ui_provenance.zig +96 -0
- package/src/primitives/canvas/ui_provenance_tests.zig +186 -0
- package/src/primitives/canvas/ui_schema.zig +825 -0
- package/src/primitives/canvas/ui_schema_tests.zig +128 -0
- package/src/primitives/canvas/ui_tests.zig +1432 -0
- package/src/primitives/canvas/vector.zig +919 -0
- package/src/primitives/canvas/vector_tests.zig +547 -0
- package/src/primitives/canvas/virtual_extent_tests.zig +317 -0
- package/src/primitives/canvas/virtual_extents.zig +540 -0
- package/src/primitives/canvas/widget_access.zig +208 -0
- package/src/primitives/canvas/widget_anchored_tests.zig +264 -0
- package/src/primitives/canvas/widget_builtin_tests.zig +3160 -0
- package/src/primitives/canvas/widget_invalidation.zig +748 -0
- package/src/primitives/canvas/widget_layout.zig +2055 -0
- package/src/primitives/canvas/widget_layout_tests.zig +2691 -0
- package/src/primitives/canvas/widget_metrics.zig +228 -0
- package/src/primitives/canvas/widget_render.zig +2534 -0
- package/src/primitives/canvas/widget_render_controls.zig +1563 -0
- package/src/primitives/canvas/widget_render_scroll.zig +136 -0
- package/src/primitives/canvas/widget_render_style.zig +626 -0
- package/src/primitives/canvas/widget_render_surfaces.zig +794 -0
- package/src/primitives/canvas/widget_routing.zig +475 -0
- package/src/primitives/canvas/widget_runtime.zig +307 -0
- package/src/primitives/canvas/widget_runtime_tests.zig +3015 -0
- package/src/primitives/canvas/widget_semantics.zig +480 -0
- package/src/primitives/canvas/widget_semantics_tests.zig +2129 -0
- package/src/primitives/canvas/widget_tests.zig +8 -0
- package/src/primitives/canvas/widget_text_input.zig +351 -0
- package/src/primitives/canvas/widget_text_select.zig +147 -0
- package/src/primitives/canvas/widget_tree.zig +232 -0
- package/src/primitives/canvas/widgets.zig +1319 -0
- package/src/primitives/diagnostics/root.zig +445 -0
- package/src/primitives/geometry/root.zig +889 -0
- package/src/primitives/json/root.zig +272 -0
- package/src/primitives/platform_info/root.zig +450 -0
- package/src/primitives/trace/root.zig +569 -0
- package/src/root.zig +165 -0
- package/src/runtime/api.zig +431 -0
- package/src/runtime/async_bridge.zig +49 -0
- package/src/runtime/automation_commands.zig +686 -0
- package/src/runtime/automation_liveness_tests.zig +140 -0
- package/src/runtime/automation_snapshot.zig +246 -0
- package/src/runtime/automation_widget_dispatch.zig +617 -0
- package/src/runtime/bridge_dispatch_tests.zig +202 -0
- package/src/runtime/bridge_payload.zig +194 -0
- package/src/runtime/bridge_permission_tests.zig +551 -0
- package/src/runtime/bridge_responses.zig +414 -0
- package/src/runtime/builtin_bridge.zig +554 -0
- package/src/runtime/canvas_budget_edge_tests.zig +415 -0
- package/src/runtime/canvas_font_tests.zig +410 -0
- package/src/runtime/canvas_fonts.zig +229 -0
- package/src/runtime/canvas_frame.zig +1734 -0
- package/src/runtime/canvas_frame_animation_tests.zig +609 -0
- package/src/runtime/canvas_frame_cache_tests.zig +333 -0
- package/src/runtime/canvas_frame_helpers.zig +414 -0
- package/src/runtime/canvas_frame_invalidation_tests.zig +544 -0
- package/src/runtime/canvas_frame_packet_tests.zig +1353 -0
- package/src/runtime/canvas_frame_patch_tests.zig +1051 -0
- package/src/runtime/canvas_frame_retained_tests.zig +753 -0
- package/src/runtime/canvas_frame_tests.zig +9 -0
- package/src/runtime/canvas_frame_text_layout_budget_tests.zig +149 -0
- package/src/runtime/canvas_image_tests.zig +362 -0
- package/src/runtime/canvas_images.zig +224 -0
- package/src/runtime/canvas_limits.zig +317 -0
- package/src/runtime/canvas_screenshot_tests.zig +289 -0
- package/src/runtime/canvas_widget_accessibility_tests.zig +1494 -0
- package/src/runtime/canvas_widget_anchored_tests.zig +678 -0
- package/src/runtime/canvas_widget_chart_tests.zig +249 -0
- package/src/runtime/canvas_widget_clipboard_tests.zig +399 -0
- package/src/runtime/canvas_widget_context_menu.zig +318 -0
- package/src/runtime/canvas_widget_context_menu_tests.zig +462 -0
- package/src/runtime/canvas_widget_control_tests.zig +2164 -0
- package/src/runtime/canvas_widget_disclosure_tests.zig +440 -0
- package/src/runtime/canvas_widget_display.zig +677 -0
- package/src/runtime/canvas_widget_event_tests.zig +1779 -0
- package/src/runtime/canvas_widget_events.zig +1098 -0
- package/src/runtime/canvas_widget_floating_tests.zig +695 -0
- package/src/runtime/canvas_widget_layout_tests.zig +26 -0
- package/src/runtime/canvas_widget_runtime.zig +1335 -0
- package/src/runtime/canvas_widget_scroll_driver_tests.zig +582 -0
- package/src/runtime/canvas_widget_scroll_drivers.zig +202 -0
- package/src/runtime/canvas_widget_scroll_tests.zig +1549 -0
- package/src/runtime/canvas_widget_semantics_tests.zig +810 -0
- package/src/runtime/canvas_widget_split_tree_tests.zig +1031 -0
- package/src/runtime/canvas_widget_state.zig +798 -0
- package/src/runtime/canvas_widget_text_tests.zig +2104 -0
- package/src/runtime/canvas_widget_window_drag_tests.zig +284 -0
- package/src/runtime/clock.zig +231 -0
- package/src/runtime/core.zig +927 -0
- package/src/runtime/effects.zig +4197 -0
- package/src/runtime/effects_audio_tests.zig +690 -0
- package/src/runtime/effects_clipboard_tests.zig +317 -0
- package/src/runtime/effects_fetch_tests.zig +1031 -0
- package/src/runtime/effects_file_tests.zig +407 -0
- package/src/runtime/effects_tests.zig +1251 -0
- package/src/runtime/flow.zig +1175 -0
- package/src/runtime/frame_profile.zig +221 -0
- package/src/runtime/gpu_surface_events.zig +639 -0
- package/src/runtime/launch_timing.zig +59 -0
- package/src/runtime/markdown_app_tests.zig +224 -0
- package/src/runtime/native_command_event_tests.zig +431 -0
- package/src/runtime/platform_bridge_tests.zig +8 -0
- package/src/runtime/platform_config_tests.zig +392 -0
- package/src/runtime/root.zig +150 -0
- package/src/runtime/runtime_event_tests.zig +1079 -0
- package/src/runtime/session_journal.zig +1522 -0
- package/src/runtime/session_record.zig +332 -0
- package/src/runtime/session_replay.zig +274 -0
- package/src/runtime/session_state.zig +30 -0
- package/src/runtime/session_tests.zig +399 -0
- package/src/runtime/shell_layout.zig +472 -0
- package/src/runtime/shell_layout_tests.zig +1246 -0
- package/src/runtime/shell_view_tests.zig +604 -0
- package/src/runtime/state.zig +110 -0
- package/src/runtime/system_services.zig +392 -0
- package/src/runtime/test_support.zig +79 -0
- package/src/runtime/tests.zig +30 -0
- package/src/runtime/ui_app.zig +3290 -0
- package/src/runtime/ui_app_huge_model_tests.zig +351 -0
- package/src/runtime/ui_app_provenance.zig +370 -0
- package/src/runtime/ui_app_tests.zig +3254 -0
- package/src/runtime/ui_app_virtual_variable_tests.zig +485 -0
- package/src/runtime/ui_app_window_tests.zig +442 -0
- package/src/runtime/validation.zig +206 -0
- package/src/runtime/view.zig +908 -0
- package/src/runtime/view_canvas.zig +850 -0
- package/src/runtime/view_widget_control.zig +433 -0
- package/src/runtime/view_widget_scroll.zig +360 -0
- package/src/runtime/view_widget_text.zig +275 -0
- package/src/runtime/view_widget_tree.zig +843 -0
- package/src/runtime/webview_view_bridge_tests.zig +664 -0
- package/src/runtime/widget_bridge.zig +231 -0
- package/src/runtime/window_command_bridge_tests.zig +403 -0
- package/src/runtime/window_storage.zig +255 -0
- package/src/runtime/window_view_runtime.zig +727 -0
- package/src/runtime/window_views.zig +334 -0
- package/src/security/root.zig +118 -0
- package/src/tooling/android.zig +1172 -0
- package/src/tooling/assets.zig +128 -0
- package/src/tooling/buildgraph.zig +379 -0
- package/src/tooling/cef.zig +671 -0
- package/src/tooling/codesign.zig +172 -0
- package/src/tooling/components/identity_tests.zig +185 -0
- package/src/tooling/components/stepper.zig +113 -0
- package/src/tooling/components/timeline.native +27 -0
- package/src/tooling/components/timeline_item.zig +131 -0
- package/src/tooling/default_icon.icns +0 -0
- package/src/tooling/default_icon.png +0 -0
- package/src/tooling/dev.zig +172 -0
- package/src/tooling/doctor.zig +349 -0
- package/src/tooling/eject_components.zig +170 -0
- package/src/tooling/embedlib.zig +290 -0
- package/src/tooling/ios.zig +528 -0
- package/src/tooling/manifest.zig +1939 -0
- package/src/tooling/package.zig +2388 -0
- package/src/tooling/process_tree.zig +114 -0
- package/src/tooling/raw_manifest.zig +193 -0
- package/src/tooling/root.zig +22 -0
- package/src/tooling/templates.zig +3191 -0
- package/src/tooling/toolchain.zig +371 -0
- package/src/tooling/verbs.zig +204 -0
- package/src/tooling/web_engine.zig +135 -0
- package/src/tooling/xcodeproj.zig +462 -0
- package/src/window_state/root.zig +507 -0
- package/index.js +0 -2
|
@@ -0,0 +1,2739 @@
|
|
|
1
|
+
// The toolkit-owned iOS host: a complete UIKit application around the
|
|
2
|
+
// embed C ABI (src/embed/c_api.zig). `native dev --target ios` and
|
|
3
|
+
// `native package --target ios` compile this file against the app's
|
|
4
|
+
// embed static library — an app project carries zero host code, and
|
|
5
|
+
// everything app-specific (bundle id, names, icons) arrives through the
|
|
6
|
+
// generated Info.plist and asset catalog. The host tier is built ON the
|
|
7
|
+
// embed ABI, not beside it: a hand-written host (see
|
|
8
|
+
// examples/mobile-canvas/ios) remains a first-class standalone use.
|
|
9
|
+
//
|
|
10
|
+
// Presentation mirrors the macOS raster path in
|
|
11
|
+
// src/platform/macos/appkit_host.m — the embed host renders the retained
|
|
12
|
+
// scene through the CPU reference renderer into the host's RETAINED
|
|
13
|
+
// staging buffer (`native_sdk_app_render_pixels_damage`, RGBA8): each
|
|
14
|
+
// changed frame the embed side rasters only its dirty region and reports
|
|
15
|
+
// the damaged rect, so the host uploads exactly that region into a
|
|
16
|
+
// shared RGBA8 MTLTexture (`replaceRegion` with the rect) and presents
|
|
17
|
+
// it as a fullscreen quad sampled by the same tiny pipeline the macOS
|
|
18
|
+
// host's canvas presenter compiles (the render pass converts to the
|
|
19
|
+
// drawable's BGRA on the way out, so no CPU swizzle pass exists). A
|
|
20
|
+
// CADisplayLink pumps `native_sdk_app_frame` and the canvas revision from
|
|
21
|
+
// `native_sdk_app_gpu_frame_state` gates re-renders, so an idle app costs
|
|
22
|
+
// one ABI call per tick and acquires no drawable and uploads no bytes;
|
|
23
|
+
// a revision bump with no visual change vends no drawable either
|
|
24
|
+
// (path=no-damage in the trace). NATIVE_SDK_GPU_FRAME_TRACE=1 prints the
|
|
25
|
+
// same per-present/nil-drawable trace lines the macOS host does — now
|
|
26
|
+
// carrying the damage rect — plus a once-per-second structural summary
|
|
27
|
+
// (ticks, idle short-circuits, presents, drawables acquired, upload
|
|
28
|
+
// bytes, present-path CPU).
|
|
29
|
+
//
|
|
30
|
+
// Lifecycle follows the app's scene state the way the macOS host follows
|
|
31
|
+
// window occlusion: on entering the background the display link pauses
|
|
32
|
+
// (a backgrounded app presents nothing, and Metal work submitted from
|
|
33
|
+
// the background is killed by the watchdog); returning to the foreground
|
|
34
|
+
// resumes the pump and re-presents the retained canvas once even when
|
|
35
|
+
// the revision is unchanged, because the drawable pool may have been
|
|
36
|
+
// purged while covered — the mobile mirror of the macOS occlusion
|
|
37
|
+
// observer's glass flush. Resign/become-active additionally forward
|
|
38
|
+
// `native_sdk_app_deactivate`/`activate`, matching the Android host's
|
|
39
|
+
// onPause/onResume.
|
|
40
|
+
//
|
|
41
|
+
// Input: UITouch sequences forward through the ABI touch/scroll exports
|
|
42
|
+
// in the same point coordinate space the viewport export established
|
|
43
|
+
// (view points; the render scale multiplies pixels, not input). A
|
|
44
|
+
// touch-slop state machine mirrors UIScrollView's delayed content
|
|
45
|
+
// touches: an under-slop touch is a tap (pointer_down + pointer_up), an
|
|
46
|
+
// over-slop move over a scrollable widget pans it through the existing
|
|
47
|
+
// scroll reconciliation (`native_sdk_app_scroll` wheel deltas), and an
|
|
48
|
+
// over-slop move elsewhere becomes pointer_down + pointer_drag so sliders
|
|
49
|
+
// and text selection keep desktop semantics. Long-press is not modeled by
|
|
50
|
+
// the embed ABI, so the host does not synthesize one.
|
|
51
|
+
//
|
|
52
|
+
// The platform keyboard keys off `native_sdk_app_text_input_state`: while
|
|
53
|
+
// an editable text widget owns focus the canvas view holds UIKit first
|
|
54
|
+
// responder (system keyboard up); when focus leaves it resigns (keyboard
|
|
55
|
+
// down). Typed characters flow through `native_sdk_app_text` and marked
|
|
56
|
+
// text (UITextInput composition, dead keys, CJK) maps onto the same
|
|
57
|
+
// `native_sdk_app_ime` set/commit/cancel path the macOS host drives from
|
|
58
|
+
// NSTextInputClient — see appkit_host.m setMarkedText:/insertText:.
|
|
59
|
+
//
|
|
60
|
+
// Layout: the viewport export carries the view's safe-area insets, which
|
|
61
|
+
// the embed host republishes over the window-chrome channel — apps pad
|
|
62
|
+
// via `on_chrome` exactly as they do for the macOS titlebar band, and
|
|
63
|
+
// apps without the hook keep the automatic runtime inset.
|
|
64
|
+
//
|
|
65
|
+
// Text metrics: the host registers a CoreText-backed measure callback
|
|
66
|
+
// (`native_sdk_app_set_text_measure`) before start, mirroring the macOS
|
|
67
|
+
// host's `native_sdk_appkit_measure_text` — layout then uses real
|
|
68
|
+
// typographic widths instead of the deterministic estimator. Glyph
|
|
69
|
+
// RENDERING stays the reference renderer's shapes; only measurement
|
|
70
|
+
// changes. Launch with --estimator-text-metrics to keep the estimator
|
|
71
|
+
// (before/after comparisons, deterministic goldens).
|
|
72
|
+
//
|
|
73
|
+
// Audio: the host registers the platform audio service
|
|
74
|
+
// (`native_sdk_app_set_audio_service`) before start, mirroring the macOS
|
|
75
|
+
// AppKit host's player: one AVAudioPlayer for local files and verified
|
|
76
|
+
// cache entries, one AVPlayer for progressive URL streams (with a parallel
|
|
77
|
+
// NSURLSession download filling the track cache: part file, size-verified,
|
|
78
|
+
// atomic rename), ~500ms position ticks only while playing, and one
|
|
79
|
+
// completion at natural end — all reported back through
|
|
80
|
+
// `native_sdk_app_audio_event`. iOS additionally owns an audio session:
|
|
81
|
+
// category playback (configured at registration), activated on the first
|
|
82
|
+
// play, and system interruptions (a phone call, another app's exclusive
|
|
83
|
+
// audio) pause the player and report the paused state honestly through an
|
|
84
|
+
// immediate position event. Background audio and now-playing-center
|
|
85
|
+
// integration are out of scope for this host today.
|
|
86
|
+
//
|
|
87
|
+
// Images: the host registers the platform image decoder
|
|
88
|
+
// (`native_sdk_app_set_image_service`) before start, mirroring the macOS
|
|
89
|
+
// host's `native_sdk_appkit_decode_image` byte for byte: CGImageSource
|
|
90
|
+
// (ImageIO) decodes PNG, JPEG, and every other codec the OS ships into
|
|
91
|
+
// straight-alpha RGBA8, so `fx.registerImageBytes` registers real pixels
|
|
92
|
+
// (album covers, fetched avatars) instead of declining. Decoding is
|
|
93
|
+
// synchronous inside the registration call and the runtime copies the
|
|
94
|
+
// pixels into its bounded image registry once — frames then reference the
|
|
95
|
+
// registered pixels by id, never re-decoding.
|
|
96
|
+
|
|
97
|
+
#import <UIKit/UIKit.h>
|
|
98
|
+
#import <Metal/Metal.h>
|
|
99
|
+
#import <QuartzCore/CAMetalLayer.h>
|
|
100
|
+
#import <AVFoundation/AVFoundation.h>
|
|
101
|
+
#import <ImageIO/ImageIO.h>
|
|
102
|
+
|
|
103
|
+
#include <dlfcn.h>
|
|
104
|
+
#include <mach-o/dyld.h>
|
|
105
|
+
#include <stdlib.h>
|
|
106
|
+
|
|
107
|
+
#include "native_sdk_app.h"
|
|
108
|
+
|
|
109
|
+
// Zig's std.debug stack-trace symbolication (pulled in by the embed lib's
|
|
110
|
+
// panic path) references `_dyld_get_image_header_containing_address`, which
|
|
111
|
+
// the iOS SDK marks __API_UNAVAILABLE(ios). Provide the documented
|
|
112
|
+
// replacement (dladdr) under the old symbol so the static lib links; it
|
|
113
|
+
// only runs while formatting a panic trace.
|
|
114
|
+
const struct mach_header *_dyld_get_image_header_containing_address(const void *address) {
|
|
115
|
+
Dl_info info;
|
|
116
|
+
if (dladdr(address, &info) != 0 && info.dli_fbase != NULL) {
|
|
117
|
+
return (const struct mach_header *)info.dli_fbase;
|
|
118
|
+
}
|
|
119
|
+
return NULL;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// ---------------------------------------------------------------- frame trace
|
|
123
|
+
|
|
124
|
+
/* Frame-trace mode (NATIVE_SDK_GPU_FRAME_TRACE=1): the iOS mirror of the
|
|
125
|
+
* macOS host's trace — one stderr line per REAL present naming how long
|
|
126
|
+
* nextDrawable held the main thread and how many bytes the frame
|
|
127
|
+
* uploaded, plus a once-per-second cumulative summary (display ticks,
|
|
128
|
+
* idle short-circuits, presents, drawables acquired, upload bytes,
|
|
129
|
+
* present-path CPU time). The summary is how the idle law shows up as a
|
|
130
|
+
* number: an idle app's drawable/upload counters must not move. */
|
|
131
|
+
static BOOL NativeSdkGpuFrameTraceEnabled(void) {
|
|
132
|
+
static BOOL enabled;
|
|
133
|
+
static dispatch_once_t once;
|
|
134
|
+
dispatch_once(&once, ^{
|
|
135
|
+
const char *value = getenv("NATIVE_SDK_GPU_FRAME_TRACE");
|
|
136
|
+
enabled = value && value[0] != 0 && strcmp(value, "0") != 0;
|
|
137
|
+
});
|
|
138
|
+
return enabled;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
static uint64_t NativeSdkTimestampNanoseconds(void) {
|
|
142
|
+
return (uint64_t)([[NSDate date] timeIntervalSince1970] * 1000000000.0);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// ------------------------------------------------------------ text metrics
|
|
146
|
+
|
|
147
|
+
// Italicizes a resolved sans face for the reserved italic span font ids
|
|
148
|
+
// (5 and 6) — the iOS mirror of appkit_host.m's NativeSdkItalicSansFont.
|
|
149
|
+
// Prefers a real italic face from the same family via font descriptor
|
|
150
|
+
// traits (SF has one; Geist does not ship a sans italic) and falls back to
|
|
151
|
+
// a sheared descriptor matrix so a future draw path slants visibly. The
|
|
152
|
+
// shear leaves advance widths unchanged, so measurement matches the
|
|
153
|
+
// upright face either way.
|
|
154
|
+
static UIFont *NativeSdkItalicSansFont(UIFont *font) {
|
|
155
|
+
if (!font) return nil;
|
|
156
|
+
UIFontDescriptor *italic = [font.fontDescriptor fontDescriptorWithSymbolicTraits:
|
|
157
|
+
(font.fontDescriptor.symbolicTraits | UIFontDescriptorTraitItalic)];
|
|
158
|
+
if (italic) {
|
|
159
|
+
UIFont *converted = [UIFont fontWithDescriptor:italic size:font.pointSize];
|
|
160
|
+
if (converted && (converted.fontDescriptor.symbolicTraits & UIFontDescriptorTraitItalic) != 0) return converted;
|
|
161
|
+
}
|
|
162
|
+
UIFontDescriptor *oblique = [font.fontDescriptor fontDescriptorWithMatrix:CGAffineTransformMake(1, 0, 0.2, 1, 0, 0)];
|
|
163
|
+
UIFont *sheared = oblique ? [UIFont fontWithDescriptor:oblique size:font.pointSize] : nil;
|
|
164
|
+
return sheared ?: font;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// Resolves the weighted sans faces behind the reserved span font ids 3
|
|
168
|
+
// (medium) and 4/6 (bold) — the iOS mirror of appkit_host.m's
|
|
169
|
+
// NativeSdkWeightedSansFont: explicit weighted candidate names first
|
|
170
|
+
// (Geist Medium / Geist Bold when bundled), then the matching SF weight.
|
|
171
|
+
// Never answers with the regular face, so weighted span ids always measure
|
|
172
|
+
// (and will draw) heavier than regular.
|
|
173
|
+
static UIFont *NativeSdkWeightedSansFont(NSArray<NSString *> *names, UIFontWeight systemWeight, CGFloat size) {
|
|
174
|
+
for (NSString *name in names) {
|
|
175
|
+
UIFont *font = [UIFont fontWithName:name size:size];
|
|
176
|
+
if (font) return font;
|
|
177
|
+
}
|
|
178
|
+
return [UIFont systemFontOfSize:size weight:systemWeight];
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Resolves a canvas font id to the UIFont measurement uses — the iOS
|
|
182
|
+
// mirror of appkit_host.m's NativeSdkFontForFontId (Geist when bundled,
|
|
183
|
+
// system fonts otherwise). Ids 3-6 are the reserved sans span variants
|
|
184
|
+
// (medium, bold, italic, bold italic); everything else keeps the regular
|
|
185
|
+
// sans/mono candidates. Resolved fonts are cached per (font id, size).
|
|
186
|
+
static UIFont *NativeSdkFontForFontId(uint64_t value, CGFloat size) {
|
|
187
|
+
static NSCache<NSString *, UIFont *> *cache = nil;
|
|
188
|
+
static dispatch_once_t onceToken;
|
|
189
|
+
dispatch_once(&onceToken, ^{
|
|
190
|
+
cache = [[NSCache alloc] init];
|
|
191
|
+
cache.countLimit = 256;
|
|
192
|
+
});
|
|
193
|
+
NSString *key = [NSString stringWithFormat:@"%llu/%.3f", (unsigned long long)value, (double)size];
|
|
194
|
+
UIFont *cached = [cache objectForKey:key];
|
|
195
|
+
if (cached) return cached;
|
|
196
|
+
UIFont *font = nil;
|
|
197
|
+
if (value == 2) {
|
|
198
|
+
NSArray<NSString *> *candidates = @[ @"Geist Mono", @"GeistMono-Regular", @"Geist Mono Regular" ];
|
|
199
|
+
for (NSString *name in candidates) {
|
|
200
|
+
font = [UIFont fontWithName:name size:size];
|
|
201
|
+
if (font) break;
|
|
202
|
+
}
|
|
203
|
+
if (!font) font = [UIFont monospacedSystemFontOfSize:size weight:UIFontWeightRegular];
|
|
204
|
+
} else {
|
|
205
|
+
NSArray<NSString *> *candidates = @[ @"Geist", @"Geist-Regular", @"Geist Sans", @"Geist Sans Regular" ];
|
|
206
|
+
UIFont *base = nil;
|
|
207
|
+
for (NSString *name in candidates) {
|
|
208
|
+
base = [UIFont fontWithName:name size:size];
|
|
209
|
+
if (base) break;
|
|
210
|
+
}
|
|
211
|
+
if (!base) base = [UIFont systemFontOfSize:size];
|
|
212
|
+
switch (value) {
|
|
213
|
+
case 3:
|
|
214
|
+
font = NativeSdkWeightedSansFont(@[ @"Geist-Medium", @"Geist Medium" ], UIFontWeightMedium, size);
|
|
215
|
+
break;
|
|
216
|
+
case 4:
|
|
217
|
+
font = NativeSdkWeightedSansFont(@[ @"Geist-Bold", @"Geist Bold" ], UIFontWeightBold, size);
|
|
218
|
+
break;
|
|
219
|
+
case 5:
|
|
220
|
+
font = NativeSdkItalicSansFont(base);
|
|
221
|
+
break;
|
|
222
|
+
case 6:
|
|
223
|
+
font = NativeSdkItalicSansFont(NativeSdkWeightedSansFont(@[ @"Geist-Bold", @"Geist Bold" ], UIFontWeightBold, size));
|
|
224
|
+
break;
|
|
225
|
+
default:
|
|
226
|
+
font = base;
|
|
227
|
+
break;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
if (font) [cache setObject:font forKey:key];
|
|
231
|
+
return font;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// CoreText-backed measure callback registered over the embed ABI: the
|
|
235
|
+
// typographic width of a single-line run, measured with the same font
|
|
236
|
+
// resolution and string-attribute metrics ([NSString sizeWithAttributes:])
|
|
237
|
+
// the macOS packet renderer draws with. Returns a negative value when the
|
|
238
|
+
// bytes are not valid UTF-8 so layout falls back to its estimator. Shaped
|
|
239
|
+
// widths are memoized shim-side.
|
|
240
|
+
static double NativeSdkMeasureText(void *context, uint64_t font_id, double size, const char *text, uintptr_t text_len) {
|
|
241
|
+
(void)context;
|
|
242
|
+
if (!text || text_len == 0) return 0;
|
|
243
|
+
CGFloat clamped = MAX(1, size);
|
|
244
|
+
@autoreleasepool {
|
|
245
|
+
NSString *value = [[NSString alloc] initWithBytes:text length:text_len encoding:NSUTF8StringEncoding];
|
|
246
|
+
if (!value) return -1;
|
|
247
|
+
static NSCache<NSString *, NSNumber *> *widthCache = nil;
|
|
248
|
+
static dispatch_once_t onceToken;
|
|
249
|
+
dispatch_once(&onceToken, ^{
|
|
250
|
+
widthCache = [[NSCache alloc] init];
|
|
251
|
+
widthCache.countLimit = 16384;
|
|
252
|
+
});
|
|
253
|
+
NSString *key = [NSString stringWithFormat:@"%llu/%.3f/%@", (unsigned long long)font_id, (double)clamped, value];
|
|
254
|
+
NSNumber *cached = [widthCache objectForKey:key];
|
|
255
|
+
if (cached) return cached.doubleValue;
|
|
256
|
+
UIFont *font = NativeSdkFontForFontId(font_id, clamped);
|
|
257
|
+
if (!font) return -1;
|
|
258
|
+
double width = [value sizeWithAttributes:@{ NSFontAttributeName : font }].width;
|
|
259
|
+
[widthCache setObject:@(width) forKey:key];
|
|
260
|
+
return width;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// --------------------------------------------------------------------- audio
|
|
265
|
+
//
|
|
266
|
+
// The platform audio player behind the embed audio service, ported from the
|
|
267
|
+
// macOS AppKit host (appkit_host.m, audio section) with the same contract:
|
|
268
|
+
// exactly one of audioPlayer/streamPlayer is non-nil, local files and
|
|
269
|
+
// verified cache hits play on AVAudioPlayer, URL sources stream on AVPlayer
|
|
270
|
+
// while a PARALLEL NSURLSession download fills the cache (a partially
|
|
271
|
+
// buffered stream must never masquerade as a cache entry), and every
|
|
272
|
+
// asynchronous report — the loaded acknowledgment with the real duration,
|
|
273
|
+
// ~500ms position ticks only while playing, buffering flips, exactly one
|
|
274
|
+
// completion, explicit failures — arrives through
|
|
275
|
+
// native_sdk_app_audio_event on the main thread. Every entry point is
|
|
276
|
+
// main-thread only; asynchronous sources (KVO, notifications, the download
|
|
277
|
+
// completion) hop to the main queue before touching player state, and the
|
|
278
|
+
// service callbacks never emit synchronously (the runtime is mid-dispatch
|
|
279
|
+
// when they run) — the local-file LOADED acknowledgment defers one loop
|
|
280
|
+
// turn exactly like the macOS host's.
|
|
281
|
+
//
|
|
282
|
+
// iOS divergences from the macOS implementation, all session-related:
|
|
283
|
+
// AVAudioSession gets the playback category at registration, is activated
|
|
284
|
+
// on the first play, and AVAudioSessionInterruptionNotification (began)
|
|
285
|
+
// pauses the transport and reports the paused state honestly through one
|
|
286
|
+
// immediate position event with playing=0 — an interruption is a
|
|
287
|
+
// platform-initiated pause the app did NOT command, so unlike app-driven
|
|
288
|
+
// pause it must echo. Interruption end never auto-resumes: the app (or the
|
|
289
|
+
// person holding the phone) decides.
|
|
290
|
+
|
|
291
|
+
/* KVO contexts for the streaming player, mirroring the macOS host: the
|
|
292
|
+
* AVPlayerItem's status flip is the stream's loaded/failed report and the
|
|
293
|
+
* AVPlayer's timeControlStatus is the honest buffering signal (waiting to
|
|
294
|
+
* play at the requested rate IS buffering — un-paused, but silent). */
|
|
295
|
+
static void *NativeSdkStreamItemStatusContext = &NativeSdkStreamItemStatusContext;
|
|
296
|
+
static void *NativeSdkStreamTimeControlContext = &NativeSdkStreamTimeControlContext;
|
|
297
|
+
|
|
298
|
+
/* CMTime helpers without linking CoreMedia's conversion functions — the
|
|
299
|
+
* struct and its flag constants are header-only, same trick as macOS. */
|
|
300
|
+
static double NativeSdkSecondsFromCMTime(CMTime time) {
|
|
301
|
+
if ((time.flags & kCMTimeFlags_Valid) == 0) return 0.0;
|
|
302
|
+
if ((time.flags & (kCMTimeFlags_Indefinite | kCMTimeFlags_PositiveInfinity | kCMTimeFlags_NegativeInfinity)) != 0) return 0.0;
|
|
303
|
+
if (time.timescale == 0) return 0.0;
|
|
304
|
+
return (double)time.value / (double)time.timescale;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
static CMTime NativeSdkCMTimeFromMs(uint64_t ms) {
|
|
308
|
+
CMTime time;
|
|
309
|
+
time.value = (CMTimeValue)ms;
|
|
310
|
+
time.timescale = 1000;
|
|
311
|
+
time.flags = kCMTimeFlags_Valid;
|
|
312
|
+
time.epoch = 0;
|
|
313
|
+
return time;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
@interface NativeSdkAudioEngine : NSObject <AVAudioPlayerDelegate>
|
|
317
|
+
@property(nonatomic) void *nativeApp;
|
|
318
|
+
/* The app's single local-file player and the shared position-tick timer. */
|
|
319
|
+
@property(nonatomic, strong) AVAudioPlayer *audioPlayer;
|
|
320
|
+
@property(nonatomic, strong) NSTimer *audioPositionTimer;
|
|
321
|
+
/* URL sources ride AVPlayer: progressive playback starts while bytes are
|
|
322
|
+
* still arriving, and seek/volume keep working mid-stream. */
|
|
323
|
+
@property(nonatomic, strong) AVPlayer *streamPlayer;
|
|
324
|
+
@property(nonatomic, strong) AVPlayerItem *streamItem;
|
|
325
|
+
@property(nonatomic) BOOL streamObservingStatus;
|
|
326
|
+
@property(nonatomic) BOOL streamLoadedEmitted;
|
|
327
|
+
/* The honest buffering mirror emitted with every audio event: YES from
|
|
328
|
+
* stream start until playback actually rolls, then tracks
|
|
329
|
+
* timeControlStatus. */
|
|
330
|
+
@property(nonatomic) BOOL streamBuffering;
|
|
331
|
+
@property(nonatomic, strong) id streamEndObserver;
|
|
332
|
+
@property(nonatomic, strong) id streamFailObserver;
|
|
333
|
+
@property(nonatomic, strong) NSURLSessionDownloadTask *audioCacheDownload;
|
|
334
|
+
/* Session state: the playback category is set once at engine creation;
|
|
335
|
+
* activation is deferred to the first play so a silent app never claims
|
|
336
|
+
* the audio route. */
|
|
337
|
+
@property(nonatomic) BOOL sessionActivated;
|
|
338
|
+
@property(nonatomic, strong) id interruptionObserver;
|
|
339
|
+
@end
|
|
340
|
+
|
|
341
|
+
@implementation NativeSdkAudioEngine
|
|
342
|
+
|
|
343
|
+
- (instancetype)init {
|
|
344
|
+
if ((self = [super init])) {
|
|
345
|
+
/* Playback category: honest foreground media playback (respects
|
|
346
|
+
* neither the ring/silent switch nor other apps' audio — the
|
|
347
|
+
* category for music, matching what fx.playAudio promises). No
|
|
348
|
+
* background modes: playback pauses with the app, and that limit
|
|
349
|
+
* is documented rather than papered over. */
|
|
350
|
+
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
|
|
351
|
+
__weak NativeSdkAudioEngine *weakSelf = self;
|
|
352
|
+
self.interruptionObserver = [[NSNotificationCenter defaultCenter]
|
|
353
|
+
addObserverForName:AVAudioSessionInterruptionNotification
|
|
354
|
+
object:[AVAudioSession sharedInstance]
|
|
355
|
+
queue:[NSOperationQueue mainQueue]
|
|
356
|
+
usingBlock:^(NSNotification *note) {
|
|
357
|
+
[weakSelf handleSessionInterruption:note];
|
|
358
|
+
}];
|
|
359
|
+
}
|
|
360
|
+
return self;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
- (void)invalidate {
|
|
364
|
+
[self audioStop];
|
|
365
|
+
if (self.interruptionObserver) {
|
|
366
|
+
[[NSNotificationCenter defaultCenter] removeObserver:self.interruptionObserver];
|
|
367
|
+
self.interruptionObserver = nil;
|
|
368
|
+
}
|
|
369
|
+
self.nativeApp = NULL;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
- (void)dealloc {
|
|
373
|
+
[self invalidate];
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/* The system took the audio route (phone call, alarm, another app's
|
|
377
|
+
* exclusive session): both player kinds are already silenced by the OS,
|
|
378
|
+
* so make the transport state match — pause explicitly, stop the tick
|
|
379
|
+
* timer, and report the paused state NOW through one position event.
|
|
380
|
+
* This is the one pause that must echo: the app did not command it.
|
|
381
|
+
* Interruption end deliberately does not auto-resume. */
|
|
382
|
+
- (void)handleSessionInterruption:(NSNotification *)note {
|
|
383
|
+
NSUInteger type = [note.userInfo[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
|
|
384
|
+
if (type != AVAudioSessionInterruptionTypeBegan) return;
|
|
385
|
+
if (!self.audioPlayer && !self.streamPlayer) return;
|
|
386
|
+
[self.audioPlayer pause];
|
|
387
|
+
[self.streamPlayer pause];
|
|
388
|
+
self.sessionActivated = NO;
|
|
389
|
+
[self stopAudioPositionTimer];
|
|
390
|
+
[self emitAudioEventOfKind:NATIVE_SDK_AUDIO_EVENT_POSITION];
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/* Emit one audio report carrying the live position/duration readout of
|
|
394
|
+
* whichever player is active. Main thread only. */
|
|
395
|
+
- (void)emitAudioEventOfKind:(int)kind {
|
|
396
|
+
if (!self.nativeApp) return;
|
|
397
|
+
AVAudioPlayer *player = self.audioPlayer;
|
|
398
|
+
AVPlayer *stream = self.streamPlayer;
|
|
399
|
+
uint64_t position_ms = 0;
|
|
400
|
+
uint64_t duration_ms = 0;
|
|
401
|
+
int playing = 0;
|
|
402
|
+
int buffering = 0;
|
|
403
|
+
if (player) {
|
|
404
|
+
NSTimeInterval position = player.currentTime;
|
|
405
|
+
NSTimeInterval duration = player.duration;
|
|
406
|
+
if (position > 0) position_ms = (uint64_t)llround(position * 1000.0);
|
|
407
|
+
if (duration > 0) duration_ms = (uint64_t)llround(duration * 1000.0);
|
|
408
|
+
playing = player.isPlaying ? 1 : 0;
|
|
409
|
+
} else if (stream) {
|
|
410
|
+
double position = NativeSdkSecondsFromCMTime(stream.currentTime);
|
|
411
|
+
double duration = self.streamItem ? NativeSdkSecondsFromCMTime(self.streamItem.duration) : 0.0;
|
|
412
|
+
if (position > 0) position_ms = (uint64_t)llround(position * 1000.0);
|
|
413
|
+
if (duration > 0) duration_ms = (uint64_t)llround(duration * 1000.0);
|
|
414
|
+
/* rate > 0 is the transport intent (un-paused); the buffering
|
|
415
|
+
* flag beside it says whether audio is actually coming out. */
|
|
416
|
+
playing = stream.rate > 0 ? 1 : 0;
|
|
417
|
+
buffering = self.streamBuffering ? 1 : 0;
|
|
418
|
+
}
|
|
419
|
+
if (kind == NATIVE_SDK_AUDIO_EVENT_COMPLETED) {
|
|
420
|
+
/* A finished player rewinds itself to zero; report the honest
|
|
421
|
+
* terminal position instead. */
|
|
422
|
+
position_ms = duration_ms;
|
|
423
|
+
playing = 0;
|
|
424
|
+
buffering = 0;
|
|
425
|
+
}
|
|
426
|
+
native_sdk_app_audio_event(self.nativeApp, kind, position_ms, duration_ms, playing, buffering);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
- (void)stopAudioPositionTimer {
|
|
430
|
+
[self.audioPositionTimer invalidate];
|
|
431
|
+
self.audioPositionTimer = nil;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
- (void)audioPositionTimerFired:(NSTimer *)timer {
|
|
435
|
+
(void)timer;
|
|
436
|
+
if (!self.audioPlayer && !self.streamPlayer) {
|
|
437
|
+
[self stopAudioPositionTimer];
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
[self emitAudioEventOfKind:NATIVE_SDK_AUDIO_EVENT_POSITION];
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
- (int)audioLoadPath:(NSString *)path {
|
|
444
|
+
[self audioStop];
|
|
445
|
+
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) return 1;
|
|
446
|
+
NSError *error = nil;
|
|
447
|
+
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path]
|
|
448
|
+
error:&error];
|
|
449
|
+
if (!player || error) return 2;
|
|
450
|
+
player.delegate = self;
|
|
451
|
+
if (![player prepareToPlay]) return 2;
|
|
452
|
+
self.audioPlayer = player;
|
|
453
|
+
/* The LOADED acknowledgment is asynchronous by contract: emitting it
|
|
454
|
+
* inside this service call would re-enter the runtime while it is
|
|
455
|
+
* still dispatching the command that asked for the load. Next loop
|
|
456
|
+
* turn, and only if this player is still the loaded one. */
|
|
457
|
+
__weak NativeSdkAudioEngine *weakSelf = self;
|
|
458
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
459
|
+
NativeSdkAudioEngine *strongSelf = weakSelf;
|
|
460
|
+
if (!strongSelf || strongSelf.audioPlayer != player) return;
|
|
461
|
+
[strongSelf emitAudioEventOfKind:NATIVE_SDK_AUDIO_EVENT_LOADED];
|
|
462
|
+
});
|
|
463
|
+
return 0;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/* URL sources: verified cache entry first (plays as a plain local file,
|
|
467
|
+
* no network), then a progressive AVPlayer stream with a parallel
|
|
468
|
+
* cache-filling download. Returns 1 for the cache hit, 0 for a started
|
|
469
|
+
* stream, 2 when the URL cannot be parsed; everything asynchronous —
|
|
470
|
+
* readiness, stalls, natural end, network death — arrives as audio
|
|
471
|
+
* events. */
|
|
472
|
+
- (int)audioLoadURL:(NSString *)urlString cachePath:(NSString *)cachePath expectedBytes:(uint64_t)expectedBytes {
|
|
473
|
+
[self audioStop];
|
|
474
|
+
NSURL *url = [NSURL URLWithString:urlString];
|
|
475
|
+
if (!url || !url.scheme) return 2;
|
|
476
|
+
if (cachePath.length > 0) {
|
|
477
|
+
NSFileManager *manager = [NSFileManager defaultManager];
|
|
478
|
+
NSDictionary *attributes = [manager attributesOfItemAtPath:cachePath error:nil];
|
|
479
|
+
if (attributes) {
|
|
480
|
+
unsigned long long size = [attributes fileSize];
|
|
481
|
+
if (expectedBytes == 0 || size == (unsigned long long)expectedBytes) {
|
|
482
|
+
if ([self audioLoadPath:cachePath] == 0) return 1;
|
|
483
|
+
/* An entry with the right size that will not decode is
|
|
484
|
+
* corrupt — fall through to discard and re-stream. */
|
|
485
|
+
}
|
|
486
|
+
/* Partial, stale, or corrupt: a bad cache entry never plays,
|
|
487
|
+
* and never survives to fool the next lookup. */
|
|
488
|
+
[manager removeItemAtPath:cachePath error:nil];
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
AVPlayerItem *item = [AVPlayerItem playerItemWithURL:url];
|
|
492
|
+
AVPlayer *player = [AVPlayer playerWithPlayerItem:item];
|
|
493
|
+
/* The default stall policy: start as soon as sustained playback is
|
|
494
|
+
* likely, keep rolling through short gaps. Stated explicitly because
|
|
495
|
+
* immediate progressive start is the contract here. */
|
|
496
|
+
player.automaticallyWaitsToMinimizeStalling = YES;
|
|
497
|
+
self.streamItem = item;
|
|
498
|
+
self.streamPlayer = player;
|
|
499
|
+
self.streamBuffering = YES;
|
|
500
|
+
self.streamLoadedEmitted = NO;
|
|
501
|
+
[item addObserver:self
|
|
502
|
+
forKeyPath:@"status"
|
|
503
|
+
options:NSKeyValueObservingOptionNew
|
|
504
|
+
context:NativeSdkStreamItemStatusContext];
|
|
505
|
+
[player addObserver:self
|
|
506
|
+
forKeyPath:@"timeControlStatus"
|
|
507
|
+
options:NSKeyValueObservingOptionNew
|
|
508
|
+
context:NativeSdkStreamTimeControlContext];
|
|
509
|
+
self.streamObservingStatus = YES;
|
|
510
|
+
__weak NativeSdkAudioEngine *weakSelf = self;
|
|
511
|
+
self.streamEndObserver = [[NSNotificationCenter defaultCenter]
|
|
512
|
+
addObserverForName:AVPlayerItemDidPlayToEndTimeNotification
|
|
513
|
+
object:item
|
|
514
|
+
queue:[NSOperationQueue mainQueue]
|
|
515
|
+
usingBlock:^(NSNotification *note) {
|
|
516
|
+
(void)note;
|
|
517
|
+
[weakSelf streamDidPlayToEnd];
|
|
518
|
+
}];
|
|
519
|
+
self.streamFailObserver = [[NSNotificationCenter defaultCenter]
|
|
520
|
+
addObserverForName:AVPlayerItemFailedToPlayToEndTimeNotification
|
|
521
|
+
object:item
|
|
522
|
+
queue:[NSOperationQueue mainQueue]
|
|
523
|
+
usingBlock:^(NSNotification *note) {
|
|
524
|
+
(void)note;
|
|
525
|
+
[weakSelf streamDidFail];
|
|
526
|
+
}];
|
|
527
|
+
if (cachePath.length > 0) {
|
|
528
|
+
[self startAudioCacheDownloadFrom:url toPath:cachePath expectedBytes:expectedBytes];
|
|
529
|
+
}
|
|
530
|
+
return 0;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/* The cache fill is a PARALLEL download, not a tee off the player's own
|
|
534
|
+
* connection: an AVAssetResourceLoader tee needs a custom URL scheme plus
|
|
535
|
+
* a hand-rolled range-request server, and a partially buffered stream
|
|
536
|
+
* must never masquerade as a cache entry. One extra request on a track's
|
|
537
|
+
* first (uncached) play buys a stock streaming path and a cache whose
|
|
538
|
+
* entries are whole files by construction: downloaded beside the final
|
|
539
|
+
* name, size-verified against the manifest, and renamed into place — a
|
|
540
|
+
* same-directory rename, so a partial file never occupies the cache name
|
|
541
|
+
* even across a crash. */
|
|
542
|
+
- (void)startAudioCacheDownloadFrom:(NSURL *)url toPath:(NSString *)cachePath expectedBytes:(uint64_t)expectedBytes {
|
|
543
|
+
NSURLSessionDownloadTask *task = [[NSURLSession sharedSession]
|
|
544
|
+
downloadTaskWithURL:url
|
|
545
|
+
completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
|
|
546
|
+
/* Background queue: file moves only, no engine state. A
|
|
547
|
+
* failed or cancelled download simply leaves no cache
|
|
548
|
+
* entry — the next play streams again. */
|
|
549
|
+
if (error || !location) return;
|
|
550
|
+
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
|
|
551
|
+
NSInteger status = ((NSHTTPURLResponse *)response).statusCode;
|
|
552
|
+
if (status != 200) return;
|
|
553
|
+
}
|
|
554
|
+
NSFileManager *manager = [NSFileManager defaultManager];
|
|
555
|
+
NSString *directory = [cachePath stringByDeletingLastPathComponent];
|
|
556
|
+
[manager createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:nil];
|
|
557
|
+
NSString *partPath = [cachePath stringByAppendingPathExtension:@"part"];
|
|
558
|
+
[manager removeItemAtPath:partPath error:nil];
|
|
559
|
+
if (![manager moveItemAtURL:location toURL:[NSURL fileURLWithPath:partPath] error:nil]) return;
|
|
560
|
+
NSDictionary *attributes = [manager attributesOfItemAtPath:partPath error:nil];
|
|
561
|
+
unsigned long long size = attributes ? [attributes fileSize] : 0;
|
|
562
|
+
if (expectedBytes != 0 && size != (unsigned long long)expectedBytes) {
|
|
563
|
+
/* Truncated or wrong content: never installed. */
|
|
564
|
+
[manager removeItemAtPath:partPath error:nil];
|
|
565
|
+
return;
|
|
566
|
+
}
|
|
567
|
+
[manager removeItemAtPath:cachePath error:nil];
|
|
568
|
+
[manager moveItemAtPath:partPath toPath:cachePath error:nil];
|
|
569
|
+
}];
|
|
570
|
+
self.audioCacheDownload = task;
|
|
571
|
+
[task resume];
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/* Release the stream player and its observers. The download is cancelled
|
|
575
|
+
* when a new load replaces the stream mid-flight (a skipped track should
|
|
576
|
+
* not keep burning bandwidth) but ORPHANED on natural completion — it is
|
|
577
|
+
* usually already done, and letting a straggler finish installs the
|
|
578
|
+
* cache entry the completed play earned. */
|
|
579
|
+
- (void)audioTearDownStreamCancellingDownload:(BOOL)cancelDownload {
|
|
580
|
+
AVPlayerItem *item = self.streamItem;
|
|
581
|
+
AVPlayer *player = self.streamPlayer;
|
|
582
|
+
if (self.streamObservingStatus) {
|
|
583
|
+
[item removeObserver:self forKeyPath:@"status" context:NativeSdkStreamItemStatusContext];
|
|
584
|
+
[player removeObserver:self forKeyPath:@"timeControlStatus" context:NativeSdkStreamTimeControlContext];
|
|
585
|
+
self.streamObservingStatus = NO;
|
|
586
|
+
}
|
|
587
|
+
if (self.streamEndObserver) {
|
|
588
|
+
[[NSNotificationCenter defaultCenter] removeObserver:self.streamEndObserver];
|
|
589
|
+
self.streamEndObserver = nil;
|
|
590
|
+
}
|
|
591
|
+
if (self.streamFailObserver) {
|
|
592
|
+
[[NSNotificationCenter defaultCenter] removeObserver:self.streamFailObserver];
|
|
593
|
+
self.streamFailObserver = nil;
|
|
594
|
+
}
|
|
595
|
+
[player pause];
|
|
596
|
+
self.streamItem = nil;
|
|
597
|
+
self.streamPlayer = nil;
|
|
598
|
+
self.streamBuffering = NO;
|
|
599
|
+
self.streamLoadedEmitted = NO;
|
|
600
|
+
if (cancelDownload) [self.audioCacheDownload cancel];
|
|
601
|
+
self.audioCacheDownload = nil;
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/* Item status flipped (main queue, hopped from KVO): readyToPlay is the
|
|
605
|
+
* stream's LOADED acknowledgment — the duration is decoded and playback
|
|
606
|
+
* is rolling or about to; failed is the honest terminal report for an
|
|
607
|
+
* unreachable host or an undecodable payload. */
|
|
608
|
+
- (void)streamItemStatusChanged {
|
|
609
|
+
AVPlayerItem *item = self.streamItem;
|
|
610
|
+
if (!item) return;
|
|
611
|
+
if (item.status == AVPlayerItemStatusReadyToPlay) {
|
|
612
|
+
if (self.streamLoadedEmitted) return;
|
|
613
|
+
self.streamLoadedEmitted = YES;
|
|
614
|
+
[self emitAudioEventOfKind:NATIVE_SDK_AUDIO_EVENT_LOADED];
|
|
615
|
+
return;
|
|
616
|
+
}
|
|
617
|
+
if (item.status == AVPlayerItemStatusFailed) {
|
|
618
|
+
[self streamDidFail];
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/* timeControlStatus flipped (main queue, hopped from KVO): waiting to
|
|
623
|
+
* play at the requested rate IS buffering. Emit the transition
|
|
624
|
+
* immediately as a position report so the UI flips its buffering state
|
|
625
|
+
* now, not at the next 500ms tick. */
|
|
626
|
+
- (void)streamTimeControlChanged {
|
|
627
|
+
AVPlayer *player = self.streamPlayer;
|
|
628
|
+
if (!player) return;
|
|
629
|
+
BOOL buffering = player.timeControlStatus == AVPlayerTimeControlStatusWaitingToPlayAtSpecifiedRate;
|
|
630
|
+
if (buffering == self.streamBuffering) return;
|
|
631
|
+
self.streamBuffering = buffering;
|
|
632
|
+
[self emitAudioEventOfKind:NATIVE_SDK_AUDIO_EVENT_POSITION];
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
/* Natural end of a streamed track. Same retire-before-emit discipline as
|
|
636
|
+
* the AVAudioPlayer delegate below: the completion Msg routinely starts
|
|
637
|
+
* the NEXT track from inside its own dispatch, and tearing down
|
|
638
|
+
* afterwards would destroy the player that load just installed. The
|
|
639
|
+
* duration is captured first so the event still carries the honest
|
|
640
|
+
* terminal position. */
|
|
641
|
+
- (void)streamDidPlayToEnd {
|
|
642
|
+
if (!self.streamPlayer) return;
|
|
643
|
+
[self stopAudioPositionTimer];
|
|
644
|
+
uint64_t duration_ms = 0;
|
|
645
|
+
if (self.streamItem) {
|
|
646
|
+
double duration = NativeSdkSecondsFromCMTime(self.streamItem.duration);
|
|
647
|
+
if (duration > 0) duration_ms = (uint64_t)llround(duration * 1000.0);
|
|
648
|
+
}
|
|
649
|
+
[self audioTearDownStreamCancellingDownload:NO];
|
|
650
|
+
if (self.nativeApp) {
|
|
651
|
+
native_sdk_app_audio_event(self.nativeApp, NATIVE_SDK_AUDIO_EVENT_COMPLETED, duration_ms, duration_ms, 0, 0);
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
/* A stream died mid-flight (network loss, server reset, undecodable
|
|
656
|
+
* bytes) or never became playable (offline with a cold cache): one
|
|
657
|
+
* FAILED event, player retired first. The cache download is cancelled
|
|
658
|
+
* too — bytes from a failing source are not trustworthy. */
|
|
659
|
+
- (void)streamDidFail {
|
|
660
|
+
if (!self.streamPlayer) return;
|
|
661
|
+
[self stopAudioPositionTimer];
|
|
662
|
+
[self audioTearDownStreamCancellingDownload:YES];
|
|
663
|
+
if (self.nativeApp) {
|
|
664
|
+
native_sdk_app_audio_event(self.nativeApp, NATIVE_SDK_AUDIO_EVENT_FAILED, 0, 0, 0, 0);
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/* First play activates the audio session (deferred from init so a silent
|
|
669
|
+
* app never claims the route); re-activation after an interruption is
|
|
670
|
+
* the same call. Activation failure is not fatal — playback proceeds and
|
|
671
|
+
* the OS arbitrates. */
|
|
672
|
+
- (void)activateSessionForPlayback {
|
|
673
|
+
if (self.sessionActivated) return;
|
|
674
|
+
self.sessionActivated = [[AVAudioSession sharedInstance] setActive:YES error:nil];
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
- (int)audioPlay {
|
|
678
|
+
[self activateSessionForPlayback];
|
|
679
|
+
if (self.streamPlayer) {
|
|
680
|
+
/* AVPlayer's play is asynchronous by nature (it starts when
|
|
681
|
+
* buffered bytes allow), so a stream's play always "applies" —
|
|
682
|
+
* readiness and stalls report through the event stream. */
|
|
683
|
+
[self.streamPlayer play];
|
|
684
|
+
} else {
|
|
685
|
+
AVAudioPlayer *player = self.audioPlayer;
|
|
686
|
+
if (!player) return 0;
|
|
687
|
+
if (![player play]) return 0;
|
|
688
|
+
}
|
|
689
|
+
if (!self.audioPositionTimer) {
|
|
690
|
+
/* Common modes so the readout keeps ticking while UIKit tracks a
|
|
691
|
+
* touch (UITrackingRunLoopMode) — the mobile mirror of macOS
|
|
692
|
+
* keeping ticks alive through menus and live-resize. */
|
|
693
|
+
NSTimer *tick = [NSTimer timerWithTimeInterval:0.5
|
|
694
|
+
target:self
|
|
695
|
+
selector:@selector(audioPositionTimerFired:)
|
|
696
|
+
userInfo:nil
|
|
697
|
+
repeats:YES];
|
|
698
|
+
[[NSRunLoop mainRunLoop] addTimer:tick forMode:NSRunLoopCommonModes];
|
|
699
|
+
self.audioPositionTimer = tick;
|
|
700
|
+
}
|
|
701
|
+
return 1;
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
- (int)audioPause {
|
|
705
|
+
if (self.streamPlayer) {
|
|
706
|
+
[self.streamPlayer pause];
|
|
707
|
+
[self stopAudioPositionTimer];
|
|
708
|
+
return 1;
|
|
709
|
+
}
|
|
710
|
+
AVAudioPlayer *player = self.audioPlayer;
|
|
711
|
+
if (!player) return 0;
|
|
712
|
+
[player pause];
|
|
713
|
+
[self stopAudioPositionTimer];
|
|
714
|
+
return 1;
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
- (int)audioStop {
|
|
718
|
+
[self stopAudioPositionTimer];
|
|
719
|
+
if (self.streamPlayer) {
|
|
720
|
+
/* Replacement or explicit stop mid-stream: the cache download
|
|
721
|
+
* dies with the playback — a skipped track should not keep
|
|
722
|
+
* burning bandwidth (its next play streams and fills again). */
|
|
723
|
+
[self audioTearDownStreamCancellingDownload:YES];
|
|
724
|
+
return 1;
|
|
725
|
+
}
|
|
726
|
+
AVAudioPlayer *player = self.audioPlayer;
|
|
727
|
+
if (!player) return 0;
|
|
728
|
+
player.delegate = nil;
|
|
729
|
+
[player stop];
|
|
730
|
+
self.audioPlayer = nil;
|
|
731
|
+
return 1;
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
- (int)audioSeekToMs:(uint64_t)positionMs {
|
|
735
|
+
if (self.streamPlayer) {
|
|
736
|
+
/* Mid-stream seek: AVPlayer clamps to the seekable ranges it has
|
|
737
|
+
* (or fetches the range it needs); exact tolerance keeps the
|
|
738
|
+
* readout honest against the requested position. */
|
|
739
|
+
CMTime zero = NativeSdkCMTimeFromMs(0);
|
|
740
|
+
[self.streamPlayer seekToTime:NativeSdkCMTimeFromMs(positionMs)
|
|
741
|
+
toleranceBefore:zero
|
|
742
|
+
toleranceAfter:zero];
|
|
743
|
+
return 1;
|
|
744
|
+
}
|
|
745
|
+
AVAudioPlayer *player = self.audioPlayer;
|
|
746
|
+
if (!player) return 0;
|
|
747
|
+
NSTimeInterval target = (NSTimeInterval)positionMs / 1000.0;
|
|
748
|
+
if (target > player.duration) target = player.duration;
|
|
749
|
+
player.currentTime = target;
|
|
750
|
+
return 1;
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
- (int)audioSetVolume:(double)volume {
|
|
754
|
+
if (self.streamPlayer) {
|
|
755
|
+
self.streamPlayer.volume = (float)volume;
|
|
756
|
+
return 1;
|
|
757
|
+
}
|
|
758
|
+
AVAudioPlayer *player = self.audioPlayer;
|
|
759
|
+
if (!player) return 0;
|
|
760
|
+
player.volume = (float)volume;
|
|
761
|
+
return 1;
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
/* AVPlayer/AVPlayerItem KVO can fire on background threads (and
|
|
765
|
+
* synchronously inside a service call); every entry point above is
|
|
766
|
+
* main-thread, between-runtime-turns only, so hop before touching player
|
|
767
|
+
* state or emitting. */
|
|
768
|
+
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey, id> *)change context:(void *)context {
|
|
769
|
+
if (context == NativeSdkStreamItemStatusContext) {
|
|
770
|
+
__weak NativeSdkAudioEngine *weakSelf = self;
|
|
771
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
772
|
+
[weakSelf streamItemStatusChanged];
|
|
773
|
+
});
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
if (context == NativeSdkStreamTimeControlContext) {
|
|
777
|
+
__weak NativeSdkAudioEngine *weakSelf = self;
|
|
778
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
779
|
+
[weakSelf streamTimeControlChanged];
|
|
780
|
+
});
|
|
781
|
+
return;
|
|
782
|
+
}
|
|
783
|
+
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/* AVAudioPlayerDelegate: natural end of the track. `flag` is NO when
|
|
787
|
+
* playback died on a decode error mid-file — report that honestly as a
|
|
788
|
+
* failure, never as a completion. The finished player is retired BEFORE
|
|
789
|
+
* the event is emitted: the completion Msg routinely starts the NEXT
|
|
790
|
+
* track from inside its own dispatch (a music app auto-advancing), and
|
|
791
|
+
* retiring afterwards would destroy the player that load just installed. */
|
|
792
|
+
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
|
|
793
|
+
if (player != self.audioPlayer) return;
|
|
794
|
+
[self stopAudioPositionTimer];
|
|
795
|
+
uint64_t duration_ms = 0;
|
|
796
|
+
if (player.duration > 0) duration_ms = (uint64_t)llround(player.duration * 1000.0);
|
|
797
|
+
player.delegate = nil;
|
|
798
|
+
self.audioPlayer = nil;
|
|
799
|
+
if (self.nativeApp) {
|
|
800
|
+
native_sdk_app_audio_event(self.nativeApp,
|
|
801
|
+
flag ? NATIVE_SDK_AUDIO_EVENT_COMPLETED : NATIVE_SDK_AUDIO_EVENT_FAILED,
|
|
802
|
+
flag ? duration_ms : 0,
|
|
803
|
+
duration_ms,
|
|
804
|
+
0,
|
|
805
|
+
0);
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error {
|
|
810
|
+
(void)error;
|
|
811
|
+
if (player != self.audioPlayer) return;
|
|
812
|
+
[self stopAudioPositionTimer];
|
|
813
|
+
player.delegate = nil;
|
|
814
|
+
self.audioPlayer = nil;
|
|
815
|
+
[self emitAudioEventOfKind:NATIVE_SDK_AUDIO_EVENT_FAILED];
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
@end
|
|
819
|
+
|
|
820
|
+
// The C callback table registered through native_sdk_app_set_audio_service;
|
|
821
|
+
// context is the (view-controller-retained) engine. These run INSIDE
|
|
822
|
+
// runtime dispatch on the main thread — they mutate player state and
|
|
823
|
+
// return synchronously, and every report the calls provoke is emitted on a
|
|
824
|
+
// later run-loop turn.
|
|
825
|
+
|
|
826
|
+
static int NativeSdkAudioServiceLoad(void *context, const char *path, uintptr_t path_len) {
|
|
827
|
+
NativeSdkAudioEngine *engine = (__bridge NativeSdkAudioEngine *)context;
|
|
828
|
+
NSString *value = [[NSString alloc] initWithBytes:path length:path_len encoding:NSUTF8StringEncoding];
|
|
829
|
+
if (!value) return 1;
|
|
830
|
+
return [engine audioLoadPath:value];
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
static int NativeSdkAudioServiceLoadUrl(void *context, const char *url, uintptr_t url_len, const char *cache_path, uintptr_t cache_path_len, uint64_t expected_bytes) {
|
|
834
|
+
NativeSdkAudioEngine *engine = (__bridge NativeSdkAudioEngine *)context;
|
|
835
|
+
NSString *urlValue = [[NSString alloc] initWithBytes:url length:url_len encoding:NSUTF8StringEncoding];
|
|
836
|
+
if (!urlValue) return 2;
|
|
837
|
+
NSString *cacheValue = @"";
|
|
838
|
+
if (cache_path && cache_path_len > 0) {
|
|
839
|
+
cacheValue = [[NSString alloc] initWithBytes:cache_path length:cache_path_len encoding:NSUTF8StringEncoding] ?: @"";
|
|
840
|
+
}
|
|
841
|
+
return [engine audioLoadURL:urlValue cachePath:cacheValue expectedBytes:expected_bytes];
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
static int NativeSdkAudioServicePlay(void *context) {
|
|
845
|
+
return [(__bridge NativeSdkAudioEngine *)context audioPlay];
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
static int NativeSdkAudioServicePause(void *context) {
|
|
849
|
+
return [(__bridge NativeSdkAudioEngine *)context audioPause];
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
static int NativeSdkAudioServiceStop(void *context) {
|
|
853
|
+
return [(__bridge NativeSdkAudioEngine *)context audioStop];
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
static int NativeSdkAudioServiceSeek(void *context, uint64_t position_ms) {
|
|
857
|
+
return [(__bridge NativeSdkAudioEngine *)context audioSeekToMs:position_ms];
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
static int NativeSdkAudioServiceSetVolume(void *context, double volume) {
|
|
861
|
+
return [(__bridge NativeSdkAudioEngine *)context audioSetVolume:volume];
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
// ---------------------------------------------------------------- image decode
|
|
865
|
+
//
|
|
866
|
+
// The platform image decoder registered through
|
|
867
|
+
// native_sdk_app_set_image_service: CGImageSource (ImageIO) handles PNG,
|
|
868
|
+
// JPEG, and every other codec the OS ships — the toolkit bundles none.
|
|
869
|
+
// This is the macOS host's native_sdk_appkit_decode_image ported into the
|
|
870
|
+
// iOS host with the identical contract: the image draws into a
|
|
871
|
+
// premultiplied RGBA8 bitmap context (the only RGBA layout
|
|
872
|
+
// CGBitmapContext can render into) and is un-premultiplied in place,
|
|
873
|
+
// because the canvas image pipeline expects straight alpha. Returns 1
|
|
874
|
+
// decoded, -1 when the decoded pixels do not fit `pixels_len`, 0 for
|
|
875
|
+
// undecodable bytes.
|
|
876
|
+
static int NativeSdkImageServiceDecode(void *context, const uint8_t *bytes, uintptr_t bytes_len, uint8_t *pixels, uintptr_t pixels_len, uintptr_t *out_width, uintptr_t *out_height) {
|
|
877
|
+
(void)context;
|
|
878
|
+
if (out_width) *out_width = 0;
|
|
879
|
+
if (out_height) *out_height = 0;
|
|
880
|
+
if (!bytes || bytes_len == 0 || !pixels) return 0;
|
|
881
|
+
@autoreleasepool {
|
|
882
|
+
NSData *data = [NSData dataWithBytesNoCopy:(void *)bytes length:bytes_len freeWhenDone:NO];
|
|
883
|
+
CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
|
|
884
|
+
if (!source) return 0;
|
|
885
|
+
CGImageRef image = CGImageSourceCreateImageAtIndex(source, 0, NULL);
|
|
886
|
+
CFRelease(source);
|
|
887
|
+
if (!image) return 0;
|
|
888
|
+
|
|
889
|
+
size_t width = CGImageGetWidth(image);
|
|
890
|
+
size_t height = CGImageGetHeight(image);
|
|
891
|
+
if (width == 0 || height == 0 || width > 8192 || height > 8192) {
|
|
892
|
+
CGImageRelease(image);
|
|
893
|
+
return 0;
|
|
894
|
+
}
|
|
895
|
+
if (out_width) *out_width = width;
|
|
896
|
+
if (out_height) *out_height = height;
|
|
897
|
+
size_t byte_len = width * height * 4;
|
|
898
|
+
if (byte_len / 4 / height != width || pixels_len < byte_len) {
|
|
899
|
+
CGImageRelease(image);
|
|
900
|
+
return -1;
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
CGColorSpaceRef color_space = CGColorSpaceCreateDeviceRGB();
|
|
904
|
+
if (!color_space) {
|
|
905
|
+
CGImageRelease(image);
|
|
906
|
+
return 0;
|
|
907
|
+
}
|
|
908
|
+
CGContextRef bitmap = CGBitmapContextCreate(pixels, width, height, 8, width * 4, color_space, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
|
|
909
|
+
CGColorSpaceRelease(color_space);
|
|
910
|
+
if (!bitmap) {
|
|
911
|
+
CGImageRelease(image);
|
|
912
|
+
return 0;
|
|
913
|
+
}
|
|
914
|
+
memset(pixels, 0, byte_len);
|
|
915
|
+
CGContextSetBlendMode(bitmap, kCGBlendModeCopy);
|
|
916
|
+
CGContextDrawImage(bitmap, CGRectMake(0, 0, (CGFloat)width, (CGFloat)height), image);
|
|
917
|
+
CGContextRelease(bitmap);
|
|
918
|
+
CGImageRelease(image);
|
|
919
|
+
|
|
920
|
+
// Un-premultiply: round to nearest so opaque pixels survive exactly.
|
|
921
|
+
for (size_t offset = 0; offset < byte_len; offset += 4) {
|
|
922
|
+
uint8_t alpha = pixels[offset + 3];
|
|
923
|
+
if (alpha == 0) {
|
|
924
|
+
pixels[offset + 0] = 0;
|
|
925
|
+
pixels[offset + 1] = 0;
|
|
926
|
+
pixels[offset + 2] = 0;
|
|
927
|
+
} else if (alpha != 255) {
|
|
928
|
+
pixels[offset + 0] = (uint8_t)MIN(255, ((size_t)pixels[offset + 0] * 255 + alpha / 2) / alpha);
|
|
929
|
+
pixels[offset + 1] = (uint8_t)MIN(255, ((size_t)pixels[offset + 1] * 255 + alpha / 2) / alpha);
|
|
930
|
+
pixels[offset + 2] = (uint8_t)MIN(255, ((size_t)pixels[offset + 2] * 255 + alpha / 2) / alpha);
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
return 1;
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
// ---------------------------------------------------------------- UITextInput
|
|
938
|
+
// Index-based position/range objects over the local marked-text store (the
|
|
939
|
+
// "document" the system IME edits is the composition only, matching the
|
|
940
|
+
// macOS host's NSTextInputClient implementation).
|
|
941
|
+
|
|
942
|
+
@interface NativeSdkTextPosition : UITextPosition
|
|
943
|
+
@property(nonatomic) NSInteger index;
|
|
944
|
+
+ (instancetype)positionWithIndex:(NSInteger)index;
|
|
945
|
+
@end
|
|
946
|
+
|
|
947
|
+
@implementation NativeSdkTextPosition
|
|
948
|
+
+ (instancetype)positionWithIndex:(NSInteger)index {
|
|
949
|
+
NativeSdkTextPosition *position = [[self alloc] init];
|
|
950
|
+
position.index = index;
|
|
951
|
+
return position;
|
|
952
|
+
}
|
|
953
|
+
@end
|
|
954
|
+
|
|
955
|
+
@interface NativeSdkTextRange : UITextRange
|
|
956
|
+
@property(nonatomic) NSInteger location;
|
|
957
|
+
@property(nonatomic) NSInteger length;
|
|
958
|
+
+ (instancetype)rangeWithLocation:(NSInteger)location length:(NSInteger)length;
|
|
959
|
+
@end
|
|
960
|
+
|
|
961
|
+
@implementation NativeSdkTextRange
|
|
962
|
+
+ (instancetype)rangeWithLocation:(NSInteger)location length:(NSInteger)length {
|
|
963
|
+
NativeSdkTextRange *range = [[self alloc] init];
|
|
964
|
+
range.location = location;
|
|
965
|
+
range.length = length;
|
|
966
|
+
return range;
|
|
967
|
+
}
|
|
968
|
+
- (BOOL)isEmpty {
|
|
969
|
+
return self.length == 0;
|
|
970
|
+
}
|
|
971
|
+
- (UITextPosition *)start {
|
|
972
|
+
return [NativeSdkTextPosition positionWithIndex:self.location];
|
|
973
|
+
}
|
|
974
|
+
- (UITextPosition *)end {
|
|
975
|
+
return [NativeSdkTextPosition positionWithIndex:self.location + self.length];
|
|
976
|
+
}
|
|
977
|
+
@end
|
|
978
|
+
|
|
979
|
+
typedef NS_ENUM(NSInteger, NativeSdkTouchMode) {
|
|
980
|
+
NativeSdkTouchModeIdle = 0,
|
|
981
|
+
// Touch down seen, under slop: undecided between tap / drag / scroll.
|
|
982
|
+
NativeSdkTouchModePending,
|
|
983
|
+
// Over slop on a scrollable widget: forwarding wheel scroll deltas.
|
|
984
|
+
NativeSdkTouchModeScrolling,
|
|
985
|
+
// Over slop elsewhere: forwarded pointer_down, forwarding pointer_drag.
|
|
986
|
+
NativeSdkTouchModeDragging,
|
|
987
|
+
};
|
|
988
|
+
|
|
989
|
+
static const CGFloat NativeSdkTouchSlop = 8.0;
|
|
990
|
+
|
|
991
|
+
@interface NativeSdkCanvasView : UIView <UIKeyInput, UITextInput>
|
|
992
|
+
@property(nonatomic) void *nativeApp;
|
|
993
|
+
@property(nonatomic, weak) UITouch *trackedTouch;
|
|
994
|
+
@property(nonatomic) NativeSdkTouchMode touchMode;
|
|
995
|
+
@property(nonatomic) CGPoint touchStartPoint;
|
|
996
|
+
@property(nonatomic) CGPoint touchLastPoint;
|
|
997
|
+
@property(nonatomic) uint64_t touchSequence;
|
|
998
|
+
@property(nonatomic, copy) NSString *markedText;
|
|
999
|
+
@property(nonatomic) NSRange markedSelectedRange;
|
|
1000
|
+
@property(nonatomic) uint64_t focusedTextWidget;
|
|
1001
|
+
@property(nonatomic, copy) NSDictionary<NSAttributedStringKey, id> *markedTextStyle;
|
|
1002
|
+
@property(nonatomic, weak) id<UITextInputDelegate> inputDelegate;
|
|
1003
|
+
@end
|
|
1004
|
+
|
|
1005
|
+
@implementation NativeSdkCanvasView
|
|
1006
|
+
|
|
1007
|
+
+ (Class)layerClass {
|
|
1008
|
+
return [CAMetalLayer class];
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
- (instancetype)initWithFrame:(CGRect)frame {
|
|
1012
|
+
if ((self = [super initWithFrame:frame])) {
|
|
1013
|
+
_markedText = @"";
|
|
1014
|
+
_markedSelectedRange = NSMakeRange(NSNotFound, 0);
|
|
1015
|
+
self.multipleTouchEnabled = NO;
|
|
1016
|
+
}
|
|
1017
|
+
return self;
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
- (BOOL)canBecomeFirstResponder {
|
|
1021
|
+
return YES;
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
// ------------------------------------------------------------------- touch
|
|
1025
|
+
|
|
1026
|
+
- (void)forwardTouchPhase:(int)phase point:(CGPoint)point pressure:(float)pressure {
|
|
1027
|
+
if (!self.nativeApp) return;
|
|
1028
|
+
native_sdk_app_touch(self.nativeApp, self.touchSequence, phase, (float)point.x, (float)point.y, pressure);
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
// True when an overflowing scrollable widget's bounds contain the point —
|
|
1032
|
+
// the pan-to-scroll decision UIScrollView makes with delayed content
|
|
1033
|
+
// touches, taken from the semantics export instead of a native hierarchy.
|
|
1034
|
+
- (BOOL)scrollableWidgetAtPoint:(CGPoint)point {
|
|
1035
|
+
if (!self.nativeApp) return NO;
|
|
1036
|
+
uintptr_t count = native_sdk_app_widget_semantics_count(self.nativeApp);
|
|
1037
|
+
for (uintptr_t index = 0; index < count; index++) {
|
|
1038
|
+
native_sdk_widget_semantics_t node = {0};
|
|
1039
|
+
if (native_sdk_app_widget_semantics_at(self.nativeApp, index, &node) != 1) continue;
|
|
1040
|
+
if (!node.has_scroll) continue;
|
|
1041
|
+
if (node.scroll_content_extent <= node.scroll_viewport_extent) continue;
|
|
1042
|
+
if (point.x < node.x || point.x > node.x + node.width) continue;
|
|
1043
|
+
if (point.y < node.y || point.y > node.y + node.height) continue;
|
|
1044
|
+
return YES;
|
|
1045
|
+
}
|
|
1046
|
+
return NO;
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
|
|
1050
|
+
if (self.trackedTouch) return;
|
|
1051
|
+
UITouch *touch = touches.anyObject;
|
|
1052
|
+
self.trackedTouch = touch;
|
|
1053
|
+
self.touchSequence += 1;
|
|
1054
|
+
self.touchMode = NativeSdkTouchModePending;
|
|
1055
|
+
self.touchStartPoint = [touch locationInView:self];
|
|
1056
|
+
self.touchLastPoint = self.touchStartPoint;
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
|
|
1060
|
+
if (!self.trackedTouch || ![touches containsObject:self.trackedTouch]) return;
|
|
1061
|
+
CGPoint point = [self.trackedTouch locationInView:self];
|
|
1062
|
+
|
|
1063
|
+
if (self.touchMode == NativeSdkTouchModePending) {
|
|
1064
|
+
CGFloat dx = point.x - self.touchStartPoint.x;
|
|
1065
|
+
CGFloat dy = point.y - self.touchStartPoint.y;
|
|
1066
|
+
if (dx * dx + dy * dy < NativeSdkTouchSlop * NativeSdkTouchSlop) return;
|
|
1067
|
+
if ([self scrollableWidgetAtPoint:self.touchStartPoint]) {
|
|
1068
|
+
self.touchMode = NativeSdkTouchModeScrolling;
|
|
1069
|
+
} else {
|
|
1070
|
+
self.touchMode = NativeSdkTouchModeDragging;
|
|
1071
|
+
[self forwardTouchPhase:NATIVE_SDK_TOUCH_PHASE_DOWN point:self.touchStartPoint pressure:1];
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
if (self.touchMode == NativeSdkTouchModeScrolling) {
|
|
1076
|
+
// Natural scrolling: finger up moves content up = offset grows, so
|
|
1077
|
+
// the wheel delta is the negated finger delta.
|
|
1078
|
+
float deltaX = (float)(self.touchLastPoint.x - point.x);
|
|
1079
|
+
float deltaY = (float)(self.touchLastPoint.y - point.y);
|
|
1080
|
+
if (self.nativeApp && (deltaX != 0 || deltaY != 0)) {
|
|
1081
|
+
native_sdk_app_scroll(self.nativeApp, self.touchSequence, (float)point.x, (float)point.y, deltaX, deltaY);
|
|
1082
|
+
}
|
|
1083
|
+
} else if (self.touchMode == NativeSdkTouchModeDragging) {
|
|
1084
|
+
[self forwardTouchPhase:NATIVE_SDK_TOUCH_PHASE_DRAG point:point pressure:1];
|
|
1085
|
+
}
|
|
1086
|
+
self.touchLastPoint = point;
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
|
|
1090
|
+
if (!self.trackedTouch || ![touches containsObject:self.trackedTouch]) return;
|
|
1091
|
+
CGPoint point = [self.trackedTouch locationInView:self];
|
|
1092
|
+
switch (self.touchMode) {
|
|
1093
|
+
case NativeSdkTouchModePending:
|
|
1094
|
+
// Under-slop touch: a tap at the start point.
|
|
1095
|
+
[self forwardTouchPhase:NATIVE_SDK_TOUCH_PHASE_DOWN point:self.touchStartPoint pressure:1];
|
|
1096
|
+
[self forwardTouchPhase:NATIVE_SDK_TOUCH_PHASE_UP point:self.touchStartPoint pressure:0];
|
|
1097
|
+
break;
|
|
1098
|
+
case NativeSdkTouchModeDragging:
|
|
1099
|
+
[self forwardTouchPhase:NATIVE_SDK_TOUCH_PHASE_UP point:point pressure:0];
|
|
1100
|
+
break;
|
|
1101
|
+
default:
|
|
1102
|
+
break;
|
|
1103
|
+
}
|
|
1104
|
+
[self resetTouchTracking];
|
|
1105
|
+
[self syncTextInput];
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
|
|
1109
|
+
if (!self.trackedTouch || ![touches containsObject:self.trackedTouch]) return;
|
|
1110
|
+
if (self.touchMode == NativeSdkTouchModeDragging) {
|
|
1111
|
+
[self forwardTouchPhase:NATIVE_SDK_TOUCH_PHASE_CANCEL point:self.touchLastPoint pressure:0];
|
|
1112
|
+
}
|
|
1113
|
+
[self resetTouchTracking];
|
|
1114
|
+
[self syncTextInput];
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
- (void)resetTouchTracking {
|
|
1118
|
+
self.trackedTouch = nil;
|
|
1119
|
+
self.touchMode = NativeSdkTouchModeIdle;
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
// ------------------------------------------------- keyboard <-> focus sync
|
|
1123
|
+
|
|
1124
|
+
// Reconcile UIKit first responder with the runtime's focus/IME-intent
|
|
1125
|
+
// state: keyboard up while an editable text widget owns focus, down when
|
|
1126
|
+
// focus leaves. Called after every dispatched input and once per display
|
|
1127
|
+
// tick (focus can also move from key handling or model updates).
|
|
1128
|
+
- (void)syncTextInput {
|
|
1129
|
+
if (!self.nativeApp || !self.window) return;
|
|
1130
|
+
native_sdk_text_input_state_t state = {0};
|
|
1131
|
+
if (native_sdk_app_text_input_state(self.nativeApp, &state) != 1) return;
|
|
1132
|
+
if (state.active) {
|
|
1133
|
+
if (state.widget_id != self.focusedTextWidget) {
|
|
1134
|
+
self.focusedTextWidget = state.widget_id;
|
|
1135
|
+
[self clearMarkedTextState];
|
|
1136
|
+
}
|
|
1137
|
+
if (!self.isFirstResponder) [self becomeFirstResponder];
|
|
1138
|
+
} else {
|
|
1139
|
+
self.focusedTextWidget = 0;
|
|
1140
|
+
if (self.isFirstResponder) {
|
|
1141
|
+
[self clearMarkedTextState];
|
|
1142
|
+
[self resignFirstResponder];
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
- (void)clearMarkedTextState {
|
|
1148
|
+
self.markedText = @"";
|
|
1149
|
+
self.markedSelectedRange = NSMakeRange(NSNotFound, 0);
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
- (void)emitKeyDownUp:(NSString *)key {
|
|
1153
|
+
if (!self.nativeApp) return;
|
|
1154
|
+
const char *bytes = key.UTF8String ?: "";
|
|
1155
|
+
uintptr_t length = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
|
|
1156
|
+
native_sdk_app_key(self.nativeApp, NATIVE_SDK_KEY_PHASE_DOWN, bytes, length, "", 0, 0);
|
|
1157
|
+
native_sdk_app_key(self.nativeApp, NATIVE_SDK_KEY_PHASE_UP, bytes, length, "", 0, 0);
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
- (void)emitImeEvent:(int)kind text:(NSString *)text cursor:(intptr_t)cursor {
|
|
1161
|
+
if (!self.nativeApp) return;
|
|
1162
|
+
NSString *value = text ?: @"";
|
|
1163
|
+
native_sdk_app_ime(self.nativeApp,
|
|
1164
|
+
kind,
|
|
1165
|
+
value.UTF8String ?: "",
|
|
1166
|
+
[value lengthOfBytesUsingEncoding:NSUTF8StringEncoding],
|
|
1167
|
+
cursor);
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
// -------------------------------------------------------------- UIKeyInput
|
|
1171
|
+
|
|
1172
|
+
- (BOOL)hasText {
|
|
1173
|
+
if (!self.nativeApp || self.focusedTextWidget == 0) return self.markedText.length > 0;
|
|
1174
|
+
native_sdk_widget_semantics_t node = {0};
|
|
1175
|
+
if (native_sdk_app_widget_semantics_by_id(self.nativeApp, self.focusedTextWidget, &node) != 1) return NO;
|
|
1176
|
+
return node.text_len > 0;
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
// Mirrors appkit_host.m insertText: committing identical marked text maps
|
|
1180
|
+
// to commit_composition; divergent marked text cancels before the plain
|
|
1181
|
+
// text insert so the runtime never double-applies the composition.
|
|
1182
|
+
- (void)insertText:(NSString *)text {
|
|
1183
|
+
if (text.length == 0) return;
|
|
1184
|
+
if ([text isEqualToString:@"\n"]) {
|
|
1185
|
+
BOOL hadMarkedText = self.markedText.length > 0;
|
|
1186
|
+
[self clearMarkedTextState];
|
|
1187
|
+
if (hadMarkedText) {
|
|
1188
|
+
[self emitImeEvent:NATIVE_SDK_IME_COMMIT_COMPOSITION text:@"" cursor:-1];
|
|
1189
|
+
}
|
|
1190
|
+
[self emitKeyDownUp:@"enter"];
|
|
1191
|
+
[self syncTextInput];
|
|
1192
|
+
return;
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
BOOL hadMarkedText = self.markedText.length > 0;
|
|
1196
|
+
NSString *previousMarkedText = self.markedText;
|
|
1197
|
+
[self clearMarkedTextState];
|
|
1198
|
+
|
|
1199
|
+
if (hadMarkedText && [previousMarkedText isEqualToString:text]) {
|
|
1200
|
+
[self emitImeEvent:NATIVE_SDK_IME_COMMIT_COMPOSITION text:@"" cursor:-1];
|
|
1201
|
+
return;
|
|
1202
|
+
}
|
|
1203
|
+
if (hadMarkedText) {
|
|
1204
|
+
[self emitImeEvent:NATIVE_SDK_IME_CANCEL_COMPOSITION text:@"" cursor:-1];
|
|
1205
|
+
}
|
|
1206
|
+
if (self.nativeApp) {
|
|
1207
|
+
native_sdk_app_text(self.nativeApp,
|
|
1208
|
+
text.UTF8String ?: "",
|
|
1209
|
+
[text lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
- (void)deleteBackward {
|
|
1214
|
+
if (self.markedText.length > 0) {
|
|
1215
|
+
[self clearMarkedTextState];
|
|
1216
|
+
[self emitImeEvent:NATIVE_SDK_IME_CANCEL_COMPOSITION text:@"" cursor:-1];
|
|
1217
|
+
return;
|
|
1218
|
+
}
|
|
1219
|
+
[self emitKeyDownUp:@"backspace"];
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
// ------------------------------------------------------------- UITextInput
|
|
1223
|
+
|
|
1224
|
+
- (NSString *)textInRange:(UITextRange *)range {
|
|
1225
|
+
NativeSdkTextRange *value = (NativeSdkTextRange *)range;
|
|
1226
|
+
if (!value || value.location < 0) return @"";
|
|
1227
|
+
NSInteger max = (NSInteger)self.markedText.length;
|
|
1228
|
+
NSInteger location = MIN(value.location, max);
|
|
1229
|
+
NSInteger length = MIN(value.length, max - location);
|
|
1230
|
+
return [self.markedText substringWithRange:NSMakeRange(location, length)];
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
- (void)replaceRange:(UITextRange *)range withText:(NSString *)text {
|
|
1234
|
+
(void)range;
|
|
1235
|
+
[self insertText:text];
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
- (UITextRange *)selectedTextRange {
|
|
1239
|
+
NSInteger caret = (NSInteger)self.markedText.length;
|
|
1240
|
+
if (self.markedSelectedRange.location != NSNotFound) {
|
|
1241
|
+
caret = MIN((NSInteger)(self.markedSelectedRange.location + self.markedSelectedRange.length), caret);
|
|
1242
|
+
}
|
|
1243
|
+
return [NativeSdkTextRange rangeWithLocation:caret length:0];
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
- (void)setSelectedTextRange:(UITextRange *)range {
|
|
1247
|
+
NativeSdkTextRange *value = (NativeSdkTextRange *)range;
|
|
1248
|
+
if (!value) return;
|
|
1249
|
+
self.markedSelectedRange = NSMakeRange(MAX(0, value.location), MAX(0, value.length));
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
- (UITextRange *)markedTextRange {
|
|
1253
|
+
if (self.markedText.length == 0) return nil;
|
|
1254
|
+
return [NativeSdkTextRange rangeWithLocation:0 length:(NSInteger)self.markedText.length];
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
// Marked text is the live composition: forward it (with the caret as a
|
|
1258
|
+
// UTF-8 byte offset) through the same set_composition path the desktop
|
|
1259
|
+
// hosts use, so dead keys and multi-stage IMEs stay correct.
|
|
1260
|
+
- (void)setMarkedText:(NSString *)markedText selectedRange:(NSRange)selectedRange {
|
|
1261
|
+
NSString *text = markedText ?: @"";
|
|
1262
|
+
BOOL hadMarkedText = self.markedText.length > 0;
|
|
1263
|
+
if (text.length == 0) {
|
|
1264
|
+
[self clearMarkedTextState];
|
|
1265
|
+
if (hadMarkedText) {
|
|
1266
|
+
[self emitImeEvent:NATIVE_SDK_IME_CANCEL_COMPOSITION text:@"" cursor:-1];
|
|
1267
|
+
}
|
|
1268
|
+
return;
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
NSUInteger cursor = text.length;
|
|
1272
|
+
if (selectedRange.location != NSNotFound) {
|
|
1273
|
+
cursor = MIN(text.length, selectedRange.location + selectedRange.length);
|
|
1274
|
+
self.markedSelectedRange = selectedRange;
|
|
1275
|
+
} else {
|
|
1276
|
+
self.markedSelectedRange = NSMakeRange(text.length, 0);
|
|
1277
|
+
}
|
|
1278
|
+
self.markedText = text;
|
|
1279
|
+
intptr_t cursorBytes = (intptr_t)[[text substringToIndex:cursor] lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
|
|
1280
|
+
[self emitImeEvent:NATIVE_SDK_IME_SET_COMPOSITION text:text cursor:cursorBytes];
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
- (void)unmarkText {
|
|
1284
|
+
BOOL hadMarkedText = self.markedText.length > 0;
|
|
1285
|
+
[self clearMarkedTextState];
|
|
1286
|
+
if (hadMarkedText) {
|
|
1287
|
+
[self emitImeEvent:NATIVE_SDK_IME_COMMIT_COMPOSITION text:@"" cursor:-1];
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
- (UITextPosition *)beginningOfDocument {
|
|
1292
|
+
return [NativeSdkTextPosition positionWithIndex:0];
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
- (UITextPosition *)endOfDocument {
|
|
1296
|
+
return [NativeSdkTextPosition positionWithIndex:(NSInteger)self.markedText.length];
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
- (UITextRange *)textRangeFromPosition:(UITextPosition *)fromPosition toPosition:(UITextPosition *)toPosition {
|
|
1300
|
+
NSInteger from = ((NativeSdkTextPosition *)fromPosition).index;
|
|
1301
|
+
NSInteger to = ((NativeSdkTextPosition *)toPosition).index;
|
|
1302
|
+
return [NativeSdkTextRange rangeWithLocation:MIN(from, to) length:ABS(to - from)];
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
- (UITextPosition *)positionFromPosition:(UITextPosition *)position offset:(NSInteger)offset {
|
|
1306
|
+
NSInteger index = ((NativeSdkTextPosition *)position).index + offset;
|
|
1307
|
+
if (index < 0 || index > (NSInteger)self.markedText.length) return nil;
|
|
1308
|
+
return [NativeSdkTextPosition positionWithIndex:index];
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
- (UITextPosition *)positionFromPosition:(UITextPosition *)position inDirection:(UITextLayoutDirection)direction offset:(NSInteger)offset {
|
|
1312
|
+
NSInteger delta = (direction == UITextLayoutDirectionLeft || direction == UITextLayoutDirectionUp) ? -offset : offset;
|
|
1313
|
+
return [self positionFromPosition:position offset:delta];
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
- (NSComparisonResult)comparePosition:(UITextPosition *)position toPosition:(UITextPosition *)other {
|
|
1317
|
+
NSInteger a = ((NativeSdkTextPosition *)position).index;
|
|
1318
|
+
NSInteger b = ((NativeSdkTextPosition *)other).index;
|
|
1319
|
+
if (a < b) return NSOrderedAscending;
|
|
1320
|
+
if (a > b) return NSOrderedDescending;
|
|
1321
|
+
return NSOrderedSame;
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
- (NSInteger)offsetFromPosition:(UITextPosition *)fromPosition toPosition:(UITextPosition *)toPosition {
|
|
1325
|
+
return ((NativeSdkTextPosition *)toPosition).index - ((NativeSdkTextPosition *)fromPosition).index;
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
- (id<UITextInputTokenizer>)tokenizer {
|
|
1329
|
+
return [[UITextInputStringTokenizer alloc] initWithTextInput:self];
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
- (UITextPosition *)positionWithinRange:(UITextRange *)range farthestInDirection:(UITextLayoutDirection)direction {
|
|
1333
|
+
if (direction == UITextLayoutDirectionLeft || direction == UITextLayoutDirectionUp) return range.start;
|
|
1334
|
+
return range.end;
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
- (UITextRange *)characterRangeByExtendingPosition:(UITextPosition *)position inDirection:(UITextLayoutDirection)direction {
|
|
1338
|
+
NSInteger index = ((NativeSdkTextPosition *)position).index;
|
|
1339
|
+
if (direction == UITextLayoutDirectionLeft || direction == UITextLayoutDirectionUp) {
|
|
1340
|
+
return [NativeSdkTextRange rangeWithLocation:0 length:index];
|
|
1341
|
+
}
|
|
1342
|
+
return [NativeSdkTextRange rangeWithLocation:index length:(NSInteger)self.markedText.length - index];
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
- (NSWritingDirection)baseWritingDirectionForPosition:(UITextPosition *)position inDirection:(UITextStorageDirection)direction {
|
|
1346
|
+
(void)position;
|
|
1347
|
+
(void)direction;
|
|
1348
|
+
return NSWritingDirectionNatural;
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
- (void)setBaseWritingDirection:(NSWritingDirection)writingDirection forRange:(UITextRange *)range {
|
|
1352
|
+
(void)writingDirection;
|
|
1353
|
+
(void)range;
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1356
|
+
- (CGRect)focusedWidgetRect {
|
|
1357
|
+
if (!self.nativeApp) return CGRectZero;
|
|
1358
|
+
native_sdk_text_input_state_t state = {0};
|
|
1359
|
+
if (native_sdk_app_text_input_state(self.nativeApp, &state) != 1 || !state.active) return CGRectZero;
|
|
1360
|
+
return CGRectMake(state.x, state.y, state.width, state.height);
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1363
|
+
- (CGRect)firstRectForRange:(UITextRange *)range {
|
|
1364
|
+
(void)range;
|
|
1365
|
+
CGRect rect = [self focusedWidgetRect];
|
|
1366
|
+
return CGRectIsEmpty(rect) ? self.bounds : rect;
|
|
1367
|
+
}
|
|
1368
|
+
|
|
1369
|
+
- (CGRect)caretRectForPosition:(UITextPosition *)position {
|
|
1370
|
+
(void)position;
|
|
1371
|
+
CGRect rect = [self focusedWidgetRect];
|
|
1372
|
+
if (CGRectIsEmpty(rect)) return CGRectMake(0, 0, 2, 24);
|
|
1373
|
+
return CGRectMake(CGRectGetMaxX(rect) - 2, rect.origin.y, 2, rect.size.height);
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
- (NSArray<UITextSelectionRect *> *)selectionRectsForRange:(UITextRange *)range {
|
|
1377
|
+
(void)range;
|
|
1378
|
+
return @[];
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
- (UITextPosition *)closestPositionToPoint:(CGPoint)point {
|
|
1382
|
+
(void)point;
|
|
1383
|
+
return [self endOfDocument];
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
- (UITextPosition *)closestPositionToPoint:(CGPoint)point withinRange:(UITextRange *)range {
|
|
1387
|
+
(void)point;
|
|
1388
|
+
return range.end;
|
|
1389
|
+
}
|
|
1390
|
+
|
|
1391
|
+
- (UITextRange *)characterRangeAtPoint:(CGPoint)point {
|
|
1392
|
+
(void)point;
|
|
1393
|
+
return nil;
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
// -------------------------------------------------------- UITextInputTraits
|
|
1397
|
+
// Deterministic input for tests and desktop-parity text handling: the
|
|
1398
|
+
// runtime owns editing behavior, so system rewriting stays off.
|
|
1399
|
+
|
|
1400
|
+
- (UITextAutocorrectionType)autocorrectionType {
|
|
1401
|
+
return UITextAutocorrectionTypeNo;
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
- (UITextSpellCheckingType)spellCheckingType {
|
|
1405
|
+
return UITextSpellCheckingTypeNo;
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
- (UITextSmartQuotesType)smartQuotesType {
|
|
1409
|
+
return UITextSmartQuotesTypeNo;
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
- (UITextSmartDashesType)smartDashesType {
|
|
1413
|
+
return UITextSmartDashesTypeNo;
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
- (UITextSmartInsertDeleteType)smartInsertDeleteType {
|
|
1417
|
+
return UITextSmartInsertDeleteTypeNo;
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
- (UITextAutocapitalizationType)autocapitalizationType {
|
|
1421
|
+
return UITextAutocapitalizationTypeNone;
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
@end
|
|
1425
|
+
|
|
1426
|
+
// ------------------------------------------------------- navigation pages
|
|
1427
|
+
//
|
|
1428
|
+
// One lightweight page in the platform navigation stack: a plain
|
|
1429
|
+
// container view holding either the LIVE canvas view (always the top
|
|
1430
|
+
// page) or a retained snapshot of a shallower page (the pages
|
|
1431
|
+
// underneath). The page carries no app logic — it exists so a real
|
|
1432
|
+
// UINavigationController can run its real push/pop transitions and its
|
|
1433
|
+
// real interactive edge-swipe-back recognizer over the single live
|
|
1434
|
+
// canvas. See the platform navigation section below for the full
|
|
1435
|
+
// contract.
|
|
1436
|
+
@interface NativeSdkNavPageViewController : UIViewController
|
|
1437
|
+
@property(nonatomic, strong) UIView *contentView;
|
|
1438
|
+
- (void)installContent:(UIView *)content;
|
|
1439
|
+
@end
|
|
1440
|
+
|
|
1441
|
+
@implementation NativeSdkNavPageViewController
|
|
1442
|
+
|
|
1443
|
+
- (void)viewDidLoad {
|
|
1444
|
+
[super viewDidLoad];
|
|
1445
|
+
self.view.backgroundColor = [UIColor whiteColor];
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
/* Install (or move in) the page's single content view, full-bleed with
|
|
1449
|
+
* autoresizing — moving the live canvas between pages is an ordinary
|
|
1450
|
+
* subview reparent, so the Metal layer keeps its drawables and scale. */
|
|
1451
|
+
- (void)installContent:(UIView *)content {
|
|
1452
|
+
if (self.contentView == content && content.superview == self.viewIfLoaded) return;
|
|
1453
|
+
if (self.contentView != content) [self.contentView removeFromSuperview];
|
|
1454
|
+
self.contentView = content;
|
|
1455
|
+
if (!content) return;
|
|
1456
|
+
[self loadViewIfNeeded];
|
|
1457
|
+
content.frame = self.view.bounds;
|
|
1458
|
+
content.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
|
|
1459
|
+
[self.view addSubview:content];
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
@end
|
|
1463
|
+
|
|
1464
|
+
@interface NativeSdkCanvasViewController : UIViewController <UITabBarDelegate, UINavigationControllerDelegate, UIGestureRecognizerDelegate>
|
|
1465
|
+
@property(nonatomic) void *nativeApp;
|
|
1466
|
+
@property(nonatomic, strong) NativeSdkAudioEngine *audioEngine;
|
|
1467
|
+
/* Declared platform chrome (the app's shell-metadata tab set + optional
|
|
1468
|
+
* primary action), projected as REAL native controls: an actual UITabBar
|
|
1469
|
+
* with system styling and accessibility, and a real UIButton for the
|
|
1470
|
+
* primary action. The canvas stays the full-bleed content region; the
|
|
1471
|
+
* bar's overlap rides additionalSafeAreaInsets so the app's layout
|
|
1472
|
+
* clears it through the existing chrome-inset channel. Selection is a
|
|
1473
|
+
* PROJECTION of the model: each display tick polls
|
|
1474
|
+
* native_sdk_app_chrome_selected_tab and moves the bar to match; a tap
|
|
1475
|
+
* dispatches the tab's declared command id through
|
|
1476
|
+
* native_sdk_app_command and the model answers — the bar is never the
|
|
1477
|
+
* source of truth. */
|
|
1478
|
+
@property(nonatomic, strong) UITabBar *chromeTabBar;
|
|
1479
|
+
@property(nonatomic, copy) NSArray<NSString *> *chromeTabCommands;
|
|
1480
|
+
@property(nonatomic, strong) UIButton *chromeActionButton;
|
|
1481
|
+
@property(nonatomic, copy) NSString *chromeActionCommand;
|
|
1482
|
+
@property(nonatomic) NSInteger chromeSelectedIndex;
|
|
1483
|
+
@property(nonatomic) int reportedFormFactor;
|
|
1484
|
+
/* The live canvas view (the app's single surface). It always lives in
|
|
1485
|
+
* the TOP page of the navigation stack below; the tab bar and primary
|
|
1486
|
+
* action stay siblings of the stack on this controller's root view, so
|
|
1487
|
+
* they hold still through push/pop exactly like the system's own bars. */
|
|
1488
|
+
@property(nonatomic, strong) NativeSdkCanvasView *canvasView;
|
|
1489
|
+
/* Platform push/pop navigation (see the section comment below): a real
|
|
1490
|
+
* UINavigationController whose lightweight pages wrap the live canvas
|
|
1491
|
+
* (top) and retained snapshots (underneath); the model's navigation
|
|
1492
|
+
* depth is polled each tick and drives the stack — never the reverse,
|
|
1493
|
+
* except the REAL interactive edge-swipe-back gesture, whose completion
|
|
1494
|
+
* dispatches the app's declared back command exactly once. */
|
|
1495
|
+
@property(nonatomic, strong) UINavigationController *navController;
|
|
1496
|
+
/* Retained shallow-page snapshots, index = depth level (bounded; a
|
|
1497
|
+
* level past the cap or without a captured frame keeps NSNull and shows
|
|
1498
|
+
* the background wash during a gesture). */
|
|
1499
|
+
@property(nonatomic, strong) NSMutableArray *navSnapshots;
|
|
1500
|
+
/* The depth the navigation stack currently reflects (-1 until the app's
|
|
1501
|
+
* projection first answers) and the selected tab seen beside it, so a
|
|
1502
|
+
* depth change that arrives WITH a tab change reads as a lateral switch
|
|
1503
|
+
* and reconciles without a transition. */
|
|
1504
|
+
@property(nonatomic) NSInteger navAppliedDepth;
|
|
1505
|
+
@property(nonatomic) NSInteger navAppliedTab;
|
|
1506
|
+
/* Transition bookkeeping: while a push/pop (host-driven or interactive)
|
|
1507
|
+
* runs, depth reconciliation defers to the next tick; navHostTransition
|
|
1508
|
+
* marks stack moves this host initiated so the delegate can tell them
|
|
1509
|
+
* from the interactive gesture's. */
|
|
1510
|
+
@property(nonatomic) BOOL navTransitionActive;
|
|
1511
|
+
@property(nonatomic) BOOL navHostTransition;
|
|
1512
|
+
/* Whether the most recent damage delivery carried pixels (set by
|
|
1513
|
+
* renderAndPresent): the transition pre-render loops its pump until the
|
|
1514
|
+
* dispatched change's frame actually lands, because the runtime
|
|
1515
|
+
* presents a change on a frame pump after its dispatch, not inside it. */
|
|
1516
|
+
@property(nonatomic) BOOL lastDeliveryHadDamage;
|
|
1517
|
+
/* The post-transition cover: the incoming page's exact frame held over
|
|
1518
|
+
* the live canvas for a few ticks after a transition lands, while the
|
|
1519
|
+
* canvas — freshly re-installed — re-presents underneath. Drawable
|
|
1520
|
+
* presents are asynchronous and composite on the render server's
|
|
1521
|
+
* schedule, not ours; the cover is what makes the canvas swap-in
|
|
1522
|
+
* invisible instead of racing it. */
|
|
1523
|
+
@property(nonatomic, strong) UIView *navFreezeOverlay;
|
|
1524
|
+
@property(nonatomic) NSInteger navOverlayTicks;
|
|
1525
|
+
/* The app's declared back command ("" when the app declares no
|
|
1526
|
+
* navigation projection — the gesture never arms without one). */
|
|
1527
|
+
@property(nonatomic, copy) NSString *navBackCommand;
|
|
1528
|
+
@property(nonatomic, strong) id<MTLDevice> device;
|
|
1529
|
+
@property(nonatomic, strong) id<MTLCommandQueue> commandQueue;
|
|
1530
|
+
@property(nonatomic, strong) id<MTLTexture> canvasTexture;
|
|
1531
|
+
/* The canvas presenter: the fullscreen-quad pipeline + nearest sampler
|
|
1532
|
+
* that draws the RGBA8 canvas texture into the BGRA8 drawable — the
|
|
1533
|
+
* iOS twin of appkit_host.m's ensureCanvasPresenter. Compiled once from
|
|
1534
|
+
* source on first present. */
|
|
1535
|
+
@property(nonatomic, strong) id<MTLRenderPipelineState> canvasRenderPipeline;
|
|
1536
|
+
@property(nonatomic, strong) id<MTLSamplerState> canvasSampler;
|
|
1537
|
+
@property(nonatomic, strong) CADisplayLink *displayLink;
|
|
1538
|
+
@property(nonatomic) uint8_t *rgbaBytes;
|
|
1539
|
+
@property(nonatomic) size_t stagingCapacity;
|
|
1540
|
+
@property(nonatomic) uint64_t lastCanvasRevision;
|
|
1541
|
+
@property(nonatomic) BOOL hasPresentedRevision;
|
|
1542
|
+
@property(nonatomic) BOOL needsPresent;
|
|
1543
|
+
@property(nonatomic) CGFloat viewportScale;
|
|
1544
|
+
/* The drawable size last applied to the layer: reassigning drawableSize
|
|
1545
|
+
* every present invalidates the layer's drawable pool on some OS
|
|
1546
|
+
* releases, so it is only written when the rendered pixel size actually
|
|
1547
|
+
* changed (mirroring the macOS host's updateDrawableSize compare). */
|
|
1548
|
+
@property(nonatomic) CGSize appliedDrawableSize;
|
|
1549
|
+
/* Scene-lifecycle observer tokens (background/foreground pump pausing,
|
|
1550
|
+
* resign/become-active runtime activation), removed on teardown. */
|
|
1551
|
+
@property(nonatomic, strong) NSArray<id> *lifecycleObservers;
|
|
1552
|
+
/* Frame-trace counters (NATIVE_SDK_GPU_FRAME_TRACE=1 only): cumulative
|
|
1553
|
+
* structural truth for the present path — how many display ticks ran,
|
|
1554
|
+
* how many short-circuited idle, how many drawables were acquired, and
|
|
1555
|
+
* how many bytes rode replaceRegion. Zero cost while the trace is off. */
|
|
1556
|
+
@property(nonatomic) uint64_t traceTickCount;
|
|
1557
|
+
@property(nonatomic) uint64_t traceIdleTickCount;
|
|
1558
|
+
@property(nonatomic) uint64_t tracePresentCount;
|
|
1559
|
+
@property(nonatomic) uint64_t traceDrawableCount;
|
|
1560
|
+
@property(nonatomic) uint64_t traceNilDrawableCount;
|
|
1561
|
+
@property(nonatomic) uint64_t traceUploadBytes;
|
|
1562
|
+
@property(nonatomic) uint64_t tracePresentCpuNs;
|
|
1563
|
+
@property(nonatomic) uint64_t traceLastSummaryNs;
|
|
1564
|
+
@end
|
|
1565
|
+
|
|
1566
|
+
@implementation NativeSdkCanvasViewController
|
|
1567
|
+
|
|
1568
|
+
- (CAMetalLayer *)metalLayer {
|
|
1569
|
+
return (CAMetalLayer *)self.canvasView.layer;
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
// The root view is a plain container: the live canvas rides inside the
|
|
1573
|
+
// navigation stack's top page (so real push/pop transitions can move
|
|
1574
|
+
// it), while the declared chrome (tab bar, primary action) stays on this
|
|
1575
|
+
// root — outside the stack — and holds still through transitions.
|
|
1576
|
+
- (void)loadView {
|
|
1577
|
+
self.view = [[UIView alloc] init];
|
|
1578
|
+
}
|
|
1579
|
+
|
|
1580
|
+
- (void)viewDidLoad {
|
|
1581
|
+
[super viewDidLoad];
|
|
1582
|
+
|
|
1583
|
+
self.device = MTLCreateSystemDefaultDevice();
|
|
1584
|
+
self.commandQueue = [self.device newCommandQueue];
|
|
1585
|
+
self.viewportScale = 1;
|
|
1586
|
+
|
|
1587
|
+
self.canvasView = [[NativeSdkCanvasView alloc] initWithFrame:self.view.bounds];
|
|
1588
|
+
CAMetalLayer *layer = [self metalLayer];
|
|
1589
|
+
layer.device = self.device;
|
|
1590
|
+
layer.pixelFormat = MTLPixelFormatBGRA8Unorm;
|
|
1591
|
+
// The drawable is only ever a render-pass target (the canvas texture
|
|
1592
|
+
// is sampled INTO it by the presenter quad; nothing blits from or
|
|
1593
|
+
// samples the drawable itself), so it keeps the compositor-optimal
|
|
1594
|
+
// framebuffer-only default.
|
|
1595
|
+
layer.framebufferOnly = YES;
|
|
1596
|
+
layer.opaque = YES;
|
|
1597
|
+
self.view.backgroundColor = [UIColor whiteColor];
|
|
1598
|
+
|
|
1599
|
+
// The navigation container: a REAL UINavigationController (bar
|
|
1600
|
+
// hidden — apps draw their own headers in canvas) as a child, its
|
|
1601
|
+
// root page holding the live canvas. Always present so the view
|
|
1602
|
+
// hierarchy is one shape for every app; without a declared
|
|
1603
|
+
// navigation projection the stack simply never moves and the
|
|
1604
|
+
// edge-swipe recognizer never arms.
|
|
1605
|
+
NativeSdkNavPageViewController *root_page = [[NativeSdkNavPageViewController alloc] init];
|
|
1606
|
+
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:root_page];
|
|
1607
|
+
nav.navigationBarHidden = YES;
|
|
1608
|
+
nav.delegate = self;
|
|
1609
|
+
nav.view.backgroundColor = [UIColor whiteColor];
|
|
1610
|
+
[self addChildViewController:nav];
|
|
1611
|
+
nav.view.frame = self.view.bounds;
|
|
1612
|
+
nav.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
|
|
1613
|
+
[self.view addSubview:nav.view];
|
|
1614
|
+
[nav didMoveToParentViewController:self];
|
|
1615
|
+
self.navController = nav;
|
|
1616
|
+
self.navSnapshots = [NSMutableArray array];
|
|
1617
|
+
self.navAppliedDepth = -1;
|
|
1618
|
+
self.navAppliedTab = -1;
|
|
1619
|
+
self.navBackCommand = @"";
|
|
1620
|
+
[root_page installContent:self.canvasView];
|
|
1621
|
+
// The REAL interactive pop recognizer: with the navigation bar
|
|
1622
|
+
// hidden its default delegate never lets it begin, so this host is
|
|
1623
|
+
// the delegate and arms it exactly while the app's projection says a
|
|
1624
|
+
// page is open (gestureRecognizerShouldBegin below). The physics,
|
|
1625
|
+
// tracking, and cancellation are entirely the system's.
|
|
1626
|
+
nav.interactivePopGestureRecognizer.delegate = self;
|
|
1627
|
+
|
|
1628
|
+
self.nativeApp = native_sdk_app_create();
|
|
1629
|
+
if (!self.nativeApp) {
|
|
1630
|
+
NSLog(@"native-sdk: native_sdk_app_create failed");
|
|
1631
|
+
return;
|
|
1632
|
+
}
|
|
1633
|
+
[self canvasView].nativeApp = self.nativeApp;
|
|
1634
|
+
|
|
1635
|
+
// Real text metrics (M5): register the CoreText measure callback before
|
|
1636
|
+
// start so the installing layout already measures with the fonts
|
|
1637
|
+
// presentation would draw with. The estimator opt-out is a LAUNCH
|
|
1638
|
+
// ARGUMENT (simctl launch <udid> <bundle> --estimator-text-metrics),
|
|
1639
|
+
// not an environment variable: the simulator's launchd replays a
|
|
1640
|
+
// previous launch's SIMCTL_CHILD_* environment, so env toggles are not
|
|
1641
|
+
// deterministic across relaunches; process arguments are.
|
|
1642
|
+
if ([NSProcessInfo.processInfo.arguments containsObject:@"--estimator-text-metrics"]) {
|
|
1643
|
+
NSLog(@"native-sdk: text measure disabled (estimator metrics)");
|
|
1644
|
+
} else {
|
|
1645
|
+
native_sdk_app_set_text_measure(self.nativeApp, NativeSdkMeasureText, NULL);
|
|
1646
|
+
[self logNativeErrorIfAny:@"text_measure"];
|
|
1647
|
+
NSLog(@"native-sdk: CoreText text measure registered");
|
|
1648
|
+
}
|
|
1649
|
+
|
|
1650
|
+
// The platform audio service (registered before start, like the text
|
|
1651
|
+
// measure, so the first effect dispatch already sees it): one real
|
|
1652
|
+
// player behind the embed audio seam — AVAudioPlayer for local files
|
|
1653
|
+
// and verified cache entries, AVPlayer for progressive URL streams.
|
|
1654
|
+
self.audioEngine = [[NativeSdkAudioEngine alloc] init];
|
|
1655
|
+
self.audioEngine.nativeApp = self.nativeApp;
|
|
1656
|
+
native_sdk_audio_service_t audioService = {
|
|
1657
|
+
.load = NativeSdkAudioServiceLoad,
|
|
1658
|
+
.load_url = NativeSdkAudioServiceLoadUrl,
|
|
1659
|
+
.play = NativeSdkAudioServicePlay,
|
|
1660
|
+
.pause = NativeSdkAudioServicePause,
|
|
1661
|
+
.stop = NativeSdkAudioServiceStop,
|
|
1662
|
+
.seek = NativeSdkAudioServiceSeek,
|
|
1663
|
+
.set_volume = NativeSdkAudioServiceSetVolume,
|
|
1664
|
+
};
|
|
1665
|
+
native_sdk_app_set_audio_service(self.nativeApp, &audioService, (__bridge void *)self.audioEngine);
|
|
1666
|
+
[self logNativeErrorIfAny:@"audio_service"];
|
|
1667
|
+
|
|
1668
|
+
// The platform image decoder (registered before start, like the audio
|
|
1669
|
+
// service, so a boot-effect fx.registerImageBytes already decodes):
|
|
1670
|
+
// CGImageSource behind the embed image seam, the same ImageIO family
|
|
1671
|
+
// the macOS host decodes through.
|
|
1672
|
+
native_sdk_image_service_t imageService = {
|
|
1673
|
+
.decode = NativeSdkImageServiceDecode,
|
|
1674
|
+
};
|
|
1675
|
+
native_sdk_app_set_image_service(self.nativeApp, &imageService, NULL);
|
|
1676
|
+
[self logNativeErrorIfAny:@"image_service"];
|
|
1677
|
+
|
|
1678
|
+
// Verification harness: with NATIVE_SDK_AUTOMATION set (simctl launch
|
|
1679
|
+
// exports SIMCTL_CHILD_* into the app) the embedded runtime publishes
|
|
1680
|
+
// snapshot.txt into the app's data container, same protocol as the
|
|
1681
|
+
// desktop -Dautomation=true runners.
|
|
1682
|
+
if (getenv("NATIVE_SDK_AUTOMATION")) {
|
|
1683
|
+
NSString *dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject
|
|
1684
|
+
stringByAppendingPathComponent:@"native-sdk-automation"];
|
|
1685
|
+
if (dir) {
|
|
1686
|
+
native_sdk_app_set_automation_dir(self.nativeApp,
|
|
1687
|
+
dir.UTF8String,
|
|
1688
|
+
[dir lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
|
|
1689
|
+
[self logNativeErrorIfAny:@"automation"];
|
|
1690
|
+
NSLog(@"native-sdk: automation dir %@", dir);
|
|
1691
|
+
}
|
|
1692
|
+
}
|
|
1693
|
+
|
|
1694
|
+
// Packaged assets: `native package` bundles the app's assets/ into an
|
|
1695
|
+
// Assets directory inside the app bundle; point the embed host at it
|
|
1696
|
+
// before start so asset-relative loads resolve. (Not "Resources": a
|
|
1697
|
+
// bundle-root directory of that name makes CFBundle read the .app as
|
|
1698
|
+
// a deep macOS-layout bundle and archive stamping breaks.) Absent in
|
|
1699
|
+
// the dev loop's minimal bundle when the app ships no assets.
|
|
1700
|
+
NSString *assetRoot = [NSBundle.mainBundle.bundlePath stringByAppendingPathComponent:@"Assets"];
|
|
1701
|
+
BOOL assetRootIsDir = NO;
|
|
1702
|
+
if ([NSFileManager.defaultManager fileExistsAtPath:assetRoot isDirectory:&assetRootIsDir] && assetRootIsDir) {
|
|
1703
|
+
native_sdk_app_set_asset_root(self.nativeApp,
|
|
1704
|
+
assetRoot.UTF8String,
|
|
1705
|
+
[assetRoot lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
|
|
1706
|
+
[self logNativeErrorIfAny:@"asset_root"];
|
|
1707
|
+
}
|
|
1708
|
+
|
|
1709
|
+
// Host chrome reports, filed BEFORE start so the pre-install chrome
|
|
1710
|
+
// query already carries them: the size class the app can switch
|
|
1711
|
+
// shells on (width derivation stays its fallback).
|
|
1712
|
+
self.chromeSelectedIndex = -1;
|
|
1713
|
+
[self reportFormFactor];
|
|
1714
|
+
|
|
1715
|
+
native_sdk_app_start(self.nativeApp);
|
|
1716
|
+
native_sdk_app_activate(self.nativeApp);
|
|
1717
|
+
[self logNativeErrorIfAny:@"start"];
|
|
1718
|
+
|
|
1719
|
+
// Declared platform chrome: build the real system controls the shell
|
|
1720
|
+
// metadata asks for (nothing when the app declares none).
|
|
1721
|
+
[self installDeclaredChrome];
|
|
1722
|
+
|
|
1723
|
+
// The navigation projection's static half: the declared back command
|
|
1724
|
+
// the completed edge-swipe dispatches. Without one the projection is
|
|
1725
|
+
// inert — the stack never moves and the gesture never begins.
|
|
1726
|
+
native_sdk_chrome_item_t back_item = {0};
|
|
1727
|
+
if (native_sdk_app_chrome_navigation_back_command(self.nativeApp, &back_item) == 1 && back_item.id) {
|
|
1728
|
+
self.navBackCommand = [[NSString alloc] initWithBytes:back_item.id
|
|
1729
|
+
length:back_item.id_len
|
|
1730
|
+
encoding:NSUTF8StringEncoding] ?: @"";
|
|
1731
|
+
NSLog(@"native-sdk: platform navigation projected (back command %@)", self.navBackCommand);
|
|
1732
|
+
}
|
|
1733
|
+
|
|
1734
|
+
self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(displayLinkTick:)];
|
|
1735
|
+
[self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
|
|
1736
|
+
|
|
1737
|
+
// Scene lifecycle: the pump follows the app's visibility the way the
|
|
1738
|
+
// macOS host follows window occlusion. A backgrounded app presents
|
|
1739
|
+
// nothing — the display link pauses (GPU work submitted from the
|
|
1740
|
+
// background is killed by the watchdog, and pixels nobody can see
|
|
1741
|
+
// are pure battery drain) — and the runtime hears about activation
|
|
1742
|
+
// honestly (deactivate on resign-active, activate on become-active;
|
|
1743
|
+
// the Android host's onPause/onResume mirror). Returning to the
|
|
1744
|
+
// foreground marks needsPresent: the drawable pool may have been
|
|
1745
|
+
// purged while covered, so the retained canvas re-presents once even
|
|
1746
|
+
// though its revision is unchanged — the mobile mirror of the macOS
|
|
1747
|
+
// occlusion observer's glass flush. The launch-time first present
|
|
1748
|
+
// needs no special case here: until the first present lands,
|
|
1749
|
+
// hasPresentedRevision stays NO and every tick presents.
|
|
1750
|
+
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
|
|
1751
|
+
__weak NativeSdkCanvasViewController *weakSelf = self;
|
|
1752
|
+
self.lifecycleObservers = @[
|
|
1753
|
+
[center addObserverForName:UIApplicationWillResignActiveNotification
|
|
1754
|
+
object:nil
|
|
1755
|
+
queue:[NSOperationQueue mainQueue]
|
|
1756
|
+
usingBlock:^(NSNotification *note) {
|
|
1757
|
+
(void)note;
|
|
1758
|
+
NativeSdkCanvasViewController *strongSelf = weakSelf;
|
|
1759
|
+
if (strongSelf.nativeApp) native_sdk_app_deactivate(strongSelf.nativeApp);
|
|
1760
|
+
}],
|
|
1761
|
+
[center addObserverForName:UIApplicationDidBecomeActiveNotification
|
|
1762
|
+
object:nil
|
|
1763
|
+
queue:[NSOperationQueue mainQueue]
|
|
1764
|
+
usingBlock:^(NSNotification *note) {
|
|
1765
|
+
(void)note;
|
|
1766
|
+
NativeSdkCanvasViewController *strongSelf = weakSelf;
|
|
1767
|
+
if (strongSelf.nativeApp) native_sdk_app_activate(strongSelf.nativeApp);
|
|
1768
|
+
}],
|
|
1769
|
+
[center addObserverForName:UIApplicationDidEnterBackgroundNotification
|
|
1770
|
+
object:nil
|
|
1771
|
+
queue:[NSOperationQueue mainQueue]
|
|
1772
|
+
usingBlock:^(NSNotification *note) {
|
|
1773
|
+
(void)note;
|
|
1774
|
+
weakSelf.displayLink.paused = YES;
|
|
1775
|
+
}],
|
|
1776
|
+
[center addObserverForName:UIApplicationWillEnterForegroundNotification
|
|
1777
|
+
object:nil
|
|
1778
|
+
queue:[NSOperationQueue mainQueue]
|
|
1779
|
+
usingBlock:^(NSNotification *note) {
|
|
1780
|
+
(void)note;
|
|
1781
|
+
NativeSdkCanvasViewController *strongSelf = weakSelf;
|
|
1782
|
+
if (!strongSelf) return;
|
|
1783
|
+
strongSelf.needsPresent = YES;
|
|
1784
|
+
strongSelf.displayLink.paused = NO;
|
|
1785
|
+
}],
|
|
1786
|
+
];
|
|
1787
|
+
}
|
|
1788
|
+
|
|
1789
|
+
- (void)dealloc {
|
|
1790
|
+
[self.displayLink invalidate];
|
|
1791
|
+
for (id observer in self.lifecycleObservers) {
|
|
1792
|
+
[[NSNotificationCenter defaultCenter] removeObserver:observer];
|
|
1793
|
+
}
|
|
1794
|
+
if (self.nativeApp) {
|
|
1795
|
+
// Stop first: the runtime's shutdown path releases the audio
|
|
1796
|
+
// channel through the still-registered service. Then cut the
|
|
1797
|
+
// engine's event path before the app is destroyed so a stray
|
|
1798
|
+
// asynchronous report cannot reach a dead runtime.
|
|
1799
|
+
native_sdk_app_stop(self.nativeApp);
|
|
1800
|
+
self.audioEngine.nativeApp = NULL;
|
|
1801
|
+
native_sdk_app_destroy(self.nativeApp);
|
|
1802
|
+
}
|
|
1803
|
+
[self.audioEngine invalidate];
|
|
1804
|
+
free(self.rgbaBytes);
|
|
1805
|
+
}
|
|
1806
|
+
|
|
1807
|
+
- (void)viewDidLayoutSubviews {
|
|
1808
|
+
[super viewDidLayoutSubviews];
|
|
1809
|
+
[self pushViewport];
|
|
1810
|
+
}
|
|
1811
|
+
|
|
1812
|
+
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
|
|
1813
|
+
[super traitCollectionDidChange:previousTraitCollection];
|
|
1814
|
+
// Size-class flips (rotation on the larger phones, iPad multitasking)
|
|
1815
|
+
// re-report the form factor; the layout pass that accompanies the
|
|
1816
|
+
// trait change pushes the viewport, which delivers the changed
|
|
1817
|
+
// chrome to the app.
|
|
1818
|
+
[self reportFormFactor];
|
|
1819
|
+
}
|
|
1820
|
+
|
|
1821
|
+
- (void)viewSafeAreaInsetsDidChange {
|
|
1822
|
+
[super viewSafeAreaInsetsDidChange];
|
|
1823
|
+
[self pushViewport];
|
|
1824
|
+
}
|
|
1825
|
+
|
|
1826
|
+
// Report the view's size in points + contentScale + safe-area insets to the
|
|
1827
|
+
// embed host (keyboard insets stay zero: IME is M3).
|
|
1828
|
+
//
|
|
1829
|
+
// The projected tab bar's overlap folds into the reported BOTTOM inset
|
|
1830
|
+
// here rather than through additionalSafeAreaInsets: the bar is a
|
|
1831
|
+
// subview of this same view, so growing the controller's safe area
|
|
1832
|
+
// would propagate back INTO the bar and squeeze its own item layout.
|
|
1833
|
+
// The viewport export is the honest seam — the app pads for the bar
|
|
1834
|
+
// through the identical chrome channel it pads for the home indicator,
|
|
1835
|
+
// and the bar keeps the system's own safe-area geometry.
|
|
1836
|
+
- (void)pushViewport {
|
|
1837
|
+
if (!self.nativeApp) return;
|
|
1838
|
+
CGSize size = self.view.bounds.size;
|
|
1839
|
+
if (size.width <= 0 || size.height <= 0) return;
|
|
1840
|
+
UIScreen *screen = self.view.window.screen ?: UIScreen.mainScreen;
|
|
1841
|
+
CGFloat scale = screen.scale > 0 ? screen.scale : 1;
|
|
1842
|
+
self.viewportScale = scale;
|
|
1843
|
+
[self metalLayer].contentsScale = scale;
|
|
1844
|
+
UIEdgeInsets safe = self.view.safeAreaInsets;
|
|
1845
|
+
if (self.chromeTabBar && !CGRectIsEmpty(self.chromeTabBar.frame)) {
|
|
1846
|
+
CGFloat bar_overlap = size.height - CGRectGetMinY(self.chromeTabBar.frame);
|
|
1847
|
+
safe.bottom = MAX(safe.bottom, bar_overlap);
|
|
1848
|
+
}
|
|
1849
|
+
native_sdk_app_viewport(self.nativeApp,
|
|
1850
|
+
(float)size.width, (float)size.height, (float)scale,
|
|
1851
|
+
(__bridge void *)[self metalLayer],
|
|
1852
|
+
(float)safe.top, (float)safe.right, (float)safe.bottom, (float)safe.left,
|
|
1853
|
+
0, 0, 0, 0);
|
|
1854
|
+
[self logNativeErrorIfAny:@"viewport"];
|
|
1855
|
+
self.needsPresent = YES;
|
|
1856
|
+
}
|
|
1857
|
+
|
|
1858
|
+
- (void)displayLinkTick:(CADisplayLink *)link {
|
|
1859
|
+
if (!self.nativeApp) return;
|
|
1860
|
+
if (NativeSdkGpuFrameTraceEnabled()) {
|
|
1861
|
+
self.traceTickCount += 1;
|
|
1862
|
+
[self emitFrameTraceSummaryIfDue];
|
|
1863
|
+
}
|
|
1864
|
+
|
|
1865
|
+
// Host-pumped frame: synthesizes the gpu_surface_frame event (first
|
|
1866
|
+
// tick installs the widget tree, later ticks re-present).
|
|
1867
|
+
native_sdk_app_frame(self.nativeApp);
|
|
1868
|
+
|
|
1869
|
+
// Keyboard show/hide follows the runtime's focus state each tick, not
|
|
1870
|
+
// only after shim-forwarded input: focus can also move from keyboard
|
|
1871
|
+
// handling (tab/escape) or model updates.
|
|
1872
|
+
[[self canvasView] syncTextInput];
|
|
1873
|
+
|
|
1874
|
+
// The projected tab bar mirrors the MODEL's selected tab each tick
|
|
1875
|
+
// (one integer readback): a Msg that moved the model moves the bar,
|
|
1876
|
+
// and a tap the app ignored snaps the bar back — model truth wins.
|
|
1877
|
+
[self syncDeclaredChromeSelection];
|
|
1878
|
+
|
|
1879
|
+
// Platform navigation mirrors the MODEL's navigation depth each tick
|
|
1880
|
+
// (one integer readback). Ordering is load-bearing: this runs BEFORE
|
|
1881
|
+
// renderAndPresent, while the retained staging buffer still holds
|
|
1882
|
+
// the pre-change frame — the snapshot a push transition slides out
|
|
1883
|
+
// from under the incoming live canvas.
|
|
1884
|
+
[self syncPlatformNavigation];
|
|
1885
|
+
|
|
1886
|
+
// The post-transition cover comes down a few ticks after the live
|
|
1887
|
+
// canvas swapped back in beneath it — enough vsyncs for the flush
|
|
1888
|
+
// present to composite, so the removal reveals identical pixels.
|
|
1889
|
+
if (self.navFreezeOverlay && !self.navTransitionActive) {
|
|
1890
|
+
if (self.navOverlayTicks > 0) {
|
|
1891
|
+
self.navOverlayTicks -= 1;
|
|
1892
|
+
} else {
|
|
1893
|
+
[self.navFreezeOverlay removeFromSuperview];
|
|
1894
|
+
self.navFreezeOverlay = nil;
|
|
1895
|
+
}
|
|
1896
|
+
}
|
|
1897
|
+
|
|
1898
|
+
// Only re-render + blit when the retained canvas actually changed.
|
|
1899
|
+
native_sdk_gpu_frame_state_t state = {0};
|
|
1900
|
+
BOOL haveState = native_sdk_app_gpu_frame_state(self.nativeApp, &state) == 1;
|
|
1901
|
+
if (!self.needsPresent && haveState && self.hasPresentedRevision &&
|
|
1902
|
+
state.canvas_revision == self.lastCanvasRevision) {
|
|
1903
|
+
if (NativeSdkGpuFrameTraceEnabled()) self.traceIdleTickCount += 1;
|
|
1904
|
+
return;
|
|
1905
|
+
}
|
|
1906
|
+
|
|
1907
|
+
if ([self renderAndPresent]) {
|
|
1908
|
+
// renderAndPresent recorded the revision the DELIVERED buffer
|
|
1909
|
+
// reflects (never this tick's sighting): a change whose frame
|
|
1910
|
+
// has not presented yet keeps the gate open, so the next tick
|
|
1911
|
+
// delivers its damage instead of stranding it off the glass.
|
|
1912
|
+
self.needsPresent = NO;
|
|
1913
|
+
}
|
|
1914
|
+
(void)haveState;
|
|
1915
|
+
}
|
|
1916
|
+
|
|
1917
|
+
/* Once-per-second cumulative counter line while the frame trace is on. */
|
|
1918
|
+
- (void)emitFrameTraceSummaryIfDue {
|
|
1919
|
+
const uint64_t now = NativeSdkTimestampNanoseconds();
|
|
1920
|
+
if (self.traceLastSummaryNs != 0 && now - self.traceLastSummaryNs < 1000000000ull) return;
|
|
1921
|
+
if (self.traceLastSummaryNs != 0) {
|
|
1922
|
+
fprintf(stderr,
|
|
1923
|
+
"native-sdk: gpu frame-trace summary ticks=%llu idle=%llu presents=%llu drawables=%llu nil=%llu upload_bytes=%llu present_cpu_us=%llu\n",
|
|
1924
|
+
(unsigned long long)self.traceTickCount,
|
|
1925
|
+
(unsigned long long)self.traceIdleTickCount,
|
|
1926
|
+
(unsigned long long)self.tracePresentCount,
|
|
1927
|
+
(unsigned long long)self.traceDrawableCount,
|
|
1928
|
+
(unsigned long long)self.traceNilDrawableCount,
|
|
1929
|
+
(unsigned long long)self.traceUploadBytes,
|
|
1930
|
+
(unsigned long long)(self.tracePresentCpuNs / 1000));
|
|
1931
|
+
}
|
|
1932
|
+
self.traceLastSummaryNs = now;
|
|
1933
|
+
}
|
|
1934
|
+
|
|
1935
|
+
- (BOOL)ensureStagingCapacity:(size_t)byteLength {
|
|
1936
|
+
if (self.stagingCapacity >= byteLength && self.rgbaBytes) return YES;
|
|
1937
|
+
free(self.rgbaBytes);
|
|
1938
|
+
self.rgbaBytes = malloc(byteLength);
|
|
1939
|
+
self.stagingCapacity = self.rgbaBytes ? byteLength : 0;
|
|
1940
|
+
return self.stagingCapacity != 0;
|
|
1941
|
+
}
|
|
1942
|
+
|
|
1943
|
+
// The canvas presenter, mirrored from appkit_host.m's
|
|
1944
|
+
// ensureCanvasPresenter: a four-vertex fullscreen quad whose fragment
|
|
1945
|
+
// stage samples the canvas texture with nearest filtering (the canvas is
|
|
1946
|
+
// already rasterized at device scale — presentation must not resample
|
|
1947
|
+
// it). Sampling is what makes the pixel formats independent: the shader
|
|
1948
|
+
// reads RGBA semantics from the RGBA8 canvas texture and the pass writes
|
|
1949
|
+
// them into the BGRA8 drawable, so the RGBA -> BGRA conversion the old
|
|
1950
|
+
// blit path paid for with a CPU swizzle over every frame's bytes now
|
|
1951
|
+
// happens inside the render pass for free.
|
|
1952
|
+
- (BOOL)ensureCanvasPresenter {
|
|
1953
|
+
if (self.canvasRenderPipeline && self.canvasSampler) return YES;
|
|
1954
|
+
if (!self.device) return NO;
|
|
1955
|
+
|
|
1956
|
+
static NSString *shaderSource =
|
|
1957
|
+
@"#include <metal_stdlib>\n"
|
|
1958
|
+
@"using namespace metal;\n"
|
|
1959
|
+
@"struct NativeSdkCanvasVertexOut { float4 position [[position]]; float2 uv; };\n"
|
|
1960
|
+
@"vertex NativeSdkCanvasVertexOut native_sdk_canvas_vertex(uint vertex_id [[vertex_id]]) {\n"
|
|
1961
|
+
@" constexpr float2 positions[4] = { float2(-1.0, -1.0), float2(1.0, -1.0), float2(-1.0, 1.0), float2(1.0, 1.0) };\n"
|
|
1962
|
+
@" constexpr float2 uvs[4] = { float2(0.0, 1.0), float2(1.0, 1.0), float2(0.0, 0.0), float2(1.0, 0.0) };\n"
|
|
1963
|
+
@" NativeSdkCanvasVertexOut out;\n"
|
|
1964
|
+
@" out.position = float4(positions[vertex_id], 0.0, 1.0);\n"
|
|
1965
|
+
@" out.uv = uvs[vertex_id];\n"
|
|
1966
|
+
@" return out;\n"
|
|
1967
|
+
@"}\n"
|
|
1968
|
+
@"fragment float4 native_sdk_canvas_fragment(NativeSdkCanvasVertexOut in [[stage_in]], texture2d<float> canvas_texture [[texture(0)]], sampler texture_sampler [[sampler(0)]]) {\n"
|
|
1969
|
+
@" return canvas_texture.sample(texture_sampler, in.uv);\n"
|
|
1970
|
+
@"}\n";
|
|
1971
|
+
|
|
1972
|
+
NSError *libraryError = nil;
|
|
1973
|
+
id<MTLLibrary> library = [self.device newLibraryWithSource:shaderSource options:nil error:&libraryError];
|
|
1974
|
+
if (!library) return NO;
|
|
1975
|
+
id<MTLFunction> vertexFunction = [library newFunctionWithName:@"native_sdk_canvas_vertex"];
|
|
1976
|
+
id<MTLFunction> fragmentFunction = [library newFunctionWithName:@"native_sdk_canvas_fragment"];
|
|
1977
|
+
if (!vertexFunction || !fragmentFunction) return NO;
|
|
1978
|
+
|
|
1979
|
+
MTLRenderPipelineDescriptor *pipelineDescriptor = [[MTLRenderPipelineDescriptor alloc] init];
|
|
1980
|
+
pipelineDescriptor.label = @"native-sdk canvas presenter";
|
|
1981
|
+
pipelineDescriptor.vertexFunction = vertexFunction;
|
|
1982
|
+
pipelineDescriptor.fragmentFunction = fragmentFunction;
|
|
1983
|
+
pipelineDescriptor.colorAttachments[0].pixelFormat = [self metalLayer].pixelFormat;
|
|
1984
|
+
|
|
1985
|
+
NSError *pipelineError = nil;
|
|
1986
|
+
id<MTLRenderPipelineState> pipeline = [self.device newRenderPipelineStateWithDescriptor:pipelineDescriptor error:&pipelineError];
|
|
1987
|
+
if (!pipeline) return NO;
|
|
1988
|
+
|
|
1989
|
+
MTLSamplerDescriptor *samplerDescriptor = [[MTLSamplerDescriptor alloc] init];
|
|
1990
|
+
samplerDescriptor.minFilter = MTLSamplerMinMagFilterNearest;
|
|
1991
|
+
samplerDescriptor.magFilter = MTLSamplerMinMagFilterNearest;
|
|
1992
|
+
samplerDescriptor.mipFilter = MTLSamplerMipFilterNotMipmapped;
|
|
1993
|
+
samplerDescriptor.sAddressMode = MTLSamplerAddressModeClampToEdge;
|
|
1994
|
+
samplerDescriptor.tAddressMode = MTLSamplerAddressModeClampToEdge;
|
|
1995
|
+
id<MTLSamplerState> sampler = [self.device newSamplerStateWithDescriptor:samplerDescriptor];
|
|
1996
|
+
if (!sampler) return NO;
|
|
1997
|
+
|
|
1998
|
+
self.canvasRenderPipeline = pipeline;
|
|
1999
|
+
self.canvasSampler = sampler;
|
|
2000
|
+
return YES;
|
|
2001
|
+
}
|
|
2002
|
+
|
|
2003
|
+
- (BOOL)renderAndPresent {
|
|
2004
|
+
const BOOL trace = NativeSdkGpuFrameTraceEnabled();
|
|
2005
|
+
const uint64_t presentBeginNs = trace ? NativeSdkTimestampNanoseconds() : 0;
|
|
2006
|
+
float scale = (float)self.viewportScale;
|
|
2007
|
+
|
|
2008
|
+
native_sdk_canvas_pixels_t info = {0};
|
|
2009
|
+
if (native_sdk_app_render_pixel_size(self.nativeApp, scale, &info) != 1) return NO;
|
|
2010
|
+
if (info.width == 0 || info.height == 0 || info.byte_len != info.width * info.height * 4) return NO;
|
|
2011
|
+
if (![self ensureStagingCapacity:info.byte_len]) return NO;
|
|
2012
|
+
if (![self ensureCanvasPresenter]) return NO;
|
|
2013
|
+
|
|
2014
|
+
// Damage render: the staging buffer is RETAINED across frames, so the
|
|
2015
|
+
// embed side copies only the region the frames since the last call
|
|
2016
|
+
// changed (captured off the runtime's own dirty-scissored raster —
|
|
2017
|
+
// no full-surface re-render) and names it. A keystroke costs the
|
|
2018
|
+
// field's pixels here, not 12+MB of surface.
|
|
2019
|
+
native_sdk_canvas_pixels_damage_t rendered = {0};
|
|
2020
|
+
if (native_sdk_app_render_pixels_damage(self.nativeApp, scale, self.rgbaBytes, info.byte_len, &rendered) != 1) {
|
|
2021
|
+
[self logNativeErrorIfAny:@"render_pixels_damage"];
|
|
2022
|
+
return NO;
|
|
2023
|
+
}
|
|
2024
|
+
const uint64_t renderEndNs = trace ? NativeSdkTimestampNanoseconds() : 0;
|
|
2025
|
+
// The delivery names the revision the buffer now reflects; the idle
|
|
2026
|
+
// gate compares the live revision against THIS, so a present the
|
|
2027
|
+
// runtime produces one pump after its change still gets delivered.
|
|
2028
|
+
self.lastCanvasRevision = rendered.revision;
|
|
2029
|
+
self.hasPresentedRevision = YES;
|
|
2030
|
+
NSUInteger width = rendered.width;
|
|
2031
|
+
NSUInteger height = rendered.height;
|
|
2032
|
+
if (width == 0 || height == 0 || rendered.byte_len != width * height * 4) {
|
|
2033
|
+
// The damage delivery above already consumed the accumulated
|
|
2034
|
+
// region: dropping the texture forces the next present to a
|
|
2035
|
+
// full upload, so a refused frame can never strand it.
|
|
2036
|
+
self.canvasTexture = nil;
|
|
2037
|
+
return NO;
|
|
2038
|
+
}
|
|
2039
|
+
|
|
2040
|
+
// The canvas texture carries the renderer's bytes verbatim: RGBA8,
|
|
2041
|
+
// uploaded straight from the staging buffer (the presenter's render
|
|
2042
|
+
// pass converts to the drawable's BGRA — see ensureCanvasPresenter).
|
|
2043
|
+
BOOL textureCreated = NO;
|
|
2044
|
+
if (!self.canvasTexture || self.canvasTexture.width != width || self.canvasTexture.height != height) {
|
|
2045
|
+
MTLTextureDescriptor *descriptor =
|
|
2046
|
+
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
|
|
2047
|
+
width:width
|
|
2048
|
+
height:height
|
|
2049
|
+
mipmapped:NO];
|
|
2050
|
+
descriptor.usage = MTLTextureUsageShaderRead;
|
|
2051
|
+
descriptor.storageMode = MTLStorageModeShared;
|
|
2052
|
+
self.canvasTexture = [self.device newTextureWithDescriptor:descriptor];
|
|
2053
|
+
textureCreated = YES;
|
|
2054
|
+
}
|
|
2055
|
+
if (!self.canvasTexture) return NO;
|
|
2056
|
+
|
|
2057
|
+
// Upload only the damaged region (`replaceRegion` with the damage
|
|
2058
|
+
// rect; `bytesPerRow` stays the full staging stride so the pointer
|
|
2059
|
+
// offset addresses the rect in place). A fresh texture holds no
|
|
2060
|
+
// pixels yet, so it takes the full surface regardless of the report.
|
|
2061
|
+
NSUInteger damageX = rendered.damage_x;
|
|
2062
|
+
NSUInteger damageY = rendered.damage_y;
|
|
2063
|
+
NSUInteger damageWidth = rendered.damage_width;
|
|
2064
|
+
NSUInteger damageHeight = rendered.damage_height;
|
|
2065
|
+
if (textureCreated) {
|
|
2066
|
+
damageX = 0;
|
|
2067
|
+
damageY = 0;
|
|
2068
|
+
damageWidth = width;
|
|
2069
|
+
damageHeight = height;
|
|
2070
|
+
}
|
|
2071
|
+
if (damageX + damageWidth > width || damageY + damageHeight > height) {
|
|
2072
|
+
self.canvasTexture = nil;
|
|
2073
|
+
return NO;
|
|
2074
|
+
}
|
|
2075
|
+
const BOOL hasDamage = damageWidth > 0 && damageHeight > 0;
|
|
2076
|
+
self.lastDeliveryHadDamage = hasDamage;
|
|
2077
|
+
const uint64_t uploadBeginNs = trace ? NativeSdkTimestampNanoseconds() : 0;
|
|
2078
|
+
if (hasDamage) {
|
|
2079
|
+
[self.canvasTexture replaceRegion:MTLRegionMake2D(damageX, damageY, damageWidth, damageHeight)
|
|
2080
|
+
mipmapLevel:0
|
|
2081
|
+
withBytes:self.rgbaBytes + (damageY * width + damageX) * 4
|
|
2082
|
+
bytesPerRow:width * 4];
|
|
2083
|
+
}
|
|
2084
|
+
const uint64_t uploadEndNs = trace ? NativeSdkTimestampNanoseconds() : 0;
|
|
2085
|
+
const uint64_t uploadBytes = (uint64_t)damageWidth * (uint64_t)damageHeight * 4;
|
|
2086
|
+
if (trace) self.traceUploadBytes += uploadBytes;
|
|
2087
|
+
|
|
2088
|
+
CAMetalLayer *layer = [self metalLayer];
|
|
2089
|
+
CGSize drawableSize = CGSizeMake(width, height);
|
|
2090
|
+
const BOOL drawableSizeChanged = !CGSizeEqualToSize(self.appliedDrawableSize, drawableSize);
|
|
2091
|
+
if (drawableSizeChanged) {
|
|
2092
|
+
layer.drawableSize = drawableSize;
|
|
2093
|
+
self.appliedDrawableSize = drawableSize;
|
|
2094
|
+
}
|
|
2095
|
+
|
|
2096
|
+
// No damage and nothing forcing a flush (no viewport/lifecycle
|
|
2097
|
+
// re-present pending, texture and drawable both current): the glass
|
|
2098
|
+
// already shows this frame — vend no drawable, encode nothing. A
|
|
2099
|
+
// revision bump with no visual change costs a copy of zero bytes.
|
|
2100
|
+
if (!hasDamage && !textureCreated && !drawableSizeChanged && !self.needsPresent && self.hasPresentedRevision) {
|
|
2101
|
+
// Not counted as a present: no drawable moved. The structural
|
|
2102
|
+
// counters keep presents == drawables.
|
|
2103
|
+
if (trace) {
|
|
2104
|
+
fprintf(stderr, "native-sdk: gpu frame-trace path=no-damage render_us=%llu\n",
|
|
2105
|
+
(unsigned long long)((renderEndNs - presentBeginNs) / 1000));
|
|
2106
|
+
}
|
|
2107
|
+
return YES;
|
|
2108
|
+
}
|
|
2109
|
+
|
|
2110
|
+
// Drawable acquisition discipline: a CAMetalLayer vends a small fixed
|
|
2111
|
+
// pool of drawables, and nextDrawable is the one call in this path
|
|
2112
|
+
// that can BLOCK the main thread — the pool hands one back on the
|
|
2113
|
+
// compositor's schedule, not ours. So the host acquires a drawable
|
|
2114
|
+
// (a) only on frames that will really present (the canvas-revision
|
|
2115
|
+
// gate in displayLinkTick already decided that) and (b) only after
|
|
2116
|
+
// every CPU cost of the frame — the reference render and the texture
|
|
2117
|
+
// upload — has been paid, so the block is the residual wait for the
|
|
2118
|
+
// glass, never a hold across our own work. Acquiring early or on
|
|
2119
|
+
// every tick is the classic stall-and-power sink: an idle app would
|
|
2120
|
+
// pin a drawable per vsync and the throttled pool would pace the
|
|
2121
|
+
// whole run loop.
|
|
2122
|
+
const uint64_t vendBeginNs = trace ? NativeSdkTimestampNanoseconds() : 0;
|
|
2123
|
+
id<CAMetalDrawable> drawable = [layer nextDrawable];
|
|
2124
|
+
const uint64_t vendEndNs = trace ? NativeSdkTimestampNanoseconds() : 0;
|
|
2125
|
+
if (trace) {
|
|
2126
|
+
if (drawable) self.traceDrawableCount += 1;
|
|
2127
|
+
else self.traceNilDrawableCount += 1;
|
|
2128
|
+
}
|
|
2129
|
+
if (!drawable) {
|
|
2130
|
+
// A declined drawable (mid-resize flux, transient pool pressure):
|
|
2131
|
+
// needsPresent stays armed upstream, so the next tick retries —
|
|
2132
|
+
// the retained canvas texture already holds the frame.
|
|
2133
|
+
if (trace) {
|
|
2134
|
+
self.tracePresentCpuNs += NativeSdkTimestampNanoseconds() - renderEndNs;
|
|
2135
|
+
fprintf(stderr, "native-sdk: gpu frame-trace path=nil-drawable vend_us=%llu\n",
|
|
2136
|
+
(unsigned long long)((vendEndNs - vendBeginNs) / 1000));
|
|
2137
|
+
}
|
|
2138
|
+
return NO;
|
|
2139
|
+
}
|
|
2140
|
+
if (drawable.texture.width != width || drawable.texture.height != height) return NO;
|
|
2141
|
+
|
|
2142
|
+
MTLRenderPassDescriptor *descriptor = [MTLRenderPassDescriptor renderPassDescriptor];
|
|
2143
|
+
descriptor.colorAttachments[0].texture = drawable.texture;
|
|
2144
|
+
// The quad covers every drawable pixel, so the pass needs no load; a
|
|
2145
|
+
// clear is the cheapest correct load action on a tiled GPU.
|
|
2146
|
+
descriptor.colorAttachments[0].loadAction = MTLLoadActionClear;
|
|
2147
|
+
descriptor.colorAttachments[0].storeAction = MTLStoreActionStore;
|
|
2148
|
+
descriptor.colorAttachments[0].clearColor = MTLClearColorMake(0, 0, 0, 1);
|
|
2149
|
+
|
|
2150
|
+
id<MTLCommandBuffer> commandBuffer = [self.commandQueue commandBuffer];
|
|
2151
|
+
if (!commandBuffer) return NO;
|
|
2152
|
+
id<MTLRenderCommandEncoder> encoder = [commandBuffer renderCommandEncoderWithDescriptor:descriptor];
|
|
2153
|
+
[encoder setRenderPipelineState:self.canvasRenderPipeline];
|
|
2154
|
+
[encoder setFragmentTexture:self.canvasTexture atIndex:0];
|
|
2155
|
+
[encoder setFragmentSamplerState:self.canvasSampler atIndex:0];
|
|
2156
|
+
[encoder drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4];
|
|
2157
|
+
[encoder endEncoding];
|
|
2158
|
+
[commandBuffer presentDrawable:drawable];
|
|
2159
|
+
[commandBuffer commit];
|
|
2160
|
+
if (trace) {
|
|
2161
|
+
const uint64_t presentEndNs = NativeSdkTimestampNanoseconds();
|
|
2162
|
+
self.tracePresentCount += 1;
|
|
2163
|
+
/* Present-path CPU excludes the reference render: upload +
|
|
2164
|
+
* drawable vend + encode/commit. The render is the renderer's
|
|
2165
|
+
* cost, not the presentation seam's. */
|
|
2166
|
+
self.tracePresentCpuNs += presentEndNs - renderEndNs;
|
|
2167
|
+
fprintf(stderr, "native-sdk: gpu frame-trace path=present frame=%llu render_us=%llu upload_us=%llu vend_us=%llu upload_bytes=%llu damage=%llux%llu+%llu+%llu total_us=%llu\n",
|
|
2168
|
+
(unsigned long long)self.tracePresentCount,
|
|
2169
|
+
(unsigned long long)((renderEndNs - presentBeginNs) / 1000),
|
|
2170
|
+
(unsigned long long)((uploadEndNs - uploadBeginNs) / 1000),
|
|
2171
|
+
(unsigned long long)((vendEndNs - vendBeginNs) / 1000),
|
|
2172
|
+
(unsigned long long)uploadBytes,
|
|
2173
|
+
(unsigned long long)damageWidth,
|
|
2174
|
+
(unsigned long long)damageHeight,
|
|
2175
|
+
(unsigned long long)damageX,
|
|
2176
|
+
(unsigned long long)damageY,
|
|
2177
|
+
(unsigned long long)((presentEndNs - presentBeginNs) / 1000));
|
|
2178
|
+
}
|
|
2179
|
+
return YES;
|
|
2180
|
+
}
|
|
2181
|
+
|
|
2182
|
+
// ---------------------------------------------------- declared platform chrome
|
|
2183
|
+
//
|
|
2184
|
+
// The projection of ShellConfig.chrome onto REAL system controls. The
|
|
2185
|
+
// honest minimal integration with the single canvas surface: the canvas
|
|
2186
|
+
// view stays the root and full-bleed; a plain UITabBar (not a
|
|
2187
|
+
// UITabBarController — there is exactly one content view controller, so
|
|
2188
|
+
// a container would be a fiction) is pinned to the bottom edge as a
|
|
2189
|
+
// sibling overlay, and its overlap is folded into
|
|
2190
|
+
// additionalSafeAreaInsets so the app pads for it through the same
|
|
2191
|
+
// chrome channel it pads for the home indicator. Icons are the app's
|
|
2192
|
+
// own declared vocabulary glyphs, rasterized by the embed library
|
|
2193
|
+
// through the canvas vector core into template images the system tints
|
|
2194
|
+
// — the artwork is the app's, the bar's styling (background material,
|
|
2195
|
+
// selection tint, accessibility) is whatever the OS ships.
|
|
2196
|
+
|
|
2197
|
+
/* A declared icon name -> template UIImage at the tab-bar glyph size,
|
|
2198
|
+
* rasterized at the screen scale so the bar draws it crisp. Nil when the
|
|
2199
|
+
* item declares no icon (a text-only tab stays honest). */
|
|
2200
|
+
- (UIImage *)chromeIconNamed:(const char *)name length:(uintptr_t)length {
|
|
2201
|
+
if (!self.nativeApp || !name || length == 0) return nil;
|
|
2202
|
+
const CGFloat points = 24;
|
|
2203
|
+
CGFloat scale = UIScreen.mainScreen.scale > 0 ? UIScreen.mainScreen.scale : 1;
|
|
2204
|
+
const uintptr_t pixels_per_side = (uintptr_t)llround(points * scale);
|
|
2205
|
+
const uintptr_t byte_len = pixels_per_side * pixels_per_side * 4;
|
|
2206
|
+
uint8_t *bytes = malloc(byte_len);
|
|
2207
|
+
if (!bytes) return nil;
|
|
2208
|
+
if (native_sdk_app_chrome_icon_pixels(self.nativeApp, name, length, pixels_per_side, bytes, byte_len) != 1) {
|
|
2209
|
+
[self logNativeErrorIfAny:@"chrome_icon"];
|
|
2210
|
+
free(bytes);
|
|
2211
|
+
return nil;
|
|
2212
|
+
}
|
|
2213
|
+
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
|
|
2214
|
+
CGContextRef context = CGBitmapContextCreate(bytes, pixels_per_side, pixels_per_side, 8, pixels_per_side * 4, space,
|
|
2215
|
+
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
|
|
2216
|
+
CGImageRef cg_image = context ? CGBitmapContextCreateImage(context) : NULL;
|
|
2217
|
+
UIImage *image = nil;
|
|
2218
|
+
if (cg_image) {
|
|
2219
|
+
UIImage *raw = [UIImage imageWithCGImage:cg_image scale:scale orientation:UIImageOrientationUp];
|
|
2220
|
+
/* Template mode: the system control owns the tint, exactly like
|
|
2221
|
+
* an asset-catalog template icon. */
|
|
2222
|
+
image = [raw imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
|
|
2223
|
+
CGImageRelease(cg_image);
|
|
2224
|
+
}
|
|
2225
|
+
if (context) CGContextRelease(context);
|
|
2226
|
+
CGColorSpaceRelease(space);
|
|
2227
|
+
free(bytes);
|
|
2228
|
+
return image;
|
|
2229
|
+
}
|
|
2230
|
+
|
|
2231
|
+
- (void)installDeclaredChrome {
|
|
2232
|
+
if (!self.nativeApp) return;
|
|
2233
|
+
const uintptr_t tab_count = native_sdk_app_chrome_tab_count(self.nativeApp);
|
|
2234
|
+
if (tab_count > 0) {
|
|
2235
|
+
UITabBar *bar = [[UITabBar alloc] init];
|
|
2236
|
+
bar.translatesAutoresizingMaskIntoConstraints = NO;
|
|
2237
|
+
bar.delegate = self;
|
|
2238
|
+
NSMutableArray<UITabBarItem *> *items = [NSMutableArray arrayWithCapacity:tab_count];
|
|
2239
|
+
NSMutableArray<NSString *> *commands = [NSMutableArray arrayWithCapacity:tab_count];
|
|
2240
|
+
for (uintptr_t index = 0; index < tab_count; index++) {
|
|
2241
|
+
native_sdk_chrome_item_t item = {0};
|
|
2242
|
+
if (native_sdk_app_chrome_tab_at(self.nativeApp, index, &item) != 1) continue;
|
|
2243
|
+
NSString *identifier = item.id ? [[NSString alloc] initWithBytes:item.id length:item.id_len encoding:NSUTF8StringEncoding] : nil;
|
|
2244
|
+
NSString *label = item.label ? [[NSString alloc] initWithBytes:item.label length:item.label_len encoding:NSUTF8StringEncoding] : nil;
|
|
2245
|
+
if (!identifier || !label) continue;
|
|
2246
|
+
UIImage *icon = [self chromeIconNamed:item.icon length:item.icon_len];
|
|
2247
|
+
UITabBarItem *bar_item = [[UITabBarItem alloc] initWithTitle:label image:icon tag:(NSInteger)commands.count];
|
|
2248
|
+
[items addObject:bar_item];
|
|
2249
|
+
[commands addObject:identifier];
|
|
2250
|
+
}
|
|
2251
|
+
if (items.count > 0) {
|
|
2252
|
+
bar.items = items;
|
|
2253
|
+
[self.view addSubview:bar];
|
|
2254
|
+
/* The bar spans the bottom edge INCLUDING the home-indicator
|
|
2255
|
+
* band (its background material fills to the glass edge,
|
|
2256
|
+
* like every system bar), with its top held the standard
|
|
2257
|
+
* item-band height above the system safe area so the items
|
|
2258
|
+
* keep their full band above the indicator. */
|
|
2259
|
+
[NSLayoutConstraint activateConstraints:@[
|
|
2260
|
+
[bar.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
|
|
2261
|
+
[bar.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
|
|
2262
|
+
[bar.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
|
|
2263
|
+
[bar.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor constant:-49],
|
|
2264
|
+
]];
|
|
2265
|
+
self.chromeTabBar = bar;
|
|
2266
|
+
self.chromeTabCommands = commands;
|
|
2267
|
+
/* The chrome channel now says a native bar owns the tab
|
|
2268
|
+
* affordance, so a canvas tab switcher can yield to it. */
|
|
2269
|
+
native_sdk_app_set_chrome_tabs_projected(self.nativeApp, 1);
|
|
2270
|
+
NSLog(@"native-sdk: declared chrome projected tabs=%lu", (unsigned long)items.count);
|
|
2271
|
+
[self syncDeclaredChromeSelection];
|
|
2272
|
+
}
|
|
2273
|
+
}
|
|
2274
|
+
|
|
2275
|
+
native_sdk_chrome_item_t action = {0};
|
|
2276
|
+
if (native_sdk_app_chrome_primary_action(self.nativeApp, &action) == 1) {
|
|
2277
|
+
NSString *identifier = action.id ? [[NSString alloc] initWithBytes:action.id length:action.id_len encoding:NSUTF8StringEncoding] : nil;
|
|
2278
|
+
NSString *label = action.label ? [[NSString alloc] initWithBytes:action.label length:action.label_len encoding:NSUTF8StringEncoding] : nil;
|
|
2279
|
+
if (identifier && label) {
|
|
2280
|
+
/* The one primary floating action: a real system button
|
|
2281
|
+
* (filled circular configuration), floating above the
|
|
2282
|
+
* content's bottom-trailing corner, clear of the bar. */
|
|
2283
|
+
UIButtonConfiguration *configuration = [UIButtonConfiguration filledButtonConfiguration];
|
|
2284
|
+
configuration.cornerStyle = UIButtonConfigurationCornerStyleCapsule;
|
|
2285
|
+
UIImage *icon = [self chromeIconNamed:action.icon length:action.icon_len];
|
|
2286
|
+
if (icon) configuration.image = icon;
|
|
2287
|
+
UIButton *button = [UIButton buttonWithConfiguration:configuration primaryAction:nil];
|
|
2288
|
+
if (!icon) [button setTitle:label forState:UIControlStateNormal];
|
|
2289
|
+
button.translatesAutoresizingMaskIntoConstraints = NO;
|
|
2290
|
+
button.accessibilityLabel = label;
|
|
2291
|
+
[button addTarget:self action:@selector(chromeActionPressed:) forControlEvents:UIControlEventTouchUpInside];
|
|
2292
|
+
[self.view addSubview:button];
|
|
2293
|
+
NSLayoutYAxisAnchor *above = self.chromeTabBar ? self.chromeTabBar.topAnchor
|
|
2294
|
+
: self.view.safeAreaLayoutGuide.bottomAnchor;
|
|
2295
|
+
[NSLayoutConstraint activateConstraints:@[
|
|
2296
|
+
[button.trailingAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.trailingAnchor constant:-16],
|
|
2297
|
+
[button.bottomAnchor constraintEqualToAnchor:above constant:-16],
|
|
2298
|
+
[button.widthAnchor constraintEqualToConstant:56],
|
|
2299
|
+
[button.heightAnchor constraintEqualToConstant:56],
|
|
2300
|
+
]];
|
|
2301
|
+
self.chromeActionButton = button;
|
|
2302
|
+
self.chromeActionCommand = identifier;
|
|
2303
|
+
NSLog(@"native-sdk: declared chrome projected primary action %@", identifier);
|
|
2304
|
+
}
|
|
2305
|
+
}
|
|
2306
|
+
}
|
|
2307
|
+
|
|
2308
|
+
/* Model -> bar, once per display tick: one integer readback of the
|
|
2309
|
+
* model's selected tab (via the app's selected_tab_fn derivation). The
|
|
2310
|
+
* bar only ever moves here, so a model change lands visually within a
|
|
2311
|
+
* tick and a tap the app ignored snaps back — deterministic both ways. */
|
|
2312
|
+
- (void)syncDeclaredChromeSelection {
|
|
2313
|
+
if (!self.nativeApp || !self.chromeTabBar) return;
|
|
2314
|
+
intptr_t selected = native_sdk_app_chrome_selected_tab(self.nativeApp);
|
|
2315
|
+
if ((NSInteger)selected == self.chromeSelectedIndex) return;
|
|
2316
|
+
self.chromeSelectedIndex = (NSInteger)selected;
|
|
2317
|
+
if (selected >= 0 && (NSUInteger)selected < self.chromeTabBar.items.count) {
|
|
2318
|
+
self.chromeTabBar.selectedItem = self.chromeTabBar.items[(NSUInteger)selected];
|
|
2319
|
+
} else {
|
|
2320
|
+
self.chromeTabBar.selectedItem = nil;
|
|
2321
|
+
}
|
|
2322
|
+
NSLog(@"native-sdk: chrome selected tab -> %ld", (long)selected);
|
|
2323
|
+
}
|
|
2324
|
+
|
|
2325
|
+
/* Bar -> model: a tap dispatches the tab's declared command id through
|
|
2326
|
+
* the embed command path (the same path native header buttons use); the
|
|
2327
|
+
* app's on_command maps it to a Msg and update moves the model. The
|
|
2328
|
+
* command dispatch is synchronous, so the model's answer is read back
|
|
2329
|
+
* immediately and the bar lands on whatever the model decided. */
|
|
2330
|
+
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
|
|
2331
|
+
if (!self.nativeApp) return;
|
|
2332
|
+
NSUInteger index = (NSUInteger)item.tag;
|
|
2333
|
+
if (index >= self.chromeTabCommands.count) return;
|
|
2334
|
+
NSString *command = self.chromeTabCommands[index];
|
|
2335
|
+
NSLog(@"native-sdk: chrome tab tap -> command %@", command);
|
|
2336
|
+
native_sdk_app_command(self.nativeApp, command.UTF8String, [command lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
|
|
2337
|
+
[self logNativeErrorIfAny:@"chrome_tab"];
|
|
2338
|
+
/* Re-assert model truth now (not next tick): force the compare to
|
|
2339
|
+
* re-read even when the model kept the same tab. */
|
|
2340
|
+
self.chromeSelectedIndex = -2;
|
|
2341
|
+
[self syncDeclaredChromeSelection];
|
|
2342
|
+
}
|
|
2343
|
+
|
|
2344
|
+
- (void)chromeActionPressed:(UIButton *)sender {
|
|
2345
|
+
(void)sender;
|
|
2346
|
+
if (!self.nativeApp || self.chromeActionCommand.length == 0) return;
|
|
2347
|
+
NSString *command = self.chromeActionCommand;
|
|
2348
|
+
NSLog(@"native-sdk: chrome primary action -> command %@", command);
|
|
2349
|
+
native_sdk_app_command(self.nativeApp, command.UTF8String, [command lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
|
|
2350
|
+
[self logNativeErrorIfAny:@"chrome_action"];
|
|
2351
|
+
}
|
|
2352
|
+
|
|
2353
|
+
// ------------------------------------------------------ platform navigation
|
|
2354
|
+
//
|
|
2355
|
+
// The projection of the app's navigation depth onto REAL UIKit push/pop
|
|
2356
|
+
// machinery. The contract, in the declared-chrome shape:
|
|
2357
|
+
//
|
|
2358
|
+
// - The MODEL owns navigation state. The app derives a depth from it
|
|
2359
|
+
// (`navigation_depth_fn`) and the host polls one integer per tick.
|
|
2360
|
+
// Depth grew by one = present the system push transition; shrank by
|
|
2361
|
+
// one = present the system pop; anything else — the first sighting, a
|
|
2362
|
+
// multi-level jump, or a depth change arriving WITH a selected-tab
|
|
2363
|
+
// change (tabs are lateral, never depth) — reconciles the stack with
|
|
2364
|
+
// no transition at all.
|
|
2365
|
+
// - The host has ONE live canvas. At rest it rides the TOP page of a
|
|
2366
|
+
// real UINavigationController (bar hidden; pages are plain
|
|
2367
|
+
// containers), and the pages underneath hold retained snapshots: on a
|
|
2368
|
+
// push, the pre-change frame still sitting in the retained staging
|
|
2369
|
+
// buffer (the damage path keeps it current) becomes the outgoing
|
|
2370
|
+
// page's snapshot, captured with zero extra renders. One snapshot per
|
|
2371
|
+
// depth level, bounded (NativeSdkNavSnapshotCap); a level without one
|
|
2372
|
+
// shows the background wash. DURING a host-driven transition both
|
|
2373
|
+
// sides are exact CPU bitmaps of the two model states (the incoming
|
|
2374
|
+
// one pre-rendered through the ordinary damage delivery, so its
|
|
2375
|
+
// pixels are the canvas's own): a Metal drawable present composites
|
|
2376
|
+
// on the render server's schedule, not the animation's, so animating
|
|
2377
|
+
// the live layer would play the transition against the previous frame
|
|
2378
|
+
// and snap at the end — bitmaps make the transition pixel-correct for
|
|
2379
|
+
// its whole run, and the live canvas swaps back onto the top page at
|
|
2380
|
+
// completion under a brief cover of the same pixels
|
|
2381
|
+
// (restoreLiveCanvasAfterTransition). Honesty judgment: a below-page
|
|
2382
|
+
// snapshot can be STALE (the shallow page may have changed since its
|
|
2383
|
+
// push) — it is only ever visible DURING the interactive gesture, and
|
|
2384
|
+
// the fresh render replaces it the moment the gesture completes.
|
|
2385
|
+
// - The interactive edge-swipe-back is the REAL recognizer
|
|
2386
|
+
// (interactivePopGestureRecognizer) with the system's physics, armed
|
|
2387
|
+
// only while the projection says a page is open AND the app declared a
|
|
2388
|
+
// back command. Completion dispatches that command exactly once
|
|
2389
|
+
// through the embed command path (the same journal entry the app's
|
|
2390
|
+
// own back button produces); cancellation dispatches nothing and the
|
|
2391
|
+
// model is untouched. If the app IGNORES the dispatched command, the
|
|
2392
|
+
// next tick's poll sees the un-popped depth and pushes the page back —
|
|
2393
|
+
// the navigation mirror of the tab bar snapping back, model truth
|
|
2394
|
+
// wins.
|
|
2395
|
+
// - The tab bar and primary action live on the root view, OUTSIDE the
|
|
2396
|
+
// stack, so they hold still through push/pop like the system's own
|
|
2397
|
+
// bars, and the safe-area/chrome insets are untouched (the canvas
|
|
2398
|
+
// fills the same bounds it always did).
|
|
2399
|
+
|
|
2400
|
+
/* Bounded snapshot retention: one full-resolution frame per depth level,
|
|
2401
|
+
* at most this many (a phone-scale frame is ~13MB, so the cap bounds the
|
|
2402
|
+
* cache near 50MB on pathologically deep stacks; real stacks hold one or
|
|
2403
|
+
* two). Levels past the cap keep NSNull and present the background wash
|
|
2404
|
+
* during a gesture — bounded memory beats a silent unbounded cache. */
|
|
2405
|
+
static const NSUInteger NativeSdkNavSnapshotCap = 4;
|
|
2406
|
+
|
|
2407
|
+
/* The retained staging buffer as a UIImage — the previously presented
|
|
2408
|
+
* frame, captured without rendering anything (the damage path keeps the
|
|
2409
|
+
* buffer current). Nil before the first render or across a size change
|
|
2410
|
+
* mid-flight; callers fall back to the background wash. */
|
|
2411
|
+
- (UIImage *)navSnapshotFromRetainedCanvas {
|
|
2412
|
+
if (!self.rgbaBytes || !self.canvasTexture) return nil;
|
|
2413
|
+
const size_t width = self.canvasTexture.width;
|
|
2414
|
+
const size_t height = self.canvasTexture.height;
|
|
2415
|
+
if (width == 0 || height == 0) return nil;
|
|
2416
|
+
const size_t byte_len = width * height * 4;
|
|
2417
|
+
if (self.stagingCapacity < byte_len) return nil;
|
|
2418
|
+
NSData *data = [NSData dataWithBytes:self.rgbaBytes length:byte_len];
|
|
2419
|
+
CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
|
|
2420
|
+
if (!provider) return nil;
|
|
2421
|
+
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
|
|
2422
|
+
/* The canvas renders an opaque surface, so alpha is skipped rather
|
|
2423
|
+
* than interpreted — no premultiply question exists. */
|
|
2424
|
+
CGImageRef image = space ? CGImageCreate(width, height, 8, 32, width * 4, space,
|
|
2425
|
+
kCGBitmapByteOrder32Big | kCGImageAlphaNoneSkipLast,
|
|
2426
|
+
provider, NULL, false, kCGRenderingIntentDefault)
|
|
2427
|
+
: NULL;
|
|
2428
|
+
if (space) CGColorSpaceRelease(space);
|
|
2429
|
+
CGDataProviderRelease(provider);
|
|
2430
|
+
if (!image) return nil;
|
|
2431
|
+
CGFloat scale = self.viewportScale > 0 ? self.viewportScale : 1;
|
|
2432
|
+
UIImage *snapshot = [UIImage imageWithCGImage:image scale:scale orientation:UIImageOrientationUp];
|
|
2433
|
+
CGImageRelease(image);
|
|
2434
|
+
return snapshot;
|
|
2435
|
+
}
|
|
2436
|
+
|
|
2437
|
+
/* A page's content for a stored snapshot slot: the image, or the honest
|
|
2438
|
+
* background wash where no frame was retained. */
|
|
2439
|
+
- (UIView *)navPageContentForSnapshot:(id)stored {
|
|
2440
|
+
if ([stored isKindOfClass:[UIImage class]]) {
|
|
2441
|
+
UIImageView *image_view = [[UIImageView alloc] initWithImage:(UIImage *)stored];
|
|
2442
|
+
return image_view;
|
|
2443
|
+
}
|
|
2444
|
+
UIView *placeholder = [[UIView alloc] init];
|
|
2445
|
+
placeholder.backgroundColor = self.view.backgroundColor;
|
|
2446
|
+
return placeholder;
|
|
2447
|
+
}
|
|
2448
|
+
|
|
2449
|
+
/* Model -> stack, once per display tick, BEFORE the tick's render (so
|
|
2450
|
+
* the retained buffer still shows the outgoing page). One integer
|
|
2451
|
+
* readback; -1 (no projection, or pre-install) leaves the stack alone.
|
|
2452
|
+
* While a transition or gesture runs, reconciliation defers — the
|
|
2453
|
+
* applied depth stays stale and the next tick retries. */
|
|
2454
|
+
- (void)syncPlatformNavigation {
|
|
2455
|
+
if (!self.nativeApp || !self.navController) return;
|
|
2456
|
+
if (self.navTransitionActive) return;
|
|
2457
|
+
const intptr_t depth_value = native_sdk_app_chrome_navigation_depth(self.nativeApp);
|
|
2458
|
+
if (depth_value < 0) return;
|
|
2459
|
+
const NSInteger depth = (NSInteger)depth_value;
|
|
2460
|
+
const NSInteger tab = (NSInteger)native_sdk_app_chrome_selected_tab(self.nativeApp);
|
|
2461
|
+
|
|
2462
|
+
if (self.navAppliedDepth < 0) {
|
|
2463
|
+
/* First sighting: adopt the model's depth with no transition
|
|
2464
|
+
* (launching straight into a deep state must not animate). The
|
|
2465
|
+
* launch stack is already one page holding the canvas, so only
|
|
2466
|
+
* a deep launch rebuilds anything. */
|
|
2467
|
+
if (depth > 0) [self reconcileNavigationStackToDepth:depth];
|
|
2468
|
+
self.navAppliedDepth = depth;
|
|
2469
|
+
self.navAppliedTab = tab;
|
|
2470
|
+
return;
|
|
2471
|
+
}
|
|
2472
|
+
if (depth == self.navAppliedDepth) {
|
|
2473
|
+
self.navAppliedTab = tab;
|
|
2474
|
+
return;
|
|
2475
|
+
}
|
|
2476
|
+
|
|
2477
|
+
const BOOL tab_moved = tab != self.navAppliedTab;
|
|
2478
|
+
if (!tab_moved && depth == self.navAppliedDepth + 1) {
|
|
2479
|
+
[self animateNavigationPush];
|
|
2480
|
+
} else if (!tab_moved && depth == self.navAppliedDepth - 1) {
|
|
2481
|
+
[self animateNavigationPop];
|
|
2482
|
+
} else {
|
|
2483
|
+
/* Lateral (a tab switch that also changed the visible page's
|
|
2484
|
+
* depth) or a multi-level jump: standard platform behavior is
|
|
2485
|
+
* no push/pop theater — reconcile instantly. */
|
|
2486
|
+
[self reconcileNavigationStackToDepth:depth];
|
|
2487
|
+
}
|
|
2488
|
+
self.navAppliedDepth = depth;
|
|
2489
|
+
self.navAppliedTab = tab;
|
|
2490
|
+
NSLog(@"native-sdk: platform navigation depth -> %ld", (long)depth);
|
|
2491
|
+
}
|
|
2492
|
+
|
|
2493
|
+
/* Render the model's CURRENT state onto the live canvas right now,
|
|
2494
|
+
* before a transition begins. Two steps, both load-bearing: one extra
|
|
2495
|
+
* frame pump (the damage contract presents a dispatched change one pump
|
|
2496
|
+
* after its revision bump, so the pump makes the new frame deliverable),
|
|
2497
|
+
* then the ordinary delivery + present. Doing this BEFORE the stack
|
|
2498
|
+
* moves matters because a drawable presented while a navigation
|
|
2499
|
+
* transition is animating composites only after the animation ends —
|
|
2500
|
+
* pre-rendering is what makes the incoming page pixel-correct for the
|
|
2501
|
+
* transition's whole run instead of snapping afterwards. */
|
|
2502
|
+
- (void)preRenderLiveCanvasForTransition {
|
|
2503
|
+
/* Bounded pump loop: the change is deliverable once the runtime's
|
|
2504
|
+
* own present has rastered it, which can take a pump or two after
|
|
2505
|
+
* the dispatch. Idle pumps cost microseconds; the pump that rasters
|
|
2506
|
+
* is work the transition needs anyway. */
|
|
2507
|
+
for (int attempt = 0; attempt < 4; attempt++) {
|
|
2508
|
+
native_sdk_app_frame(self.nativeApp);
|
|
2509
|
+
self.lastDeliveryHadDamage = NO;
|
|
2510
|
+
const BOOL presented = [self renderAndPresent];
|
|
2511
|
+
if (NativeSdkGpuFrameTraceEnabled()) {
|
|
2512
|
+
native_sdk_gpu_frame_state_t probe = {0};
|
|
2513
|
+
const BOOL have = native_sdk_app_gpu_frame_state(self.nativeApp, &probe) == 1;
|
|
2514
|
+
fprintf(stderr, "native-sdk: nav pre-render attempt=%d presented=%d damage=%d revision_live=%llu revision_delivered=%llu\n",
|
|
2515
|
+
attempt, presented ? 1 : 0, self.lastDeliveryHadDamage ? 1 : 0,
|
|
2516
|
+
have ? (unsigned long long)probe.canvas_revision : 0,
|
|
2517
|
+
(unsigned long long)self.lastCanvasRevision);
|
|
2518
|
+
}
|
|
2519
|
+
if (presented && self.lastDeliveryHadDamage) return;
|
|
2520
|
+
}
|
|
2521
|
+
}
|
|
2522
|
+
|
|
2523
|
+
/* Depth grew by one: the outgoing frame (the retained buffer BEFORE the
|
|
2524
|
+
* pre-render) becomes the current top page's snapshot, the incoming
|
|
2525
|
+
* state pre-renders and its exact pixels become the pushed page's
|
|
2526
|
+
* content, and the REAL system push slides it in — pixel-correct on
|
|
2527
|
+
* both sides for the animation's whole run. The transition animates
|
|
2528
|
+
* bitmaps of the two model states deliberately: a drawable present
|
|
2529
|
+
* composites on the render server's schedule, so animating the live
|
|
2530
|
+
* layer plays the transition against the PREVIOUS frame and snaps at
|
|
2531
|
+
* the end — the honest choice is exact CPU pixels during the ~350ms
|
|
2532
|
+
* animation, with the live canvas swapped back in at completion
|
|
2533
|
+
* (restoreLiveCanvasAfterTransition). */
|
|
2534
|
+
- (void)animateNavigationPush {
|
|
2535
|
+
UIImage *outgoing = [self navSnapshotFromRetainedCanvas];
|
|
2536
|
+
[self preRenderLiveCanvasForTransition];
|
|
2537
|
+
UIImage *incoming = [self navSnapshotFromRetainedCanvas];
|
|
2538
|
+
NativeSdkNavPageViewController *top = (NativeSdkNavPageViewController *)self.navController.topViewController;
|
|
2539
|
+
id stored = (outgoing && self.navSnapshots.count < NativeSdkNavSnapshotCap) ? (id)outgoing : (id)[NSNull null];
|
|
2540
|
+
[self.navSnapshots addObject:stored];
|
|
2541
|
+
[top installContent:[self navPageContentForSnapshot:stored]];
|
|
2542
|
+
NativeSdkNavPageViewController *page = [[NativeSdkNavPageViewController alloc] init];
|
|
2543
|
+
[page installContent:[self navPageContentForSnapshot:(incoming ?: (id)[NSNull null])]];
|
|
2544
|
+
self.navHostTransition = YES;
|
|
2545
|
+
[self.navController pushViewController:page animated:YES];
|
|
2546
|
+
}
|
|
2547
|
+
|
|
2548
|
+
/* Depth shrank by one through the model (the app's own back button, a
|
|
2549
|
+
* programmatic Msg): the outgoing DEEP frame rides the popped page out
|
|
2550
|
+
* while the pre-rendered shallow frame is revealed underneath —
|
|
2551
|
+
* bitmaps on both sides, same reasoning as the push. The stored
|
|
2552
|
+
* snapshot for the popped level is discarded, and the revealed page's
|
|
2553
|
+
* content is the FRESH shallow frame, never the possibly-stale stored
|
|
2554
|
+
* one. */
|
|
2555
|
+
- (void)animateNavigationPop {
|
|
2556
|
+
NSArray<__kindof UIViewController *> *stack = self.navController.viewControllers;
|
|
2557
|
+
if (stack.count < 2) {
|
|
2558
|
+
[self reconcileNavigationStackToDepth:MAX(self.navAppliedDepth - 1, 0)];
|
|
2559
|
+
return;
|
|
2560
|
+
}
|
|
2561
|
+
UIImage *outgoing = [self navSnapshotFromRetainedCanvas];
|
|
2562
|
+
[self preRenderLiveCanvasForTransition];
|
|
2563
|
+
UIImage *incoming = [self navSnapshotFromRetainedCanvas];
|
|
2564
|
+
NativeSdkNavPageViewController *top = (NativeSdkNavPageViewController *)stack.lastObject;
|
|
2565
|
+
NativeSdkNavPageViewController *below = (NativeSdkNavPageViewController *)stack[stack.count - 2];
|
|
2566
|
+
[top installContent:[self navPageContentForSnapshot:(outgoing ?: (id)[NSNull null])]];
|
|
2567
|
+
[below installContent:[self navPageContentForSnapshot:(incoming ?: (id)[NSNull null])]];
|
|
2568
|
+
if (self.navSnapshots.count > 0) [self.navSnapshots removeLastObject];
|
|
2569
|
+
self.navHostTransition = YES;
|
|
2570
|
+
[self.navController popViewControllerAnimated:YES];
|
|
2571
|
+
}
|
|
2572
|
+
|
|
2573
|
+
/* A host-driven transition just landed: put the live canvas back on the
|
|
2574
|
+
* top page, but keep the page's transition bitmap ABOVE it for a few
|
|
2575
|
+
* ticks while the canvas re-presents underneath (needsPresent flushes
|
|
2576
|
+
* the retained texture) — the swap is invisible because the bitmap IS
|
|
2577
|
+
* the canvas's current frame. */
|
|
2578
|
+
- (void)restoreLiveCanvasAfterTransition {
|
|
2579
|
+
NativeSdkNavPageViewController *top = (NativeSdkNavPageViewController *)self.navController.topViewController;
|
|
2580
|
+
if (top.contentView == self.canvasView) return;
|
|
2581
|
+
UIView *cover = top.contentView;
|
|
2582
|
+
[top installContent:self.canvasView];
|
|
2583
|
+
if (cover) {
|
|
2584
|
+
cover.frame = top.view.bounds;
|
|
2585
|
+
cover.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
|
|
2586
|
+
[top.view addSubview:cover];
|
|
2587
|
+
[self.navFreezeOverlay removeFromSuperview];
|
|
2588
|
+
self.navFreezeOverlay = cover;
|
|
2589
|
+
self.navOverlayTicks = 3;
|
|
2590
|
+
}
|
|
2591
|
+
self.needsPresent = YES;
|
|
2592
|
+
}
|
|
2593
|
+
|
|
2594
|
+
/* Rebuild the stack to exactly depth+1 pages with no animation (first
|
|
2595
|
+
* sighting, lateral tab switches, multi-level jumps): snapshots for the
|
|
2596
|
+
* levels that retained one, the background wash for the rest, the live
|
|
2597
|
+
* canvas on top. */
|
|
2598
|
+
- (void)reconcileNavigationStackToDepth:(NSInteger)depth {
|
|
2599
|
+
while ((NSInteger)self.navSnapshots.count > depth) [self.navSnapshots removeLastObject];
|
|
2600
|
+
while ((NSInteger)self.navSnapshots.count < depth) [self.navSnapshots addObject:[NSNull null]];
|
|
2601
|
+
NSMutableArray<UIViewController *> *pages = [NSMutableArray arrayWithCapacity:(NSUInteger)depth + 1];
|
|
2602
|
+
for (NSInteger level = 0; level < depth; level++) {
|
|
2603
|
+
NativeSdkNavPageViewController *page = [[NativeSdkNavPageViewController alloc] init];
|
|
2604
|
+
[page installContent:[self navPageContentForSnapshot:self.navSnapshots[(NSUInteger)level]]];
|
|
2605
|
+
[pages addObject:page];
|
|
2606
|
+
}
|
|
2607
|
+
NativeSdkNavPageViewController *top = [[NativeSdkNavPageViewController alloc] init];
|
|
2608
|
+
[top installContent:self.canvasView];
|
|
2609
|
+
[pages addObject:top];
|
|
2610
|
+
self.navHostTransition = YES;
|
|
2611
|
+
[self.navController setViewControllers:pages animated:NO];
|
|
2612
|
+
self.navHostTransition = NO;
|
|
2613
|
+
self.needsPresent = YES;
|
|
2614
|
+
}
|
|
2615
|
+
|
|
2616
|
+
/* A completed interactive pop: UIKit already moved the stack (that IS
|
|
2617
|
+
* the gesture — real recognizer, real physics), so now the model hears
|
|
2618
|
+
* about it: the declared back command dispatches exactly once, the live
|
|
2619
|
+
* canvas moves onto the new top page (replacing the stale snapshot the
|
|
2620
|
+
* gesture revealed — the honest swap the section comment names), and
|
|
2621
|
+
* the applied depth follows the stack so the next tick's poll sees
|
|
2622
|
+
* agreement. */
|
|
2623
|
+
- (void)completeInteractivePop {
|
|
2624
|
+
if (self.navSnapshots.count > 0) [self.navSnapshots removeLastObject];
|
|
2625
|
+
if (self.navAppliedDepth > 0) self.navAppliedDepth -= 1;
|
|
2626
|
+
if (self.nativeApp && self.navBackCommand.length > 0) {
|
|
2627
|
+
NSLog(@"native-sdk: navigation swipe-back -> command %@", self.navBackCommand);
|
|
2628
|
+
native_sdk_app_command(self.nativeApp,
|
|
2629
|
+
self.navBackCommand.UTF8String,
|
|
2630
|
+
[self.navBackCommand lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
|
|
2631
|
+
[self logNativeErrorIfAny:@"navigation_back"];
|
|
2632
|
+
/* The dispatch just moved the model to the shallow state; the
|
|
2633
|
+
* transition is over, so render it now — the fresh frame both
|
|
2634
|
+
* replaces the (possibly stale) revealed snapshot on the glass
|
|
2635
|
+
* and covers the canvas swap-in below. */
|
|
2636
|
+
[self preRenderLiveCanvasForTransition];
|
|
2637
|
+
NativeSdkNavPageViewController *top = (NativeSdkNavPageViewController *)self.navController.topViewController;
|
|
2638
|
+
UIImage *fresh = [self navSnapshotFromRetainedCanvas];
|
|
2639
|
+
[top installContent:[self navPageContentForSnapshot:(fresh ?: (id)[NSNull null])]];
|
|
2640
|
+
}
|
|
2641
|
+
[self restoreLiveCanvasAfterTransition];
|
|
2642
|
+
}
|
|
2643
|
+
|
|
2644
|
+
/* Every animated stack move lands here (host pushes/pops and the
|
|
2645
|
+
* interactive gesture alike). The transition coordinator's completion
|
|
2646
|
+
* is the one honest place cancellation is knowable: a cancelled swipe
|
|
2647
|
+
* completes with isCancelled and dispatches nothing — the model was
|
|
2648
|
+
* never touched, so there is nothing to undo. */
|
|
2649
|
+
- (void)navigationController:(UINavigationController *)navigationController
|
|
2650
|
+
willShowViewController:(UIViewController *)viewController
|
|
2651
|
+
animated:(BOOL)animated {
|
|
2652
|
+
(void)viewController;
|
|
2653
|
+
const BOOL host_initiated = self.navHostTransition;
|
|
2654
|
+
self.navHostTransition = NO;
|
|
2655
|
+
id<UIViewControllerTransitionCoordinator> coordinator = navigationController.transitionCoordinator;
|
|
2656
|
+
if (!animated || !coordinator) return;
|
|
2657
|
+
self.navTransitionActive = YES;
|
|
2658
|
+
__weak NativeSdkCanvasViewController *weakSelf = self;
|
|
2659
|
+
[coordinator animateAlongsideTransition:nil
|
|
2660
|
+
completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
|
|
2661
|
+
NativeSdkCanvasViewController *strongSelf = weakSelf;
|
|
2662
|
+
if (!strongSelf) return;
|
|
2663
|
+
strongSelf.navTransitionActive = NO;
|
|
2664
|
+
if (context.isCancelled) return;
|
|
2665
|
+
if (host_initiated) {
|
|
2666
|
+
[strongSelf restoreLiveCanvasAfterTransition];
|
|
2667
|
+
return;
|
|
2668
|
+
}
|
|
2669
|
+
[strongSelf completeInteractivePop];
|
|
2670
|
+
}];
|
|
2671
|
+
}
|
|
2672
|
+
|
|
2673
|
+
/* Arm the REAL edge-swipe-back exactly while the projection says a page
|
|
2674
|
+
* is open and a back command exists to dispatch; never mid-transition
|
|
2675
|
+
* (a second gesture stacked on a running pop is how stacks corrupt). */
|
|
2676
|
+
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
|
|
2677
|
+
if (gestureRecognizer == self.navController.interactivePopGestureRecognizer) {
|
|
2678
|
+
if (self.navTransitionActive) return NO;
|
|
2679
|
+
/* The gesture drags the LIVE canvas, so it only begins while
|
|
2680
|
+
* the canvas actually sits on the top page (not during the
|
|
2681
|
+
* few covered ticks after a transition lands). */
|
|
2682
|
+
NativeSdkNavPageViewController *top = (NativeSdkNavPageViewController *)self.navController.topViewController;
|
|
2683
|
+
if (top.contentView != self.canvasView) return NO;
|
|
2684
|
+
if (self.navBackCommand.length == 0) return NO;
|
|
2685
|
+
return self.navController.viewControllers.count > 1;
|
|
2686
|
+
}
|
|
2687
|
+
return YES;
|
|
2688
|
+
}
|
|
2689
|
+
|
|
2690
|
+
/* The host-reported form factor: the platform's own horizontal size
|
|
2691
|
+
* class, reported over the window-chrome channel so apps switch shells
|
|
2692
|
+
* on host truth (width derivation stays their fallback). */
|
|
2693
|
+
- (void)reportFormFactor {
|
|
2694
|
+
if (!self.nativeApp) return;
|
|
2695
|
+
int form_factor = NATIVE_SDK_FORM_FACTOR_UNKNOWN;
|
|
2696
|
+
switch (self.traitCollection.horizontalSizeClass) {
|
|
2697
|
+
case UIUserInterfaceSizeClassCompact: form_factor = NATIVE_SDK_FORM_FACTOR_COMPACT; break;
|
|
2698
|
+
case UIUserInterfaceSizeClassRegular: form_factor = NATIVE_SDK_FORM_FACTOR_REGULAR; break;
|
|
2699
|
+
default: break;
|
|
2700
|
+
}
|
|
2701
|
+
if (form_factor == self.reportedFormFactor) return;
|
|
2702
|
+
self.reportedFormFactor = form_factor;
|
|
2703
|
+
native_sdk_app_set_form_factor(self.nativeApp, form_factor);
|
|
2704
|
+
[self logNativeErrorIfAny:@"form_factor"];
|
|
2705
|
+
NSLog(@"native-sdk: form factor %s",
|
|
2706
|
+
form_factor == NATIVE_SDK_FORM_FACTOR_COMPACT ? "compact"
|
|
2707
|
+
: form_factor == NATIVE_SDK_FORM_FACTOR_REGULAR ? "regular"
|
|
2708
|
+
: "unknown");
|
|
2709
|
+
}
|
|
2710
|
+
|
|
2711
|
+
- (void)logNativeErrorIfAny:(NSString *)stage {
|
|
2712
|
+
const char *name = native_sdk_app_last_error_name(self.nativeApp);
|
|
2713
|
+
if (name && name[0] != '\0') {
|
|
2714
|
+
NSLog(@"native-sdk: %@ error %s", stage, name);
|
|
2715
|
+
}
|
|
2716
|
+
}
|
|
2717
|
+
|
|
2718
|
+
@end
|
|
2719
|
+
|
|
2720
|
+
@interface NativeSdkAppDelegate : UIResponder <UIApplicationDelegate>
|
|
2721
|
+
@property(nonatomic, strong) UIWindow *window;
|
|
2722
|
+
@end
|
|
2723
|
+
|
|
2724
|
+
@implementation NativeSdkAppDelegate
|
|
2725
|
+
|
|
2726
|
+
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
|
|
2727
|
+
self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
|
|
2728
|
+
self.window.rootViewController = [[NativeSdkCanvasViewController alloc] init];
|
|
2729
|
+
[self.window makeKeyAndVisible];
|
|
2730
|
+
return YES;
|
|
2731
|
+
}
|
|
2732
|
+
|
|
2733
|
+
@end
|
|
2734
|
+
|
|
2735
|
+
int main(int argc, char *argv[]) {
|
|
2736
|
+
@autoreleasepool {
|
|
2737
|
+
return UIApplicationMain(argc, argv, nil, NSStringFromClass([NativeSdkAppDelegate class]));
|
|
2738
|
+
}
|
|
2739
|
+
}
|