@elurjs/android 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/README.md +10 -2
  2. package/index.mjs +11 -0
  3. package/package.json +29 -4
  4. package/template/.gitkeep +0 -0
  5. package/template/app/build.gradle.kts +192 -0
  6. package/template/app/proguard-rules-elur.pro +12 -0
  7. package/template/app/proguard-rules.pro +3 -0
  8. package/template/app/src/main/AndroidManifest.xml +81 -0
  9. package/template/app/src/main/assets/oss-notices.txt +153 -0
  10. package/template/app/src/main/assets/tck_pixel.png +0 -0
  11. package/template/app/src/main/cpp/CMakeLists.txt +117 -0
  12. package/template/app/src/main/cpp/dlEncoder.h +117 -0
  13. package/template/app/src/main/cpp/dlEncoderJsi.cpp +315 -0
  14. package/template/app/src/main/cpp/dlEncoderQjs.cpp +394 -0
  15. package/template/app/src/main/cpp/dlOps.inc +145 -0
  16. package/template/app/src/main/cpp/elurBridge.cpp +1350 -0
  17. package/template/app/src/main/cpp/elurBridgeHermes.cpp +1294 -0
  18. package/template/app/src/main/cpp/elurSkia.cpp +287 -0
  19. package/template/app/src/main/cpp/elurSkiaTree.cpp +448 -0
  20. package/template/app/src/main/cpp/elurUiWorklet.cpp +1233 -0
  21. package/template/app/src/main/cpp/elurYoga.cpp +1060 -0
  22. package/template/app/src/main/cpp/elurYoga.h +82 -0
  23. package/template/app/src/main/cpp/hermes-libs/LICENSE +21 -0
  24. package/template/app/src/main/cpp/hermes-libs/arm64-v8a/libhermesvm.so +0 -0
  25. package/template/app/src/main/cpp/hermes-libs/include/hermes/AsyncDebuggerAPI.h +276 -0
  26. package/template/app/src/main/cpp/hermes-libs/include/hermes/CompileJS.h +97 -0
  27. package/template/app/src/main/cpp/hermes-libs/include/hermes/DebuggerAPI.h +502 -0
  28. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/CrashManager.h +107 -0
  29. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/CtorConfig.h +145 -0
  30. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/DebuggerTypes.h +193 -0
  31. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/GCConfig.h +211 -0
  32. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/GCTripwireContext.h +40 -0
  33. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/HermesExport.h +14 -0
  34. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/JSOutOfMemoryError.h +27 -0
  35. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/RuntimeConfig.h +141 -0
  36. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/SamplingProfiler.h +270 -0
  37. package/template/app/src/main/cpp/hermes-libs/include/hermes/RuntimeTaskRunner.h +64 -0
  38. package/template/app/src/main/cpp/hermes-libs/include/hermes/SynthTrace.h +1566 -0
  39. package/template/app/src/main/cpp/hermes-libs/include/hermes/SynthTraceParser.h +37 -0
  40. package/template/app/src/main/cpp/hermes-libs/include/hermes/ThreadSafetyAnalysis.h +75 -0
  41. package/template/app/src/main/cpp/hermes-libs/include/hermes/TimerStats.h +23 -0
  42. package/template/app/src/main/cpp/hermes-libs/include/hermes/TraceInterpreter.h +334 -0
  43. package/template/app/src/main/cpp/hermes-libs/include/hermes/TracingRuntime.h +328 -0
  44. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/CDPAgent.h +131 -0
  45. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/CDPDebugAPI.h +73 -0
  46. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/CallbackOStream.h +89 -0
  47. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/ConsoleMessage.h +135 -0
  48. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/DebuggerDomainAgent.h +280 -0
  49. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/DebuggerDomainCoordinator.h +137 -0
  50. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/DomainAgent.h +107 -0
  51. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/DomainState.h +140 -0
  52. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/HeapProfilerDomainAgent.h +71 -0
  53. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/JSONValueInterfaces.h +40 -0
  54. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/MessageConverters.h +82 -0
  55. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/MessageInterfaces.h +72 -0
  56. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/MessageTypes.h +1279 -0
  57. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/MessageTypesInlines.h +313 -0
  58. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/ProfilerDomainAgent.h +38 -0
  59. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/RemoteObjectConverters.h +77 -0
  60. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/RemoteObjectsTable.h +127 -0
  61. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/RuntimeDomainAgent.h +138 -0
  62. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/Dummy.h +24 -0
  63. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/Extensions.h +20 -0
  64. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/ExtensionsBytecode.h +23 -0
  65. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/Intrinsics.h +44 -0
  66. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/JSIUtils.h +123 -0
  67. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/TextEncoder.h +29 -0
  68. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/contrib/ContribDummy.h +24 -0
  69. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/contrib/ContribExtensions.h +23 -0
  70. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/contrib/TextDecoder.h +30 -0
  71. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/contrib/TextDecoderUtils.h +113 -0
  72. package/template/app/src/main/cpp/hermes-libs/include/hermes/hermes.h +242 -0
  73. package/template/app/src/main/cpp/hermes-libs/include/hermes/hermes_tracing.h +52 -0
  74. package/template/app/src/main/cpp/hermes-libs/include/hermes_abi/HermesABIHelpers.h +295 -0
  75. package/template/app/src/main/cpp/hermes-libs/include/hermes_abi/HermesABIRuntimeWrapper.h +25 -0
  76. package/template/app/src/main/cpp/hermes-libs/include/hermes_abi/hermes_abi.h +642 -0
  77. package/template/app/src/main/cpp/hermes-libs/include/hermes_abi/hermes_vtable.h +29 -0
  78. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/HermesSandboxRuntime.h +41 -0
  79. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_compiled.h +12 -0
  80. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_dbg_compiled-impl.h +8516 -0
  81. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_dbg_compiled.h +137 -0
  82. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_opt_compiled-impl.h +3945 -0
  83. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_opt_compiled.h +119 -0
  84. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/wasm-rt-fb.h +124 -0
  85. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/wasm-rt-impl.h +66 -0
  86. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/wasm-rt.h +456 -0
  87. package/template/app/src/main/cpp/hermes-libs/include/jsi/JSIDynamic.h +26 -0
  88. package/template/app/src/main/cpp/hermes-libs/include/jsi/decorator.h +1157 -0
  89. package/template/app/src/main/cpp/hermes-libs/include/jsi/hermes-interfaces.h +242 -0
  90. package/template/app/src/main/cpp/hermes-libs/include/jsi/instrumentation.h +132 -0
  91. package/template/app/src/main/cpp/hermes-libs/include/jsi/jsi-inl.h +434 -0
  92. package/template/app/src/main/cpp/hermes-libs/include/jsi/jsi.h +2266 -0
  93. package/template/app/src/main/cpp/hermes-libs/include/jsi/jsilib.h +59 -0
  94. package/template/app/src/main/cpp/hermes-libs/include/jsi/threadsafe.h +79 -0
  95. package/template/app/src/main/cpp/hermes-libs/jsi-impl/jsi.cpp +1111 -0
  96. package/template/app/src/main/cpp/hermes-libs/x86_64/libhermesvm.so +0 -0
  97. package/template/app/src/main/java/com/elur/universal/BinaryCodec.kt +121 -0
  98. package/template/app/src/main/java/com/elur/universal/DlDecoder.kt +260 -0
  99. package/template/app/src/main/java/com/elur/universal/DlOpsDecode.kt +158 -0
  100. package/template/app/src/main/java/com/elur/universal/ElurBoxDrawable.kt +161 -0
  101. package/template/app/src/main/java/com/elur/universal/ElurBridge.kt +238 -0
  102. package/template/app/src/main/java/com/elur/universal/ElurBridgeHermes.kt +223 -0
  103. package/template/app/src/main/java/com/elur/universal/ElurCanvasView.kt +202 -0
  104. package/template/app/src/main/java/com/elur/universal/ElurCryptoModule.kt +206 -0
  105. package/template/app/src/main/java/com/elur/universal/ElurCustomLayout.kt +185 -0
  106. package/template/app/src/main/java/com/elur/universal/ElurEditText.kt +17 -0
  107. package/template/app/src/main/java/com/elur/universal/ElurFontRegistry.kt +190 -0
  108. package/template/app/src/main/java/com/elur/universal/ElurHttpModule.kt +306 -0
  109. package/template/app/src/main/java/com/elur/universal/ElurImageService.kt +348 -0
  110. package/template/app/src/main/java/com/elur/universal/ElurLicensesActivity.kt +84 -0
  111. package/template/app/src/main/java/com/elur/universal/ElurListView.kt +954 -0
  112. package/template/app/src/main/java/com/elur/universal/ElurManifest.kt +117 -0
  113. package/template/app/src/main/java/com/elur/universal/ElurMetrics.kt +325 -0
  114. package/template/app/src/main/java/com/elur/universal/ElurModuleRegistrar.kt +14 -0
  115. package/template/app/src/main/java/com/elur/universal/ElurPermissionGate.kt +36 -0
  116. package/template/app/src/main/java/com/elur/universal/ElurRenderer.kt +6164 -0
  117. package/template/app/src/main/java/com/elur/universal/ElurRowYoga.kt +130 -0
  118. package/template/app/src/main/java/com/elur/universal/ElurScrollView.kt +240 -0
  119. package/template/app/src/main/java/com/elur/universal/ElurShellView.kt +117 -0
  120. package/template/app/src/main/java/com/elur/universal/ElurSkiaCanvasView.kt +162 -0
  121. package/template/app/src/main/java/com/elur/universal/ElurSkiaTreeRenderer.kt +968 -0
  122. package/template/app/src/main/java/com/elur/universal/ElurStateModule.kt +69 -0
  123. package/template/app/src/main/java/com/elur/universal/ElurSwipeDriver.kt +34 -0
  124. package/template/app/src/main/java/com/elur/universal/ElurTckModule.kt +99 -0
  125. package/template/app/src/main/java/com/elur/universal/ElurTextMeasure.kt +16 -0
  126. package/template/app/src/main/java/com/elur/universal/ElurTrace.kt +24 -0
  127. package/template/app/src/main/java/com/elur/universal/ElurUiModule.kt +48 -0
  128. package/template/app/src/main/java/com/elur/universal/ElurUiWorklet.kt +305 -0
  129. package/template/app/src/main/java/com/elur/universal/JsBridge.kt +67 -0
  130. package/template/app/src/main/java/com/elur/universal/JsThread.kt +189 -0
  131. package/template/app/src/main/java/com/elur/universal/MainActivity.kt +844 -0
  132. package/template/app/src/main/java/com/elur/universal/ModuleRegistry.kt +701 -0
  133. package/template/app/src/main/java/com/elur/universal/YogaRowScope.kt +97 -0
  134. package/template/app/src/main/res/values/ids.xml +10 -0
  135. package/template/app/src/main/res/values/strings.xml +8 -0
  136. package/template/app/src/main/res/values-es/strings.xml +5 -0
  137. package/template/app/src/main/res/xml/network_security_config.xml +10 -0
  138. package/template/build.gradle.kts +5 -0
  139. package/template/gradle/libs.versions.toml +12 -0
  140. package/template/gradle/wrapper/gradle-wrapper.jar +0 -0
  141. package/template/gradle/wrapper/gradle-wrapper.properties +8 -0
  142. package/template/gradle.properties +23 -0
  143. package/template/gradlew +251 -0
  144. package/template/gradlew.bat +94 -0
  145. package/template/settings.gradle.kts +32 -0
