diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.cpp index 1899ca0a444..f601a71bf6c 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.cpp @@ -125,29 +125,12 @@ void FabricUIManagerBinding::pullAndExecuteTransaction(SurfaceId surfaceId) { std::shared_ptr mountingCoordinator; { - std::shared_lock lock(surfaceHandlerRegistryMutex_); - auto iterator = surfaceHandlerRegistry_.find(surfaceId); - if (iterator == surfaceHandlerRegistry_.end()) { + std::scoped_lock lock(pullableMountingCoordinatorsMutex_); + auto pullable = pullableMountingCoordinators_.extract(surfaceId); + if (pullable.empty()) { return; } - const auto* surfaceHandler = std::get_if(&iterator->second); - jni::local_ref javaSurfaceHandler; - if (surfaceHandler == nullptr) { - javaSurfaceHandler = - std::get>( - iterator->second) - .lockLocal(); - if (javaSurfaceHandler) { - surfaceHandler = &javaSurfaceHandler->cthis()->getSurfaceHandler(); - } - } - if (surfaceHandler != nullptr) { - mountingCoordinator = surfaceHandler->getMountingCoordinator(); - } - } - - if (mountingCoordinator == nullptr) { - return; + mountingCoordinator = std::move(pullable.mapped()); } auto mountingManager = getMountingManager("pullAndExecuteTransaction"); @@ -732,8 +715,19 @@ void FabricUIManagerBinding::schedulerShouldRenderTransactions( // commit thread). Just notify Java that a transaction is available; the UI // thread calls back into `pullAndExecuteTransaction` at its next mount // dispatch. - mountingManager->onTransactionAvailable( - mountingCoordinator->getSurfaceId()); + auto surfaceId = mountingCoordinator->getSurfaceId(); + { + std::scoped_lock lock(pullableMountingCoordinatorsMutex_); + auto& pullable = pullableMountingCoordinators_[surfaceId]; + if (pullable != nullptr && pullable != mountingCoordinator) { + LOG(WARNING) + << "FabricUIManagerBinding::schedulerShouldRenderTransactions: " + << "surface " << surfaceId + << " was restarted while the previous surface's commit waits to be pulled"; + } + pullable = mountingCoordinator; + } + mountingManager->onTransactionAvailable(surfaceId); } else if (ReactNativeFeatureFlags:: enableAccumulatedUpdatesInRawPropsAndroid()) { auto mountingTransaction = mountingCoordinator->pullTransaction( diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.h b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.h index 97229f08fdc..68c47706ba7 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.h @@ -167,6 +167,12 @@ class FabricUIManagerBinding : public jni::HybridClass, std::mutex pendingTransactionsMutex_; std::vector pendingTransactions_; + // Pull model: keeps the coordinator that reported a surface's commit alive + // until the UI thread handles the pull, as iOS does by capturing it in the + // block it dispatches to the main queue. Java only gets the surface id. + std::mutex pullableMountingCoordinatorsMutex_; + std::unordered_map> pullableMountingCoordinators_; + float pointScaleFactor_ = 1; bool enableFabricLogs_{false}; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/test_helper/FabricMountingManagerTestHelper.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/test_helper/FabricMountingManagerTestHelper.cpp index ab92780e3c0..0486e452976 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/test_helper/FabricMountingManagerTestHelper.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/test_helper/FabricMountingManagerTestHelper.cpp @@ -7,16 +7,21 @@ #include "FabricMountingManagerTestHelper.h" +#include #include #include #include +#include +#include #include #include #include #include #include +#include #include #include +#include #include namespace facebook::react { @@ -31,6 +36,30 @@ static LayoutConstraints makeLayoutConstraints( .layoutDirection = LayoutDirection::LeftToRight}; } +class FabricMountingManagerTestHelper::DeleteRecorder + : public MountingOverrideDelegate { + public: + bool shouldOverridePullTransaction() const override { + return true; + } + + std::optional pullTransaction( + SurfaceId surfaceId, + MountingTransaction::Number number, + const TransactionTelemetry& telemetry, + ShadowViewMutationList mutations) const override { + for (const auto& mutation : mutations) { + if (mutation.type == ShadowViewMutation::Delete) { + deletedTags.push_back(mutation.oldChildShadowView.tag); + } + } + return MountingTransaction{ + surfaceId, number, std::move(mutations), telemetry}; + } + + mutable std::vector deletedTags; +}; + namespace { ShadowView makeShadowView(jint surfaceId, jint tag) { @@ -43,6 +72,13 @@ ShadowView makeShadowView(jint surfaceId, jint tag) { return sv; } +void runNoJavaScript(std::function&& /*unused*/) {} + +std::vector toTags(jni::alias_ref tags) { + auto region = tags->getRegion(0, static_cast(tags->size())); + return {region.get(), region.get() + tags->size()}; +} + } // namespace FabricMountingManagerTestHelper::FabricMountingManagerTestHelper( @@ -285,6 +321,85 @@ void FabricMountingManagerTestHelper::mountPendingTransaction() { } } +jni::local_ref +FabricMountingManagerTestHelper::createRuntimeExecutor() { + return JRuntimeExecutor::newObjectCxxArgs(runNoJavaScript); +} + +jni::local_ref +FabricMountingManagerTestHelper::createRuntimeScheduler() { + // Work scheduled here never runs and stays queued. A queued task holds the + // UIManager, which holds this scheduler, so both outlive the test. + runtimeScheduler_ = std::make_shared(runNoJavaScript); + return JRuntimeScheduler::newObjectCxxArgs(runtimeScheduler_); +} + +void FabricMountingManagerTestHelper::registerViewComponent( + ComponentFactory* componentFactory) { + componentFactory->buildRegistryFunction = + [](const EventDispatcher::Weak& eventDispatcher, + const std::shared_ptr& contextContainer) { + auto providerRegistry = + std::make_shared(); + providerRegistry->add( + concreteComponentDescriptorProvider()); + return providerRegistry->createComponentDescriptorRegistry( + {.eventDispatcher = eventDispatcher, + .contextContainer = contextContainer, + .flavor = nullptr}); + }; +} + +void FabricMountingManagerTestHelper::commitViews( + jint surfaceId, + jni::alias_ref tags) { + auto children = + std::make_shared>>(); + for (auto tag : toTags(tags)) { + auto props = std::make_shared(); + props->collapsable = false; + children->push_back(viewComponentDescriptor_->createShadowNode( + {.props = props}, + viewComponentDescriptor_->createFamily( + {.tag = tag, .surfaceId = surfaceId, .instanceHandle = nullptr}))); + } + javaUIManager_->getBinding() + ->getScheduler() + ->getUIManager() + ->getShadowTreeRegistry() + .visit(surfaceId, [&](const ShadowTree& shadowTree) { + shadowTree.commit( + [&](const RootShadowNode& oldRootShadowNode) { + return std::make_shared( + oldRootShadowNode, + ShadowNodeFragment{ + .props = ShadowNodeFragment::propsPlaceholder(), + .children = children}); + }, + {}); + }); +} + +void FabricMountingManagerTestHelper::recordPulledDeletes(jint surfaceId) { + deleteRecorder_ = std::make_shared(); + javaUIManager_->getBinding() + ->getScheduler() + ->getUIManager() + ->getShadowTreeRegistry() + .visit(surfaceId, [&](const ShadowTree& shadowTree) { + shadowTree.getMountingCoordinator()->setMountingOverrideDelegate( + deleteRecorder_); + }); +} + +jni::local_ref +FabricMountingManagerTestHelper::pulledDeleteTags() { + const auto& tags = deleteRecorder_->deletedTags; + auto array = jni::JArrayInt::newArray(tags.size()); + array->setRegion(0, static_cast(tags.size()), tags.data()); + return array; +} + void FabricMountingManagerTestHelper::registerNatives() { registerHybrid({ makeNativeMethod( @@ -332,6 +447,23 @@ void FabricMountingManagerTestHelper::registerNatives() { makeNativeMethod( "resetFeatureFlags", FabricMountingManagerTestHelper::resetFeatureFlags), + makeNativeMethod( + "createRuntimeExecutor", + FabricMountingManagerTestHelper::createRuntimeExecutor), + makeNativeMethod( + "createRuntimeScheduler", + FabricMountingManagerTestHelper::createRuntimeScheduler), + makeNativeMethod( + "registerViewComponent", + FabricMountingManagerTestHelper::registerViewComponent), + makeNativeMethod( + "commitViews", FabricMountingManagerTestHelper::commitViews), + makeNativeMethod( + "recordPulledDeletes", + FabricMountingManagerTestHelper::recordPulledDeletes), + makeNativeMethod( + "pulledDeleteTags", + FabricMountingManagerTestHelper::pulledDeleteTags), }); } diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/test_helper/FabricMountingManagerTestHelper.h b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/test_helper/FabricMountingManagerTestHelper.h index cb191189bed..40f50eeb9c5 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/test_helper/FabricMountingManagerTestHelper.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/test_helper/FabricMountingManagerTestHelper.h @@ -8,11 +8,14 @@ #pragma once #include +#include +#include #include #include #include #include +#include #include #include @@ -45,6 +48,17 @@ class FabricMountingManagerTestHelper : public jni::HybridClass createRuntimeExecutor(); + jni::local_ref createRuntimeScheduler(); + void registerViewComponent(ComponentFactory *componentFactory); + + void commitViews(jint surfaceId, jni::alias_ref tags); + void recordPulledDeletes(jint surfaceId); + jni::local_ref pulledDeleteTags(); + static void registerNatives(); private: @@ -65,6 +79,9 @@ class FabricMountingManagerTestHelper : public jni::HybridClass shadowTreeDelegate_; std::unique_ptr shadowTree_; std::unordered_map> queuedShadowNodes_; + std::shared_ptr runtimeScheduler_; + class DeleteRecorder; + std::shared_ptr deleteRecorder_; }; } // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/FabricMountingManagerInstrumentationTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/FabricMountingManagerInstrumentationTest.kt index cc92999b13e..f88622d5e48 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/FabricMountingManagerInstrumentationTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/FabricMountingManagerInstrumentationTest.kt @@ -8,6 +8,7 @@ package com.facebook.react.fabric import android.graphics.Rect +import android.view.View import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import com.facebook.react.ReactRootView @@ -17,6 +18,7 @@ import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReadableType import com.facebook.react.bridge.WritableNativeArray import com.facebook.react.bridge.WritableNativeMap +import com.facebook.react.fabric.events.EventBeatManager import com.facebook.react.fabric.mounting.MountingManager import com.facebook.react.fabric.mounting.MountingManager.MountItemExecutor import com.facebook.react.fabric.mounting.mountitems.IntBufferBatchMountItem @@ -24,6 +26,7 @@ import com.facebook.react.internal.featureflags.ReactNativeFeatureFlags import com.facebook.react.internal.featureflags.ReactNativeFeatureFlagsCxxInterop import com.facebook.react.internal.featureflags.ReactNativeFeatureFlagsDefaults import com.facebook.react.internal.featureflags.ReactNativeFeatureFlagsForTests +import com.facebook.react.uimanager.DisplayMetricsHolder import com.facebook.react.uimanager.PixelUtil import com.facebook.react.uimanager.ThemedReactContext import com.facebook.react.uimanager.ViewManager @@ -54,6 +57,7 @@ import org.mockito.Mockito.`when` class FabricMountingManagerInstrumentationTest { private lateinit var mountingManager: MountingManager private lateinit var themedReactContext: ThemedReactContext + private val surfaceId = 1 private var nativeFeatureFlagsHelper: FabricMountingManagerTestHelper? = null @@ -80,9 +84,16 @@ class FabricMountingManagerInstrumentationTest { @After fun tearDown() { - nativeFeatureFlagsHelper?.resetFeatureFlags() - ReactNativeFeatureFlags.dangerouslyReset() - ReactNativeFeatureFlagsCxxInterop.dangerouslyReset() + try { + while (cleanups.isNotEmpty()) { + cleanups.removeLast()() + } + } finally { + bindingDependencies.clear() + nativeFeatureFlagsHelper?.resetFeatureFlags() + ReactNativeFeatureFlags.dangerouslyReset() + ReactNativeFeatureFlagsCxxInterop.dangerouslyReset() + } } private fun startSurface() { @@ -471,4 +482,151 @@ class FabricMountingManagerInstrumentationTest { view.setPadding(left, top, right, bottom) } } + + // ---- Surface lifecycle through a real FabricUIManagerBinding ---- + + /** + * The pull model is tested with Props 2.0 (accumulated, exclusive and reconciled props, and props + * diffed on insert); the push model with all of these flags off. + */ + private fun overrideCxxFlags(pullModel: Boolean) { + ReactNativeFeatureFlagsCxxInterop.dangerouslyForceOverride( + object : ReactNativeFeatureFlagsDefaults() { + override fun enableMountingCoordinatorPullModelAndroid(): Boolean = pullModel + + override fun enableAccumulatedUpdatesInRawPropsAndroid(): Boolean = pullModel + + override fun enableExclusivePropsUpdateAndroid(): Boolean = pullModel + + override fun enablePropsUpdateReconciliationAndroid(): Boolean = pullModel + + override fun enablePreallocatedPropsDiffOnInsertAndroid(): Boolean = pullModel + } + ) + } + + /** + * Run in reverse order after each test: stop the surfaces a test leaves running, then unregister + * the bindings. + */ + private val cleanups = ArrayDeque<() -> Unit>() + + /** + * Kept alive until the bindings are unregistered, as a React instance keeps them: the native + * binding's event beat uses the event beat manager, and the helper owns the view component + * descriptor of the committed views. + */ + private val bindingDependencies = mutableListOf() + + private fun registerBinding(fabricUIManager: FabricUIManager): FabricMountingManagerTestHelper { + val binding = FabricUIManagerBinding() + val helper = FabricMountingManagerTestHelper.create(fabricUIManager) + cleanups.addLast { runOnUiThread { binding.unregister() } } + val componentFactory = ComponentFactory() + val eventBeatManager = EventBeatManager() + bindingDependencies.addAll(listOf(helper, eventBeatManager)) + helper.registerViewComponent(componentFactory) + DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(themedReactContext) + binding.register( + helper.createRuntimeExecutor(), + helper.createRuntimeScheduler(), + fabricUIManager, + eventBeatManager, + componentFactory, + ) + return helper + } + + private fun runOnUiThread(block: () -> Unit) { + InstrumentationRegistry.getInstrumentation().runOnMainSync(block) + } + + private val rootMeasureSpec = View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY) + + private fun startSurfaceWithHandler(fabricUIManager: FabricUIManager): SurfaceHandlerBinding { + val surfaceHandler = SurfaceHandlerBinding("TestModule") + surfaceHandler.setLayoutConstraints( + rootMeasureSpec, + rootMeasureSpec, + 0, + 0, + false, + false, + 1f, + 1f, + ) + fabricUIManager.startSurface( + surfaceHandler, + themedReactContext, + ReactRootView(themedReactContext), + ) + return surfaceHandler + } + + /** Starts a surface through the bridgeless path and returns its id and a function stopping it. */ + private fun startBridgelessSurface(fabricUIManager: FabricUIManager): Pair Unit> { + val surfaceHandler = startSurfaceWithHandler(fabricUIManager) + return surfaceHandler.surfaceId to { fabricUIManager.stopSurface(surfaceHandler) } + } + + /** Starts a surface through the legacy path and returns its id and a function stopping it. */ + private fun startLegacySurface(fabricUIManager: FabricUIManager): Pair Unit> { + val surfaceId = + fabricUIManager.startSurface( + ReactRootView(themedReactContext), + "TestModule", + null, + rootMeasureSpec, + rootMeasureSpec, + ) + return surfaceId to { fabricUIManager.stopSurface(surfaceId) } + } + + @Test + fun native_stopSurfaceWithSurfaceHandler_pullModel_pullsDeletes() { + assertStoppingSurfacePullsDeletes(pullModel = true, ::startBridgelessSurface) + } + + @Test + fun native_stopSurfaceWithSurfaceHandler_pushModel_pullsDeletes() { + assertStoppingSurfacePullsDeletes(pullModel = false, ::startBridgelessSurface) + } + + /** The legacy stop also runs on the UI thread, where its stop commit pulls inline. */ + @Test + fun native_stopSurface_pullModel_pullsDeletes() { + assertStoppingSurfacePullsDeletes(pullModel = true, ::startLegacySurface) + } + + /** + * The transaction that stops a surface deletes its views. Mounting override delegates, such as + * LayoutAnimations and C++ Animated, must see it pulled. + */ + private fun assertStoppingSurfacePullsDeletes( + pullModel: Boolean, + startSurface: (FabricUIManager) -> Pair Unit>, + ) { + overrideCxxFlags(pullModel) + val fabricUIManager = createFabricUIManager() + val helper = registerBinding(fabricUIManager) + lateinit var stopSurface: () -> Unit + var running = true + var mounted = false + runOnUiThread { + val (surfaceId, stop) = startSurface(fabricUIManager) + stopSurface = stop + cleanups.addLast { if (running) runOnUiThread(stop) } + helper.recordPulledDeletes(surfaceId) + helper.commitViews(surfaceId, intArrayOf(42, 43)) + mounted = fabricUIManager.resolveView(42) != null + } + assertThat(mounted).isTrue() + + runOnUiThread { + running = false + stopSurface() + } + + assertThat(helper.pulledDeleteTags()).containsExactlyInAnyOrder(42, 43) + } } diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/FabricMountingManagerTestHelper.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/FabricMountingManagerTestHelper.kt index 2a97d57cd4d..5edd4f0c00c 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/FabricMountingManagerTestHelper.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/FabricMountingManagerTestHelper.kt @@ -9,6 +9,8 @@ package com.facebook.react.fabric import com.facebook.jni.HybridClassBase import com.facebook.react.bridge.NativeMap +import com.facebook.react.bridge.RuntimeExecutor +import com.facebook.react.bridge.RuntimeScheduler import com.facebook.soloader.SoLoader /** @@ -16,8 +18,8 @@ import com.facebook.soloader.SoLoader * around the preallocation queue, executeMount, destroyUnmountedShadowNode, and the * allocatedViewRegistry_ lifecycle. */ -class FabricMountingManagerTestHelper private constructor(fabricUIManager: FabricUIManager) : - HybridClassBase() { +internal class FabricMountingManagerTestHelper +private constructor(fabricUIManager: FabricUIManager) : HybridClassBase() { init { initHybrid(fabricUIManager) @@ -67,6 +69,21 @@ class FabricMountingManagerTestHelper private constructor(fabricUIManager: Fabri external fun resetFeatureFlags() + // A FabricUIManagerBinding registered on the helper's FabricUIManager with these never runs + // JavaScript: its surfaces mount only what the helper commits. + external fun createRuntimeExecutor(): RuntimeExecutor + + external fun createRuntimeScheduler(): RuntimeScheduler + + external fun registerViewComponent(componentFactory: ComponentFactory) + + external fun commitViews(surfaceId: Int, tags: IntArray) + + /** Records the Delete mutations of every transaction pulled for the surface from now on. */ + external fun recordPulledDeletes(surfaceId: Int) + + external fun pulledDeleteTags(): IntArray + companion object { init { SoLoader.loadLibrary("fabricjni")