@bugsee/react-native 0.0.0-stage → 7.0.0-beta1

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 (250) hide show
  1. package/BugseeReactNative.podspec +95 -0
  2. package/LICENSE +21 -0
  3. package/README.md +552 -2
  4. package/android/build.gradle +162 -0
  5. package/android/consumer-rules.pro +2 -0
  6. package/android/src/main/AndroidManifest.xml +33 -0
  7. package/android/src/main/java/com/bugsee/reactnative/AppearanceBridge.java +82 -0
  8. package/android/src/main/java/com/bugsee/reactnative/AttributeBridge.java +209 -0
  9. package/android/src/main/java/com/bugsee/reactnative/BreadcrumbFilterBridge.java +443 -0
  10. package/android/src/main/java/com/bugsee/reactnative/BridgeJson.java +168 -0
  11. package/android/src/main/java/com/bugsee/reactnative/BugseeModule.java +1869 -0
  12. package/android/src/main/java/com/bugsee/reactnative/BugseeOptionEnums.java +136 -0
  13. package/android/src/main/java/com/bugsee/reactnative/BugseePackage.java +42 -0
  14. package/android/src/main/java/com/bugsee/reactnative/BugseeReactNativeWrapper.java +200 -0
  15. package/android/src/main/java/com/bugsee/reactnative/BugseeStatusMapper.java +66 -0
  16. package/android/src/main/java/com/bugsee/reactnative/BugseeTokens.java +22 -0
  17. package/android/src/main/java/com/bugsee/reactnative/ConsoleEchoDedup.java +202 -0
  18. package/android/src/main/java/com/bugsee/reactnative/CreatedReports.java +127 -0
  19. package/android/src/main/java/com/bugsee/reactnative/DataRequestBridge.java +375 -0
  20. package/android/src/main/java/com/bugsee/reactnative/ExceptionBridge.java +88 -0
  21. package/android/src/main/java/com/bugsee/reactnative/ExceptionExecutors.java +33 -0
  22. package/android/src/main/java/com/bugsee/reactnative/LogFilterBridge.java +375 -0
  23. package/android/src/main/java/com/bugsee/reactnative/NetworkEvents.java +227 -0
  24. package/android/src/main/java/com/bugsee/reactnative/NetworkFilterBridge.java +498 -0
  25. package/android/src/main/java/com/bugsee/reactnative/PluginEndpoint.java +48 -0
  26. package/android/src/main/java/com/bugsee/reactnative/ReactNativeWebException.java +19 -0
  27. package/android/src/main/java/com/bugsee/reactnative/ReactNativeWrapperInitProvider.java +61 -0
  28. package/android/src/main/java/com/bugsee/reactnative/ReactRootOriginTracker.java +867 -0
  29. package/android/src/main/java/com/bugsee/reactnative/ReportArgs.java +58 -0
  30. package/android/src/main/java/com/bugsee/reactnative/ReportHandlerBridge.java +336 -0
  31. package/android/src/main/java/com/bugsee/reactnative/ReportHandlerDeadlines.java +57 -0
  32. package/android/src/main/java/com/bugsee/reactnative/ReportOps.java +287 -0
  33. package/android/src/main/java/com/bugsee/reactnative/SecureRectanglePulls.java +113 -0
  34. package/android/src/main/java/com/bugsee/reactnative/SecureRectangleStore.java +692 -0
  35. package/android/src/main/java/com/bugsee/reactnative/SpanHandles.java +143 -0
  36. package/android/src/main/java/com/bugsee/reactnative/WrapperChannelHolder.java +137 -0
  37. package/android/src/main/java/com/bugsee/reactnative/WrapperEventBus.java +110 -0
  38. package/android/src/main/java/com/bugsee/reactnative/WrapperRegistrar.java +54 -0
  39. package/app.plugin.js +4 -0
  40. package/ios/BGSRNConsoleCapture.h +52 -0
  41. package/ios/BGSRNConsoleCapture.mm +344 -0
  42. package/ios/BugseeModule.h +25 -0
  43. package/ios/BugseeModule.mm +2728 -0
  44. package/ios/Package.swift +71 -0
  45. package/ios/Support/Package.resolved +14 -0
  46. package/ios/Support/Package.swift +44 -0
  47. package/ios/Support/Sources/BugseeRNSupport/BGSRNAttributes.m +52 -0
  48. package/ios/Support/Sources/BugseeRNSupport/BGSRNCreatedReportOps.m +236 -0
  49. package/ios/Support/Sources/BugseeRNSupport/BGSRNCreatedReports.m +184 -0
  50. package/ios/Support/Sources/BugseeRNSupport/BGSRNDataRequestBridge.m +431 -0
  51. package/ios/Support/Sources/BugseeRNSupport/BGSRNErrorMessage.m +40 -0
  52. package/ios/Support/Sources/BugseeRNSupport/BGSRNEventBus.m +70 -0
  53. package/ios/Support/Sources/BugseeRNSupport/BGSRNExceptions.m +63 -0
  54. package/ios/Support/Sources/BugseeRNSupport/BGSRNGuardedEmit.mm +32 -0
  55. package/ios/Support/Sources/BugseeRNSupport/BGSRNJSON.m +40 -0
  56. package/ios/Support/Sources/BugseeRNSupport/BGSRNLaunchHold.m +147 -0
  57. package/ios/Support/Sources/BugseeRNSupport/BGSRNMainThread.m +23 -0
  58. package/ios/Support/Sources/BugseeRNSupport/BGSRNNetworkEvents.m +159 -0
  59. package/ios/Support/Sources/BugseeRNSupport/BGSRNNetworkFilter.m +155 -0
  60. package/ios/Support/Sources/BugseeRNSupport/BGSRNPluginEndpoint.m +21 -0
  61. package/ios/Support/Sources/BugseeRNSupport/BGSRNReactRootOriginTracker.m +63 -0
  62. package/ios/Support/Sources/BugseeRNSupport/BGSRNReactWindow.m +251 -0
  63. package/ios/Support/Sources/BugseeRNSupport/BGSRNReportArgs.m +47 -0
  64. package/ios/Support/Sources/BugseeRNSupport/BGSRNReportDeadlines.m +8 -0
  65. package/ios/Support/Sources/BugseeRNSupport/BGSRNReportHandlerBridge.m +308 -0
  66. package/ios/Support/Sources/BugseeRNSupport/BGSRNReportOps.m +345 -0
  67. package/ios/Support/Sources/BugseeRNSupport/BGSRNSecureRectangles.m +508 -0
  68. package/ios/Support/Sources/BugseeRNSupport/BGSRNSettleOnce.m +62 -0
  69. package/ios/Support/Sources/BugseeRNSupport/BGSRNSpanHandles.m +136 -0
  70. package/ios/Support/Sources/BugseeRNSupport/BGSRNStatusMapper.m +18 -0
  71. package/ios/Support/Sources/BugseeRNSupport/BGSRNTokens.m +9 -0
  72. package/ios/Support/Sources/BugseeRNSupport/BGSRNValues.m +5 -0
  73. package/ios/Support/Sources/BugseeRNSupport/BGSRNWrapper.m +54 -0
  74. package/ios/Support/Sources/BugseeRNSupport/BGSRNWrapperChannelHolder.m +59 -0
  75. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNAttributes.h +63 -0
  76. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNCreatedReportOps.h +51 -0
  77. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNCreatedReports.h +81 -0
  78. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNDataRequestBridge.h +118 -0
  79. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNErrorMessage.h +30 -0
  80. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNEventBus.h +45 -0
  81. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNExceptions.h +31 -0
  82. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNGuardedEmit.h +31 -0
  83. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNJSON.h +25 -0
  84. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNLaunchHold.h +86 -0
  85. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNMainThread.h +32 -0
  86. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNNetworkEvents.h +28 -0
  87. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNNetworkFilter.h +28 -0
  88. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNPluginEndpoint.h +17 -0
  89. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNReactRootOriginTracker.h +48 -0
  90. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNReactWindow.h +135 -0
  91. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNReportArgs.h +17 -0
  92. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNReportDeadlines.h +37 -0
  93. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNReportHandlerBridge.h +94 -0
  94. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNReportOps.h +86 -0
  95. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNSecureRectangles.h +198 -0
  96. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNSettleOnce.h +25 -0
  97. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNSpanHandles.h +49 -0
  98. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNStatusMapper.h +26 -0
  99. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNTokens.h +14 -0
  100. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNValues.h +18 -0
  101. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNWrapper.h +40 -0
  102. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNWrapperChannelHolder.h +74 -0
  103. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNAttributesTests.m +194 -0
  104. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNCreatedReportOpsTests.m +274 -0
  105. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNCreatedReportsTests.m +240 -0
  106. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNDataRequestBridgeTests.m +685 -0
  107. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNErrorMessageTests.m +102 -0
  108. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNEventBusTests.m +136 -0
  109. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNExceptionsTests.m +68 -0
  110. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNFakeReport.h +41 -0
  111. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNFakeReport.m +166 -0
  112. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNGuardedEmitTests.mm +85 -0
  113. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNJSONTests.m +281 -0
  114. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNLaunchHoldTests.m +230 -0
  115. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNMainThreadTests.m +97 -0
  116. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNNetworkEventsTests.m +99 -0
  117. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNNetworkFilterTests.m +134 -0
  118. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNPluginEndpointTests.m +38 -0
  119. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNReactRootOriginTrackerTests.m +210 -0
  120. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNReactWindowTests.m +548 -0
  121. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNReportArgsTests.m +51 -0
  122. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNReportDeadlinesTests.m +22 -0
  123. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNReportHandlerBridgeTests.m +382 -0
  124. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNReportOpsTests.m +295 -0
  125. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNSecureRectanglesTests.m +568 -0
  126. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNSettleOnceTests.m +134 -0
  127. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNSpanHandlesTests.m +153 -0
  128. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNStatusMapperTests.m +81 -0
  129. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNValuesTests.m +32 -0
  130. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNWrapperChannelHolderTests.m +205 -0
  131. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNWrapperTests.m +66 -0
  132. package/ios/react-native-spm-prefix.h +10 -0
  133. package/native-versions.json +10 -0
  134. package/package.json +62 -3
  135. package/plugin/build/bundle-phase.d.ts +41 -0
  136. package/plugin/build/bundle-phase.js +116 -0
  137. package/plugin/build/bundle-phase.js.map +1 -0
  138. package/plugin/build/dsym-script.d.ts +32 -0
  139. package/plugin/build/dsym-script.js +159 -0
  140. package/plugin/build/dsym-script.js.map +1 -0
  141. package/plugin/build/endpoint.d.ts +30 -0
  142. package/plugin/build/endpoint.js +69 -0
  143. package/plugin/build/endpoint.js.map +1 -0
  144. package/plugin/build/gradle.d.ts +65 -0
  145. package/plugin/build/gradle.js +1066 -0
  146. package/plugin/build/gradle.js.map +1 -0
  147. package/plugin/build/index.d.ts +85 -0
  148. package/plugin/build/index.js +217 -0
  149. package/plugin/build/index.js.map +1 -0
  150. package/plugin/build/manifest.d.ts +48 -0
  151. package/plugin/build/manifest.js +69 -0
  152. package/plugin/build/manifest.js.map +1 -0
  153. package/plugin/build/native-versions.baked.json +4 -0
  154. package/plugin/build/native-versions.d.ts +10 -0
  155. package/plugin/build/native-versions.js +27 -0
  156. package/plugin/build/native-versions.js.map +1 -0
  157. package/plugin/build/pbx-string.d.ts +8 -0
  158. package/plugin/build/pbx-string.js +31 -0
  159. package/plugin/build/pbx-string.js.map +1 -0
  160. package/plugin/build/podfile.d.ts +3 -0
  161. package/plugin/build/podfile.js +28 -0
  162. package/plugin/build/podfile.js.map +1 -0
  163. package/plugin/build/properties.d.ts +19 -0
  164. package/plugin/build/properties.js +41 -0
  165. package/plugin/build/properties.js.map +1 -0
  166. package/plugin/build/scheme.d.ts +20 -0
  167. package/plugin/build/scheme.js +107 -0
  168. package/plugin/build/scheme.js.map +1 -0
  169. package/react-native.config.js +26 -0
  170. package/scripts/bugsee-sourcemaps.gradle +201 -0
  171. package/scripts/bugsee-xcode.sh +83 -0
  172. package/scripts/compose-then-inject.js +113 -0
  173. package/scripts/hermes-sourcemaps.js +634 -0
  174. package/scripts/hermesc-preserve-js.cmd +6 -0
  175. package/scripts/hermesc-preserve-js.js +200 -0
  176. package/scripts/hermesc-preserve-js.sh +7 -0
  177. package/src/NativeBugsee.ts +622 -0
  178. package/src/apm/notify.ts +58 -0
  179. package/src/apm/span.ts +403 -0
  180. package/src/apm/types.ts +57 -0
  181. package/src/appearance/report.ts +171 -0
  182. package/src/architecture.ts +48 -0
  183. package/src/attributes/errors.ts +39 -0
  184. package/src/attributes/validate.ts +150 -0
  185. package/src/breadcrumbs/add.ts +58 -0
  186. package/src/breadcrumbs/data.ts +33 -0
  187. package/src/breadcrumbs/filter.ts +215 -0
  188. package/src/breadcrumbs/types.ts +64 -0
  189. package/src/bridge/json.ts +110 -0
  190. package/src/console/capture.ts +180 -0
  191. package/src/console/dedup.ts +175 -0
  192. package/src/data/validate.ts +259 -0
  193. package/src/errorName.ts +32 -0
  194. package/src/exceptions/ErrorBoundary.tsx +92 -0
  195. package/src/exceptions/RootErrorReporter.tsx +61 -0
  196. package/src/exceptions/debugIds.ts +118 -0
  197. package/src/exceptions/handlers.ts +236 -0
  198. package/src/exceptions/options.ts +85 -0
  199. package/src/exceptions/payload.ts +456 -0
  200. package/src/exceptions/report.ts +170 -0
  201. package/src/exceptions/sha1.ts +148 -0
  202. package/src/exceptions/stack.ts +355 -0
  203. package/src/index.ts +944 -0
  204. package/src/logs/filter.ts +90 -0
  205. package/src/logs/log.ts +36 -0
  206. package/src/network/add.ts +165 -0
  207. package/src/network/filter.ts +198 -0
  208. package/src/options/AndroidLaunchOptions.ts +78 -0
  209. package/src/options/BugseeLaunchOptions.ts +190 -0
  210. package/src/options/IOSLaunchOptions.ts +57 -0
  211. package/src/options/android-options-manifest.json +646 -0
  212. package/src/options/createDefaultLaunchOptions.ts +29 -0
  213. package/src/options/endpoint.ts +58 -0
  214. package/src/options/enums.ts +104 -0
  215. package/src/options/ios-enums.json +19 -0
  216. package/src/options/keys.ts +39 -0
  217. package/src/options/option-enums.json +34 -0
  218. package/src/options/option-keys.json +107 -0
  219. package/src/report/BugseeReport.ts +264 -0
  220. package/src/report/CreatedReport.ts +127 -0
  221. package/src/report/dispatcher.ts +95 -0
  222. package/src/report/errors.ts +48 -0
  223. package/src/report/fields.ts +40 -0
  224. package/src/report/types.ts +157 -0
  225. package/src/report/validate.ts +197 -0
  226. package/src/secure/BugseeSecure.tsx +202 -0
  227. package/src/secure/ancestry.ts +622 -0
  228. package/src/secure/drivers.ts +342 -0
  229. package/src/secure/followEvents.ts +57 -0
  230. package/src/secure/hold.ts +99 -0
  231. package/src/secure/measureLoop.ts +323 -0
  232. package/src/secure/nativeAnimation.ts +1005 -0
  233. package/src/secure/rectangles.ts +93 -0
  234. package/src/secure/registry.ts +237 -0
  235. package/src/secure/surface.ts +83 -0
  236. package/src/secure/tracker.ts +723 -0
  237. package/src/secure/transition.ts +488 -0
  238. package/src/secure/unit.ts +22 -0
  239. package/src/status.ts +16 -0
  240. package/src/version.ts +9 -0
  241. package/src/viewtree/anchor.tsx +105 -0
  242. package/src/viewtree/constants.ts +20 -0
  243. package/src/viewtree/fiber.ts +251 -0
  244. package/src/viewtree/requests.ts +347 -0
  245. package/src/viewtree/walk.ts +902 -0
  246. package/src/wrapper/channel.ts +33 -0
  247. package/src/wrapper/collect.ts +52 -0
  248. package/src/wrapper/events.ts +45 -0
  249. package/src/wrapper/identity.ts +54 -0
  250. package/src/wrapper/lifecycle-events.ts +89 -0