@@ -0,0 +1,968 @@
1
+ // ElurSkiaTreeRenderer.kt — host Android del render-tree compartido
2
+ // (native/skia-tree, propuesta skia-renderer-arbol fase 4 — surface
3
+ // "custom" opt-in). Mismo contrato duck-typed que ElurRenderer ante el
4
+ // bridge JNI: applyDisplayListBinary, measureNode, baselineNode,
5
+ // requestFrame, callCommand… La selección vive en MainActivity
6
+ // (extra `surface` dev / campo `surface` del manifiesto en release);
7
+ // este objeto nunca decide — recibe ops.
8
+ //
9
+ // Superficie: SurfaceView raster (ANativeWindow lock→SkSurface→post en
10
+ // la lib nativa). Unidades: el árbol trabaja en dp — los rects Layout,
11
+ // el hit-test y la medida comparten espacio; los MotionEvent se
12
+ // dividen por density al cruzar a JNI. PV overlay: FrameLayout hermano
13
+ // del SurfaceView — las platform views son Views reales posicionadas
14
+ // por márgenes a su rect absoluto (mismo patrón GtkOverlay de Linux).
15
+ package com.elur.universal
16
+
17
+ import android.util.Log
18
+ import android.view.MotionEvent
19
+ import android.view.SurfaceHolder
20
+ import android.view.SurfaceView
21
+ import android.view.View
22
+ import android.widget.FrameLayout
23
+ import org.json.JSONArray
24
+ import org.json.JSONObject
25
+
26
+ class ElurSkiaTreeRenderer(
27
+ private val container: ElurShellView,
28
+ private val bridge: JsBridge,
29
+ private val benchmarkMode: Boolean,
30
+ ) : ElurHostRenderer {
31
+
32
+ companion object {
33
+ private const val TAG = "ElurSkiaTree"
34
+ val isAvailable: Boolean by lazy {
35
+ runCatching { System.loadLibrary("elur-skiatree") }.isSuccess
36
+ }
37
+ private const val EVENT_CONTRACT_VERSION_HOST = 5
38
+ private const val LONG_PRESS_MS = 400L
39
+ private const val FLING_MIN_DP_S = 250f
40
+ private const val FLING_END_DP_S = 30f
41
+ private const val FLING_TAU_S = 0.25
42
+
43
+ private val LEAF_TYPES = setOf("text", "text-input", "button", "image", "switch", "slider")
44
+ private val TEXT_MEASURE_KEYS =
45
+ setOf(
46
+ "fontSize",
47
+ "fontWeight",
48
+ "lineHeight",
49
+ "fontFamily",
50
+ "fontStyle",
51
+ "letterSpacing",
52
+ "textTransform",
53
+ "textAlign",
54
+ "textDecoration",
55
+ )
56
+ }
57
+
58
+ private val density = container.resources.displayMetrics.density
59
+ private val mainHandler = android.os.Handler(android.os.Looper.getMainLooper())
60
+
61
+ /**
62
+ * Vista raíz del carril: SurfaceView (pintura nativa) + overlay de platform views reales (hijos
63
+ * del FrameLayout, posicionados por márgenes al rect Yoga).
64
+ */
65
+ val root = FrameLayout(container.context)
66
+ private val surfaceView = SurfaceView(container.context)
67
+ private val pvOverlay =
68
+ FrameLayout(container.context).apply {
69
+ // La capa no captura eventos donde no hay widget: el táctil cae
70
+ // al SurfaceView; los hijos PV sí reciben sus eventos.
71
+ isClickable = false
72
+ }
73
+
74
+ private val pvViews = HashMap<Int, View>()
75
+ private val warnedOps = HashSet<String>()
76
+ private var destroyed = false
77
+ private var focusedId = 0
78
+
79
+ /**
80
+ * Hojas medibles en el espejo (mismo isLeafType que el árbol C++). `absorbedLeaf` mapea texto
81
+ * absorbido por un button a la hoja real que mide Yoga — paridad con absorbedByButton del
82
+ * carril views.
83
+ */
84
+ private val nodeTypes = HashMap<Int, String>()
85
+ private val absorbedLeaf = HashMap<Int, Int>()
86
+ private val zeroRetries = HashMap<Int, Int>()
87
+ private val remeasureSeq = java.util.concurrent.atomic.AtomicInteger(0)
88
+ private var lastAppliedLayoutSeq = 0
89
+ private var pressTarget = 0
90
+ private var scrollTarget = 0
91
+ private var lastTouchX = 0f
92
+ private var lastTouchY = 0f
93
+ private var downX = 0f
94
+ private var downY = 0f
95
+ private var beyondSlop = false
96
+ private var velY = 0f // dp/s — EMA del último tramo del gesto
97
+ private var lastMoveT = 0L
98
+ private var flingTarget = 0
99
+ private var flingRunning = false
100
+ private val touchSlopPx by lazy {
101
+ android.view.ViewConfiguration.get(container.context).scaledTouchSlop.toFloat()
102
+ }
103
+ private var renderPosted = false
104
+ private var longPressFired = false
105
+ private var navDepthLocal = 0
106
+
107
+ override var onNavDepthChanged: ((Int) -> Unit)? = null
108
+ override var onBackInterceptChanged: ((Boolean) -> Unit)? = null
109
+ override var onFirstApply: (() -> Unit)? = null
110
+ override var nativeListEnabled = false
111
+ override var cesmEnabled = false
112
+
113
+ // ── módulos (mismo registry que el carril views — ADR-0076) ─────
114
+ val moduleRegistry =
115
+ ModuleRegistry(
116
+ postToJs = { handler, payload ->
117
+ if (!destroyed)
118
+ runCatching { bridge.callHandlerWithString(handler, payload) }
119
+ },
120
+ postToJsCoalesced = { handler, payload, key ->
121
+ if (!destroyed)
122
+ runCatching {
123
+ bridge.callHandlerWithStringCoalesced(handler, payload, key)
124
+ }
125
+ },
126
+ capabilities = { setOf("commands", "events") },
127
+ cesmIo = { null },
128
+ timeoutScheduler = { ms, action -> mainHandler.postDelayed(action, ms) },
129
+ permissionRequester = { perm, cont ->
130
+ val act = container.context as? android.app.Activity
131
+ if (act == null) false
132
+ else {
133
+ ElurPermissionGate.ensure(act, perm, cont)
134
+ true
135
+ }
136
+ },
137
+ )
138
+
139
+ override fun registerModule(module: ElurModule) = moduleRegistry.register(module)
140
+
141
+ fun callCommand(callId: Int, module: String, command: String, argsJson: String) {
142
+ mainHandler.post {
143
+ if (!destroyed) moduleRegistry.dispatch(callId, module, command, argsJson)
144
+ }
145
+ }
146
+
147
+ fun cancelCommand(callId: Int) {
148
+ mainHandler.post { if (!destroyed) moduleRegistry.cancel(callId) }
149
+ }
150
+
151
+ // ── superficie ────────────────────────────────────────────────
152
+
153
+ init {
154
+ root.addView(
155
+ surfaceView,
156
+ FrameLayout.LayoutParams(
157
+ FrameLayout.LayoutParams.MATCH_PARENT,
158
+ FrameLayout.LayoutParams.MATCH_PARENT,
159
+ ),
160
+ )
161
+ root.addView(
162
+ pvOverlay,
163
+ FrameLayout.LayoutParams(
164
+ FrameLayout.LayoutParams.MATCH_PARENT,
165
+ FrameLayout.LayoutParams.MATCH_PARENT,
166
+ ),
167
+ )
168
+ container.addView(
169
+ root,
170
+ FrameLayout.LayoutParams(
171
+ FrameLayout.LayoutParams.MATCH_PARENT,
172
+ FrameLayout.LayoutParams.MATCH_PARENT,
173
+ ),
174
+ )
175
+ // U12/edge-to-edge: mismo contrato de insets que views — el
176
+ // viewport Yoga es la ventana completa y el padding del root
177
+ // desplaza surface+overlay fuera de status/nav bar (y del IME).
178
+ androidx.core.view.ViewCompat.setOnApplyWindowInsetsListener(root) { v, insets ->
179
+ val sys = insets.getInsets(androidx.core.view.WindowInsetsCompat.Type.systemBars())
180
+ val ime = insets.getInsets(androidx.core.view.WindowInsetsCompat.Type.ime())
181
+ val bottom = if (ime.bottom > 0) ime.bottom else sys.bottom
182
+ v.setPadding(0, sys.top, 0, bottom)
183
+ insets
184
+ }
185
+ androidx.core.view.ViewCompat.requestApplyInsets(root)
186
+ nativeInit(density)
187
+ // ADR-0087 — el contexto UI de worklets comparte el container;
188
+ // viewLookup solo resuelve PVs del overlay (los nodos del árbol
189
+ // no son Views en este carril).
190
+ ElurUiWorklet.attach(
191
+ lookup = { id -> pvViews[id] },
192
+ post = { handler, payload ->
193
+ if (!destroyed) {
194
+ try {
195
+ bridge.callHandlerWithString(handler, payload)
196
+ } catch (e: Exception) {
197
+ Log.e(TAG, "[uiwk] reply a hilo JS caído", e)
198
+ }
199
+ }
200
+ },
201
+ )
202
+ ElurUiWorklet.density = density
203
+ ElurUiWorklet.cesmAttach = { name -> bridge.cesmAttachUi(name) }
204
+ ElurUiWorklet.cesmDetach = { name -> bridge.cesmDetachUi(name) }
205
+ surfaceView.holder.addCallback(
206
+ object : SurfaceHolder.Callback {
207
+ override fun surfaceCreated(holder: SurfaceHolder) {
208
+ nativeSetSurface(holder.surface, surfaceView.width, surfaceView.height)
209
+ postRender()
210
+ }
211
+ override fun surfaceChanged(holder: SurfaceHolder, fmt: Int, w: Int, h: Int) {
212
+ nativeSetSurface(holder.surface, w, h)
213
+ postRender()
214
+ }
215
+ override fun surfaceDestroyed(holder: SurfaceHolder) {
216
+ nativeReleaseSurface()
217
+ }
218
+ },
219
+ )
220
+ surfaceView.setOnTouchListener { _, ev -> onTouch(ev) }
221
+ }
222
+
223
+ private var statFrames = 0
224
+ private var statJanky = 0
225
+ private var statTotalNs = 0L
226
+ private var statMaxNs = 0L
227
+
228
+ private fun postRender() {
229
+ if (renderPosted || destroyed) return
230
+ renderPosted = true
231
+ mainHandler.post {
232
+ renderPosted = false
233
+ if (destroyed) return@post
234
+ val t0 = System.nanoTime()
235
+ nativeRender()
236
+ // La SurfaceView no pasa por el pipeline View/FrameTimeline:
237
+ // el jank del carril solo se puede medir aquí (lock→unlock).
238
+ val dt = System.nanoTime() - t0
239
+ statFrames++
240
+ statTotalNs += dt
241
+ if (dt > statMaxNs) statMaxNs = dt
242
+ if (dt > 16_700_000) statJanky++
243
+ if (benchmarkMode && statFrames % 32 == 0) {
244
+ Log.i(
245
+ "ElurSkiaTree",
246
+ "[skiatree-render] frames=$statFrames jank=$statJanky " +
247
+ "avgMs=${statTotalNs / statFrames / 1000000.0} " +
248
+ "maxMs=${statMaxNs / 1000000.0}"
249
+ )
250
+ }
251
+ }
252
+ }
253
+
254
+ // ── ops ───────────────────────────────────────────────────────
255
+
256
+ /**
257
+ * Punto de entrada del bridge (hilo JS) — postea a main como el carril views
258
+ * (applyDisplayListBinary).
259
+ */
260
+ fun applyDisplayListBinary(data: ByteArray) {
261
+ val postedAt = System.nanoTime()
262
+ container.post {
263
+ if (destroyed) return@post
264
+ val t0 = System.nanoTime()
265
+ val queueWaitMs = (t0 - postedAt) / 1_000_000.0
266
+ val decoded = DlDecoder.decode(data)
267
+ // R4.4/ADR-0085 — frames host-initiated (id<0 = -seq): solo se
268
+ // descarta un replay fuera de orden (paridad con views).
269
+ val f = decoded.frame
270
+ if (f < 0 && -f in 1 until 1_000_000 && -f <= lastAppliedLayoutSeq) {
271
+ ElurMetrics.recordStale()
272
+ return@post
273
+ }
274
+ if (f < 0 && -f in 1 until 1_000_000) lastAppliedLayoutSeq = -f
275
+ val dirtyLeaves = HashSet<Int>()
276
+ for (op in decoded.ops) {
277
+ when (op) {
278
+ is WireOp.UpdateText -> dirtyLeaves.add(leafOf(op.id))
279
+ is WireOp.UpdateProps -> dirtyLeaves.add(leafOf(op.id))
280
+ is WireOp.UpdateStyle ->
281
+ if (op.style.keys.any { TEXT_MEASURE_KEYS.contains(it) }) {
282
+ dirtyLeaves.add(leafOf(op.id))
283
+ }
284
+ else -> {}
285
+ }
286
+ applyOp(op)
287
+ }
288
+ // Backstop: hoja que quedó en rect 0 teniendo contenido (el
289
+ // yoga pass midió antes de que aterrizara el texto).
290
+ for (op in decoded.ops) {
291
+ val l = op as? WireOp.Layout ?: continue
292
+ if (l.w > 0 && l.h > 0) {
293
+ zeroRetries.remove(l.id)
294
+ continue
295
+ }
296
+ val t = nodeTypes[l.id] ?: continue
297
+ if (t in LEAF_TYPES && nativeMeasure(l.id, 0f, 0, 0f, 0) != 0L) {
298
+ val tries = zeroRetries[l.id] ?: 0
299
+ if (tries < 8) {
300
+ zeroRetries[l.id] = tries + 1
301
+ dirtyLeaves.add(l.id)
302
+ Log.w(TAG, "hoja ${l.id} en rect 0 — re-medida ${tries + 1}/8")
303
+ }
304
+ }
305
+ }
306
+ if (dirtyLeaves.isNotEmpty()) {
307
+ ElurMetrics.recordRemeasure(dirtyLeaves.size)
308
+ bridge.requestLeafRemeasure(
309
+ dirtyLeaves.toIntArray(),
310
+ remeasureSeq.incrementAndGet()
311
+ )
312
+ }
313
+ ElurMetrics.recordCommit(
314
+ decoded.frame.toLong(),
315
+ decoded.ops.size,
316
+ data.size,
317
+ (System.nanoTime() - t0) / 1_000_000.0,
318
+ queueWaitMs,
319
+ dirtyLeaves.size
320
+ )
321
+ postRender()
322
+ onFirstApply?.invoke()
323
+ }
324
+ }
325
+
326
+ private fun leafOf(id: Int) = absorbedLeaf[id] ?: id
327
+
328
+ /**
329
+ * Carril JSON (flush) — mismo dispatch que el binario; el decode JSON lo resuelve el DlDecoder
330
+ * de la capa manual si existe.
331
+ */
332
+ fun applyDisplayList(json: String) {
333
+ container.post {
334
+ if (destroyed) return@post
335
+ val ops = JSONObject(json).optJSONArray("ops") ?: JSONArray(json)
336
+ for (i in 0 until ops.length()) applyJsonOp(ops.getJSONObject(i))
337
+ postRender()
338
+ }
339
+ }
340
+
341
+ private fun applyOp(op: WireOp) {
342
+ when (op) {
343
+ is WireOp.CreateNode -> {
344
+ knownNodes.add(op.id)
345
+ nodeTypes[op.id] = op.type
346
+ nativeCreateNode(op.id, op.type)
347
+ }
348
+ is WireOp.UpdateText -> nativeUpdateText(op.id, op.value)
349
+ is WireOp.UpdateStyle -> updateStyle(op.id, op.style)
350
+ is WireOp.UpdateProps -> updateProps(op.id, op.props)
351
+ is WireOp.InsertChild -> {
352
+ if (nodeTypes[op.childId] == "text" && nodeTypes[op.parentId] == "button") {
353
+ absorbedLeaf[op.childId] = op.parentId
354
+ }
355
+ nativeInsertChild(op.parentId, op.childId, op.index)
356
+ }
357
+ is WireOp.RemoveChild -> {
358
+ absorbedLeaf.remove(op.childId)
359
+ nativeRemoveChild(op.parentId, op.childId)
360
+ }
361
+ is WireOp.MoveChild -> nativeMoveChild(op.parentId, op.childId, op.index)
362
+ is WireOp.DeleteNode -> {
363
+ knownNodes.remove(op.id)
364
+ lastMeasures.remove(op.id)
365
+ nodeTypes.remove(op.id)
366
+ absorbedLeaf.remove(op.id)
367
+ zeroRetries.remove(op.id)
368
+ nativeDeleteNode(op.id)
369
+ }
370
+ is WireOp.AttachEvent ->
371
+ nativeAttachEvent(op.id, op.event, op.handler, op.continuous, op.payload)
372
+ is WireOp.DetachEvent -> nativeDetachEvent(op.id, op.event)
373
+ is WireOp.ResetNode -> nativeResetNode(op.id)
374
+ is WireOp.Layout -> layoutNode(op.id, op.x, op.y, op.w, op.h)
375
+ is WireOp.CreatePlatformView -> createPlatformView(op.id, op.module, op.view, op.props)
376
+ is WireOp.UpdatePlatformViewProps -> updatePvProps(op.id, op.props)
377
+ is WireOp.SetPlatformViewVisible ->
378
+ pvViews[op.id]?.visibility = if (op.visible) View.VISIBLE else View.GONE
379
+ is WireOp.NavPush -> onNav(op.depth)
380
+ is WireOp.NavPop -> onNav(op.depth)
381
+ is WireOp.NavReplace -> onNav(op.depth)
382
+ else -> warnOnce("op", op.javaClass.simpleName)
383
+ }
384
+ }
385
+
386
+ private fun applyJsonOp(op: JSONObject) {
387
+ when (op.optString("op")) {
388
+ "create-node" -> nativeCreateNode(op.getInt("id"), op.getString("type"))
389
+ "update-text" -> nativeUpdateText(op.getInt("id"), op.getString("value"))
390
+ "insert-child" ->
391
+ nativeInsertChild(
392
+ op.getInt("parentId"),
393
+ op.getInt("childId"),
394
+ op.getInt("index")
395
+ )
396
+ "remove-child" -> nativeRemoveChild(op.getInt("parentId"), op.getInt("childId"))
397
+ "move-child" ->
398
+ nativeMoveChild(op.getInt("parentId"), op.getInt("childId"), op.getInt("index"))
399
+ "delete-node" -> nativeDeleteNode(op.getInt("id"))
400
+ "reset-node" -> nativeResetNode(op.getInt("id"))
401
+ else -> warnOnce("op-json", op.optString("op"))
402
+ }
403
+ }
404
+
405
+ private fun updateStyle(id: Int, style: Map<String, Any>) {
406
+ val keys = style.keys.toTypedArray()
407
+ val isNum = BooleanArray(keys.size)
408
+ val nums = DoubleArray(keys.size)
409
+ val strs = arrayOfNulls<String>(keys.size)
410
+ for ((i, k) in keys.withIndex()) {
411
+ when (val v = style[k]) {
412
+ is Number -> {
413
+ isNum[i] = true
414
+ nums[i] = v.toDouble()
415
+ }
416
+ // NULL = retira la clave (mismo contrato que el carril
417
+ // Linux: str vacío borra en setStyle).
418
+ JSONObject.NULL -> strs[i] = ""
419
+ else -> strs[i] = v.toString()
420
+ }
421
+ }
422
+ nativeUpdateStyle(id, keys, isNum, nums, strs)
423
+ }
424
+
425
+ private fun updateProps(id: Int, props: JSONObject) {
426
+ val keys = props.keys()
427
+ while (keys.hasNext()) {
428
+ val k = keys.next()
429
+ val v = props.opt(k)
430
+ // Escalares aplanados (mismo contrato que el glue Linux:
431
+ // objetos/arrays no cruzan — fase posterior del carril).
432
+ when (v) {
433
+ null, JSONObject.NULL -> nativeSetProp(id, k, "")
434
+ is String, is Number, is Boolean -> nativeSetProp(id, k, v.toString())
435
+ else -> warnOnce("prop-obj", "$k:${v.javaClass.simpleName}")
436
+ }
437
+ }
438
+ }
439
+
440
+ private fun layoutNode(id: Int, x: Float, y: Float, w: Float, h: Float) {
441
+ pvViews[id]?.let { v ->
442
+ val lp = v.layoutParams as? FrameLayout.LayoutParams ?: FrameLayout.LayoutParams(0, 0)
443
+ lp.width = Math.round(w * density)
444
+ lp.height = Math.round(h * density)
445
+ lp.leftMargin = Math.round(x * density)
446
+ lp.topMargin = Math.round(y * density)
447
+ lp.gravity = android.view.Gravity.TOP or android.view.Gravity.LEFT
448
+ v.layoutParams = lp
449
+ return
450
+ }
451
+ nativeLayout(id, x, y, w, h)
452
+ }
453
+
454
+ // ── platform views (Views reales en el overlay — ADR-0181) ──────
455
+
456
+ private fun createPlatformView(id: Int, module: String, view: String, props: JSONObject?) {
457
+ val emit: PlatformViewEmit = { event, dataJson -> emitBound(id, event, dataJson) }
458
+ val v =
459
+ moduleRegistry.platformViewFactory(module, view)?.invoke(container.context, emit)
460
+ ?: ElurRenderer.PlatformViews.create(module, view, container.context)
461
+ if (v == null) {
462
+ warnOnce("pv", "$module:$view")
463
+ return
464
+ }
465
+ pvViews[id] = v
466
+ pvOverlay.addView(v)
467
+ if (props != null) updatePvProps(id, props)
468
+ }
469
+
470
+ private fun updatePvProps(id: Int, props: JSONObject) {
471
+ val v = pvViews[id] ?: return
472
+ if (props.has("sensitive") || props.has("enabled")) {
473
+ v.isEnabled = props.optBoolean("sensitive", props.optBoolean("enabled", true))
474
+ }
475
+ }
476
+
477
+ private fun onNav(depth: Int) {
478
+ if (depth != navDepthLocal) {
479
+ navDepthLocal = depth
480
+ onNavDepthChanged?.invoke(depth)
481
+ }
482
+ }
483
+
484
+ // ── eventos nodo→JS (mismo envelope que el carril views) ────────
485
+
486
+ /**
487
+ * handler+payload del binding (id,event) viven en el árbol — nativeEventInfo los devuelve como
488
+ * "handler\tpayload".
489
+ */
490
+ private fun emitBound(id: Int, event: String, dataJson: String) {
491
+ val info = nativeEventInfo(id, event) ?: return
492
+ val tab = info.indexOf('\t')
493
+ if (tab < 0) return
494
+ val handler = info.substring(0, tab)
495
+ val payload = info.substring(tab + 1)
496
+ val data =
497
+ if (payload.length > 2) {
498
+ val inner = payload.substring(1, payload.length - 1)
499
+ val base = dataJson.substring(0, dataJson.length - 1)
500
+ if (base.endsWith("{")) "$base$inner}" else "$base,$inner}"
501
+ } else dataJson
502
+ val env =
503
+ "{\"v\":$EVENT_CONTRACT_VERSION_HOST,\"event\":\"$event\",\"origin\":\"user\"," +
504
+ "\"ts\":${android.os.SystemClock.uptimeMillis()},\"data\":$data}"
505
+ if (!destroyed) bridge.callHandlerWithString(handler, env)
506
+ }
507
+
508
+ // ── input ─────────────────────────────────────────────────────
509
+
510
+ private val longPressRunnable = Runnable {
511
+ longPressFired = true
512
+ val id = nativeHitTest(lastTouchX / density, lastTouchY / density, "longPress")
513
+ if (id != 0) emitBound(id, "longPress", jsonXY(lastTouchX / density, lastTouchY / density))
514
+ }
515
+
516
+ private fun jsonXY(x: Float, y: Float) = "{\"x\":$x,\"y\":$y}"
517
+
518
+ private fun onTouch(ev: MotionEvent): Boolean {
519
+ val x = ev.x
520
+ val y = ev.y
521
+ when (ev.actionMasked) {
522
+ MotionEvent.ACTION_DOWN -> {
523
+ lastTouchX = x
524
+ lastTouchY = y
525
+ downX = x
526
+ downY = y
527
+ beyondSlop = false
528
+ flingRunning = false
529
+ pressTarget = nativeHitTest(x / density, y / density, "press")
530
+ scrollTarget = nativeScrollableAt(x / density, y / density)
531
+ velY = 0f
532
+ lastMoveT = ev.eventTime
533
+ longPressFired = false
534
+ mainHandler.postDelayed(longPressRunnable, LONG_PRESS_MS)
535
+ val id = nativeNodeAt(x / density, y / density)
536
+ if (id != focusedId) setFocus(id)
537
+ return true
538
+ }
539
+ MotionEvent.ACTION_MOVE -> {
540
+ val dtMs = ev.eventTime - lastMoveT
541
+ if (dtMs > 0) {
542
+ val inst = (y - lastTouchY) / density / dtMs * 1000f
543
+ velY = velY * 0.7f + inst * 0.3f
544
+ lastMoveT = ev.eventTime
545
+ }
546
+ val dx = (x - lastTouchX) / density
547
+ val dy = (y - lastTouchY) / density
548
+ lastTouchX = x
549
+ lastTouchY = y
550
+ if (Math.hypot((x - downX).toDouble(), (y - downY).toDouble()) > touchSlopPx) {
551
+ beyondSlop = true
552
+ mainHandler.removeCallbacks(longPressRunnable)
553
+ }
554
+ if (beyondSlop && scrollTarget != 0 && nativeScrollBy(scrollTarget, -dx, -dy)) {
555
+ emitScroll(scrollTarget)
556
+ postRender()
557
+ }
558
+ return true
559
+ }
560
+ MotionEvent.ACTION_UP -> {
561
+ mainHandler.removeCallbacks(longPressRunnable)
562
+ val id = nativeHitTest(x / density, y / density, "press")
563
+ if (!longPressFired && !beyondSlop && id != 0 && id == pressTarget) {
564
+ val type = nativeNodeType(id)
565
+ if (type == "switch") {
566
+ emitBound(id, "change", "{\"checked\":${nativeSwitchToggle(id)}}")
567
+ postRender()
568
+ } else if (type == "slider") {
569
+ val lx = nativeLocalX(id, x / density)
570
+ emitBound(id, "change", "{\"value\":${nativeSliderSetAt(id, lx)}}")
571
+ postRender()
572
+ } else {
573
+ emitBound(id, "press", jsonXY(x / density, y / density))
574
+ }
575
+ }
576
+ // Fling: dedo levantado con velocidad residual — el gesto
577
+ // sigue con decaimiento exponencial (mismo modelo que el
578
+ // glue Linux; el offset sigue viviendo en el árbol).
579
+ if (beyondSlop && scrollTarget != 0 && Math.abs(velY) > FLING_MIN_DP_S) {
580
+ flingTarget = scrollTarget
581
+ if (!flingRunning) {
582
+ flingRunning = true
583
+ flingLastT = 0L
584
+ android.view.Choreographer.getInstance().postFrameCallback(flingCallback)
585
+ }
586
+ }
587
+ pressTarget = 0
588
+ scrollTarget = 0
589
+ return true
590
+ }
591
+ MotionEvent.ACTION_CANCEL -> {
592
+ mainHandler.removeCallbacks(longPressRunnable)
593
+ pressTarget = 0
594
+ scrollTarget = 0
595
+ return true
596
+ }
597
+ }
598
+ return false
599
+ }
600
+
601
+ private var flingLastT = 0L
602
+ private val flingCallback =
603
+ object : android.view.Choreographer.FrameCallback {
604
+ override fun doFrame(frameTimeNanos: Long) {
605
+ if (destroyed || !flingRunning || flingTarget == 0) {
606
+ flingRunning = false
607
+ return
608
+ }
609
+ val dtS =
610
+ if (flingLastT == 0L) 0.016f
611
+ else ((frameTimeNanos - flingLastT) / 1e9).toFloat()
612
+ flingLastT = frameTimeNanos
613
+ val step = -velY * dtS
614
+ velY *= Math.exp(-dtS.toDouble() / FLING_TAU_S).toFloat()
615
+ val settled = Math.abs(velY) < FLING_END_DP_S
616
+ if (!nativeScrollBy(flingTarget, 0f, step) || settled) {
617
+ flingRunning = false
618
+ return
619
+ }
620
+ emitScroll(flingTarget)
621
+ postRender()
622
+ android.view.Choreographer.getInstance().postFrameCallback(this)
623
+ }
624
+ }
625
+
626
+ private fun emitScroll(id: Int) {
627
+ emitBound(
628
+ id,
629
+ "scroll",
630
+ "{\"y\":${nativeScrollY(id)},\"vh\":${nativeNodeH(id)},\"node\":$id}"
631
+ )
632
+ }
633
+
634
+ private fun setFocus(id: Int) {
635
+ if (focusedId != 0) emitBound(focusedId, "blur", "{}")
636
+ focusedId = id
637
+ nativeSetFocused(id)
638
+ if (id != 0) emitBound(id, "focus", "{}")
639
+ }
640
+
641
+ // ── vtable del espejo Yoga / caps (nombres que el bridge invoca) ──
642
+
643
+ /**
644
+ * ADR-0122 — el espejo llama measureNode/baselineNode en el hilo JS DURANTE calculateLayout. El
645
+ * árbol vive en main (ops+paint+input); toda medida cruza a main: en pasada collect se encola y
646
+ * el drain corre el lote tras el apply del frame (una latch), fuera de defer una latch por hoja
647
+ * como la pasada final de views.
648
+ */
649
+ @Volatile private var deferring = false
650
+ private data class MeasureReq(
651
+ val id: Int,
652
+ val w: Float,
653
+ val wMode: Int,
654
+ val h: Float,
655
+ val hMode: Int,
656
+ )
657
+ private val pendingMeasures = ArrayList<MeasureReq>()
658
+ private val lastMeasures = java.util.concurrent.ConcurrentHashMap<Int, Long>()
659
+ private val knownNodes = java.util.concurrent.ConcurrentHashMap.newKeySet<Int>()
660
+
661
+ fun setMeasureDefer(defer: Boolean) {
662
+ deferring = defer
663
+ if (!defer) pendingMeasures.clear()
664
+ }
665
+
666
+ /** Drena el lote encolado en la pasada collect — una tarea, un latch (R4.3). */
667
+ fun drainMeasureBatch(): IntArray? {
668
+ val reqs = pendingMeasures.toList()
669
+ pendingMeasures.clear()
670
+ if (reqs.isEmpty()) return IntArray(0)
671
+ val latch = java.util.concurrent.CountDownLatch(1)
672
+ var posted = false
673
+ try {
674
+ posted =
675
+ mainHandler.post {
676
+ try {
677
+ for (r in reqs) {
678
+ if (!knownNodes.contains(r.id)) continue
679
+ val packed = nativeMeasure(r.id, r.w, r.wMode, r.h, r.hMode)
680
+ if (packed != 0L) lastMeasures[r.id] = packed
681
+ }
682
+ } finally {
683
+ latch.countDown()
684
+ }
685
+ }
686
+ } catch (_: RuntimeException) {}
687
+ val budgetMs = (500L + reqs.size * 40L).coerceAtMost(5000L)
688
+ val ok = posted && latch.await(budgetMs, java.util.concurrent.TimeUnit.MILLISECONDS)
689
+ if (!ok) {
690
+ ElurMetrics.recordMeasureTimeout()
691
+ return null
692
+ }
693
+ return reqs.map { it.id }.toIntArray()
694
+ }
695
+
696
+ fun measureNode(id: Int, wPx: Float, wMode: Int, hPx: Float, hMode: Int): Long {
697
+ // La hoja puede no existir aún en el árbol (mide antes del
698
+ // apply del frame) — en collect se encola; fuera de defer el
699
+ // latch la resuelve tras el apply si ya aterrizó.
700
+ if (!knownNodes.contains(id)) {
701
+ if (deferring && !destroyed) pendingMeasures.add(MeasureReq(id, wPx, wMode, hPx, hMode))
702
+ return 0L
703
+ }
704
+ if (deferring) {
705
+ pendingMeasures.add(MeasureReq(id, wPx, wMode, hPx, hMode))
706
+ return lastMeasures[id] ?: 0L
707
+ }
708
+ if (android.os.Looper.myLooper() == android.os.Looper.getMainLooper()) {
709
+ val packed = nativeMeasure(id, wPx, wMode, hPx, hMode)
710
+ if (packed != 0L) lastMeasures[id] = packed
711
+ return packed
712
+ }
713
+ val latch = java.util.concurrent.CountDownLatch(1)
714
+ var packed = 0L
715
+ val posted =
716
+ try {
717
+ mainHandler.post {
718
+ try {
719
+ packed = nativeMeasure(id, wPx, wMode, hPx, hMode)
720
+ } finally {
721
+ latch.countDown()
722
+ }
723
+ }
724
+ } catch (_: RuntimeException) {
725
+ false
726
+ }
727
+ val ok = posted && latch.await(500, java.util.concurrent.TimeUnit.MILLISECONDS)
728
+ if (ok && packed != 0L) lastMeasures[id] = packed
729
+ return if (ok) packed else lastMeasures[id] ?: 0L
730
+ }
731
+
732
+ fun baselineNode(id: Int, wPx: Float, hPx: Float): Float {
733
+ if (android.os.Looper.myLooper() == android.os.Looper.getMainLooper()) {
734
+ return nativeBaseline(id, wPx, hPx)
735
+ }
736
+ val latch = java.util.concurrent.CountDownLatch(1)
737
+ var out = hPx
738
+ val posted =
739
+ try {
740
+ mainHandler.post {
741
+ try {
742
+ out = nativeBaseline(id, wPx, hPx)
743
+ } finally {
744
+ latch.countDown()
745
+ }
746
+ }
747
+ } catch (_: RuntimeException) {
748
+ false
749
+ }
750
+ if (!posted || !latch.await(500, java.util.concurrent.TimeUnit.MILLISECONDS)) return hPx
751
+ return out
752
+ }
753
+
754
+ fun requestFrame() {
755
+ container.post {
756
+ if (destroyed) return@post
757
+ android.view.Choreographer.getInstance().postFrameCallback {
758
+ if (!destroyed) {
759
+ bridge.callHandler("__elur_frame")
760
+ bridge.flushPending()
761
+ }
762
+ }
763
+ }
764
+ }
765
+
766
+ // ADR-0134: timers del host — disparo en el looper del JsThread y
767
+ // re-entrada por "__elur_timer" (misma disciplina que views).
768
+ private val timerTokens = HashMap<Int, Any>()
769
+
770
+ fun setTimer(id: Int, ms: Int) {
771
+ val token = Any()
772
+ synchronized(timerTokens) { timerTokens.put(id, token)?.let { JsThread.cancel(it) } }
773
+ JsThread.postDelayed(token, ms.coerceAtLeast(0).toLong()) {
774
+ val live =
775
+ synchronized(timerTokens) {
776
+ if (timerTokens[id] === token) {
777
+ timerTokens.remove(id)
778
+ true
779
+ } else false
780
+ }
781
+ if (live && !destroyed) {
782
+ bridge.callHandlerWithString("__elur_timer", id.toString())
783
+ bridge.flushPending()
784
+ }
785
+ }
786
+ }
787
+
788
+ fun clearTimer(id: Int) {
789
+ synchronized(timerTokens) { timerTokens.remove(id) }?.let { JsThread.cancel(it) }
790
+ }
791
+
792
+ /** Reloj determinista (`-e now <ms>`, docs §3.16); ≤0 = real. */
793
+ fun debugNow(): Double = ElurTrace.debugNowMs.toDouble()
794
+
795
+ fun openUrl(url: String) {
796
+ container.post {
797
+ try {
798
+ container.context.startActivity(
799
+ android.content.Intent(
800
+ android.content.Intent.ACTION_VIEW,
801
+ android.net.Uri.parse(url)
802
+ )
803
+ .addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
804
+ )
805
+ } catch (e: Exception) {
806
+ Log.w(TAG, "[openUrl] sin app para $url", e)
807
+ }
808
+ }
809
+ }
810
+
811
+ /** ADR-0191 — errores de producción JS→host; nunca lanza hacia el engine. */
812
+ fun reportError(kind: String, json: String) {
813
+ runCatching { ElurMetrics.recordError(kind, json) }
814
+ }
815
+
816
+ // ADR-0087: el contexto UI de worklets es agnóstico del aplicador —
817
+ // viewLookup solo resuelve los Platform Views del overlay (los
818
+ // nodos del árbol no tienen View; un worklet que los toque no-opea,
819
+ // igual que un id inexistente en views).
820
+ fun uiWorkletStart(specJson: String) {
821
+ ElurUiWorklet.register(specJson, container)
822
+ }
823
+
824
+ fun uiWorkletCancel(id: String) {
825
+ ElurUiWorklet.cancel(id, container)
826
+ }
827
+
828
+ fun uiWorkletSyncSignal(name: String, v: Double) {
829
+ ElurUiWorklet.syncSignal(name, v, container)
830
+ }
831
+
832
+ fun uiWorkletReset() {
833
+ ElurUiWorklet.reset(container)
834
+ }
835
+
836
+ fun supportsNativeList(): Boolean = false
837
+ fun supportsSkia(): Boolean = ElurSkiaCanvasView.isAvailable
838
+ fun supportsSkiaTree(): Boolean = isAvailable
839
+ /** ADR-0194 — backend del carril; este glue solo expone raster ANativeWindow. */
840
+ fun skiaBackend(): String = if (isAvailable) "raster" else ""
841
+ fun colorScheme(): String =
842
+ if ((container.resources.configuration.uiMode and
843
+ android.content.res.Configuration.UI_MODE_NIGHT_MASK) ==
844
+ android.content.res.Configuration.UI_MODE_NIGHT_YES
845
+ )
846
+ "dark"
847
+ else "light"
848
+
849
+ // ── ciclo de vida / stubs del contrato MainActivity ──────────────
850
+
851
+ override fun destroy() {
852
+ if (destroyed) return
853
+ destroyed = true
854
+ flingRunning = false
855
+ mainHandler.removeCallbacksAndMessages(null)
856
+ // ADR-0087: el contexto UI muere con la sesión (mismo teardown
857
+ // que views — los emits posteriores caen en el guard).
858
+ ElurUiWorklet.reset(container)
859
+ ElurUiWorklet.viewLookup = { null }
860
+ knownNodes.clear()
861
+ lastMeasures.clear()
862
+ pendingMeasures.clear()
863
+ nodeTypes.clear()
864
+ absorbedLeaf.clear()
865
+ zeroRetries.clear()
866
+ nativeShutdown()
867
+ }
868
+
869
+ override fun onConfigurationChanged() {
870
+ nativeSetFontScale(container.resources.configuration.fontScale)
871
+ nativeSetRtl(container.resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_RTL)
872
+ nativeInvalidate()
873
+ postRender()
874
+ }
875
+
876
+ override fun onEngineFailed() {}
877
+ override fun installYogaCountSampler() {}
878
+ override fun setInspectEnabled(on: Boolean) {}
879
+
880
+ // Edge-swipe back: mismos canales que views (__elur_swipe_*,
881
+ // ADR-0013) — la guarda navDepthLocal>=2 sustituye al "preview
882
+ // montado" del carril views (stack de 1 nunca commitea). El
883
+ // arrastre visual (translate top/prev) es fase posterior; el
884
+ // commit/cancel ya llega al reconciler igual.
885
+ private var swiping = false
886
+
887
+ override fun onSwipeBegin() {
888
+ if (swiping) return
889
+ swiping = true
890
+ bridge.callHandler("__elur_swipe_begin")
891
+ try {
892
+ bridge.flushPending()
893
+ } catch (e: Exception) {}
894
+ }
895
+
896
+ override fun onSwipeMove(dx: Float) {}
897
+
898
+ override fun swipeActive(): Boolean = swiping
899
+
900
+ override fun onSwipeEnd(dx: Float, vx: Float, cancelled: Boolean) {
901
+ if (!swiping) return
902
+ swiping = false
903
+ val w = container.width.toFloat().coerceAtLeast(1f)
904
+ val commit =
905
+ !cancelled && navDepthLocal >= 2 && (dx.coerceIn(0f, w) / w >= 0.33f || vx >= 300f)
906
+ bridge.callHandler(if (commit) "__elur_swipe_commit" else "__elur_swipe_cancel")
907
+ try {
908
+ bridge.flushPending()
909
+ } catch (e: Exception) {}
910
+ }
911
+ override fun onHotkey(event: android.view.KeyEvent, focus: View?): Boolean = false
912
+
913
+ private fun warnOnce(kind: String, what: String) {
914
+ if (warnedOps.add("$kind:$what")) {
915
+ Log.w(TAG, "[skia-tree] no soportado en este carril: $kind=$what")
916
+ }
917
+ }
918
+
919
+ // ── JNI ────────────────────────────────────────────────────────
920
+
921
+ private external fun nativeInit(density: Float)
922
+ private external fun nativeSetSurface(surface: android.view.Surface, w: Int, h: Int)
923
+ private external fun nativeReleaseSurface()
924
+ private external fun nativeCreateNode(id: Int, type: String)
925
+ private external fun nativeUpdateText(id: Int, value: String)
926
+ private external fun nativeUpdateStyle(
927
+ id: Int,
928
+ keys: Array<String>,
929
+ isNum: BooleanArray,
930
+ nums: DoubleArray,
931
+ strs: Array<String?>,
932
+ )
933
+ private external fun nativeSetProp(id: Int, key: String, flat: String)
934
+ private external fun nativeInsertChild(parent: Int, child: Int, index: Int)
935
+ private external fun nativeRemoveChild(parent: Int, child: Int)
936
+ private external fun nativeMoveChild(parent: Int, child: Int, index: Int)
937
+ private external fun nativeDeleteNode(id: Int)
938
+ private external fun nativeAttachEvent(
939
+ id: Int,
940
+ event: String,
941
+ handler: String,
942
+ continuous: Boolean,
943
+ payload: String?,
944
+ )
945
+ private external fun nativeDetachEvent(id: Int, event: String)
946
+ private external fun nativeResetNode(id: Int)
947
+ private external fun nativeLayout(id: Int, x: Float, y: Float, w: Float, h: Float)
948
+ private external fun nativeMeasure(id: Int, w: Float, wMode: Int, h: Float, hMode: Int): Long
949
+ private external fun nativeBaseline(id: Int, w: Float, h: Float): Float
950
+ private external fun nativeSetFontScale(s: Float)
951
+ private external fun nativeSetRtl(rtl: Boolean)
952
+ private external fun nativeSetFocused(id: Int)
953
+ private external fun nativeHitTest(x: Float, y: Float, event: String): Int
954
+ private external fun nativeNodeAt(x: Float, y: Float): Int
955
+ private external fun nativeScrollableAt(x: Float, y: Float): Int
956
+ private external fun nativeScrollBy(id: Int, dx: Float, dy: Float): Boolean
957
+ private external fun nativeScrollY(id: Int): Float
958
+ private external fun nativeNodeH(id: Int): Float
959
+ private external fun nativeMaxScrollY(id: Int): Float
960
+ private external fun nativeSwitchToggle(id: Int): Boolean
961
+ private external fun nativeSliderSetAt(id: Int, localX: Float): Float
962
+ private external fun nativeLocalX(id: Int, absX: Float): Float
963
+ private external fun nativeEventInfo(id: Int, event: String): String?
964
+ private external fun nativeNodeType(id: Int): String
965
+ private external fun nativeRender(): Boolean
966
+ private external fun nativeInvalidate()
967
+ private external fun nativeShutdown()
968
+ }