@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,1060 @@
1
+ // elurYoga.cpp — árbol Yoga único en C++ (P1-TREE)
2
+ // Reemplaza el árbol Yoga Java de ElurRenderer: un YGNodeRef por id,
3
+ // medición de hojas via JNI a Kotlin (view.measure), layout fuera del
4
+ // UI thread. Emite ops `layout` (ABI 17) — Kotlin las aplica como
5
+ // LayoutParams absolutos; el path Skia los consumirá directo nativo.
6
+
7
+ #include "elurYoga.h"
8
+ #include "yoga/Yoga.h"
9
+ #include <android/log.h>
10
+ #include <array>
11
+ #include <cmath>
12
+ #include <layout/elur_layout_style.h>
13
+ #include <unordered_map>
14
+ #include <vector>
15
+
16
+ #define LOG_TAG "elur-yoga"
17
+ #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
18
+
19
+ namespace elur {
20
+
21
+ namespace {
22
+
23
+ struct Entry {
24
+ YGNodeRef node;
25
+ std::string type;
26
+ // Último layout emitido por wire — el DFS re-corre el árbol entero
27
+ // cada frame dirty; sin este cache cada flush enviaría ~N ops layout
28
+ // (medido: ~30ms/flush con ~2700 nodos, stress 2026-09-11). Emitir
29
+ // solo el delta → O(cambio) en vez de O(árbol).
30
+ bool emitted = false;
31
+ float lastL = 0, lastT = 0, lastW = -1, lastH = -1;
32
+ // ADR-0122: nodo con delegado de layout — sus dims auto las fija el
33
+ // delegado y los rects de sus hijos llegan vía g_customRects.
34
+ bool custom = false;
35
+ };
36
+
37
+ std::unordered_map<int, Entry> g_nodes;
38
+ YGNodeRef g_root = nullptr;
39
+ YGConfigRef g_config = nullptr;
40
+ JavaVM *g_jvm = nullptr;
41
+ jobject g_renderer = nullptr;
42
+ jmethodID g_measureMid = nullptr;
43
+ jmethodID g_baselineMid = nullptr;
44
+ jmethodID g_deferMid = nullptr;
45
+ jmethodID g_drainMid = nullptr;
46
+ jmethodID g_customMeasureMid = nullptr;
47
+ jmethodID g_customLayoutMid = nullptr;
48
+ float g_vpW = 0, g_vpH = 0, g_density = 1;
49
+ // Dirección ambiente del layout (force_rtl / locale RTL). Los nodos con
50
+ // direction:Inherit la heredan desde el root — ADR-0118, mismo rol que
51
+ // dir=rtl en <html> en web.
52
+ YGDirection g_direction = YGDirectionLTR;
53
+ bool g_dirty = false;
54
+ bool g_hasViewport = false;
55
+ // Hijos text absorbidos por un button (caso label): su nodo queda
56
+ // huérfano del árbol — el button es la hoja real que mide. Redirige
57
+ // update-text del hijo → dirty del button.
58
+ std::unordered_map<int, int> g_absorbedByButton;
59
+
60
+ // ADR-0122: rects delegados [l,t,w,h] en unidades lógicas — hijos
61
+ // directos de nodos `custom` (su posición la decide el delegado, no
62
+ // Yoga). Se reconstruye en cada pasada de layout antes de emitir.
63
+ std::unordered_map<int, std::array<float, 4>> g_customRects;
64
+
65
+ // ── ADR-0121: árboles Yoga de fila (ElurListView) ───────────────────
66
+ // Un árbol por view-holder: la plantilla se registra al inflar y los
67
+ // binds de estilo parchean el mismo nodo. El contexto del nodo marca
68
+ // fila con el bit 62 para que measureLeaf enrute a measureRowNode en
69
+ // vez de al renderer principal.
70
+ constexpr int64_t ROW_CTX_MARK = 1LL << 62;
71
+
72
+ struct RowTree {
73
+ YGNodeRef root;
74
+ std::unordered_map<int, YGNodeRef> nodes;
75
+ };
76
+ std::unordered_map<int, RowTree> g_rowTrees;
77
+ int g_nextRowTreeId = 1;
78
+ jobject g_rowYoga = nullptr; // singleton ElurRowYoga (global ref)
79
+ jmethodID g_rowMeasureMid = nullptr;
80
+
81
+ int64_t rowCtx(int treeId, int key) {
82
+ return ROW_CTX_MARK | ((int64_t)(treeId & 0x3fffffff) << 32) | (uint32_t)key;
83
+ }
84
+
85
+ bool isRowContainer(const std::string &type) {
86
+ return type == "row" || type == "column" || type == "list";
87
+ }
88
+
89
+ JNIEnv *getEnv(bool &attached) {
90
+ attached = false;
91
+ JNIEnv *env = nullptr;
92
+ if (g_jvm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) !=
93
+ JNI_OK) {
94
+ g_jvm->AttachCurrentThread(&env, nullptr);
95
+ attached = true;
96
+ }
97
+ return env;
98
+ }
99
+
100
+ // Medida de hojas de fila (contexto marcado ROW_CTX_MARK): delega en
101
+ // ElurRowYoga.measureRowNode(treeId, key, w, wMode, h, hMode) — la View
102
+ // reciclada real se mide en el mismo thread que CalculateLayout (UI).
103
+ bool rowMeasure(int64_t ctx, float w, YGMeasureMode wMode, float h,
104
+ YGMeasureMode hMode, YGSize &out) {
105
+ if (!g_rowYoga || !g_rowMeasureMid)
106
+ return false;
107
+ int treeId = static_cast<int>((ctx >> 32) & 0x3fffffff);
108
+ int key = static_cast<int>(static_cast<uint32_t>(ctx & 0xffffffff));
109
+ bool attached;
110
+ JNIEnv *env = getEnv(attached);
111
+ jlong packed = env->CallLongMethod(g_rowYoga, g_rowMeasureMid, treeId, key,
112
+ w * g_density, static_cast<jint>(wMode),
113
+ h * g_density, static_cast<jint>(hMode));
114
+ if (env->ExceptionCheck()) {
115
+ env->ExceptionClear();
116
+ if (attached)
117
+ g_jvm->DetachCurrentThread();
118
+ return false;
119
+ }
120
+ if (attached)
121
+ g_jvm->DetachCurrentThread();
122
+ out.width =
123
+ static_cast<float>(static_cast<int32_t>(packed >> 32)) / g_density;
124
+ out.height = static_cast<float>(static_cast<int32_t>(packed & 0xffffffffLL)) /
125
+ g_density;
126
+ return true;
127
+ }
128
+
129
+ // MeasureFunc de hojas → Kotlin measureNode(id, w, wMode, h, hMode) → long
130
+ // (width<<32 | height en bits de int). Corre en el hilo JS durante
131
+ // calculateLayout — view.measure() no exige UI thread.
132
+ // Yoga 3.x (ADR-0110): el callback recibe YGNodeConstRef.
133
+ YGSize measureLeaf(YGNodeConstRef node, float w, YGMeasureMode wMode, float h,
134
+ YGMeasureMode hMode) {
135
+ int64_t ctx =
136
+ static_cast<int64_t>(reinterpret_cast<intptr_t>(YGNodeGetContext(node)));
137
+ if (ctx == 0)
138
+ return {0, 0};
139
+ // ADR-0121: hojas de árbol de fila — su contexto va marcado y mide la
140
+ // View reciclada real vía ElurRowYoga.measureRowNode.
141
+ if (ctx & ROW_CTX_MARK) {
142
+ YGSize out{0, 0};
143
+ rowMeasure(ctx, w, wMode, h, hMode, out);
144
+ return out;
145
+ }
146
+ if (!g_renderer || !g_measureMid)
147
+ return {0, 0};
148
+ int id = static_cast<int>(ctx);
149
+
150
+ bool attached;
151
+ JNIEnv *env = getEnv(attached);
152
+ // ADR-0120: el contrato JNI de medida sigue en px (Android mide px);
153
+ // el árbol corre en unidades lógicas — conversión en el borde.
154
+ jlong packed = env->CallLongMethod(g_renderer, g_measureMid, id,
155
+ w * g_density, static_cast<jint>(wMode),
156
+ h * g_density, static_cast<jint>(hMode));
157
+ if (env->ExceptionCheck()) {
158
+ env->ExceptionClear();
159
+ if (attached)
160
+ g_jvm->DetachCurrentThread();
161
+ return {0, 0};
162
+ }
163
+ if (attached)
164
+ g_jvm->DetachCurrentThread();
165
+ YGSize out;
166
+ out.width =
167
+ static_cast<float>(static_cast<int32_t>(packed >> 32)) / g_density;
168
+ out.height = static_cast<float>(static_cast<int32_t>(packed & 0xffffffffLL)) /
169
+ g_density;
170
+ return out;
171
+ }
172
+
173
+ // ADR-0122: la medida delegada NO es una measure func de Yoga — 3.2.1
174
+ // prohíbe hijos en nodos con measure func (assertFatal). En su lugar el
175
+ // nodo custom queda contenedor normal: post-pasada, customMeasure fija
176
+ // las dims auto vía SetWidth/Height y customLayout sustituye los rects
177
+ // de los hijos (ver yogaLayoutIfDirty).
178
+
179
+ // BaselineFunc de hojas → Kotlin baselineNode(id, w, h) — corre en el
180
+ // hilo JS durante calculateLayout, igual que measureLeaf. Yoga llama a
181
+ // la baseline solo si algún hermano usa align baseline. Fallback h =
182
+ // borde inferior, la semántica por defecto de Yoga sin baseline func.
183
+ float baselineLeaf(YGNodeConstRef node, float w, float h) {
184
+ int64_t ctx =
185
+ static_cast<int64_t>(reinterpret_cast<intptr_t>(YGNodeGetContext(node)));
186
+ // Las hojas de fila no llevan baseline func (baseline=bottom por
187
+ // defecto) — el check es defensivo por si se habilitara.
188
+ if (ctx == 0 || (ctx & ROW_CTX_MARK))
189
+ return h;
190
+ if (!g_renderer || !g_baselineMid)
191
+ return h;
192
+ int id = static_cast<int>(ctx);
193
+ bool attached;
194
+ JNIEnv *env = getEnv(attached);
195
+ // ADR-0120: w/h llegan en unidades lógicas; baselineNode devuelve px.
196
+ jfloat b = env->CallFloatMethod(g_renderer, g_baselineMid, id, w * g_density,
197
+ h * g_density);
198
+ if (env->ExceptionCheck()) {
199
+ env->ExceptionClear();
200
+ if (attached)
201
+ g_jvm->DetachCurrentThread();
202
+ return h;
203
+ }
204
+ if (attached)
205
+ g_jvm->DetachCurrentThread();
206
+ return b <= 0 ? h : b / g_density;
207
+ }
208
+
209
+ bool isLeafType(const std::string &type) {
210
+ return type == "text" || type == "image" || type == "text-input" ||
211
+ type == "switch" || type == "slider";
212
+ }
213
+
214
+ void clearPadding(YGNodeRef node) {
215
+ for (int e = YGEdgeLeft; e <= YGEdgeAll; e++)
216
+ YGNodeStyleSetPadding(node, static_cast<YGEdge>(e), YGUndefined);
217
+ }
218
+
219
+ // ADR-0118: edges físicos + lógicos (Start/End resuelven por direction
220
+ // del nodo — RTL flex) + shorthands Horizontal/Vertical. Sufijos
221
+ // "InlineStart"/"InlineEnd" (nombres CSS lógicos) equivalen a Start/End.
222
+ bool sameLayout(float a, float b) {
223
+ // NaN (nodo aún no medido) debe comparar igual — si no, cada frame
224
+ // re-emitiría los nodos sin layout.
225
+ return a == b || (a != a && b != b);
226
+ }
227
+
228
+ // DFS: emite ops layout SOLO de nodos cuyo rect cambió (delta vs el
229
+ // último emitido — Entry.emitted/lastL…). Las coords son relativas al
230
+ // padre: si el padre se movió, el hijo no re-emite — la View ya viaja
231
+ // con él (LayoutParams margins en Kotlin).
232
+ void emitLayout(YGNodeRef node, int id, DLBuf &out, int &count) {
233
+ float l = YGNodeLayoutGetLeft(node);
234
+ float t = YGNodeLayoutGetTop(node);
235
+ float w = YGNodeLayoutGetWidth(node);
236
+ float h = YGNodeLayoutGetHeight(node);
237
+ // ADR-0122: hijo directo de un nodo `custom` — su rect lo decidió
238
+ // el delegado, no el flex de la pasada principal.
239
+ auto cr = g_customRects.find(id);
240
+ if (cr != g_customRects.end()) {
241
+ l = cr->second[0];
242
+ t = cr->second[1];
243
+ w = cr->second[2];
244
+ h = cr->second[3];
245
+ }
246
+ // Contenedores lógicos (list): hijas absolutas no aportan altura al
247
+ // padre → Yoga da 0 y View.draw() early-return las haría invisibles.
248
+ // FrameLayout sin layout-op wrappea contenido: replicarlo aquí —
249
+ // bounds del padre cubren el bbox de sus hijas. ADR-0118: el mismo
250
+ // caso aplica a display:contents — Yoga la deja 0x0 y sus hijas
251
+ // vienen en coords del abuelo; la View contents a 0,0 expandida al
252
+ // bbox deja a las hijas dentro de sus bounds para que HWUI las
253
+ // despache (sin la expansión una View 0x0 no dibuja descendientes).
254
+ // La View no pinta caja propia: Kotlin omite su background/borde.
255
+ const bool needH = h <= 0 && cr == g_customRects.end();
256
+ const bool needW = w <= 0 && cr == g_customRects.end();
257
+ if (needH || needW) {
258
+ for (uint32_t i = 0; i < YGNodeGetChildCount(node); i++) {
259
+ YGNodeRef c = YGNodeGetChild(node, i);
260
+ if (needH) {
261
+ const float cb = YGNodeLayoutGetTop(c) + YGNodeLayoutGetHeight(c);
262
+ if (cb > h)
263
+ h = cb;
264
+ }
265
+ if (needW) {
266
+ const float cr = YGNodeLayoutGetLeft(c) + YGNodeLayoutGetWidth(c);
267
+ if (cr > w)
268
+ w = cr;
269
+ }
270
+ }
271
+ }
272
+ auto it = g_nodes.find(id);
273
+ Entry *e = it != g_nodes.end() ? &it->second : nullptr;
274
+ if (!e || !e->emitted || !sameLayout(e->lastL, l) ||
275
+ !sameLayout(e->lastT, t) || !sameLayout(e->lastW, w) ||
276
+ !sameLayout(e->lastH, h)) {
277
+ out.u8(static_cast<uint8_t>(DLOp::Layout));
278
+ out.i32(id);
279
+ out.f32(l);
280
+ out.f32(t);
281
+ out.f32(w);
282
+ out.f32(h);
283
+ count++;
284
+ if (e) {
285
+ e->emitted = true;
286
+ e->lastL = l;
287
+ e->lastT = t;
288
+ e->lastW = w;
289
+ e->lastH = h;
290
+ }
291
+ }
292
+ for (uint32_t i = 0; i < YGNodeGetChildCount(node); i++) {
293
+ YGNodeRef child = YGNodeGetChild(node, i);
294
+ int cid =
295
+ static_cast<int>(reinterpret_cast<intptr_t>(YGNodeGetContext(child)));
296
+ emitLayout(child, cid, out, count);
297
+ }
298
+ }
299
+
300
+ // ADR-0122: DFS pre-orden sobre el árbol — ids de nodos con delegado
301
+ // de layout (un custom dentro del hijo de otro queda después de su
302
+ // ancestro: al procesarlo ya tiene rect delegado).
303
+ void collectCustom(YGNodeRef node, std::vector<int> &out) {
304
+ int id = static_cast<int>(reinterpret_cast<intptr_t>(YGNodeGetContext(node)));
305
+ auto it = g_nodes.find(id);
306
+ if (it != g_nodes.end() && it->second.custom)
307
+ out.push_back(id);
308
+ for (uint32_t i = 0; i < YGNodeGetChildCount(node); i++) {
309
+ collectCustom(YGNodeGetChild(node, i), out);
310
+ }
311
+ }
312
+
313
+ } // namespace
314
+
315
+ void yogaInit(JavaVM *jvm, jobject renderer) {
316
+ g_jvm = jvm;
317
+ yogaReset();
318
+ bool attached;
319
+ JNIEnv *env = getEnv(attached);
320
+ if (g_renderer)
321
+ env->DeleteGlobalRef(g_renderer);
322
+ g_renderer = env->NewGlobalRef(renderer);
323
+ jclass cls = env->GetObjectClass(g_renderer);
324
+ g_measureMid = env->GetMethodID(cls, "measureNode", "(IFIFI)J");
325
+ g_baselineMid = env->GetMethodID(cls, "baselineNode", "(IFF)F");
326
+ // Sondas opcionales (defer/drain/ADR-0122): un renderer sin el
327
+ // método (ElurSkiaTreeRenderer) deja NoSuchMethodError pendiente y
328
+ // la SIGUIENTE llamada JNI aborta — cada sonda limpia al salir.
329
+ auto optMid = [&](const char *n, const char *sig) {
330
+ jmethodID m = env->GetMethodID(cls, n, sig);
331
+ if (env->ExceptionCheck())
332
+ env->ExceptionClear();
333
+ return m;
334
+ };
335
+ g_deferMid = optMid("setMeasureDefer", "(Z)V");
336
+ g_drainMid = optMid("drainMeasureBatch", "()[I");
337
+ // ADR-0122: delegados de layout — dims auto (customMeasure) y rects
338
+ // de hijos (customLayout) resueltos por el registro de Kotlin.
339
+ g_customMeasureMid = optMid("customMeasure", "(IFF)J");
340
+ g_customLayoutMid = optMid("customLayout", "(IFF)[I");
341
+ env->DeleteLocalRef(cls);
342
+ if (attached)
343
+ g_jvm->DetachCurrentThread();
344
+
345
+ if (!g_config) {
346
+ g_config = YGConfigNew();
347
+ // ADR-0110 / decisión de stack §1: errata None explícita — Yoga 3.2
348
+ // default ya es W3C-conforme (main activaba MinSizeUndefinedInsteadOfAuto
349
+ // |FlexFirstPassUsesRunningTotals); fijarlo explícito blinda el contrato
350
+ // si el default upstream cambia.
351
+ YGConfigSetErrata(g_config, YGErrataNone);
352
+ }
353
+ }
354
+
355
+ void yogaReset() {
356
+ // El container persistente se desarma primero: sus hijos viven en
357
+ // g_nodes y se liberan en el loop — un free del padre con hijos
358
+ // colgando dejaría refs muertas dentro de g_root.
359
+ if (g_root) {
360
+ while (YGNodeGetChildCount(g_root) > 0)
361
+ YGNodeRemoveChild(g_root, YGNodeGetChild(g_root, 0));
362
+ YGNodeFree(g_root);
363
+ g_root = nullptr;
364
+ }
365
+ for (auto &[id, e] : g_nodes)
366
+ YGNodeFree(e.node);
367
+ g_nodes.clear();
368
+ g_absorbedByButton.clear();
369
+ g_customRects.clear();
370
+ g_root = nullptr;
371
+ g_dirty = false;
372
+ // ADR-0121: los árboles de fila mueren con el renderer — las listas
373
+ // que los poseían quedan destruidas con el resto del árbol.
374
+ for (auto &[tid, t] : g_rowTrees) {
375
+ for (auto &[key, node] : t.nodes)
376
+ YGNodeFree(node);
377
+ if (t.root)
378
+ YGNodeFree(t.root);
379
+ }
380
+ g_rowTrees.clear();
381
+ if (g_renderer && g_jvm) {
382
+ bool attached;
383
+ JNIEnv *env = getEnv(attached);
384
+ env->DeleteGlobalRef(g_renderer);
385
+ g_renderer = nullptr;
386
+ if (attached)
387
+ g_jvm->DetachCurrentThread();
388
+ }
389
+ }
390
+
391
+ // Métrica del registro real — JsThread-confined (ver elurYoga.h).
392
+ int yogaNodeCount() { return static_cast<int>(g_nodes.size()); }
393
+
394
+ // Container persistente: modela el ViewGroup del host (parentId 0 del
395
+ // wire). Vive fuera de g_nodes — no es direccionable ni borrable por
396
+ // stream; solo es padre de las raíces documentales insertadas. Las
397
+ // raíces coexisten (swap de documento, overlays) — antes el primer
398
+ // nodo creado era la raíz y un segundo árbol nunca entraba al layout.
399
+ void ensureRoot() {
400
+ if (!g_root)
401
+ g_root = g_config ? YGNodeNewWithConfig(g_config) : YGNodeNew();
402
+ }
403
+
404
+ void yogaCreateNode(int id, const std::string &type) {
405
+ YGNodeRef node = YGNodeNewWithConfig(g_config);
406
+ if (type == "column")
407
+ YGNodeStyleSetFlexDirection(node, YGFlexDirectionColumn);
408
+ else if (type == "row")
409
+ YGNodeStyleSetFlexDirection(node, YGFlexDirectionRow);
410
+ else if (type == "scroll-view")
411
+ // ADR-0128: contenedor de scroll — los hijos se miden sin límite en
412
+ // el eje principal (mismo efecto que el bloque con overflow:auto web).
413
+ YGNodeStyleSetOverflow(node, YGOverflowScroll);
414
+ if (isLeafType(type)) {
415
+ YGNodeSetMeasureFunc(node, measureLeaf);
416
+ YGNodeSetBaselineFunc(node, baselineLeaf);
417
+ }
418
+ g_nodes[id] = {node, type};
419
+ YGNodeSetContext(node, reinterpret_cast<void *>(static_cast<intptr_t>(id)));
420
+ ensureRoot();
421
+ g_dirty = true;
422
+ }
423
+
424
+ void yogaInsertChild(int parentId, int childId, int index) {
425
+ auto c = g_nodes.find(childId);
426
+ if (c == g_nodes.end())
427
+ return;
428
+ // parentId 0 = container del host: en el mirror es g_root, el nodo
429
+ // persistente creado en yogaInit. Antes la raíz era "el primer nodo
430
+ // creado" y este insert era no-op — un segundo mount (swap de
431
+ // documento SDUI) quedaba fuera del árbol de layout: vistas creadas
432
+ // sin rect, invisibles.
433
+ YGNodeRef parent = nullptr;
434
+ if (parentId == 0) {
435
+ ensureRoot();
436
+ parent = g_root;
437
+ } else {
438
+ auto p = g_nodes.find(parentId);
439
+ if (p == g_nodes.end())
440
+ return;
441
+ // button absorbe el hijo text como label (mismo caso que Kotlin):
442
+ // no entra al árbol; el padre pasa a medirse como hoja.
443
+ if (p->second.type == "button") {
444
+ YGNodeSetMeasureFunc(p->second.node, measureLeaf);
445
+ YGNodeSetBaselineFunc(p->second.node, baselineLeaf);
446
+ g_absorbedByButton[childId] = parentId;
447
+ // Pasa a hoja medida: el padding que llegó antes vive ya en la View.
448
+ clearPadding(p->second.node);
449
+ return;
450
+ }
451
+ parent = p->second.node;
452
+ }
453
+ // Re-parenting/reorder: el reconciler puede re-insertar un hijo ya
454
+ // montado (popPreview del swipe-back, move-child). YGNodeInsertChild
455
+ // aborta si el hijo ya tiene owner → detach primero.
456
+ if (YGNodeRef owner = YGNodeGetOwner(c->second.node)) {
457
+ YGNodeRemoveChild(owner, c->second.node);
458
+ }
459
+ uint32_t count = YGNodeGetChildCount(parent);
460
+ YGNodeInsertChild(parent, c->second.node,
461
+ static_cast<uint32_t>(index) > count
462
+ ? count
463
+ : static_cast<uint32_t>(index));
464
+ g_dirty = true;
465
+ }
466
+
467
+ void yogaRemoveChild(int parentId, int childId) {
468
+ auto c = g_nodes.find(childId);
469
+ if (c == g_nodes.end())
470
+ return;
471
+ // Hijo absorbido: nunca se insertó en el árbol — solo limpiar la
472
+ // redirección o un markLeafDirty futuro caería en el padre equivocado.
473
+ auto absorbed = g_absorbedByButton.find(childId);
474
+ if (absorbed != g_absorbedByButton.end() && absorbed->second == parentId) {
475
+ g_absorbedByButton.erase(absorbed);
476
+ auto p = g_nodes.find(parentId);
477
+ if (p != g_nodes.end() && YGNodeHasMeasureFunc(p->second.node))
478
+ YGNodeMarkDirty(p->second.node);
479
+ g_dirty = true;
480
+ return;
481
+ }
482
+ YGNodeRef parent;
483
+ if (parentId == 0) {
484
+ if (!g_root)
485
+ return;
486
+ parent = g_root;
487
+ } else {
488
+ auto p = g_nodes.find(parentId);
489
+ if (p == g_nodes.end())
490
+ return;
491
+ parent = p->second.node;
492
+ }
493
+ YGNodeRemoveChild(parent, c->second.node);
494
+ g_dirty = true;
495
+ }
496
+
497
+ void yogaMoveChild(int parentId, int childId, int index) {
498
+ yogaRemoveChild(parentId, childId);
499
+ yogaInsertChild(parentId, childId, index);
500
+ }
501
+
502
+ // Re-medida post-apply: Kotlin llama tras aplicar update-text/props.
503
+ // YGNodeMarkDirty solo aplica a nodos con measureFunc — el check es por
504
+ // la función real, no por el tipo: el reconciler recicla ids y el set
505
+ // `measuredIds` de Kotlin puede apuntar a un nodo recreado de otro tipo
506
+ // (un button sin hijo absorbido no tiene measureFunc — aborta Yoga).
507
+ void yogaMarkLeafDirty(int id) {
508
+ // Texto absorbido por un button → la hoja real es el button.
509
+ auto redir = g_absorbedByButton.find(id);
510
+ if (redir != g_absorbedByButton.end())
511
+ id = redir->second;
512
+ auto it = g_nodes.find(id);
513
+ if (it == g_nodes.end())
514
+ return;
515
+ // ADR-0122: contenedor con delegado — MarkDirty solo sirve en
516
+ // measure-funcs; basta re-correr la pasada (los delegados vuelven
517
+ // a resolver en collectCustom).
518
+ if (it->second.custom) {
519
+ g_dirty = true;
520
+ return;
521
+ }
522
+ if (YGNodeHasMeasureFunc(it->second.node)) {
523
+ YGNodeMarkDirty(it->second.node);
524
+ g_dirty = true;
525
+ }
526
+ }
527
+
528
+ void yogaDeleteNode(int id) {
529
+ auto it = g_nodes.find(id);
530
+ if (it == g_nodes.end())
531
+ return;
532
+ YGNodeRef node = it->second.node;
533
+ if (YGNodeRef owner = YGNodeGetOwner(node))
534
+ YGNodeRemoveChild(owner, node);
535
+ // destroy libera el nodo (detach no). Hijos: detach primero, luego free.
536
+ while (YGNodeGetChildCount(node) > 0) {
537
+ YGNodeRemoveChild(node, YGNodeGetChild(node, 0));
538
+ }
539
+ YGNodeFree(node);
540
+ g_nodes.erase(it);
541
+ g_absorbedByButton.erase(id);
542
+ g_customRects.erase(id);
543
+ // Si el borrado es un Button padre, sus hijos absorbidos quedan huérfanos
544
+ // de redirección — purgar los que apuntaban a él.
545
+ for (auto ab = g_absorbedByButton.begin(); ab != g_absorbedByButton.end();) {
546
+ ab = (ab->second == id) ? g_absorbedByButton.erase(ab) : std::next(ab);
547
+ }
548
+ g_dirty = true;
549
+ }
550
+
551
+ // ADR-0122: marca un nodo con delegado de layout. No instala measure
552
+ // func — Yoga 3.2.1 prohíbe hijos en nodos con measure (assertFatal);
553
+ // el delegado se resuelve post-pasada en yogaLayoutIfDirty.
554
+ void yogaSetCustomLayout(int id, bool on) {
555
+ auto it = g_nodes.find(id);
556
+ if (it == g_nodes.end())
557
+ return;
558
+ Entry &e = it->second;
559
+ if (e.custom == on)
560
+ return;
561
+ e.custom = on;
562
+ g_dirty = true;
563
+ }
564
+
565
+ // ADR-0122: re-medida de un hijo al ancho/alto que el delegado ofrece —
566
+ // corre CalculateLayout standalone de su subárbol (adjunto: re-deriva
567
+ // sus coords internas al ancho del delegado; su rect propio lo sustituye
568
+ // g_customRects). h<0 = YGUndefined. Devuelve el tamaño en px.
569
+ bool yogaMeasureChild(int id, float wPx, float hPx, float out[2]) {
570
+ auto it = g_nodes.find(id);
571
+ if (it == g_nodes.end())
572
+ return false;
573
+ YGNodeRef n = it->second.node;
574
+ YGNodeCalculateLayout(n, wPx / g_density,
575
+ hPx >= 0 ? hPx / g_density : YGUndefined, g_direction);
576
+ out[0] = YGNodeLayoutGetWidth(n) * g_density;
577
+ out[1] = YGNodeLayoutGetHeight(n) * g_density;
578
+ return true;
579
+ }
580
+
581
+ void yogaSetStyle(int id, const std::string &key, double num,
582
+ const std::string &str, bool isNum) {
583
+ auto it = g_nodes.find(id);
584
+ if (it == g_nodes.end())
585
+ return;
586
+ // ADR-0122: `layout` activa el delegado del nodo — va por el canal
587
+ // de estilo (JsThread) porque el árbol es JsThread-confined.
588
+ if (key == "layout") {
589
+ yogaSetCustomLayout(id, !str.empty());
590
+ return;
591
+ }
592
+ // Hoja medida: el padding lo lleva la View (Kotlin applyLeafPadding) y
593
+ // la medida de texto ya lo incluye — aplicarlo también aquí lo contaría
594
+ // dos veces en la caja.
595
+ if (key.rfind("padding", 0) == 0 && YGNodeHasMeasureFunc(it->second.node))
596
+ return;
597
+ if (elur::layout::applyStyleProp(it->second.node, key, num, str, isNum))
598
+ g_dirty = true;
599
+ }
600
+
601
+ // ── ADR-0121: API pública de los árboles de fila — el estado vive en
602
+ // el namespace anónimo junto a ROW_CTX_MARK (ver arriba). Los rects se
603
+ // devuelven en px (la conversión vive aquí — Kotlin solo posiciona).
604
+ int yogaRowTreeCreate(JNIEnv *env, jobject rowYoga) {
605
+ if (!g_rowYoga) {
606
+ g_rowYoga = env->NewGlobalRef(rowYoga);
607
+ jclass cls = env->GetObjectClass(rowYoga);
608
+ g_rowMeasureMid = env->GetMethodID(cls, "measureRowNode", "(IIFIFI)J");
609
+ env->DeleteLocalRef(cls);
610
+ }
611
+ int id = g_nextRowTreeId++;
612
+ RowTree t;
613
+ t.root = g_config ? YGNodeNewWithConfig(g_config) : YGNodeNew();
614
+ g_rowTrees[id] = t;
615
+ return id;
616
+ }
617
+
618
+ void yogaRowNode(int treeId, int key, int parentKey, const std::string &type) {
619
+ auto t = g_rowTrees.find(treeId);
620
+ if (t == g_rowTrees.end())
621
+ return;
622
+ YGNodeRef n = g_config ? YGNodeNewWithConfig(g_config) : YGNodeNew();
623
+ t->second.nodes[key] = n;
624
+ // La dirección por defecto viene del tipo, igual que en yogaCreateNode
625
+ // del árbol principal — un flexDirection de estilo la sobrescribe.
626
+ if (type == "column")
627
+ YGNodeStyleSetFlexDirection(n, YGFlexDirectionColumn);
628
+ else if (type == "row")
629
+ YGNodeStyleSetFlexDirection(n, YGFlexDirectionRow);
630
+ // Hojas: medida intrínseca vía measureRowNode (la View real). El
631
+ // contexto marcado enruta measureLeaf al mid de fila. Sin baseline
632
+ // func en filas — Yoga aplica baseline=bottom por defecto.
633
+ if (!isRowContainer(type)) {
634
+ YGNodeSetMeasureFunc(n, measureLeaf);
635
+ YGNodeSetContext(n, reinterpret_cast<void *>(
636
+ static_cast<intptr_t>(rowCtx(treeId, key))));
637
+ }
638
+ YGNodeRef parent = parentKey == 0 ? t->second.root
639
+ : t->second.nodes.count(parentKey)
640
+ ? t->second.nodes[parentKey]
641
+ : t->second.root;
642
+ YGNodeInsertChild(parent, n, YGNodeGetChildCount(parent));
643
+ }
644
+
645
+ void yogaRowStyle(int treeId, int key, const std::string &name, bool isNum,
646
+ double num, const std::string &str) {
647
+ auto t = g_rowTrees.find(treeId);
648
+ if (t == g_rowTrees.end())
649
+ return;
650
+ auto n = t->second.nodes.find(key);
651
+ if (n == t->second.nodes.end())
652
+ return;
653
+ // ADR-0122: los delegados no aplican dentro de filas (la medida
654
+ // delegada es del árbol principal) — `layout` se ignora aquí.
655
+ if (name == "layout")
656
+ return;
657
+ if (name.rfind("padding", 0) == 0 && YGNodeHasMeasureFunc(n->second))
658
+ return;
659
+ elur::layout::applyStyleProp(n->second, name, num, str, isNum);
660
+ }
661
+
662
+ // Reset de una propiedad bound: el campo resolvió a null → Undefined
663
+ // (o su default numérico/enum). Cobertura = keys de layout que pueden
664
+ // venir por bind; el resto no se resetea porque nunca llegó por esta
665
+ // vía.
666
+ void yogaRowStyleReset(int treeId, int key, const std::string &name) {
667
+ auto t = g_rowTrees.find(treeId);
668
+ if (t == g_rowTrees.end())
669
+ return;
670
+ auto n = t->second.nodes.find(key);
671
+ if (n == t->second.nodes.end())
672
+ return;
673
+ YGNodeRef node = n->second;
674
+ if (name == "width")
675
+ YGNodeStyleSetWidth(node, YGUndefined);
676
+ else if (name == "height")
677
+ YGNodeStyleSetHeight(node, YGUndefined);
678
+ else if (name == "minWidth")
679
+ YGNodeStyleSetMinWidth(node, YGUndefined);
680
+ else if (name == "minHeight")
681
+ YGNodeStyleSetMinHeight(node, YGUndefined);
682
+ else if (name == "maxWidth")
683
+ YGNodeStyleSetMaxWidth(node, YGUndefined);
684
+ else if (name == "maxHeight")
685
+ YGNodeStyleSetMaxHeight(node, YGUndefined);
686
+ else if (name == "flexGrow")
687
+ YGNodeStyleSetFlexGrow(node, 0);
688
+ else if (name == "flexShrink")
689
+ YGNodeStyleSetFlexShrink(node, 0);
690
+ else if (name == "aspectRatio")
691
+ YGNodeStyleSetAspectRatio(node, YGUndefined);
692
+ else if (name.rfind("margin", 0) == 0)
693
+ YGNodeStyleSetMargin(node, elur::layout::edgeOf(name.substr(6)),
694
+ YGUndefined);
695
+ else if (name.rfind("padding", 0) == 0)
696
+ YGNodeStyleSetPadding(node, elur::layout::edgeOf(name.substr(7)),
697
+ YGUndefined);
698
+ else if (name == "gap" || name == "rowGap" || name == "columnGap")
699
+ YGNodeStyleSetGap(node, YGGutterAll, YGUndefined);
700
+ else if (name == "position")
701
+ YGNodeStyleSetPositionType(node, YGPositionTypeRelative);
702
+ else if (name.rfind("inset", 0) == 0 || name == "left" || name == "top" ||
703
+ name == "right" || name == "bottom" || name == "start" ||
704
+ name == "end")
705
+ YGNodeStyleSetPosition(node, elur::layout::edgeOf(name.substr(5)),
706
+ YGUndefined);
707
+ }
708
+
709
+ jintArray yogaRowLayout(JNIEnv *env, int treeId, float wPx, bool forceWidth) {
710
+ auto t = g_rowTrees.find(treeId);
711
+ if (t == g_rowTrees.end())
712
+ return nullptr;
713
+ // ADR-0121 — el ancho raíz solo se fuerza con spec EXACTLY (fila
714
+ // MATCH_PARENT). Con AT_MOST/UNSPECIFIED (WRAP_CONTENT horizontal) el
715
+ // ancho lo decide el estilo del template; wPx<0 = ancho libre.
716
+ const float wLogical = wPx >= 0 ? wPx / g_density : YGUndefined;
717
+ if (forceWidth)
718
+ YGNodeStyleSetWidth(t->second.root, wLogical);
719
+ YGNodeCalculateLayout(t->second.root, wLogical, YGUndefined, g_direction);
720
+ // [key, l, t, w, h] en px — mismo rounding que applyLayout (ADR-0120).
721
+ jintArray out = env->NewIntArray(t->second.nodes.size() * 5);
722
+ std::vector<jint> buf;
723
+ buf.reserve(t->second.nodes.size() * 5);
724
+ for (auto &[key, node] : t->second.nodes) {
725
+ buf.push_back(key);
726
+ buf.push_back(
727
+ static_cast<jint>(lroundf(YGNodeLayoutGetLeft(node) * g_density)));
728
+ buf.push_back(
729
+ static_cast<jint>(lroundf(YGNodeLayoutGetTop(node) * g_density)));
730
+ buf.push_back(
731
+ static_cast<jint>(lroundf(YGNodeLayoutGetWidth(node) * g_density)));
732
+ buf.push_back(
733
+ static_cast<jint>(lroundf(YGNodeLayoutGetHeight(node) * g_density)));
734
+ }
735
+ env->SetIntArrayRegion(out, 0, buf.size(), buf.data());
736
+ return out;
737
+ }
738
+
739
+ void yogaRowFree(int treeId) {
740
+ auto t = g_rowTrees.find(treeId);
741
+ if (t == g_rowTrees.end())
742
+ return;
743
+ for (auto &[key, node] : t->second.nodes)
744
+ YGNodeFree(node);
745
+ if (t->second.root)
746
+ YGNodeFree(t->second.root);
747
+ g_rowTrees.erase(t);
748
+ }
749
+
750
+ void yogaSetViewport(float w, float h, float density, bool rtl) {
751
+ // ADR-0120: el viewport entra en px físicos; el árbol corre en
752
+ // unidades lógicas (px/density) y PointScaleFactor redondea el
753
+ // resultado al grid de px en el borde absoluto de cada nodo.
754
+ g_density = density > 0 ? density : 1;
755
+ g_vpW = w / g_density;
756
+ g_vpH = h / g_density;
757
+ // RTL ambiente: el parámetro direction de CalculateLayout resuelve los
758
+ // nodos con direction:Inherit — el equivalente de dir=rtl en <html>.
759
+ g_direction = rtl ? YGDirectionRTL : YGDirectionLTR;
760
+ if (g_config)
761
+ YGConfigSetPointScaleFactor(g_config, g_density);
762
+ g_hasViewport = true;
763
+ g_dirty = true;
764
+ // resize del viewport: la app puede no tener ops pendientes —
765
+ // el árbol es nativo, emitimos el frame de layout directo.
766
+ yogaFlushLayoutFrame(0);
767
+ }
768
+
769
+ int yogaLayoutIfDirty(DLBuf &out) {
770
+ if (!g_dirty || !g_hasViewport || !g_root)
771
+ return 0;
772
+ g_dirty = false;
773
+ YGNodeStyleSetWidth(g_root, g_vpW);
774
+ YGNodeStyleSetHeight(g_root, g_vpH);
775
+ // Las raíces documentales (hijas del container) llenan el viewport —
776
+ // mismo forzado que antes se hacía sobre el único root: un segundo
777
+ // mount coexistiendo (swap SDUI/overlay) recibe el mismo tamaño.
778
+ for (uint32_t i = 0; i < YGNodeGetChildCount(g_root); i++) {
779
+ YGNodeRef child = YGNodeGetChild(g_root, i);
780
+ YGNodeStyleSetWidth(child, g_vpW);
781
+ YGNodeStyleSetHeight(child, g_vpH);
782
+ }
783
+ // R4.3/ADR-0085: medición agrupada — rondas collect→drain→re-dirty.
784
+ // En la pasada collect measureNode encola lo no cacheado y devuelve
785
+ // la última medida sin bloquear; drainMeasureBatch mide el lote en
786
+ // main (un latch por pasada, no uno por hoja) y devuelve los ids
787
+ // resueltos → se re-marcan dirty y el layout recorre con medidas
788
+ // exactas. Converge cuando una pasada no pide nada nuevo; cota 3
789
+ // rondas + pasada final sin defer (latch por hoja) para residuales.
790
+ bool attached = false;
791
+ JNIEnv *env = g_renderer ? getEnv(attached) : nullptr;
792
+ bool needFinal = false;
793
+ if (env && g_deferMid && g_drainMid) {
794
+ for (int round = 0; round < 3; round++) {
795
+ env->CallVoidMethod(g_renderer, g_deferMid, JNI_TRUE);
796
+ YGNodeCalculateLayout(g_root, g_vpW, g_vpH, g_direction);
797
+ jobject idsObj = env->CallObjectMethod(g_renderer, g_drainMid);
798
+ env->CallVoidMethod(g_renderer, g_deferMid, JNI_FALSE);
799
+ if (env->ExceptionCheck()) {
800
+ env->ExceptionClear();
801
+ needFinal = true;
802
+ if (idsObj)
803
+ env->DeleteLocalRef(idsObj);
804
+ break;
805
+ }
806
+ if (!idsObj) { // drain falló (post/timeout) → pasada bloqueante
807
+ needFinal = true;
808
+ break;
809
+ }
810
+ jintArray ids = static_cast<jintArray>(idsObj);
811
+ jsize n = env->GetArrayLength(ids);
812
+ if (n == 0) { // convergió — las medidas exactas ya están en cache
813
+ env->DeleteLocalRef(idsObj);
814
+ break;
815
+ }
816
+ jint *elems = env->GetIntArrayElements(ids, nullptr);
817
+ for (jsize i = 0; i < n; i++) {
818
+ auto it = g_nodes.find(elems[i]);
819
+ if (it != g_nodes.end() && YGNodeHasMeasureFunc(it->second.node))
820
+ YGNodeMarkDirty(it->second.node);
821
+ }
822
+ env->ReleaseIntArrayElements(ids, elems, JNI_ABORT);
823
+ env->DeleteLocalRef(idsObj);
824
+ if (round == 2)
825
+ needFinal = true;
826
+ }
827
+ if (needFinal)
828
+ YGNodeCalculateLayout(g_root, g_vpW, g_vpH, g_direction);
829
+ } else {
830
+ YGNodeCalculateLayout(g_root, g_vpW, g_vpH, g_direction);
831
+ }
832
+ if (attached)
833
+ g_jvm->DetachCurrentThread();
834
+ // ADR-0122: nodos `custom` — dos fases post-pasada.
835
+ // A) medida: el delegado responde customMeasure(w,h computados) y las
836
+ // dims cuyo estilo es auto se fijan con SetWidth/Height → un
837
+ // recálculo las materializa. Se salta si el padre también es
838
+ // custom: entonces su rect lo decide el delegado del padre.
839
+ // B) rects: customLayout devuelve los rects de los hijos
840
+ // (measureChild dentro corre el CalculateLayout del subárbol).
841
+ // DFS pre-orden ⇒ un custom anidado dentro del hijo de otro ya
842
+ // tiene su rect en g_customRects cuando le toca.
843
+ g_customRects.clear();
844
+ {
845
+ std::vector<int> customIds;
846
+ collectCustom(g_root, customIds);
847
+ if (!customIds.empty()) {
848
+ bool envAttached = false;
849
+ JNIEnv *env = g_renderer ? getEnv(envAttached) : nullptr;
850
+ // Fase A — dims auto las decide el delegado.
851
+ bool dimsChanged = false;
852
+ for (int id : customIds) {
853
+ auto it = g_nodes.find(id);
854
+ if (it == g_nodes.end())
855
+ continue;
856
+ YGNodeRef node = it->second.node;
857
+ if (YGNodeRef owner = YGNodeGetOwner(node)) {
858
+ int oid = static_cast<int>(
859
+ reinterpret_cast<intptr_t>(YGNodeGetContext(owner)));
860
+ auto oe = g_nodes.find(oid);
861
+ if (oe != g_nodes.end() && oe->second.custom)
862
+ continue; // el delegado del padre decide su rect
863
+ }
864
+ if (!env || !g_customMeasureMid)
865
+ break;
866
+ jlong packed =
867
+ env->CallLongMethod(g_renderer, g_customMeasureMid, id,
868
+ YGNodeLayoutGetWidth(node) * g_density,
869
+ YGNodeLayoutGetHeight(node) * g_density);
870
+ if (env->ExceptionCheck()) {
871
+ env->ExceptionClear();
872
+ break;
873
+ }
874
+ const float mw =
875
+ static_cast<float>(static_cast<int32_t>(packed >> 32)) / g_density;
876
+ const float mh =
877
+ static_cast<float>(static_cast<int32_t>(packed & 0xffffffffLL)) /
878
+ g_density;
879
+ const auto sw = YGNodeStyleGetWidth(node);
880
+ const auto sh = YGNodeStyleGetHeight(node);
881
+ if ((sw.unit == YGUnitUndefined || sw.unit == YGUnitAuto) && mw > 0 &&
882
+ mw != sw.value) {
883
+ YGNodeStyleSetWidth(node, mw);
884
+ dimsChanged = true;
885
+ }
886
+ if ((sh.unit == YGUnitUndefined || sh.unit == YGUnitAuto) && mh > 0 &&
887
+ mh != sh.value) {
888
+ YGNodeStyleSetHeight(node, mh);
889
+ dimsChanged = true;
890
+ }
891
+ }
892
+ if (dimsChanged)
893
+ YGNodeCalculateLayout(g_root, g_vpW, g_vpH, g_direction);
894
+ // Fase B — rects de hijos directos por delegado.
895
+ for (int id : customIds) {
896
+ auto it = g_nodes.find(id);
897
+ if (it == g_nodes.end())
898
+ continue;
899
+ float wLog, hLog;
900
+ auto cr = g_customRects.find(id);
901
+ if (cr != g_customRects.end()) {
902
+ wLog = cr->second[2];
903
+ hLog = cr->second[3];
904
+ } else {
905
+ wLog = YGNodeLayoutGetWidth(it->second.node);
906
+ hLog = YGNodeLayoutGetHeight(it->second.node);
907
+ }
908
+ if (!env || !g_customLayoutMid)
909
+ break;
910
+ jobject res = env->CallObjectMethod(g_renderer, g_customLayoutMid, id,
911
+ wLog * g_density, hLog * g_density);
912
+ if (env->ExceptionCheck()) {
913
+ env->ExceptionClear();
914
+ break;
915
+ }
916
+ if (!res)
917
+ continue;
918
+ jintArray flat = static_cast<jintArray>(res);
919
+ jsize n = env->GetArrayLength(flat);
920
+ jint *elems = env->GetIntArrayElements(flat, nullptr);
921
+ for (jsize i = 0; i + 4 < n; i += 5) {
922
+ g_customRects[elems[i]] = {
923
+ elems[i + 1] / g_density, elems[i + 2] / g_density,
924
+ elems[i + 3] / g_density, elems[i + 4] / g_density};
925
+ }
926
+ env->ReleaseIntArrayElements(flat, elems, JNI_ABORT);
927
+ env->DeleteLocalRef(res);
928
+ }
929
+ if (envAttached)
930
+ g_jvm->DetachCurrentThread();
931
+ }
932
+ }
933
+ int count = 0;
934
+ for (uint32_t i = 0; i < YGNodeGetChildCount(g_root); i++) {
935
+ YGNodeRef child = YGNodeGetChild(g_root, i);
936
+ int cid =
937
+ static_cast<int>(reinterpret_cast<intptr_t>(YGNodeGetContext(child)));
938
+ emitLayout(child, cid, out, count);
939
+ }
940
+ return count;
941
+ }
942
+
943
+ void yogaFlushLayoutFrame(int reqSeq) {
944
+ if (!g_dirty)
945
+ return;
946
+ DLBuf w;
947
+ int layoutOps = yogaLayoutIfDirty(w);
948
+ if (layoutOps == 0)
949
+ return;
950
+ // V12 + R4.4/ADR-0085: id negativo monotónico — frame host-initiated,
951
+ // distinguible de los commits JS (positivos): el renderer los aplica
952
+ // pero nunca los ack-ea. reqSeq > 0: la respuesta lleva -reqSeq y
953
+ // queda ligada al requestLeafRemeasure que la originó (el renderer
954
+ // descarta respuestas con seq superado = geometría de contenido ya
955
+ // obsoleto). reqSeq <= 0: sin request (resize) — contador interno
956
+ // con base 1e6 para no colisionar con los seq del renderer.
957
+ static int g_internalLayoutSeq = 0;
958
+ const int seq = reqSeq > 0 ? reqSeq : (1000000 + ++g_internalLayoutSeq);
959
+ DLBuf frame;
960
+ frame.header(-seq, layoutOps);
961
+ frame.bytes.insert(frame.bytes.end(), w.bytes.begin(), w.bytes.end());
962
+
963
+ if (!g_renderer)
964
+ return;
965
+ bool attached;
966
+ JNIEnv *env = getEnv(attached);
967
+ jclass cls = env->GetObjectClass(g_renderer);
968
+ jmethodID mid = env->GetMethodID(cls, "applyDisplayListBinary", "([B)V");
969
+ if (mid) {
970
+ jbyteArray jarr = env->NewByteArray(frame.bytes.size());
971
+ env->SetByteArrayRegion(
972
+ jarr, 0, frame.bytes.size(),
973
+ reinterpret_cast<const jbyte *>(frame.bytes.data()));
974
+ env->CallVoidMethod(g_renderer, mid, jarr);
975
+ env->DeleteLocalRef(jarr);
976
+ }
977
+ env->DeleteLocalRef(cls);
978
+ if (attached)
979
+ g_jvm->DetachCurrentThread();
980
+ }
981
+
982
+ } // namespace elur
983
+
984
+ // ── ADR-0121: exports JNI de árboles de fila ────────────────────────
985
+ // Los símbolos viven en ambas variantes del bridge (elurYoga.cpp se
986
+ // compila en elur-bridge y elur-bridge-hermes): ElurRowYoga no carga
987
+ // librería propia — los nombres se resuelven contra la lib del engine
988
+ // activo, ya cargada antes de que exista ninguna lista.
989
+ extern "C" JNIEXPORT jint JNICALL
990
+ Java_com_elur_universal_ElurRowYoga_nativeTreeCreate(JNIEnv *env,
991
+ jobject thiz) {
992
+ return elur::yogaRowTreeCreate(env, thiz);
993
+ }
994
+
995
+ extern "C" JNIEXPORT void JNICALL
996
+ Java_com_elur_universal_ElurRowYoga_nativeRowNode(JNIEnv *env, jobject thiz,
997
+ jint treeId, jint key,
998
+ jint parentKey,
999
+ jstring type) {
1000
+ const char *c = env->GetStringUTFChars(type, nullptr);
1001
+ elur::yogaRowNode(treeId, key, parentKey, c ? c : "");
1002
+ if (c)
1003
+ env->ReleaseStringUTFChars(type, c);
1004
+ }
1005
+
1006
+ extern "C" JNIEXPORT void JNICALL
1007
+ Java_com_elur_universal_ElurRowYoga_nativeRowStyle(JNIEnv *env, jobject thiz,
1008
+ jint treeId, jint key,
1009
+ jstring name, jboolean isNum,
1010
+ jdouble num, jstring str) {
1011
+ const char *n = env->GetStringUTFChars(name, nullptr);
1012
+ const char *s = str ? env->GetStringUTFChars(str, nullptr) : nullptr;
1013
+ elur::yogaRowStyle(treeId, key, n ? n : "", isNum, num, s ? s : "");
1014
+ if (n)
1015
+ env->ReleaseStringUTFChars(name, n);
1016
+ if (s)
1017
+ env->ReleaseStringUTFChars(str, s);
1018
+ }
1019
+
1020
+ extern "C" JNIEXPORT void JNICALL
1021
+ Java_com_elur_universal_ElurRowYoga_nativeRowStyleReset(JNIEnv *env,
1022
+ jobject thiz,
1023
+ jint treeId, jint key,
1024
+ jstring name) {
1025
+ const char *n = env->GetStringUTFChars(name, nullptr);
1026
+ elur::yogaRowStyleReset(treeId, key, n ? n : "");
1027
+ if (n)
1028
+ env->ReleaseStringUTFChars(name, n);
1029
+ }
1030
+
1031
+ extern "C" JNIEXPORT jintArray JNICALL
1032
+ Java_com_elur_universal_ElurRowYoga_nativeRowLayout(JNIEnv *env, jobject thiz,
1033
+ jint treeId, jfloat wPx,
1034
+ jboolean forceWidth) {
1035
+ return elur::yogaRowLayout(env, treeId, wPx, forceWidth == JNI_TRUE);
1036
+ }
1037
+
1038
+ extern "C" JNIEXPORT void JNICALL
1039
+ Java_com_elur_universal_ElurRowYoga_nativeRowFree(JNIEnv *env, jobject thiz,
1040
+ jint treeId) {
1041
+ elur::yogaRowFree(treeId);
1042
+ }
1043
+
1044
+ // ── ADR-0122: delegados de layout por subárbol ──────────────────────
1045
+ // Mismo patrón que ElurRowYoga: símbolos en ambas variantes del bridge,
1046
+ // resolución lazy contra la lib del engine activo.
1047
+ extern "C" JNIEXPORT jintArray JNICALL
1048
+ Java_com_elur_universal_ElurCustomLayout_nativeMeasureChild(JNIEnv *env,
1049
+ jobject thiz,
1050
+ jint id, jfloat wPx,
1051
+ jfloat hPx) {
1052
+ float out[2];
1053
+ if (!elur::yogaMeasureChild(id, wPx, hPx, out))
1054
+ return nullptr;
1055
+ jintArray r = env->NewIntArray(2);
1056
+ jint buf[2] = {static_cast<jint>(lroundf(out[0])),
1057
+ static_cast<jint>(lroundf(out[1]))};
1058
+ env->SetIntArrayRegion(r, 0, 2, buf);
1059
+ return r;
1060
+ }