@@ -0,0 +1,867 @@
1
+ package com.bugsee.reactnative;
2
+
3
+ import android.app.Activity;
4
+ import android.graphics.Point;
5
+ import android.util.Log;
6
+ import android.view.Display;
7
+ import android.view.View;
8
+ import android.view.ViewGroup;
9
+ import android.view.ViewTreeObserver;
10
+
11
+ import androidx.annotation.NonNull;
12
+ import androidx.annotation.Nullable;
13
+ import androidx.annotation.UiThread;
14
+
15
+ import com.facebook.react.bridge.LifecycleEventListener;
16
+ import com.facebook.react.bridge.ReactApplicationContext;
17
+ import com.facebook.react.bridge.UiThreadUtil;
18
+ import com.facebook.react.bridge.UIManager;
19
+ import com.facebook.react.uimanager.ReactRoot;
20
+ import com.facebook.react.uimanager.RootView;
21
+ import com.facebook.react.uimanager.RootViewUtil;
22
+ import com.facebook.react.uimanager.UIManagerHelper;
23
+
24
+ import java.lang.ref.WeakReference;
25
+ import java.util.ArrayList;
26
+ import java.util.Arrays;
27
+ import java.util.Iterator;
28
+ import java.util.LinkedHashSet;
29
+ import java.util.List;
30
+ import java.util.Map;
31
+ import java.util.Set;
32
+ import java.util.concurrent.ConcurrentHashMap;
33
+
34
+ /**
35
+ * Keeps {@link SecureRectangleStore}'s per-surface display origins in step
36
+ * with each React root view, so rectangles JS measured with {@code
37
+ * measureInWindow} are served to the SDK in display pixels.
38
+ *
39
+ * <p>The origin of the activity root (a {@link ReactRoot}) is its {@code
40
+ * getLocationOnScreen} less React Native's own viewport offset for it
41
+ * ({@link RootViewUtil#getViewportOffset}, the formula {@code
42
+ * ReactSurfaceView} feeds Fabric's layout constraints, which the root shadow
43
+ * node's {@code Translate(viewportOffset)} adds to {@code measureInWindow}).
44
+ * With edge-to-edge on and a full-screen window that is (0, 0); with it off,
45
+ * it is the status-bar/cutout inset; in split-screen or freeform it is also
46
+ * the window's own position on the display.
47
+ *
48
+ * <p>Fabric {@code measureInWindow} stops at the nearest {@code RootNodeKind}
49
+ * ancestor ({@code ModalHostViewShadowNode} sets that trait), so a rectangle
50
+ * inside a {@code <Modal>} is relative to the modal's content, which is
51
+ * mounted in the dialog's {@code DialogRootViewGroup}. That root is a {@link
52
+ * RootView} but not a {@link ReactRoot}: nothing feeds its viewport offset to
53
+ * Fabric, and the modal host node's transform is the identity. Its origin is
54
+ * therefore its {@code getLocationOnScreen} alone ({@link #surfaceOrigin}).
55
+ * Each surface has its own origin; a single {@code setOrigin} for the display
56
+ * cannot serve both.
57
+ *
58
+ * <p>A surface's key is the React tag of its {@code <Modal>} host, which JS
59
+ * reads off the fiber tree; {@link #watchSurface} resolves the dialog root
60
+ * from it when JS first publishes there, and retries on every refresh until
61
+ * the dialog root exists.
62
+ *
63
+ * <p>Re-read on every global layout of a watched root (rotation, insets
64
+ * arriving, a window resize), on host resume, on every JS publish, and at
65
+ * most every {@link SecureRectanglePulls#ORIGIN_REFRESH_MIN_INTERVAL_MS}
66
+ * while the SDK pulls (a window can move without a relayout). All view access
67
+ * is on the UI thread; the store is thread-safe.
68
+ */
69
+ final class ReactRootOriginTracker implements LifecycleEventListener {
70
+
71
+ private static final String TAG = "BugseeRN";
72
+
73
+ private final LifecycleSource lifecycle;
74
+ private final RootFinder rootFinder;
75
+ private final SecureRectangleStore store;
76
+
77
+ /**
78
+ * The owning module's claim on {@link #store}: every lane write carries
79
+ * it, so a tracker whose runtime has been replaced writes nothing.
80
+ */
81
+ private final int claim;
82
+
83
+ /** UI thread only: the activity React root, when found. */
84
+ @Nullable
85
+ private RootHandle root;
86
+
87
+ /**
88
+ * Extra surfaces (a {@code <Modal>}'s {@code DialogRootViewGroup})
89
+ * registered via {@link #watch}, each paired with the layout-listener
90
+ * token from {@link RootHandle#addOnGlobalLayoutListener}. UI thread only.
91
+ */
92
+ private final List<WatchedRoot> watched = new ArrayList<>();
93
+
94
+ /**
95
+ * The layout-listener registration for {@link #root}, if any, released
96
+ * through this same token later. Which observer it is removed from is
97
+ * the token's business (see {@link ViewTreeObserverToken}), not a fresh
98
+ * lookup on the root: a root no longer attached to its window hands back
99
+ * a different, "floating" observer, and removing from that one would
100
+ * silently leak the real registration.
101
+ */
102
+ @Nullable
103
+ private LayoutListenerToken layoutToken;
104
+
105
+ /** A watched surface and the layout token that must be released with it. */
106
+ private static final class WatchedRoot {
107
+ final RootHandle handle;
108
+ final LayoutListenerToken token;
109
+
110
+ WatchedRoot(@NonNull final RootHandle handle,
111
+ @NonNull final LayoutListenerToken token) {
112
+ this.handle = handle;
113
+ this.token = token;
114
+ }
115
+ }
116
+
117
+ /** Finds a {@code <Modal>}'s dialog root from its host's React tag. */
118
+ private final SurfaceResolver surfaceResolver;
119
+
120
+ /**
121
+ * Surface keys JS has published on whose dialog root could not be found
122
+ * yet. Retried on every {@link #refresh}. UI thread only.
123
+ */
124
+ private final Set<Integer> pendingSurfaces = new LinkedHashSet<>();
125
+
126
+ /**
127
+ * Each watched surface's last origin, for {@link #cachedSurfaceOrigin}
128
+ * (the {@code vh} walk asks from the JS thread). Written on the UI
129
+ * thread.
130
+ */
131
+ private final Map<Integer, int[]> surfaceOrigins = new ConcurrentHashMap<>();
132
+
133
+ /**
134
+ * A copy of the {@code {x, y}} last passed to {@link
135
+ * SecureRectangleStore#setOrigin}, for {@link #currentOrigin()} (Task
136
+ * 6.5's {@code vh} data request). UI thread only, like everything else
137
+ * that is not explicitly annotated otherwise.
138
+ */
139
+ @Nullable
140
+ private int[] lastOrigin;
141
+
142
+ /**
143
+ * Set once {@link #dispose()} is called, synchronously, so a
144
+ * {@link #refreshSoon()} already queued on the UI thread -- or one
145
+ * raced in just after -- still finds it set when it runs. Without this,
146
+ * a refresh that lands between dispose() posting {@link #detach()} and
147
+ * that detach actually running would re-find and re-register against
148
+ * the root dispose() is in the middle of tearing down.
149
+ */
150
+ private volatile boolean disposed;
151
+
152
+ ReactRootOriginTracker(@NonNull final ReactApplicationContext context,
153
+ @NonNull final SecureRectangleStore store, final int claim) {
154
+ this(new ContextLifecycleSource(context), new ActivityRootFinder(context),
155
+ new ModalSurfaceResolver(context), store, claim);
156
+ }
157
+
158
+ /**
159
+ * Test seam. {@link ReactApplicationContext} needs a real Android
160
+ * {@code Context} to construct, and {@link View}'s window/observer
161
+ * behaviour cannot be faked in a plain JVM test -- {@link
162
+ * ViewTreeObserver} is {@code final}, so even a stubbed instance cannot
163
+ * be told to report itself alive or dead. {@link LifecycleSource} and
164
+ * {@link RootFinder} let a test drive the dispose/attach/detach state
165
+ * machine with plain Java fakes instead.
166
+ */
167
+ ReactRootOriginTracker(@NonNull final LifecycleSource lifecycle,
168
+ @NonNull final RootFinder rootFinder, @NonNull final SecureRectangleStore store) {
169
+ this(lifecycle, rootFinder, surfaceKey -> null, store);
170
+ }
171
+
172
+ /**
173
+ * Test seam, as above, with a fake {@link SurfaceResolver} too. Writes
174
+ * with whatever claim {@code store} holds now.
175
+ */
176
+ ReactRootOriginTracker(@NonNull final LifecycleSource lifecycle,
177
+ @NonNull final RootFinder rootFinder, @NonNull final SurfaceResolver surfaceResolver,
178
+ @NonNull final SecureRectangleStore store) {
179
+ this(lifecycle, rootFinder, surfaceResolver, store, store.currentClaim());
180
+ }
181
+
182
+ /** Test seam, as above, writing with {@code claim}. */
183
+ ReactRootOriginTracker(@NonNull final LifecycleSource lifecycle,
184
+ @NonNull final RootFinder rootFinder, @NonNull final SurfaceResolver surfaceResolver,
185
+ @NonNull final SecureRectangleStore store, final int claim) {
186
+ this.lifecycle = lifecycle;
187
+ this.rootFinder = rootFinder;
188
+ this.surfaceResolver = surfaceResolver;
189
+ this.store = store;
190
+ this.claim = claim;
191
+ lifecycle.addLifecycleEventListener(this);
192
+ refreshSoon();
193
+ }
194
+
195
+ /** Re-reads the origin on the UI thread. Safe from any thread. */
196
+ void refreshSoon() {
197
+ UiThreadUtil.runOnUiThread(this::refresh);
198
+ }
199
+
200
+ void dispose() {
201
+ disposed = true;
202
+ lifecycle.removeLifecycleEventListener(this);
203
+ UiThreadUtil.runOnUiThread(this::detach);
204
+ }
205
+
206
+ @Override
207
+ public void onHostResume() {
208
+ refresh();
209
+ }
210
+
211
+ @Override
212
+ public void onHostPause() {
213
+ }
214
+
215
+ @Override
216
+ public void onHostDestroy() {
217
+ detach();
218
+ }
219
+
220
+ /**
221
+ * Never throws: this runs from layout and lifecycle callbacks of the host
222
+ * app, where an exception would crash it over a redaction offset.
223
+ *
224
+ * <p>Package-visible (rather than {@code private}) so a JVM test can call
225
+ * it directly: posting through {@link UiThreadUtil} never actually runs
226
+ * the posted runnable outside a real Android main-thread {@code Looper}.
227
+ */
228
+ @UiThread
229
+ void refresh() {
230
+ if (disposed) {
231
+ return;
232
+ }
233
+ try {
234
+ RootHandle current = root;
235
+ if (current == null || !current.isAttachedToWindow()) {
236
+ detachPrimary();
237
+ current = rootFinder.findCurrentRoot();
238
+ if (current != null) {
239
+ layoutToken = current.addOnGlobalLayoutListener(this::refresh);
240
+ root = current;
241
+ }
242
+ }
243
+
244
+ if (current != null) {
245
+ publishOrigin(current, true);
246
+ }
247
+ refreshWatched();
248
+ resolvePending();
249
+ } catch (Throwable t) {
250
+ Log.w(TAG, "secure rectangles: could not read the React root's display origin: "
251
+ + t.getClass().getName());
252
+ }
253
+ }
254
+
255
+ /**
256
+ * JS published on {@code surfaceKey} (a {@code <Modal>} host's tag):
257
+ * watch its dialog root. Safe from any thread: posts to the UI thread.
258
+ * Until the root is found its rectangles fail closed in the store.
259
+ */
260
+ void watchSurface(final int surfaceKey) {
261
+ if (surfaceKey <= SecureRectangleStore.MAIN_SURFACE) {
262
+ return;
263
+ }
264
+ UiThreadUtil.runOnUiThread(() -> watchSurfaceNow(surfaceKey));
265
+ }
266
+
267
+ /** Package-visible for the same reason as {@link #refresh()}. */
268
+ @UiThread
269
+ void watchSurfaceNow(final int surfaceKey) {
270
+ if (disposed || surfaceKey <= SecureRectangleStore.MAIN_SURFACE || isWatched(surfaceKey)) {
271
+ return;
272
+ }
273
+ final RootHandle handle = resolveQuietly(surfaceKey);
274
+ if (handle == null) {
275
+ pendingSurfaces.add(surfaceKey);
276
+ return;
277
+ }
278
+ pendingSurfaces.remove(surfaceKey);
279
+ watchNow(handle);
280
+ }
281
+
282
+ /**
283
+ * The display origin of {@code surfaceKey}'s dialog root, watching it
284
+ * first if needed; {@code null} when it cannot be found. For the {@code
285
+ * vh} walk, which asks once per {@code <Modal>} per walk.
286
+ */
287
+ @UiThread
288
+ @Nullable
289
+ int[] surfaceOriginNow(final int surfaceKey) {
290
+ watchSurfaceNow(surfaceKey);
291
+ for (final WatchedRoot entry : watched) {
292
+ if (entry.handle.surfaceKey() == surfaceKey) {
293
+ publishOrigin(entry.handle, false);
294
+ }
295
+ }
296
+ return cachedSurfaceOrigin(surfaceKey);
297
+ }
298
+
299
+ /** The last origin read for {@code surfaceKey}, or {@code null}. Any thread. */
300
+ @Nullable
301
+ int[] cachedSurfaceOrigin(final int surfaceKey) {
302
+ final int[] origin = surfaceOrigins.get(surfaceKey);
303
+ return origin == null ? null : origin.clone();
304
+ }
305
+
306
+ /** Package-visible for the same reason as {@link #refresh()}. */
307
+ @UiThread
308
+ void watchNow(@NonNull final RootHandle handle) {
309
+ if (disposed || isWatched(handle.surfaceKey())) {
310
+ return;
311
+ }
312
+ final LayoutListenerToken token = handle.addOnGlobalLayoutListener(this::refresh);
313
+ watched.add(new WatchedRoot(handle, token));
314
+ publishOrigin(handle, false);
315
+ }
316
+
317
+ @UiThread
318
+ private boolean isWatched(final int surfaceKey) {
319
+ for (final WatchedRoot existing : watched) {
320
+ if (existing.handle.surfaceKey() == surfaceKey) {
321
+ return true;
322
+ }
323
+ }
324
+ return false;
325
+ }
326
+
327
+ @UiThread
328
+ @Nullable
329
+ private RootHandle resolveQuietly(final int surfaceKey) {
330
+ try {
331
+ return surfaceResolver.resolve(surfaceKey);
332
+ } catch (Throwable t) {
333
+ Log.w(TAG, "secure surface: could not resolve a dialog root ("
334
+ + t.getClass().getSimpleName() + ")");
335
+ return null;
336
+ }
337
+ }
338
+
339
+ /**
340
+ * Retries every pending surface. One whose rectangles JS has cleared
341
+ * meanwhile (its Modal unmounted before its root was found) is not
342
+ * retried: it is dropped with its empty lane.
343
+ */
344
+ @UiThread
345
+ private void resolvePending() {
346
+ if (pendingSurfaces.isEmpty()) {
347
+ return;
348
+ }
349
+ for (final Integer surfaceKey : new ArrayList<>(pendingSurfaces)) {
350
+ if (!store.hasRectangles(surfaceKey)) {
351
+ pendingSurfaces.remove(surfaceKey);
352
+ store.dropSurfaceIfEmptyForRuntime(claim, surfaceKey);
353
+ continue;
354
+ }
355
+ watchSurfaceNow(surfaceKey);
356
+ }
357
+ }
358
+
359
+ @UiThread
360
+ private void refreshWatched() {
361
+ final Iterator<WatchedRoot> it = watched.iterator();
362
+ while (it.hasNext()) {
363
+ final WatchedRoot entry = it.next();
364
+ if (!entry.handle.isAttachedToWindow()) {
365
+ it.remove();
366
+ forget(entry);
367
+ continue;
368
+ }
369
+ publishOrigin(entry.handle, false);
370
+ }
371
+ }
372
+
373
+ /**
374
+ * Stops watching a dialog root. If its surface still holds rectangles,
375
+ * its origin no longer holds: the store serves the surface as the whole
376
+ * display again and the key goes back to pending, so a later refresh
377
+ * watches whatever root then hosts it. Otherwise its empty lane goes.
378
+ */
379
+ @UiThread
380
+ private void forget(@NonNull final WatchedRoot entry) {
381
+ entry.token.release();
382
+ final int surfaceKey = entry.handle.surfaceKey();
383
+ surfaceOrigins.remove(surfaceKey);
384
+ if (disposed) {
385
+ // The runtime is gone: its Modal surfaces are the module's to
386
+ // drop (SecureRectangleStore.releaseRuntime), not to retry.
387
+ return;
388
+ }
389
+ if (store.hasRectangles(surfaceKey)) {
390
+ store.forgetOriginForRuntime(claim, surfaceKey);
391
+ pendingSurfaces.add(surfaceKey);
392
+ } else {
393
+ store.dropSurfaceIfEmptyForRuntime(claim, surfaceKey);
394
+ }
395
+ }
396
+
397
+ /**
398
+ * Where {@code measureInWindow}'s (0, 0) sits on the display for the
399
+ * root in {@code snapshot}: {@code locationOnScreen - viewportOffset} for
400
+ * a {@link ReactRoot} (the activity root), {@code locationOnScreen} alone
401
+ * for any other {@link RootView} (a {@code <Modal>}'s dialog root). Pure,
402
+ * so a JVM test checks the choice.
403
+ */
404
+ @NonNull
405
+ static int[] surfaceOrigin(@NonNull final OriginSnapshot snapshot) {
406
+ return snapshot.reactRoot
407
+ ? SecureRectangleStore.displayOrigin(snapshot.onScreen, snapshot.viewport.x, snapshot.viewport.y)
408
+ : new int[] { snapshot.onScreen[0], snapshot.onScreen[1] };
409
+ }
410
+
411
+ @UiThread
412
+ private void publishOrigin(@NonNull final RootHandle handle, final boolean primary) {
413
+ // Resolved once, atomically: the handle holds the root's view only
414
+ // weakly, and reading location/viewport/display as separate calls
415
+ // could see the view collected partway through, mixing a real value
416
+ // read before that with a made-up default (0,0) / DEFAULT_DISPLAY
417
+ // read after it -- publishing a wrong origin is a privacy defect,
418
+ // not a cosmetic one, so a gone-mid-refresh view aborts the whole
419
+ // read instead: nothing new is published and the previous origin
420
+ // stands.
421
+ // A root that is not attached has no place on screen yet: its
422
+ // location reads (0, 0). Nothing is recorded; the surface keeps
423
+ // failing closed until its first layout after attaching.
424
+ if (!handle.isAttachedToWindow()) {
425
+ return;
426
+ }
427
+ final OriginSnapshot snapshot = handle.resolveOrigin();
428
+ if (snapshot == null) {
429
+ return;
430
+ }
431
+ if (snapshot.displaySize != null) {
432
+ store.setDisplayBounds(snapshot.displayId, snapshot.displaySize.x, snapshot.displaySize.y);
433
+ }
434
+ final int[] origin = surfaceOrigin(snapshot);
435
+ // The activity root is the main surface whatever its own view id:
436
+ // JS publishes everything outside a <Modal> there.
437
+ final int surface = primary ? SecureRectangleStore.MAIN_SURFACE : handle.surfaceKey();
438
+ store.setOriginForRuntime(claim, snapshot.displayId, surface, origin[0], origin[1]);
439
+ if (primary) {
440
+ lastOrigin = origin;
441
+ } else {
442
+ surfaceOrigins.put(surface, origin.clone());
443
+ }
444
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
445
+ Log.d(TAG, "secure origin display=" + snapshot.displayId
446
+ + " surface=" + surface
447
+ + " kind=" + (primary ? "activity" : "dialog")
448
+ + " onScreen=" + snapshot.onScreen[0] + "," + snapshot.onScreen[1]
449
+ + " viewport=" + snapshot.viewport.x + "," + snapshot.viewport.y
450
+ + " origin=" + origin[0] + "," + origin[1]
451
+ + " served=" + Arrays.toString(store.snapshot(snapshot.displayId)));
452
+ }
453
+ }
454
+
455
+ /**
456
+ * The React root's current display origin, for {@link DataRequestBridge}
457
+ * (Task 6.5): the {@code vh} data request is answered on the same thread
458
+ * the SDK asks on -- the main thread, per the spec -- so a synchronous
459
+ * re-read here is safe and catches a window that moved without a layout
460
+ * pass (Ruling I1), the same way a secure-rectangle pull does.
461
+ *
462
+ * <p>{@code null} before any root has ever been found -- an app that never
463
+ * calls {@code Bugsee.wrap} answers every {@code vh} request natively,
464
+ * which the spec allows.
465
+ */
466
+ @UiThread
467
+ @Nullable
468
+ int[] currentOrigin() {
469
+ refresh();
470
+ return lastOrigin == null ? null : lastOrigin.clone();
471
+ }
472
+
473
+ /** Package-visible for the same reason as {@link #refresh()}. */
474
+ @UiThread
475
+ void detach() {
476
+ detachPrimary();
477
+ // Surfaces that still hold rectangles stay pending (failing closed)
478
+ // for a root a recreated activity brings back; refresh re-watches
479
+ // them. After dispose() nothing refreshes again.
480
+ for (final WatchedRoot entry : new ArrayList<>(watched)) {
481
+ forget(entry);
482
+ }
483
+ watched.clear();
484
+ surfaceOrigins.clear();
485
+ if (disposed) {
486
+ pendingSurfaces.clear();
487
+ }
488
+ }
489
+
490
+ /** How many surfaces wait for their dialog root. Tests read it. */
491
+ @UiThread
492
+ int pendingSurfaceCount() {
493
+ return pendingSurfaces.size();
494
+ }
495
+
496
+ @UiThread
497
+ private void detachPrimary() {
498
+ root = null;
499
+ final LayoutListenerToken token = layoutToken;
500
+ layoutToken = null;
501
+ if (token != null) {
502
+ token.release();
503
+ }
504
+ }
505
+
506
+ /** What this class needs from the wrapper's {@link ReactApplicationContext}. */
507
+ interface LifecycleSource {
508
+ void addLifecycleEventListener(LifecycleEventListener listener);
509
+
510
+ void removeLifecycleEventListener(LifecycleEventListener listener);
511
+ }
512
+
513
+ private static final class ContextLifecycleSource implements LifecycleSource {
514
+ private final ReactApplicationContext context;
515
+
516
+ ContextLifecycleSource(final ReactApplicationContext context) {
517
+ this.context = context;
518
+ }
519
+
520
+ @Override
521
+ public void addLifecycleEventListener(final LifecycleEventListener listener) {
522
+ context.addLifecycleEventListener(listener);
523
+ }
524
+
525
+ @Override
526
+ public void removeLifecycleEventListener(final LifecycleEventListener listener) {
527
+ context.removeLifecycleEventListener(listener);
528
+ }
529
+ }
530
+
531
+ /** Finds the current React root, if any. */
532
+ interface RootFinder {
533
+ @Nullable
534
+ RootHandle findCurrentRoot();
535
+ }
536
+
537
+ /** What this class needs from the current React root and its window. */
538
+ interface RootHandle {
539
+ boolean isAttachedToWindow();
540
+
541
+ /**
542
+ * Opaque key for {@link SecureRectangleStore}'s per-surface origin.
543
+ * The activity React root and a dialog root must not share one.
544
+ */
545
+ int surfaceKey();
546
+
547
+ /**
548
+ * The root's current on-screen location, viewport offset and display
549
+ * id, resolved as one atomic snapshot -- or {@code null} if the
550
+ * underlying view is no longer reachable. Reading these as separate
551
+ * calls could resolve a weakly-held view once for one field and find
552
+ * it already collected for the next, silently blending a real value
553
+ * with a made-up default.
554
+ */
555
+ @Nullable
556
+ OriginSnapshot resolveOrigin();
557
+
558
+ /**
559
+ * Registers a layout callback and returns the token that removes it
560
+ * again, from whichever observer holds it by then.
561
+ */
562
+ LayoutListenerToken addOnGlobalLayoutListener(Runnable onLayout);
563
+ }
564
+
565
+ /** Finds a {@code <Modal>}'s dialog root from its host's React tag. */
566
+ interface SurfaceResolver {
567
+ /** UI thread. {@code null} while the dialog root does not exist. */
568
+ @Nullable
569
+ RootHandle resolve(int surfaceKey);
570
+ }
571
+
572
+ /**
573
+ * A root's location, viewport offset, display id and kind, read
574
+ * together. {@code reactRoot} is whether the root is a {@link ReactRoot}
575
+ * (whose viewport offset Fabric applies) rather than a dialog root.
576
+ */
577
+ static final class OriginSnapshot {
578
+ final int[] onScreen;
579
+ final Point viewport;
580
+ final int displayId;
581
+ final boolean reactRoot;
582
+ /** The display's real size in pixels ({@code Display.getRealSize}), or {@code null}. */
583
+ @Nullable
584
+ final Point displaySize;
585
+
586
+ OriginSnapshot(final int[] onScreen, final Point viewport, final int displayId) {
587
+ this(onScreen, viewport, displayId, true);
588
+ }
589
+
590
+ OriginSnapshot(final int[] onScreen, final Point viewport, final int displayId,
591
+ final boolean reactRoot) {
592
+ this(onScreen, viewport, displayId, reactRoot, null);
593
+ }
594
+
595
+ OriginSnapshot(final int[] onScreen, final Point viewport, final int displayId,
596
+ final boolean reactRoot, @Nullable final Point displaySize) {
597
+ this.onScreen = onScreen;
598
+ this.viewport = viewport;
599
+ this.displayId = displayId;
600
+ this.reactRoot = reactRoot;
601
+ this.displaySize = displaySize;
602
+ }
603
+ }
604
+
605
+ /** A layout-listener registration. UI thread only. */
606
+ interface LayoutListenerToken {
607
+ /** Removes the registration. Idempotent: only the first call does anything. */
608
+ void release();
609
+ }
610
+
611
+ /**
612
+ * The idempotency every production {@link LayoutListenerToken} shares:
613
+ * {@link #releaseNow()} runs on the first {@link #release()} only.
614
+ * Package-visible so a JVM test can check the guard itself.
615
+ */
616
+ abstract static class ReleaseOnceToken implements LayoutListenerToken {
617
+ /** UI thread only, like every other call on a token. */
618
+ private boolean released;
619
+
620
+ @Override
621
+ public final void release() {
622
+ if (released) {
623
+ return;
624
+ }
625
+ released = true;
626
+ releaseNow();
627
+ }
628
+
629
+ abstract void releaseNow();
630
+ }
631
+
632
+ private static final class ActivityRootFinder implements RootFinder {
633
+ private final ReactApplicationContext context;
634
+
635
+ ActivityRootFinder(final ReactApplicationContext context) {
636
+ this.context = context;
637
+ }
638
+
639
+ @Nullable
640
+ @Override
641
+ public RootHandle findCurrentRoot() {
642
+ final Activity activity = context.getCurrentActivity();
643
+ if (activity == null || activity.getWindow() == null) {
644
+ return null;
645
+ }
646
+ final View view = firstRootView(activity.getWindow().getDecorView());
647
+ return view == null ? null : new ViewRootHandle(view, ViewRootHandle.surfaceKeyOf(view));
648
+ }
649
+ }
650
+
651
+ /**
652
+ * Production {@link SurfaceResolver}: the {@code <Modal>} host view for
653
+ * the tag forwards {@code getChildAt} to its {@code DialogRootViewGroup}
654
+ * ({@code ReactModalHostView}), so the dialog root is the React root of
655
+ * the host's first child. {@code null} until the modal has content.
656
+ */
657
+ private static final class ModalSurfaceResolver implements SurfaceResolver {
658
+ private final ReactApplicationContext context;
659
+
660
+ ModalSurfaceResolver(final ReactApplicationContext context) {
661
+ this.context = context;
662
+ }
663
+
664
+ @Nullable
665
+ @Override
666
+ public RootHandle resolve(final int surfaceKey) {
667
+ if (!context.hasActiveReactInstance()) {
668
+ return null;
669
+ }
670
+ final UIManager uiManager = UIManagerHelper.getUIManagerForReactTag(context, surfaceKey);
671
+ if (uiManager == null) {
672
+ return null;
673
+ }
674
+ final View host = uiManager.resolveView(surfaceKey);
675
+ if (!(host instanceof ViewGroup) || ((ViewGroup) host).getChildCount() == 0) {
676
+ return null;
677
+ }
678
+ final View child = ((ViewGroup) host).getChildAt(0);
679
+ final RootView root = child == null ? null : RootViewUtil.getRootView(child);
680
+ if (!(root instanceof View) || root instanceof ReactRoot) {
681
+ return null;
682
+ }
683
+ return new ViewRootHandle((View) root, surfaceKey);
684
+ }
685
+ }
686
+
687
+ @Nullable
688
+ private static View firstRootView(@NonNull final View view) {
689
+ if (view instanceof RootView) {
690
+ return view;
691
+ }
692
+ if (view instanceof ViewGroup) {
693
+ final ViewGroup group = (ViewGroup) view;
694
+ for (int i = 0; i < group.getChildCount(); i++) {
695
+ final View found = firstRootView(group.getChildAt(i));
696
+ if (found != null) {
697
+ return found;
698
+ }
699
+ }
700
+ }
701
+ return null;
702
+ }
703
+
704
+ /**
705
+ * Production {@link RootHandle}, backed by a real {@link View}. Holds it
706
+ * weakly, same as the field this replaced: the root belongs to an
707
+ * activity that may die before {@link #dispose()} is called.
708
+ */
709
+ private static final class ViewRootHandle implements RootHandle {
710
+ private final WeakReference<View> view;
711
+ private final int surfaceKey;
712
+
713
+ ViewRootHandle(final View view, final int surfaceKey) {
714
+ this.view = new WeakReference<>(view);
715
+ this.surfaceKey = surfaceKey;
716
+ }
717
+
718
+ /**
719
+ * React tags for RootViews are positive; {@link View#NO_ID} falls
720
+ * back to identity so two untagged roots still stay apart.
721
+ */
722
+ static int surfaceKeyOf(@NonNull final View view) {
723
+ final int id = view.getId();
724
+ return id != View.NO_ID ? id : System.identityHashCode(view);
725
+ }
726
+
727
+ @Nullable
728
+ private View view() {
729
+ return view.get();
730
+ }
731
+
732
+ @Override
733
+ public boolean isAttachedToWindow() {
734
+ final View v = view();
735
+ return v != null && v.isAttachedToWindow();
736
+ }
737
+
738
+ @Override
739
+ public int surfaceKey() {
740
+ return surfaceKey;
741
+ }
742
+
743
+ @Nullable
744
+ @Override
745
+ public OriginSnapshot resolveOrigin() {
746
+ final View v = view();
747
+ if (v == null) {
748
+ return null;
749
+ }
750
+ final int[] onScreen = new int[2];
751
+ v.getLocationOnScreen(onScreen);
752
+ // Read for every root, so the log shows it; only a ReactRoot's is
753
+ // subtracted (surfaceOrigin).
754
+ final boolean reactRoot = v instanceof ReactRoot;
755
+ final Point viewport = RootViewUtil.getViewportOffset(v);
756
+ final Display display = v.getDisplay();
757
+ final int displayId = display == null ? Display.DEFAULT_DISPLAY : display.getDisplayId();
758
+ Point size = null;
759
+ if (display != null) {
760
+ size = new Point();
761
+ display.getRealSize(size);
762
+ }
763
+ return new OriginSnapshot(onScreen, viewport, displayId, reactRoot, size);
764
+ }
765
+
766
+ @Override
767
+ public LayoutListenerToken addOnGlobalLayoutListener(final Runnable onLayout) {
768
+ final View v = view();
769
+ if (v == null) {
770
+ return NoOpToken.INSTANCE;
771
+ }
772
+ return new ViewTreeObserverToken(v, onLayout);
773
+ }
774
+ }
775
+
776
+ /**
777
+ * Whether {@link ViewTreeObserverToken}'s listener should replace its
778
+ * saved observer with the view's current one: only a cleared or dead
779
+ * saved observer, and only while the view is attached. Pure, so a JVM
780
+ * test can check the decision itself.
781
+ */
782
+ static boolean shouldRehome(final boolean savedAlive, final boolean viewAttached) {
783
+ return !savedAlive && viewAttached;
784
+ }
785
+
786
+ /**
787
+ * A layout listener on a real {@link View}, and the one place that knows
788
+ * which {@link ViewTreeObserver} it has to be removed from.
789
+ *
790
+ * <p>That is not simply "the observer it was added to". A listener added
791
+ * before the view is attached goes onto a "floating" observer; on attach,
792
+ * Android merges it into the window's observer and kills the floating
793
+ * one. And a detached view's {@code getViewTreeObserver()} hands back a
794
+ * floating observer again, not the window's that still holds the
795
+ * listener. So the observer reference is re-homed from inside the
796
+ * listener, when {@link #shouldRehome} says so: only once the saved
797
+ * observer is gone or dead (a live one is always the observer holding
798
+ * the listener, even if the view has since moved to another window), and
799
+ * only while the view is attached -- only a window's observer ever
800
+ * dispatches a global layout ({@code ViewRootImpl} calls it on
801
+ * {@code mAttachInfo.mTreeObserver}), and while the view is attached,
802
+ * that is exactly what its {@code getViewTreeObserver()} returns.
803
+ * Otherwise the saved reference stands -- which is what lets a root
804
+ * replaced inside a live window still be removed from that window's
805
+ * observer.
806
+ *
807
+ * <p>The view and the observer are held weakly: a live observer
808
+ * transitively pins the view, and so the activity, and this token can
809
+ * outlive both
810
+ * {@link #dispose()} (which posts detach() to the UI thread) and a host
811
+ * reload.
812
+ */
813
+ private static final class ViewTreeObserverToken extends ReleaseOnceToken {
814
+ private final WeakReference<View> view;
815
+ private final ViewTreeObserver.OnGlobalLayoutListener listener;
816
+ /** UI thread only: re-homed by {@link #listener}, read by release. */
817
+ private WeakReference<ViewTreeObserver> observer;
818
+
819
+ ViewTreeObserverToken(@NonNull final View v, @NonNull final Runnable onLayout) {
820
+ this.view = new WeakReference<>(v);
821
+ this.listener = () -> {
822
+ // Before onLayout: that may detach(), and so release this.
823
+ final ViewTreeObserver saved = observer.get();
824
+ final View current = view.get();
825
+ if (current != null
826
+ && shouldRehome(saved != null && saved.isAlive(), current.isAttachedToWindow())) {
827
+ observer = new WeakReference<>(current.getViewTreeObserver());
828
+ }
829
+ onLayout.run();
830
+ };
831
+ final ViewTreeObserver o = v.getViewTreeObserver();
832
+ this.observer = new WeakReference<>(o);
833
+ o.addOnGlobalLayoutListener(listener);
834
+ }
835
+
836
+ /**
837
+ * From the saved observer if it is alive; otherwise -- it was the
838
+ * floating one, killed by the merge on attach before any layout could
839
+ * re-home it -- from the view's current observer, if that is alive.
840
+ * A dead observer throws on any call but {@code isAlive()}.
841
+ */
842
+ @Override
843
+ void releaseNow() {
844
+ final ViewTreeObserver saved = observer.get();
845
+ if (saved != null && saved.isAlive()) {
846
+ saved.removeOnGlobalLayoutListener(listener);
847
+ return;
848
+ }
849
+ final View v = view.get();
850
+ if (v == null) {
851
+ return;
852
+ }
853
+ final ViewTreeObserver current = v.getViewTreeObserver();
854
+ if (current.isAlive()) {
855
+ current.removeOnGlobalLayoutListener(listener);
856
+ }
857
+ }
858
+ }
859
+
860
+ private enum NoOpToken implements LayoutListenerToken {
861
+ INSTANCE;
862
+
863
+ @Override
864
+ public void release() {
865
+ }
866
+ }
867
+ }