@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,69 @@
1
+ package com.elur.universal
2
+
3
+ import org.json.JSONObject
4
+
5
+ // Módulo nativo "state" (U21/ADR-0075): retiene el último snapshot de
6
+ // NavState emitido por JS (comando "save", fire-and-forget) y lo
7
+ // devuelve por "getRestore" cuando la activity se recrea tras muerte
8
+ // de proceso. La serialización es íntegramente JS (src/app/state.ts —
9
+ // el host nunca inspecciona el payload, solo lo almacena en el Bundle).
10
+ //
11
+ // Flujo: JS empuja {v,nav,app} tras cada commit de nav → MainActivity
12
+ // escribe lastSnapshot en onSaveInstanceState → tras force-stop el
13
+ // sistema recrea con savedInstanceState → el módulo nace ya sembrado
14
+ // con ese json → mount negocia getRestore antes del push inicial.
15
+ //
16
+ // Hot reload (dev, ADR-0111): un relaunch por devSeq/engine-flip con
17
+ // mismo asset siembra el snapshot vía el holder de proceso
18
+ // `pendingHotSnapshot` — finish()+startActivity no entrega
19
+ // savedInstanceState; la memoria del proceso sí sobrevive. El seed se
20
+ // consume una sola vez: un boot posterior sin el extra `hotReload` no
21
+ // lo ve.
22
+ class ElurStateModule(savedJson: String?) : ElurModule {
23
+ override val name = "state"
24
+
25
+ /** Último snapshot recibido — MainActivity lo vuelca a outState. */
26
+ var lastSnapshot: String? = null
27
+ private set
28
+
29
+ /** Snapshot rescatado del Bundle o del holder de hot reload — inmutable tras la recreación. */
30
+ private val restoreJson: String? = savedJson
31
+
32
+ companion object {
33
+ /**
34
+ * Snapshot en tránsito entre instancias de activity del mismo proceso — solo se
35
+ * siembra/consume en el relaunch dev con `hotReload=true`.
36
+ */
37
+ @Volatile var pendingHotSnapshot: String? = null
38
+
39
+ fun consumeHotSnapshot(): String? {
40
+ val s = pendingHotSnapshot
41
+ pendingHotSnapshot = null
42
+ return s
43
+ }
44
+ }
45
+
46
+ override fun onCommand(callId: Int, command: String, argsJson: String, reply: ModuleReply) {
47
+ when (command) {
48
+ // argsJson ya es el snapshot completo ({v,nav,app}) — se
49
+ // almacena tal cual, sin parsear campos.
50
+ "save" -> {
51
+ lastSnapshot = argsJson
52
+ android.util.Log.i("ElurState", "[state] save len=${argsJson.length}")
53
+ // §4.2.2: reply único por callId — aunque JS lo invoque
54
+ // fire-and-forget, una invocación sin respuesta deja el
55
+ // slot pending ocupado hasta reset (fuga de callIds).
56
+ reply.ok("{}")
57
+ }
58
+ "getRestore" -> {
59
+ android.util.Log.i("ElurState", "[state] getRestore has=${restoreJson != null}")
60
+ if (restoreJson != null) {
61
+ reply.ok(JSONObject().put("snapshot", JSONObject(restoreJson)).toString())
62
+ } else {
63
+ reply.ok(JSONObject().put("snapshot", JSONObject.NULL).toString())
64
+ }
65
+ }
66
+ else -> reply.err("unknown_command", "comando desconocido: $command")
67
+ }
68
+ }
69
+ }
@@ -0,0 +1,34 @@
1
+ // ElurSwipeDriver.kt — costura del swipe-back edge entre ElurShellView
2
+ // y el renderer activo. Lo implementan ElurRenderer (Platform Views,
3
+ // default) y ElurSkiaTreeRenderer (surface "custom" opt-in) — la shell
4
+ // no conoce qué carril pinta debajo.
5
+ package com.elur.universal
6
+
7
+ interface ElurSwipeDriver {
8
+ fun onSwipeBegin()
9
+ fun onSwipeMove(dx: Float)
10
+ fun swipeActive(): Boolean
11
+ /** `cancelled=true` = cancelación gestual (volver al estado previo). */
12
+ fun onSwipeEnd(dx: Float, velocityX: Float, cancelled: Boolean)
13
+ }
14
+
15
+ /**
16
+ * Superficie pública que MainActivity consume del renderer activo — la implementan ElurRenderer
17
+ * (Platform Views, default) y ElurSkiaTreeRenderer (surface "custom" opt-in). La selección es de
18
+ * arranque (extra `surface` / manifiesto) — nunca en caliente.
19
+ */
20
+ interface ElurHostRenderer : ElurSwipeDriver {
21
+ var onNavDepthChanged: ((Int) -> Unit)?
22
+ var onBackInterceptChanged: ((Boolean) -> Unit)?
23
+ var onFirstApply: (() -> Unit)?
24
+ var nativeListEnabled: Boolean
25
+ var cesmEnabled: Boolean
26
+ fun registerModule(module: ElurModule)
27
+ fun measureNodeInWindow(id: Int): FloatArray? = null
28
+ fun onEngineFailed()
29
+ fun installYogaCountSampler()
30
+ fun setInspectEnabled(on: Boolean)
31
+ fun onConfigurationChanged()
32
+ fun onHotkey(event: android.view.KeyEvent, focus: android.view.View?): Boolean
33
+ fun destroy()
34
+ }
@@ -0,0 +1,99 @@
1
+ package com.elur.universal
2
+
3
+ import java.util.concurrent.ConcurrentHashMap
4
+ import org.json.JSONObject
5
+
6
+ // Carril TCK-módulos (spec §18, ADR-0095): impl host conforme del
7
+ // módulo de contrato "elur.tck". Espejo semántico de
8
+ // src/native/tck.ts#createTckModuleImpl — mismo wire, mismos errores,
9
+ // mismo ciclo de vida de handles. Un host es module-capable si
10
+ // runModuleTck(runtime) pasa contra esta clase registrada.
11
+ //
12
+ // Ejercita el contrato completo:
13
+ // echo — request/response main
14
+ // slow — worker + cancel cooperativo (nunca responde solo)
15
+ // fail — propagación del vocabulario canónico de errores
16
+ // emitTick — evento discrete
17
+ // emitFrame — evento continuous con coalesceKey (colapsa a último)
18
+ // probe/* — host object con estado nativo + handle_invalid
19
+ // tck-perm — permission.request estándar vía permissionRequester
20
+ class ElurTckModule : ElurModule, ElurEventSource {
21
+ override val name = "elur.tck"
22
+ override val permissions =
23
+ mapOf(
24
+ "tck-perm" to "android.permission.POST_NOTIFICATIONS",
25
+ )
26
+
27
+ private var emit: ((String, String, String?) -> Unit)? = null
28
+ private val probes = HandleTable()
29
+ private val pendings = ConcurrentHashMap<Int, ModuleReply>()
30
+ @Volatile private var probeN = 0
31
+
32
+ override fun attach(e: (String, String, String?) -> Unit) {
33
+ emit = e
34
+ }
35
+
36
+ override fun threading(command: String): String = if (command == "slow") "worker" else "main"
37
+
38
+ override fun onCommand(
39
+ callId: Int,
40
+ command: String,
41
+ argsJson: String,
42
+ reply: ModuleReply,
43
+ ) {
44
+ val args =
45
+ try {
46
+ JSONObject(argsJson)
47
+ } catch (t: Throwable) {
48
+ JSONObject()
49
+ }
50
+ when (command) {
51
+ "echo" -> reply.ok(JSONObject().put("pong", args.optString("msg")).toString())
52
+ "slow" -> pendings[callId] = reply
53
+ "fail" -> reply.err(args.optString("code").ifEmpty { "internal" }, "tck fail")
54
+ "emitTick" -> {
55
+ emit?.invoke("tick", "{\"v\":${args.optDouble("v")}}", null)
56
+ reply.ok("{}")
57
+ }
58
+ "emitFrame" -> {
59
+ emit?.invoke(
60
+ "frame",
61
+ "{\"v\":${args.optDouble("v")}}",
62
+ "$name:frame",
63
+ )
64
+ reply.ok("{}")
65
+ }
66
+ "probe/create" -> {
67
+ val id = probes.create(JSONObject())
68
+ reply.ok(JSONObject().put("handleId", id).put("n", probeN).toString())
69
+ }
70
+ "probe/bump" -> {
71
+ val hid = args.optString("handleId")
72
+ if (probes.get(hid) == null) {
73
+ reply.err("unavailable", "handle_invalid")
74
+ } else {
75
+ probeN++
76
+ reply.ok(JSONObject().put("n", probeN).toString())
77
+ }
78
+ }
79
+ "release" -> {
80
+ probes.release(args.optString("handleId"))
81
+ reply.ok("{}")
82
+ }
83
+ else -> reply.err("unknown_command", command)
84
+ }
85
+ }
86
+
87
+ override fun onCancel(callId: Int) {
88
+ pendings.remove(callId)?.err("cancelled", "tck cancel")
89
+ }
90
+
91
+ override fun onSessionEnd() {
92
+ probes.releaseAll()
93
+ probeN = 0
94
+ for ((_, reply) in pendings) {
95
+ reply.err("session_reset", "fin de epoch")
96
+ }
97
+ pendings.clear()
98
+ }
99
+ }
@@ -0,0 +1,16 @@
1
+ package com.elur.universal
2
+
3
+ /**
4
+ * ADR-0116: resolución de medida de hojas de texto — la matemática es pura y JVM-testeable;
5
+ * el cálculo de `desired*` (PrecomputedTextCompat + StaticLayout) vive en ElurRenderer.
6
+ * `wMode`/`hMode` usan los códigos de YGMeasureMode: 0=Unspecified, 1=Exactly, 2=AtMost.
7
+ */
8
+ internal fun resolveMeasureSize(desired: Int, spec: Float, mode: Int): Int =
9
+ when (mode) {
10
+ 1 -> spec.toInt().coerceAtLeast(0)
11
+ 2 -> minOf(desired, spec.toInt().coerceAtLeast(0))
12
+ else -> desired
13
+ }
14
+
15
+ internal fun packMeasuredSize(width: Int, height: Int): Long =
16
+ (width.toLong() shl 32) or (height.toLong() and 0xffffffffL)
@@ -0,0 +1,24 @@
1
+ package com.elur.universal
2
+
3
+ /**
4
+ * Flag de traza on-device — extra `trace` del intent (verificación DoD: un tap físico debe ser
5
+ * trazable de extremo a extremo: touch → click → handler JS → commit → adapter). Apagada no emite
6
+ * nada; encendida emite líneas `[trace]` por hop en logcat y el volcado `[rect]` tras cada commit
7
+ * aplicado (paridad geométrica, docs §3.16).
8
+ */
9
+ object ElurTrace {
10
+ @JvmField var enabled = false
11
+
12
+ /**
13
+ * Reloj determinista para la paridad geométrica — extra `now` del intent (`-e now <ms>`).
14
+ * Expuesto a JS como `ElurBridge.debugNow()`; `clock()` lo consulta en nowMs(). `-1` = reloj
15
+ * real.
16
+ */
17
+ @JvmField var debugNowMs: Long = -1
18
+
19
+ /**
20
+ * Aviso strict de scroll-view (docs §3.16): ids ya reportados para no repetir el Log.w en cada
21
+ * layout.
22
+ */
23
+ @JvmField val scrollWarned = java.util.HashSet<Int>()
24
+ }
@@ -0,0 +1,48 @@
1
+ package com.elur.universal
2
+
3
+ import org.json.JSONObject
4
+
5
+ /**
6
+ * Módulo builtin "ui" (ADR-0200 / ADR-0202):
7
+ * - `measureInWindow { id }` → `{ x, y, width, height }` en unidades lógicas
8
+ * - `setBackIntercept { active }` → `{}` (habilita `OnBackPressedCallback` en la ruta raíz)
9
+ *
10
+ * Ambos comandos corren en el hilo `main` (UI), garantizando orden FIFO tras cualquier
11
+ * `applyDisplayList` previamente encolado.
12
+ */
13
+ class ElurUiModule(private val renderer: ElurHostRenderer) : ElurModule {
14
+ override val name = "ui"
15
+
16
+ override fun threading(command: String): String = "main"
17
+
18
+ override fun onSessionEnd() {
19
+ renderer.onBackInterceptChanged?.invoke(false)
20
+ }
21
+
22
+ override fun onCommand(callId: Int, command: String, argsJson: String, reply: ModuleReply) {
23
+ val args = runCatching { JSONObject(argsJson) }.getOrNull() ?: JSONObject()
24
+ when (command) {
25
+ "setBackIntercept" -> {
26
+ renderer.onBackInterceptChanged?.invoke(args.optBoolean("active", false))
27
+ reply.ok("{}")
28
+ }
29
+ "measureInWindow" -> {
30
+ val id = args.optInt("id", 0)
31
+ val rect = if (id > 0) renderer.measureNodeInWindow(id) else null
32
+ if (rect != null && rect.size >= 4) {
33
+ reply.ok(
34
+ JSONObject()
35
+ .put("x", rect[0].toDouble())
36
+ .put("y", rect[1].toDouble())
37
+ .put("width", rect[2].toDouble())
38
+ .put("height", rect[3].toDouble())
39
+ .toString()
40
+ )
41
+ } else {
42
+ reply.ok("{\"x\":0,\"y\":0,\"width\":0,\"height\":0}")
43
+ }
44
+ }
45
+ else -> reply.err("unknown_command", "comando desconocido: $command")
46
+ }
47
+ }
48
+ }
@@ -0,0 +1,305 @@
1
+ package com.elur.universal
2
+
3
+ import android.annotation.SuppressLint
4
+ import android.view.Choreographer
5
+ import android.view.View
6
+ import org.json.JSONObject
7
+
8
+ /**
9
+ * UIThreadRunner host-side (ADR-0087): segundo contexto JS en el hilo de UI — los worklets
10
+ * re-evaluados corren en el Choreographer del propio hilo sin tocar el JsThread principal.
11
+ * Señal→View por el mapa `binds` del spec: cada write del worklet muta la propiedad compositor
12
+ * directa (alpha/translationX/Y/scaleX/Y/rotation — subconjunto del vocabulario que no pasa por
13
+ * Yoga).
14
+ *
15
+ * Ciclo de vida: register/cancel/syncSignal postean al hilo UI (son llamados desde JsThread); el
16
+ * frame callback se auto-postea mientras el contexto UI tenga worklets vivos (idle = cero coste).
17
+ * Los resultados "done|cancelled" vuelven a JS por postToJs del renderer (__elur_uiwk). reset()
18
+ * cierra todo — teardown de sesión.
19
+ */
20
+ object ElurUiWorklet {
21
+
22
+ var viewLookup: (Int) -> View? = { null }
23
+ var postToJs: (handler: String, payload: String) -> Unit = { _, _ -> }
24
+ var density: Float = 1f
25
+
26
+ // ADR-0087 §cesm — resolución de región workletSafe → Region* la hace
27
+ // el bridge del motor activo (lo cablea el renderer en attach). 0 =
28
+ // canal off / región inexistente / no workletSafe → lecturas neutras.
29
+ var cesmAttach: (name: String) -> Long = { 0 }
30
+ var cesmDetach: (name: String) -> Unit = {}
31
+ /** Regiones con attach vivo — para detach en reset (vida = sesión). */
32
+ private val cesmAttached = mutableSetOf<String>()
33
+
34
+ /** specId → viewId con canal drag adjunto — para detach en cancel/reset. */
35
+ private val dragViews = HashMap<String, Int>()
36
+
37
+ // ADR-0087 §bind — listas con row-worklets vivos (gate Kotlin: bindRow
38
+ // sale sin JNI si la lista no tiene worklet — el bind es el hot-path
39
+ // más caliente del sistema). specId → listId para retirar en cancel.
40
+ private val bindLists = mutableSetOf<Int>()
41
+ private val bindBySpec = HashMap<String, Int>()
42
+
43
+ /** {"ok":bool} — eval de src fallida → cancelled inmediato. */
44
+ external fun nativeRegister(specJson: String): String
45
+ /** Finals del punto de corte ({id,finals}) — null si el id no existía. */
46
+ external fun nativeCancel(id: String): String
47
+ /** true si el set marcó scroll-worklets dirty — el llamador debe postear frame. */
48
+ external fun nativeSetSignal(name: String, v: Double): Boolean
49
+ external fun nativeReset()
50
+ /** {"finished":[{id,finals}], "cancelled":[{id,finals}]} */
51
+ external fun nativeTick(nowMs: Double): String
52
+ external fun nativeHasActive(): Boolean
53
+ /** {"finished":[],"cancelled":[{id,finals}]} — eval síncrono de kind:"bind". */
54
+ external fun nativeBindRow(listId: Int, rowView: View, pos: Double): String
55
+ /** Registra nombre → Region* en el contexto UI (0 = no adjuntar). */
56
+ external fun nativeCesmBind(name: String, addr: Long)
57
+
58
+ fun attach(lookup: (Int) -> View?, post: (String, String) -> Unit) {
59
+ viewLookup = lookup
60
+ postToJs = post
61
+ }
62
+
63
+ /** Desde JsThread (ElurBridge.uiWorkletStart) — cola al hilo UI. */
64
+ fun register(specJson: String, container: View) {
65
+ container.post {
66
+ val res = JSONObject(nativeRegister(specJson))
67
+ if (res.optBoolean("ok")) {
68
+ val spec = JSONObject(specJson)
69
+ // ADR-0087 §cesm — las regiones del spec se resuelven a
70
+ // Region* y se registran en el contexto (una vez por
71
+ // nombre; compartidas entre worklets de la sesión).
72
+ spec.optJSONObject("cesm")?.let { cm ->
73
+ for (alias in cm.keys()) {
74
+ val rn = cm.getString(alias)
75
+ if (rn !in cesmAttached) {
76
+ nativeCesmBind(rn, cesmAttach(rn))
77
+ cesmAttached.add(rn)
78
+ }
79
+ }
80
+ }
81
+ if (spec.optString("kind") == "bind") {
82
+ val l = spec.getInt("list")
83
+ bindLists.add(l)
84
+ bindBySpec[spec.getString("id")] = l
85
+ }
86
+ val d = spec.optInt("drag", -1)
87
+ if (d >= 0) {
88
+ attachDrag(d, container)
89
+ dragViews[spec.getString("id")] = d
90
+ }
91
+ postFrame()
92
+ } else {
93
+ emit(JSONObject(specJson).optString("id"), "cancelled", null)
94
+ }
95
+ }
96
+ }
97
+
98
+ fun cancel(id: String, container: View) {
99
+ container.post {
100
+ val dv = dragViews.remove(id)
101
+ if (dv != null) detachDrag(dv)
102
+ val bl = bindBySpec.remove(id)
103
+ if (bl != null && !bindBySpec.values.contains(bl)) bindLists.remove(bl)
104
+ val res = JSONObject(nativeCancel(id))
105
+ emit(
106
+ id,
107
+ "cancelled",
108
+ if (res.isNull("finals")) null else res.optJSONObject("finals"),
109
+ )
110
+ }
111
+ }
112
+
113
+ /** Sync main→UI del valor de signal fuera del ciclo del worklet. */
114
+ fun syncSignal(name: String, v: Double, container: View) {
115
+ container.post { if (nativeSetSignal(name, v)) postFrame() }
116
+ }
117
+
118
+ /**
119
+ * Feed scroll-driven (ADR-0087 §scroll): el RecyclerView reporta su offset al signal
120
+ * `__scroll_<listId>` del contexto UI. SOLO desde el hilo UI (onScrolled ya corre ahí — postear
121
+ * colaría el evento un frame tarde). Si el set marcó scroll-worklets dirty se agenda el frame
122
+ * que los re-evalúa; sin subs es un map-set barato (no-op funcional).
123
+ */
124
+ fun setSignalNow(name: String, v: Double) {
125
+ if (nativeSetSignal(name, v)) postFrame()
126
+ }
127
+
128
+ fun reset(container: View) {
129
+ container.post {
130
+ nativeReset()
131
+ for (v in dragViews.values) detachDrag(v)
132
+ dragViews.clear()
133
+ bindLists.clear()
134
+ bindBySpec.clear()
135
+ for (rn in cesmAttached) cesmDetach(rn)
136
+ cesmAttached.clear()
137
+ }
138
+ }
139
+
140
+ /**
141
+ * ADR-0087 §bind — desde ElurListView.onBindViewHolder (ya corre en el hilo UI): los
142
+ * kind:"bind" de esta lista evalúan síncrono con el proxy `row` escribiendo sobre este
143
+ * itemView, antes de su primer dibujo.
144
+ */
145
+ fun bindRow(listId: Int, rowView: View, pos: Int) {
146
+ if (listId !in bindLists) return
147
+ // El eval arranca de identidad compositor — la fila reciclada no
148
+ // arrastra el transform que el worklet escribió en el bind previo.
149
+ rowView.alpha = 1f
150
+ rowView.translationX = 0f
151
+ rowView.translationY = 0f
152
+ rowView.scaleX = 1f
153
+ rowView.scaleY = 1f
154
+ rowView.rotation = 0f
155
+ drain(JSONObject(nativeBindRow(listId, rowView, pos.toDouble())), "cancelled", "cancelled")
156
+ }
157
+
158
+ /**
159
+ * Canal táctil de kind:"drag" (ADR-0087 §gestures + ADR-0089): el listener alimenta
160
+ * `__drag_<viewId>_dx|_dy|_p|_vx|_vy` en unidades lógicas — delta desde el DOWN, fase
161
+ * 1=down/2=move/0=up|cancel y velocidad de suelta en lógicas/s (VelocityTracker, 0 en
162
+ * DOWN/MOVE). Datos antes que p: el tick siempre lee un snapshot consistente. El listener
163
+ * consume el gesto (true): en v1 el canal drag es dueño del toque sobre ese view — click queda
164
+ * vedado por diseño.
165
+ */
166
+ private fun attachDrag(viewId: Int, container: View, tries: Int = 0) {
167
+ val view = viewLookup(viewId)
168
+ if (view == null) {
169
+ // El create-node del mismo commit puede aplicarse después de este
170
+ // post — reintenta unos frames antes de rendirse.
171
+ if (tries < 5) container.postDelayed({ attachDrag(viewId, container, tries + 1) }, 16)
172
+ else android.util.Log.w("elur-uiwk", "attachDrag: viewId=$viewId no resuelto")
173
+ return
174
+ }
175
+ var downX = 0f
176
+ var downY = 0f
177
+ var vel: android.view.VelocityTracker? = null
178
+ @SuppressLint("ClickableViewAccessibility")
179
+ view.setOnTouchListener { _, ev ->
180
+ when (ev.actionMasked) {
181
+ android.view.MotionEvent.ACTION_DOWN -> {
182
+ downX = ev.rawX
183
+ downY = ev.rawY
184
+ vel?.recycle()
185
+ vel = android.view.VelocityTracker.obtain().apply { addMovement(ev) }
186
+ feedDrag(viewId, 0.0, 0.0, 1.0, 0.0, 0.0)
187
+ // Eval síncrono de la fase down: si el primer MOVE
188
+ // coalesciera en el mismo frame el worklet perdería
189
+ // el evento de ancla del gesto (ADR-0087 §gestures).
190
+ tick(System.nanoTime() / 1_000_000.0)
191
+ }
192
+ android.view.MotionEvent.ACTION_MOVE -> {
193
+ vel?.addMovement(ev)
194
+ feedDrag(
195
+ viewId,
196
+ ((ev.rawX - downX) / density).toDouble(),
197
+ ((ev.rawY - downY) / density).toDouble(),
198
+ 2.0,
199
+ 0.0,
200
+ 0.0,
201
+ )
202
+ }
203
+ android.view.MotionEvent.ACTION_UP, android.view.MotionEvent.ACTION_CANCEL -> {
204
+ // ADR-0089 §gestures — la velocidad de suelta la
205
+ // decide el worklet (fling → dismiss/snap-back), no
206
+ // el host: VelocityTracker da px/s y viaja en
207
+ // unidades lógicas como el resto del canal.
208
+ val t = vel
209
+ var vx = 0.0
210
+ var vy = 0.0
211
+ if (t != null) {
212
+ t.addMovement(ev)
213
+ t.computeCurrentVelocity(1000)
214
+ vx = (t.xVelocity / density).toDouble()
215
+ vy = (t.yVelocity / density).toDouble()
216
+ t.recycle()
217
+ vel = null
218
+ }
219
+ feedDrag(
220
+ viewId,
221
+ ((ev.rawX - downX) / density).toDouble(),
222
+ ((ev.rawY - downY) / density).toDouble(),
223
+ 0.0,
224
+ vx,
225
+ vy,
226
+ )
227
+ }
228
+ }
229
+ true
230
+ }
231
+ }
232
+
233
+ private fun detachDrag(viewId: Int) {
234
+ viewLookup(viewId)?.setOnTouchListener(null)
235
+ }
236
+
237
+ private fun feedDrag(viewId: Int, dx: Double, dy: Double, p: Double, vx: Double, vy: Double) {
238
+ val base = "__drag_${viewId}_"
239
+ setSignalNow(base + "dx", dx)
240
+ setSignalNow(base + "dy", dy)
241
+ setSignalNow(base + "vx", vx)
242
+ setSignalNow(base + "vy", vy)
243
+ setSignalNow(base + "p", p)
244
+ }
245
+
246
+ private var framePosted = false
247
+ private fun postFrame() {
248
+ if (framePosted) return
249
+ framePosted = true
250
+ Choreographer.getInstance().postFrameCallback { nowNs ->
251
+ framePosted = false
252
+ tick(nowNs / 1_000_000.0)
253
+ }
254
+ }
255
+
256
+ private fun tick(nowMs: Double) {
257
+ val res = JSONObject(nativeTick(nowMs))
258
+ drain(res, "finished", "done")
259
+ drain(res, "cancelled", "cancelled")
260
+ if (nativeHasActive()) postFrame()
261
+ }
262
+
263
+ private fun drain(res: JSONObject, field: String, status: String) {
264
+ val arr = res.optJSONArray(field) ?: return
265
+ for (i in 0 until arr.length()) {
266
+ val e = arr.optJSONObject(i) ?: continue
267
+ emit(e.optString("id"), status, e.optJSONObject("finals"))
268
+ }
269
+ }
270
+
271
+ private fun emit(id: String, status: String, finals: JSONObject?) {
272
+ val p = JSONObject().put("id", id).put("status", status)
273
+ if (finals != null) p.put("finals", finals)
274
+ postToJs("__elur_uiwk", p.toString())
275
+ }
276
+
277
+ /**
278
+ * Write compositor — invocado desde C++ (UI thread) por cada binding de un write de signal del
279
+ * worklet. Whitelist del vocabulario (ADR-0024): sin Yoga, sin bridge — la propiedad de View
280
+ * directa. translate* llega en unidades lógicas (px = lógico × density).
281
+ */
282
+ @JvmStatic
283
+ fun applyProp(viewId: Int, key: String, value: Double) {
284
+ val view = viewLookup(viewId) ?: return
285
+ applyPropOn(view, key, value)
286
+ }
287
+
288
+ /**
289
+ * ADR-0087 §bind — mismo mapa compositor que applyProp pero sobre un View directo: el itemView
290
+ * siendo bindeado por un row-worklet kind:"bind", que no tiene viewId propio en el renderer.
291
+ */
292
+ @JvmStatic
293
+ fun applyPropOn(view: View, key: String, value: Double) {
294
+ val px = (value * density).toFloat()
295
+ val v = value.toFloat()
296
+ when (key) {
297
+ "opacity" -> view.alpha = v
298
+ "translateX" -> view.translationX = px
299
+ "translateY" -> view.translationY = px
300
+ "scaleX" -> view.scaleX = v
301
+ "scaleY" -> view.scaleY = v
302
+ "rotate" -> view.rotation = v
303
+ }
304
+ }
305
+ }
@@ -0,0 +1,67 @@
1
+ package com.elur.universal
2
+
3
+ interface JsBridge {
4
+ fun callHandler(name: String)
5
+ fun callHandlerWithString(name: String, value: String)
6
+ /**
7
+ * Variante latest-wins para eventos continuos (onScroll, seek): entregas pendientes con la
8
+ * misma clave se coalescen — ver JsThread. `coalesceKey` discrimina por identidad del origen
9
+ * (nodo/item): sin ella dos scroll-views o dos filas con el mismo handler continuo se
10
+ * sobrescriben (U08).
11
+ */
12
+ fun callHandlerWithStringCoalesced(name: String, value: String, coalesceKey: String = name)
13
+ fun flushPending()
14
+ /** P1-TREE: viewport del container en px reales + density (árbol Yoga en C++). */
15
+ fun setViewport(w: Float, h: Float, density: Float, rtl: Boolean)
16
+ /**
17
+ * Re-medida post-apply: el contenido de update-text/update-props aterriza en la View después
18
+ * del layout del batch; sin este aviso la hoja conserva la medida vacía cacheada. Corre en el
19
+ * hilo JS (post interno). R4.4: `reqSeq` liga la respuesta al request — el frame de layout sale
20
+ * con id `-reqSeq` y el renderer descarta respuestas superadas por un request más nuevo.
21
+ */
22
+ fun requestLeafRemeasure(ids: IntArray, reqSeq: Int)
23
+
24
+ /**
25
+ * ADR-0112: conteo real del árbol Yoga nativo (g_nodes). La lectura es JsThread-confined — esta
26
+ * API postea la lectura y entrega el valor por callback en main. -1 si el engine no lo
27
+ * implementa.
28
+ */
29
+ fun yogaNodeCount(cb: (Int) -> Unit) {
30
+ cb(-1)
31
+ }
32
+
33
+ /**
34
+ * ADR-0112: bytes del heap JS (QuickJS `JS_ComputeMemoryUsage` / Hermes
35
+ * `instrumentation().getHeapInfo`). Misma disciplina: lectura JsThread-confined, callback en
36
+ * main. -1 si el engine no lo expone.
37
+ */
38
+ fun jsHeapBytes(cb: (Long) -> Unit) {
39
+ cb(-1)
40
+ }
41
+
42
+ // CESM (ADR-0055): opt-in del host + regiones por nombre. El write
43
+ // es directo (no postea — llamarlo desde el hilo productor).
44
+ fun cesmSetEnabled(enabled: Boolean)
45
+ fun cesmCreateRegion(name: String, byteLength: Long, workletSafe: Boolean): Long
46
+ fun cesmWrite(handle: Long, values: DoubleArray): Boolean
47
+ /**
48
+ * ADR-0105 — región `mode:"ring"`: buffer circular de bytes SPSC (producer/consumer por nombre;
49
+ * JS adjunta y ve ringWrite/ringRead). `cesmRingWrite` devuelve los bytes que entraron (0 =
50
+ * lleno; backpressure explícito — nunca se descartan bytes sin leer).
51
+ */
52
+ fun cesmCreateRing(name: String, byteLength: Long, workletSafe: Boolean): Long = 0
53
+ fun cesmRingWrite(handle: Long, bytes: ByteArray): Long = 0
54
+ fun cesmRingRead(handle: Long, n: Int): ByteArray? = null
55
+ /** ADR-0106 — codec binario: ops por nombre (attach efímero host-side). */
56
+ fun cesmRingWriteByName(name: String, bytes: ByteArray): Long = 0
57
+ fun cesmRingReadByName(name: String, n: Int): ByteArray? = null
58
+ fun cesmRelease(handle: Long): Boolean
59
+ /**
60
+ * ADR-0087 §cesm — attach de una región workletSafe para lectura seqlock desde el contexto UI
61
+ * de worklets. Devuelve el Region* raw (0 si el canal está off, la región no existe o no es
62
+ * workletSafe). El bridge retiene la región hasta cesmDetachUi — vida del attach = sesión UI.
63
+ */
64
+ fun cesmAttachUi(name: String): Long = 0
65
+ /** Libera la retención de un attach UI previo. */
66
+ fun cesmDetachUi(name: String) {}
67
+ }