diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java index e9137940991d..db61fe34fd02 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java @@ -480,6 +480,8 @@ public void initialize() { mReactApplicationContext.internal_registerInteropModule( RCTEventEmitter.class, interopEventEmitter); } + // Last, so that a throw above can't leak the context: invalidate() is never called then. + TextLayoutManager.createSpannableCache(mReactApplicationContext); } @Override @@ -500,6 +502,8 @@ public void invalidate() { } mDestroyed = true; + // Before the teardown hooks below, which can throw and would otherwise leak the context. + TextLayoutManager.destroySpannableCache(mReactApplicationContext); mEventDispatcher.removeBatchEventDispatchedListener(mBatchEventDispatchedListener); mEventDispatcher.invalidate(); @@ -680,7 +684,8 @@ public long measureText( ? (ReactTextViewManagerCallback) textViewManager : null, attachmentsPositions, - mTextEffectRegistry); + mTextEffectRegistry, + mReactApplicationContext); } @AnyThread diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/TextLayoutManager.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/TextLayoutManager.kt index 9f1a798a5fd2..f60b5b043c3d 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/TextLayoutManager.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/TextLayoutManager.kt @@ -31,6 +31,9 @@ import com.facebook.common.logging.FLog import com.facebook.infer.annotation.Assertions import com.facebook.react.bridge.JavaOnlyArray import com.facebook.react.bridge.JavaOnlyMap +import com.facebook.react.bridge.ReactContext +import com.facebook.react.bridge.ReactNoCrashSoftException +import com.facebook.react.bridge.ReactSoftExceptionLogger import com.facebook.react.bridge.ReadableMap import com.facebook.react.bridge.WritableArray import com.facebook.react.common.ReactConstants @@ -43,6 +46,7 @@ import com.facebook.react.uimanager.PixelUtil import com.facebook.react.uimanager.PixelUtil.dpToPx import com.facebook.react.uimanager.PixelUtil.pxToDp import com.facebook.react.uimanager.ReactAccessibilityDelegate +import com.facebook.react.uimanager.ThemedReactContext import com.facebook.react.util.AndroidVersion.VERSION_CODE_VANILLA_ICE_CREAM import com.facebook.react.views.text.internal.span.CustomLetterSpacingSpan import com.facebook.react.views.text.internal.span.CustomLineHeightSpan @@ -123,7 +127,11 @@ internal object TextLayoutManager { // can arrive a fraction of a pixel short of it (e.g. 371.99997 instead of 372). internal const val PIXEL_SIZE_TOLERANCE: Float = 0.001f - private val tagToSpannableCache = ConcurrentHashMap() + // TextInput spannables keyed by react tag, one map per React instance. Tags restart from the same + // value in every instance, so entries must not be shared across instances. FabricUIManager + // creates and destroys the map for its ReactApplicationContext. + private val tagToSpannableCaches = + ConcurrentHashMap>() // These wrappers mirror Android 15 APIs but use reflection because some internal targets still // compile against Android 14. They return null when the API is unavailable or cannot be invoked. @@ -188,12 +196,30 @@ internal object TextLayoutManager { null } - fun setCachedSpannableForTag(reactTag: Int, sp: Spannable) { - tagToSpannableCache[reactTag] = sp + // Views hold a ThemedReactContext while FabricUIManager holds the ReactApplicationContext it + // wraps. Every cache access goes through this so both resolve to the same key. + private fun spannableCacheKey(reactContext: ReactContext): ReactContext = + if (reactContext is ThemedReactContext) reactContext.reactApplicationContext else reactContext + + @JvmStatic + fun createSpannableCache(reactContext: ReactContext) { + tagToSpannableCaches[spannableCacheKey(reactContext)] = ConcurrentHashMap() + } + + @JvmStatic + fun destroySpannableCache(reactContext: ReactContext) { + tagToSpannableCaches.remove(spannableCacheKey(reactContext)) + } + + internal fun getSpannableCache(reactContext: ReactContext): ConcurrentHashMap? = + tagToSpannableCaches[spannableCacheKey(reactContext)] + + fun setCachedSpannableForTag(reactContext: ReactContext, reactTag: Int, sp: Spannable) { + getSpannableCache(reactContext)?.put(reactTag, sp) } - fun deleteCachedSpannableForTag(reactTag: Int) { - tagToSpannableCache.remove(reactTag) + fun deleteCachedSpannableForTag(reactContext: ReactContext, reactTag: Int) { + getSpannableCache(reactContext)?.remove(reactTag) } fun isRTL(attributedString: MapBuffer): Boolean { @@ -808,25 +834,15 @@ internal object TextLayoutManager { attributedString: MapBuffer, reactTextViewManagerCallback: ReactTextViewManagerCallback?, textEffectRegistry: TextEffectRegistry?, - ): Spannable { - val text: Spannable? - if (attributedString.contains(AS_KEY_CACHE_ID)) { - val cacheId = attributedString.getInt(AS_KEY_CACHE_ID) - text = checkNotNull(tagToSpannableCache[cacheId]) - } else { - text = - createSpannableFromAttributedString( - assets, - fontWeightAdjustment, - attributedString.getMapBuffer(AS_KEY_FRAGMENTS), - reactTextViewManagerCallback, - null, - textEffectRegistry, - ) - } - - return text - } + ): Spannable = + createSpannableFromAttributedString( + assets, + fontWeightAdjustment, + attributedString.getMapBuffer(AS_KEY_FRAGMENTS), + reactTextViewManagerCallback, + null, + textEffectRegistry, + ) @OptIn(UnstableReactNativeAPI::class) private fun createSpannableFromAttributedString( @@ -1233,20 +1249,36 @@ internal object TextLayoutManager { heightYogaMeasureMode: YogaMeasureMode, reactTextViewManagerCallback: ReactTextViewManagerCallback?, textEffectRegistry: TextEffectRegistry? = null, - ): Layout { - val text = - getOrCreateSpannableForText( - assets, - fontWeightAdjustment, - attributedString, - reactTextViewManagerCallback, - textEffectRegistry, - ) - + spannableCacheOwner: ReactContext? = null, + ): Layout? { + val text: Spannable val paint: TextPaint if (attributedString.contains(AS_KEY_CACHE_ID)) { + val cacheId = attributedString.getInt(AS_KEY_CACHE_ID) + // The instance's map is gone once FabricUIManager.invalidate() ran; a layout of that + // instance still in flight measures nothing. + val cache = spannableCacheOwner?.let { getSpannableCache(it) } ?: return null + text = + cache[cacheId] + ?: run { + // Only ReactEditText.finalize() evicts within a live instance, so this means a + // collected view's shadow node is still being measured. + ReactSoftExceptionLogger.logSoftException( + TAG, + ReactNoCrashSoftException("No cached spannable for TextInput $cacheId"), + ) + return null + } paint = text.getSpans(0, 0, ReactTextPaintHolderSpan::class.java)[0].textPaint } else { + text = + getOrCreateSpannableForText( + assets, + fontWeightAdjustment, + attributedString, + reactTextViewManagerCallback, + textEffectRegistry, + ) val baseTextAttributes = TextAttributeProps.fromMapBuffer(attributedString.getMapBuffer(AS_KEY_BASE_ATTRIBUTES)) paint = scratchPaintWithAttributes(baseTextAttributes, assets, fontWeightAdjustment) @@ -1688,6 +1720,7 @@ internal object TextLayoutManager { reactTextViewManagerCallback: ReactTextViewManagerCallback?, attachmentsPositions: FloatArray?, textEffectRegistry: TextEffectRegistry? = null, + spannableCacheOwner: ReactContext? = null, ): Long { // TODO(5578671): Handle text direction (see View#getTextDirectionHeuristic) val layout = @@ -1702,7 +1735,8 @@ internal object TextLayoutManager { heightYogaMeasureMode, reactTextViewManagerCallback, textEffectRegistry, - ) + spannableCacheOwner, + ) ?: return YogaMeasureOutput.make(0f, 0f) val maximumNumberOfLines = if (paragraphAttributes.contains(PA_KEY_MAX_NUMBER_OF_LINES)) @@ -2007,7 +2041,7 @@ internal object TextLayoutManager { YogaMeasureMode.EXACTLY, reactTextViewManagerCallback, textEffectRegistry, - ) + )!! return FontMetricsUtil.getFontMetrics( layout.text, layout, diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditText.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditText.kt index 8c98928ea7cf..90b293418323 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditText.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditText.kt @@ -315,7 +315,7 @@ public open class ReactEditText public constructor(context: Context) : AppCompat if (DEBUG_MODE) { FLog.e(TAG, "finalize[$id] delete cached spannable") } - TextLayoutManager.deleteCachedSpannableForTag(id) + TextLayoutManager.deleteCachedSpannableForTag(UIManagerHelper.getReactContext(this), id) } // After the text changes inside an EditText, TextView checks if a layout() has been requested. @@ -1288,7 +1288,7 @@ public open class ReactEditText public constructor(context: Context) : AppCompat sb.length, Spannable.SPAN_INCLUSIVE_INCLUSIVE, ) - TextLayoutManager.setCachedSpannableForTag(id, sb) + TextLayoutManager.setCachedSpannableForTag(UIManagerHelper.getReactContext(this), id, sb) } public fun setEventDispatcher(eventDispatcher: EventDispatcher?) { diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/FabricUIManagerTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/FabricUIManagerTest.kt index 38033aae0a54..025b2587b4de 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/FabricUIManagerTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/FabricUIManagerTest.kt @@ -13,14 +13,17 @@ import com.facebook.react.bridge.BridgeReactContext import com.facebook.react.bridge.JavaOnlyArray import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.internal.featureflags.ReactNativeFeatureFlagsForTests +import com.facebook.react.modules.core.ReactChoreographer import com.facebook.react.uimanager.ViewManagerRegistry import com.facebook.react.uimanager.events.BatchEventDispatchedListener +import com.facebook.react.views.text.TextLayoutManager import com.facebook.testutils.fakes.FakeBatchEventDispatchedListener import com.facebook.testutils.shadows.ShadowSoLoader import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith +import org.mockito.kotlin.mock import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config @@ -61,4 +64,18 @@ class FabricUIManagerTest { val className = command::class.java.name.substringAfterLast(".") assertThat(className).isEqualTo("DispatchIntCommandMountItem") } + + @Test + fun initializeAndInvalidate_createAndDestroySpannableCache() { + val originalChoreographer = ReactChoreographer.overrideInstanceForTest(mock()) + try { + underTest.initialize() + assertThat(TextLayoutManager.getSpannableCache(reactContext)).isNotNull() + + underTest.invalidate() + assertThat(TextLayoutManager.getSpannableCache(reactContext)).isNull() + } finally { + ReactChoreographer.overrideInstanceForTest(originalChoreographer) + } + } } diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/textinput/ReactEditTextSpannableCacheTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/textinput/ReactEditTextSpannableCacheTest.kt new file mode 100644 index 000000000000..ea5d1a688ade --- /dev/null +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/textinput/ReactEditTextSpannableCacheTest.kt @@ -0,0 +1,134 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.views.textinput + +import android.text.SpannableString +import android.util.DisplayMetrics +import android.view.Gravity +import androidx.core.content.res.ResourcesCompat.ID_NULL +import com.facebook.react.bridge.ReactApplicationContext +import com.facebook.react.bridge.ReactSoftExceptionLogger +import com.facebook.react.common.annotations.UnstableReactNativeAPI +import com.facebook.react.common.mapbuffer.WritableMapBuffer +import com.facebook.react.internal.featureflags.ReactNativeFeatureFlagsForTests +import com.facebook.react.uimanager.DisplayMetricsHolder +import com.facebook.react.uimanager.StateWrapper +import com.facebook.react.uimanager.ThemedReactContext +import com.facebook.react.views.text.ReactTextUpdate +import com.facebook.react.views.text.TextLayoutManager +import com.facebook.yoga.YogaMeasureMode +import com.facebook.yoga.YogaMeasureOutput +import org.assertj.core.api.Assertions.assertThat +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.kotlin.mock +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment + +@RunWith(RobolectricTestRunner::class) +class ReactEditTextSpannableCacheTest { + + private val oldRuntime = mock() + private val newRuntime = mock() + private val softExceptions = mutableListOf() + private val softExceptionListener = + ReactSoftExceptionLogger.ReactSoftExceptionListener { _, cause -> softExceptions.add(cause) } + + @Before + fun setup() { + ReactNativeFeatureFlagsForTests.setUp() + DisplayMetricsHolder.setScreenDisplayMetrics(DisplayMetrics()) + ReactSoftExceptionLogger.addListener(softExceptionListener) + } + + @After + fun tearDown() { + ReactSoftExceptionLogger.removeListener(softExceptionListener) + TextLayoutManager.destroySpannableCache(oldRuntime) + TextLayoutManager.destroySpannableCache(newRuntime) + } + + @Test + fun `a view from a destroyed runtime does not evict a new runtime's spannable for the same tag`() { + TextLayoutManager.createSpannableCache(oldRuntime) + val staleView = createViewWithCachedText(oldRuntime) + TextLayoutManager.destroySpannableCache(oldRuntime) + TextLayoutManager.createSpannableCache(newRuntime) + createViewWithCachedText(newRuntime) + + runFinalizer(staleView) + + assertThat(YogaMeasureOutput.getHeight(measureCachedText(newRuntime))).isPositive() + } + + @Test + fun `measuring after the runtime's cache is destroyed returns zero`() { + TextLayoutManager.createSpannableCache(oldRuntime) + createViewWithCachedText(oldRuntime) + TextLayoutManager.destroySpannableCache(oldRuntime) + + assertThat(measureCachedText(oldRuntime)).isEqualTo(YogaMeasureOutput.make(0f, 0f)) + assertThat(softExceptions).isEmpty() + } + + @Test + fun `measuring after the view's finalizer evicted it returns zero and logs a soft exception`() { + TextLayoutManager.createSpannableCache(newRuntime) + runFinalizer(createViewWithCachedText(newRuntime)) + + assertThat(measureCachedText(newRuntime)).isEqualTo(YogaMeasureOutput.make(0f, 0f)) + assertThat(softExceptions).hasSize(1) + } + + private fun createViewWithCachedText(runtime: ReactApplicationContext): ReactEditText { + val themedContext = + ThemedReactContext(runtime, RuntimeEnvironment.getApplication(), null, ID_NULL) + val view = ReactTextInputManager().createViewInstance(themedContext) + view.id = TAG + view.stateWrapper = mock() + view.maybeSetTextFromState( + ReactTextUpdate( + SpannableString("text"), + 0, + view.gravity and Gravity.HORIZONTAL_GRAVITY_MASK, + 0, + 0, + ), + ) + return view + } + + private fun runFinalizer(view: ReactEditText) { + ReactEditText::class.java.getDeclaredMethod("finalize").apply { isAccessible = true }(view) + } + + @OptIn(UnstableReactNativeAPI::class) + private fun measureCachedText(runtime: ReactApplicationContext): Long = + TextLayoutManager.measureText( + RuntimeEnvironment.getApplication().assets, + 0, + WritableMapBuffer().put(TextLayoutManager.AS_KEY_CACHE_ID, TAG), + WritableMapBuffer() + .put(TextLayoutManager.PA_KEY_TEXT_BREAK_STRATEGY, "simple") + .put(TextLayoutManager.PA_KEY_HYPHENATION_FREQUENCY, "none"), + 100f, + YogaMeasureMode.EXACTLY, + 100f, + YogaMeasureMode.EXACTLY, + null, + null, + null, + runtime, + ) + + private companion object { + const val TAG = 42 + } +}