diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactSoftExceptionLogger.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactSoftExceptionLogger.kt index 877f2fc2843e..93606045a862 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactSoftExceptionLogger.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactSoftExceptionLogger.kt @@ -12,6 +12,7 @@ import com.facebook.common.logging.FLog import com.facebook.proguard.annotations.DoNotStrip import com.facebook.react.bridge.ReactSoftExceptionLogger.Categories.CLIPPING_PROHIBITED_VIEW import com.facebook.react.bridge.ReactSoftExceptionLogger.Categories.RVG_ADD_CHILDREN_FOR_ACCESSIBILITY +import com.facebook.react.bridge.ReactSoftExceptionLogger.Categories.RVG_CLIPPING_BAND import com.facebook.react.bridge.ReactSoftExceptionLogger.Categories.RVG_IS_VIEW_CLIPPED import com.facebook.react.bridge.ReactSoftExceptionLogger.Categories.RVG_ON_VIEW_REMOVED import com.facebook.react.bridge.ReactSoftExceptionLogger.Categories.SOFT_ASSERTIONS @@ -23,6 +24,7 @@ internal object ReactSoftExceptionLogger { @Retention(AnnotationRetention.SOURCE) @StringDef( RVG_ADD_CHILDREN_FOR_ACCESSIBILITY, + RVG_CLIPPING_BAND, RVG_IS_VIEW_CLIPPED, RVG_ON_VIEW_REMOVED, CLIPPING_PROHIBITED_VIEW, @@ -35,6 +37,7 @@ internal object ReactSoftExceptionLogger { object Categories { const val RVG_ADD_CHILDREN_FOR_ACCESSIBILITY: String = "ReactViewGroup.addChildrenForAccessibility" + const val RVG_CLIPPING_BAND: String = "ReactViewGroup.clippingBand" const val RVG_IS_VIEW_CLIPPED: String = "ReactViewGroup.isViewClipped" const val RVG_ON_VIEW_REMOVED: String = "ReactViewGroup.onViewRemoved" const val CLIPPING_PROHIBITED_VIEW: String = "ReactClippingProhibitedView" diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ClippingBand.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ClippingBand.kt new file mode 100644 index 000000000000..0f7bec4a93cb --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ClippingBand.kt @@ -0,0 +1,186 @@ +/* + * 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.view + +import android.graphics.Rect +import android.view.View +import androidx.annotation.VisibleForTesting +import kotlin.math.max +import kotlin.math.min + +/** Tests turn this off to compare the band with checking every child. */ +@VisibleForTesting internal var clippingBandEnabled: Boolean = true + +/** + * The children of a clipping [ReactViewGroup] that a new clipping rect can change, so that only + * those are updated instead of every child. + * + * Per axis, the running maximum of the children's ends and the running minimum of their starts are + * monotone in any child order, so binary searches find the band of children that can intersect a + * rect. In a list, that is the rows near the rect. + * + * Children outside the band are left as they are, which requires every child outside [rect] to be + * clipped: a pass over every child establishes it, adding, removing or laying out a child keeps it + * ([State.STALE]), and a focused, animating or excluded child left attached breaks it + * ([State.UNKNOWN]). + */ +internal class ClippingBand { + + enum class State { + /** A child outside [rect] may be attached: the next update checks every child. */ + UNKNOWN, + /** Children were added, removed or laid out: the band is rebuilt on the next update. */ + STALE, + /** The band applies. */ + VALID, + /** + * The attached children didn't match the band, which shouldn't happen. Every update checks + * every child until clipping is turned off or the view is recycled. + */ + DISABLED, + } + + var state: State = State.UNKNOWN + private set + + /** The clipping rect the invariant holds for. */ + val rect: Rect = Rect() + + /** + * Whether a child isn't laid out yet: those are left out of the running bounds below, as their + * empty frame at the origin would make the band reach every child before them. + */ + private var hasChildrenNotLaidOut = false + + private var maxBottoms = IntArray(0) + private var minTops = IntArray(0) + private var maxRights = IntArray(0) + private var minLefts = IntArray(0) + + /** The number of updates that only checked the bands, and the size of the last ones. */ + @VisibleForTesting var bandUpdateCount: Int = 0 + @VisibleForTesting var lastBandSize: Int = 0 + + /** A child was added, removed or laid out against [clippingRect]. */ + fun onChildChanged(clippingRect: Rect?) { + when { + state == State.DISABLED || state == State.UNKNOWN -> Unit + // A child attached against a clipping rect other than [rect] may be outside [rect]. + clippingRect != rect -> state = State.UNKNOWN + else -> state = State.STALE + } + } + + /** A child outside the clipping rect stays attached, or was laid out without an update. */ + fun invalidate() { + if (state != State.DISABLED) { + state = State.UNKNOWN + } + } + + /** + * Every child is about to be checked: unless one outside the rect stays attached, the band is + * then rebuilt. + */ + fun onCheckingAllChildren() { + if (state != State.DISABLED) { + state = State.STALE + } + } + + /** Every child was checked against [clippingRect], and every child outside it is clipped. */ + fun onAllChildrenChecked(clippingRect: Rect, childArray: Array, count: Int) { + rect.set(clippingRect) + build(childArray, count) + } + + fun disable() { + state = State.DISABLED + } + + /** Rebuilds the band from the children's frames, after [State.STALE]. */ + fun build(childArray: Array, count: Int) { + if (state == State.DISABLED) { + return + } + if (maxBottoms.size < count) { + maxBottoms = IntArray(childArray.size) + minTops = IntArray(childArray.size) + maxRights = IntArray(childArray.size) + minLefts = IntArray(childArray.size) + } + hasChildrenNotLaidOut = false + var maxBottom = Int.MIN_VALUE + var maxRight = Int.MIN_VALUE + for (i in 0.. bound) high = mid else low = mid + 1 + } + return low + } + + /** The first index of the non-decreasing [values] whose value is at least [bound]. */ + fun firstAtLeast(values: IntArray, count: Int, bound: Int): Int { + var low = 0 + var high = count + while (low < high) { + val mid = (low + high) ushr 1 + if (values[mid] >= bound) high = mid else low = mid + 1 + } + return low + } + } +} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.kt index e0cc00328fa7..a331341cfbcc 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.kt @@ -26,6 +26,7 @@ import android.view.ViewGroup import android.view.ViewStructure import android.view.accessibility.AccessibilityEvent import android.view.accessibility.AccessibilityManager +import androidx.annotation.VisibleForTesting import com.facebook.common.logging.FLog import com.facebook.react.R import com.facebook.react.bridge.ReactNoCrashSoftException @@ -72,6 +73,7 @@ import com.facebook.react.views.view.CanvasUtil.enableZ import java.util.ArrayList import kotlin.concurrent.Volatile import kotlin.math.max +import kotlin.math.min /** * Backing for a React View. Has support for borders, but since borders aren't common, lazy @@ -141,6 +143,16 @@ public open class ReactViewGroup public constructor(context: Context?) : internal var allChildrenCount: Int = 0 private set + /** + * The children a clipping rect can change, so that a new clipping rect only updates those; see + * [ClippingBand]. Created on the first update with enough children. + */ + private var clippingBand: ClippingBand? = null + + @VisibleForTesting + internal val clippingBandForTesting: ClippingBand? + get() = clippingBand + internal var clippingRect: Rect? = null public override var hitSlopRect: Rect? = null @@ -192,6 +204,7 @@ public open class ReactViewGroup public constructor(context: Context?) : inSubviewClippingLoop = false allChildren = null allChildrenCount = 0 + clippingBand = null clippingRect = null hitSlopRect = null axOrderList = null @@ -526,6 +539,7 @@ public open class ReactViewGroup public constructor(context: Context?) : } _removeClippedSubviews = newValue childrenRemovedWhileTransitioning = null + clippingBand = null if (newValue) { val clippingRect = Rect() calculateClippingRect(this, clippingRect) @@ -552,6 +566,7 @@ public open class ReactViewGroup public constructor(context: Context?) : val clippingRect = checkNotNull(clippingRect) getDrawingRect(clippingRect) updateClippingToRect(clippingRect) + clippingBand = null this.allChildren = null this.clippingRect = null allChildrenCount = 0 @@ -606,10 +621,121 @@ public open class ReactViewGroup public constructor(context: Context?) : childrenRemovedWhileTransitioning?.contains(child.id) == true internal fun updateClippingToRect(clippingRect: Rect, excludedViewsSet: Set? = null) { + if (!clippingBandEnabled || allChildrenCount < MIN_CHILDREN_FOR_CLIPPING_BAND) { + updateClippingForChildren(clippingRect, excludedViewsSet, 0, allChildrenCount, 0) + clippingBand?.invalidate() + return + } + val band = clippingBand ?: ClippingBand().also { clippingBand = it } + val childArray = checkNotNull(allChildren) + if (band.state == ClippingBand.State.STALE) { + band.build(childArray, allChildrenCount) + } + if ( + excludedViewsSet == null && + band.state == ClippingBand.State.VALID && + updateClippingInBand(band, clippingRect) + ) { + return + } + band.onCheckingAllChildren() + updateClippingForChildren(clippingRect, excludedViewsSet, 0, allChildrenCount, 0) + when { + excludedViewsSet != null -> band.invalidate() + // Unless a child outside the rect stayed attached, which invalidates the band. + band.state == ClippingBand.State.STALE -> + band.onAllChildrenChecked(clippingRect, childArray, allChildrenCount) + else -> Unit + } + } + + /** + * Updates the children in the bands of [ClippingBand.rect] and [clippingRect]. Returns `false`, + * changing nothing, when every child must be checked instead. + */ + private fun updateClippingInBand(band: ClippingBand, clippingRect: Rect): Boolean { + if ( + band.mayIntersectChildNotLaidOut(band.rect) || + band.mayIntersectChildNotLaidOut(clippingRect) + ) { + return false + } + val count = allChildrenCount + val oldStart = band.start(band.rect, count) + val oldEnd = max(oldStart, band.end(band.rect, count)) + val newStart = band.start(clippingRect, count) + val newEnd = max(newStart, band.end(clippingRect, count)) + val oldFirst = oldStart <= newStart + val firstStart = if (oldFirst) oldStart else newStart + var firstEnd = if (oldFirst) oldEnd else newEnd + var secondStart = if (oldFirst) newStart else oldStart + var secondEnd = if (oldFirst) newEnd else oldEnd + if (secondStart <= firstEnd) { + // The bands overlap or touch: update them as one. + firstEnd = max(firstEnd, secondEnd) + secondStart = firstEnd + secondEnd = firstEnd + } + val size = (firstEnd - firstStart) + (secondEnd - secondStart) + if (size * 2 > count) { + // A child that spans the others, like a background, makes the bands most of the children. + return false + } + + // Every attached child must be in the bands: a child that gets attached is inserted after the + // attached children before it, and those outside the bands are all clipped. + val childArray = checkNotNull(allChildren) + var attachedInBands = 0 + for (i in firstStart..?, + start: Int, + end: Int, + clippedBefore: Int, + ): Int { val childArray = checkNotNull(allChildren) inSubviewClippingLoop = true - var clippedSoFar = 0 - for (i in 0..= 0) setViewClipped(child, false) @@ -686,6 +808,10 @@ public open class ReactViewGroup public constructor(context: Context?) : } else if (intersects) { // If there is any intersection we need to inform the child to update its clipping rect needUpdateClippingRecursive = true + } else if (!isClipped) { + // A focused, animating or excluded child outside the rect stays attached, so not every child + // outside the band is clipped. + clippingBand?.invalidate() } if (needUpdateClippingRecursive) { @@ -696,9 +822,15 @@ public open class ReactViewGroup public constructor(context: Context?) : } private fun updateSubviewClipStatus(subview: View) { - if (!_removeClippedSubviews || parent == null) { + if (!_removeClippedSubviews) { return } + if (parent == null) { + // The child isn't attached or detached for its new frame, so it may now be outside the band. + clippingBand?.invalidate() + return + } + clippingBand?.onChildChanged(clippingRect) val clippingRect = checkNotNull(clippingRect) val allChildren = checkNotNull(allChildren) @@ -830,6 +962,7 @@ public open class ReactViewGroup public constructor(context: Context?) : index: Int, ) { check(_removeClippedSubviews) + clippingBand?.onChildChanged(clippingRect) setViewClipped(child, true) // the view has not been added, so it is "clipped" addInArray(child, index) @@ -870,6 +1003,7 @@ public open class ReactViewGroup public constructor(context: Context?) : assertOnUiThread() check(_removeClippedSubviews) + clippingBand?.onChildChanged(clippingRect) val allChildren = checkNotNull(allChildren) view.removeOnLayoutChangeListener(childrenLayoutChangeListener) val index = indexOfChildInAllChildren(view) @@ -888,6 +1022,7 @@ public open class ReactViewGroup public constructor(context: Context?) : internal fun removeAllViewsWithSubviewClippingEnabled() { check(_removeClippedSubviews) + clippingBand?.onChildChanged(clippingRect) val allChildren = checkNotNull(allChildren) for (i in 0.. list.height + + fun scrollTo(position: Int) { + if (horizontal) container.scrollTo(position, 0) else container.scrollTo(0, position) + container.updateClippingRect() + } + } + + private lateinit var context: Context + + @Before + fun setUp() { + ReactNativeFeatureFlagsForTests.setUp() + context = RuntimeEnvironment.getApplication() + } + + @After + fun tearDown() { + clippingBandEnabled = true + } + + @Test fun rows() = assertSameAttachedChildren(Layout.ROWS) + + @Test fun sortedRowPieces() = assertSameAttachedChildren(Layout.SORTED_PIECES) + + @Test fun centeredRowPieces() = assertSameAttachedChildren(Layout.CENTERED_PIECES) + + @Test fun horizontalList() = assertSameAttachedChildren(Layout.HORIZONTAL) + + @Test + fun scrollingOnlyUpdatesTheRowsNearTheVisibleArea() { + val scrolling = newScrollingList(horizontal = false) + val rows = addRows(scrolling.list, 1000) + scrolling.scrollTo(0) + + for (position in listOf(100, 150, 5_000, 4_950, 0, 99_000)) { + scrolling.scrollTo(position) + + assertThat(attached(scrolling.list)) + .describedAs("position $position") + .isEqualTo(rows.filter { it.bottom > position && it.top < position + 500 }.map { it.id }) + assertThat(band(scrolling.list).lastBandSize).isLessThan(20) + } + // The first update after adding the rows checks every child. + assertThat(band(scrolling.list).bandUpdateCount).isEqualTo(6) + } + + @Test + fun rowsAddedWhileScrollingKeepTheBand() { + val scrolling = newScrollingList(horizontal = false) + val rows = addRows(scrolling.list, 50).toMutableList() + scrolling.scrollTo(0) + scrolling.scrollTo(100) + + for (step in 1..10) { + // As a list renders more of its items, between scroll updates. + repeat(5) { + val row = child(rows.size + 1, 0, rows.size * ROW_SIZE, 500, (rows.size + 1) * ROW_SIZE) + scrolling.list.addViewWithSubviewClippingEnabled(row, rows.size) + rows.add(row) + } + scrolling.scrollTo(100 + step * 200) + } + + assertThat(band(scrolling.list).bandUpdateCount).isEqualTo(11) + val position = 100 + 10 * 200 + assertThat(attached(scrolling.list)) + .isEqualTo(rows.filter { it.bottom > position && it.top < position + 500 }.map { it.id }) + } + + /** A child kept attached by focus comes before the rows attached after a jump. */ + @Test + fun focusedChildThenJumpForward() { + fun run(useBand: Boolean): List { + clippingBandEnabled = useBand + val parent = newClippingParent() + val rows = addRows(parent, 100) + parent.updateClippingToRect(Rect(0, 0, 500, 1000)) + parent.updateClippingToRect(Rect(0, 10, 500, 1010)) + parent.requestChildFocus(rows[3], rows[3]) + parent.updateClippingToRect(Rect(0, 5_000, 500, 6_000)) + return attached(parent) + } + val withoutBand = run(useBand = false) + assertThat(run(useBand = true)).isEqualTo(withoutBand).startsWith(4) + } + + @Test + fun childrenNotLaidOutYetDoNotStopTheBand() { + val parent = newClippingParent() + addRows(parent, 100) + // Rows that were just mounted, before their layout. + repeat(5) { + parent.addViewWithSubviewClippingEnabled(child(200 + it, 0, 0, 0, 0), parent.allChildrenCount) + } + parent.updateClippingToRect(Rect(0, 0, 500, 1000)) + + parent.updateClippingToRect(Rect(0, 2_000, 500, 3_000)) + parent.updateClippingToRect(Rect(0, 2_100, 500, 3_100)) + + assertThat(band(parent).bandUpdateCount).isEqualTo(2) + assertThat(attached(parent)).isEqualTo((22..31).toList()) + } + + @Test + fun childNotLaidOutAtTheOriginOfTheRect() { + fun run(useBand: Boolean): List> { + clippingBandEnabled = useBand + val parent = newClippingParent() + addRows(parent, 50) + parent.addViewWithSubviewClippingEnabled(child(100, 0, 0, 0, 0), parent.allChildrenCount) + parent.updateClippingToRect(Rect(0, 1_000, 500, 1_500)) + parent.updateClippingToRect(Rect(0, 1_010, 500, 1_510)) + // A rect that strictly contains the origin, and so the child that isn't laid out. + parent.updateClippingToRect(Rect(-10, -10, 500, 500)) + val atOrigin = attached(parent) + parent.updateClippingToRect(Rect(0, 2_000, 500, 2_500)) + return listOf(atOrigin, attached(parent)) + } + val withBand = run(useBand = true) + assertThat(withBand).isEqualTo(run(useBand = false)) + assertThat(withBand[0]).contains(100) + } + + @Test + fun zeroHeightRowsKeepTheBand() { + val parent = newClippingParent() + // Rows separated by zero-height separators. + var id = 1 + repeat(50) { row -> + parent.addViewWithSubviewClippingEnabled( + child(id++, 0, row * ROW_SIZE, 500, row * ROW_SIZE + ROW_SIZE - 1), + parent.allChildrenCount, + ) + parent.addViewWithSubviewClippingEnabled( + child(id++, 0, row * ROW_SIZE + ROW_SIZE - 1, 500, row * ROW_SIZE + ROW_SIZE - 1), + parent.allChildrenCount, + ) + } + parent.updateClippingToRect(Rect(0, 0, 500, 500)) + + for (top in listOf(100, 1_000, 1_050)) { + parent.updateClippingToRect(Rect(0, top, 500, top + 500)) + } + + assertThat(band(parent).bandUpdateCount).isEqualTo(3) + assertThat(attached(parent)).contains(22, 24) + } + + /** + * A child attached against a clipping rect the band doesn't know of, as [ReactVirtualView] can. + */ + @Test + fun childAddedAgainstAnotherClippingRect() { + fun run(useBand: Boolean): List { + clippingBandEnabled = useBand + val parent = newClippingParent() + addRows(parent, 100) + parent.updateClippingToRect(checkNotNull(parent.clippingRect).apply { set(0, 0, 500, 1000) }) + parent.updateClippingToRect(checkNotNull(parent.clippingRect).apply { set(0, 10, 500, 1010) }) + // The clipping rect changes without an update, then a child is attached against it. + checkNotNull(parent.clippingRect).set(0, 5_000, 500, 6_000) + parent.addViewWithSubviewClippingEnabled( + child(500, 0, 5_500, 500, 5_600), + parent.allChildrenCount, + ) + parent.updateClippingToRect(checkNotNull(parent.clippingRect).apply { set(0, 20, 500, 1020) }) + if (useBand) { + assertThat(band(parent).state).isNotEqualTo(ClippingBand.State.DISABLED) + } + return attached(parent) + } + assertThat(run(useBand = true)).isEqualTo(run(useBand = false)) + } + + /** A clipping view clipped out by its parent doesn't update its children when they move. */ + @Test + fun childLaidOutWhileItsClippingViewIsDetached() { + fun run(useBand: Boolean): List { + clippingBandEnabled = useBand + val outer = newClippingParent() + val inner = ReactViewGroup(context) + inner.id = 999 + inner.layout(0, 0, 500, 300) + inner.removeClippedSubviews = true + val children = + (0 until 20).map { + child(it + 1, 0, if (it == 0) 0 else (it - 1) * ROW_SIZE, 500, it * ROW_SIZE) + } + children.forEachIndexed { i, child -> inner.addViewWithSubviewClippingEnabled(child, i) } + outer.addViewWithSubviewClippingEnabled(inner, 0) + outer.updateClippingToRect(Rect(0, 0, 500, 1000)) + inner.updateClippingToRect(Rect(0, 0, 500, 250)) + inner.updateClippingToRect(Rect(0, 10, 500, 260)) + // The outer view scrolls away, and the inner view's first child grows meanwhile. + outer.updateClippingToRect(Rect(0, 5_000, 500, 6_000)) + children.forEachIndexed { i, child -> child.layout(0, i * ROW_SIZE, 500, (i + 1) * ROW_SIZE) } + outer.updateClippingToRect(Rect(0, 0, 500, 1000)) + inner.updateClippingToRect(Rect(0, 10, 500, 260)) + return attached(inner) + } + assertThat(run(useBand = true)).isEqualTo(run(useBand = false)) + } + + @Test + fun childLaidOutUnderAClippingViewWithoutParent() { + fun run(useBand: Boolean): List { + clippingBandEnabled = useBand + val parent = ReactViewGroup(context) + parent.layout(0, 0, 500, 100_000) + parent.removeClippedSubviews = true + val rows = addRows(parent, 20) + parent.updateClippingToRect(Rect(0, 0, 500, 300)) + rows[15].layout(0, ROW_SIZE, 500, 2 * ROW_SIZE) + parent.updateClippingToRect(Rect(0, 10, 500, 310)) + return attached(parent) + } + assertThat(run(useBand = true)).isEqualTo(run(useBand = false)) + } + + /** + * A child added without the clipping bookkeeping makes the view check every child from then on. + */ + @Test + fun childAddedWithoutClippingStopsTheBand() { + fun run(useBand: Boolean): List> { + clippingBandEnabled = useBand + val parent = newClippingParent() + addRows(parent, 100) + parent.updateClippingToRect(Rect(0, 0, 500, 1000)) + parent.updateClippingToRect(Rect(0, 10, 500, 1010)) + parent.addView(child(500, 0, 0, 10, 10)) + return (1..5).map { + parent.updateClippingToRect(Rect(0, it * 300, 500, it * 300 + 1000)) + attached(parent) + } + } + val withoutBand = run(useBand = false) + clippingBandEnabled = true + val parent = newClippingParent() + assertThat(run(useBand = true)).isEqualTo(withoutBand) + addRows(parent, 100) + parent.updateClippingToRect(Rect(0, 0, 500, 1000)) + parent.addView(child(500, 0, 0, 10, 10)) + parent.updateClippingToRect(Rect(0, 300, 500, 1300)) + parent.updateClippingToRect(Rect(0, 600, 500, 1600)) + assertThat(band(parent).state).isEqualTo(ClippingBand.State.DISABLED) + assertThat(band(parent).bandUpdateCount).isEqualTo(0) + } + + /** A child that spans the others makes the band most of the children; every child is checked. */ + @Test + fun childSpanningTheList() { + fun run(useBand: Boolean): Pair, Int> { + clippingBandEnabled = useBand + val parent = newClippingParent() + parent.addViewWithSubviewClippingEnabled(child(5_000, 0, 0, 500, 100_000), 0) + repeat(100) { + parent.addViewWithSubviewClippingEnabled( + child(it + 1, 0, it * ROW_SIZE, 500, (it + 1) * ROW_SIZE), + it + 1, + ) + } + for (top in listOf(0, 10, 3_000, 6_000, 6_010)) { + parent.updateClippingToRect(Rect(0, top, 500, top + 1000)) + } + return attached(parent) to (parent.clippingBandForTesting?.bandUpdateCount ?: 0) + } + val (withoutBand, _) = run(useBand = false) + val (withBand, bandUpdates) = run(useBand = true) + assertThat(withBand).isEqualTo(withoutBand) + // Near the end, the band is the spanning child and the visible rows; elsewhere, most children. + assertThat(bandUpdates).isLessThan(5) + } + + @Test + fun turningClippingOffAndOnAgain() { + fun run(useBand: Boolean): List> { + clippingBandEnabled = useBand + val parent = newClippingParent() + addRows(parent, 50) + parent.updateClippingToRect(Rect(0, 0, 500, 500)) + parent.updateClippingToRect(Rect(0, 100, 500, 600)) + val before = attached(parent) + parent.removeClippedSubviews = false + val unclipped = attached(parent) + if (useBand) { + assertThat(parent.clippingBandForTesting).isNull() + } + parent.removeClippedSubviews = true + parent.updateClippingToRect(Rect(0, 1_000, 500, 1_500)) + parent.updateClippingToRect(Rect(0, 1_100, 500, 1_600)) + return listOf(before, unclipped, attached(parent)) + } + assertThat(run(useBand = true)).isEqualTo(run(useBand = false)) + } + + @Test + fun recyclingReleasesTheBand() { + val parent = newClippingParent() + addRows(parent, 50) + parent.updateClippingToRect(Rect(0, 0, 500, 500)) + assertThat(parent.clippingBandForTesting).isNotNull() + + parent.recycleView() + + assertThat(parent.clippingBandForTesting).isNull() + } + + @Test + fun fewChildrenAreAllChecked() { + val parent = newClippingParent() + addRows(parent, 10) + parent.updateClippingToRect(Rect(0, 0, 500, 300)) + parent.updateClippingToRect(Rect(0, 100, 500, 400)) + + assertThat(parent.clippingBandForTesting).isNull() + assertThat(attached(parent)).isEqualTo((2..4).toList()) + } + + private fun assertSameAttachedChildren(layout: Layout) { + var scrolls = 0 + var bandUpdates = 0 + var bandSizes = 0L + var children = 0L + for (seed in 1..8) { + val withoutBand = runSteps(layout, seed, useBand = false) + val withBand = runSteps(layout, seed, useBand = true) + assertThat(withBand.attached) + .describedAs("$layout seed $seed") + .isEqualTo(withoutBand.attached) + scrolls += withBand.scrolls + bandUpdates += withBand.bandUpdates + bandSizes += withBand.bandSizes + children += withBand.children + } + // Focus, animations and excluded children make some updates check every child; the band + // applies to most of the others, and is a small part of the children. Rows out of order widen + // it. + assertThat(bandUpdates) + .describedAs("$layout band updates of $scrolls scrolls") + .isGreaterThan(scrolls / 3) + assertThat(bandSizes * 4).describedAs("$layout band sizes vs children").isLessThan(children) + } + + private class Steps( + val attached: List>, + val scrolls: Int, + val bandUpdates: Int, + val bandSizes: Long, + val children: Long, + ) + + /** + * Applies random changes to a list in a scroll container: scrolls and jumps, rows added at the + * end or anywhere, removed and laid out, excluded, focused and animating children, the list + * moving in its container, and clipping turned off and on. Returns the ids of the attached + * children after each change. + */ + private fun runSteps(layout: Layout, seed: Int, useBand: Boolean): Steps { + clippingBandEnabled = useBand + val random = Random(seed.toLong() * 31 + layout.ordinal) + val horizontal = layout == Layout.HORIZONTAL + val scrolling = newScrollingList(horizontal) + val list = scrolling.list + val piecesPerRow = + if (layout == Layout.SORTED_PIECES || layout == Layout.CENTERED_PIECES) 3 else 1 + var nextId = 1 + var rowCount = 0 + + fun layoutPiece(view: View, row: Int, piece: Int, extra: Int = 0) { + val start = row * ROW_SIZE + val (pieceStart, pieceEnd) = + when { + piece == 0 -> start to start + ROW_SIZE + extra + layout == Layout.SORTED_PIECES -> (start + piece * 20) to (start + piece * 20 + 15) + // Centered: the second piece is shorter and starts after the third. + else -> (start + if (piece == 1) 30 else 10) to (start + if (piece == 1) 60 else 90) + } + if (horizontal) view.layout(pieceStart, 0, pieceEnd, 500) + else view.layout(20, pieceStart, 480, pieceEnd) + } + + fun newPiece(row: Int, piece: Int): View { + val view = View(context) + view.id = nextId++ + layoutPiece(view, row, piece) + return view + } + + fun addRow() { + repeat(piecesPerRow) { piece -> + list.addViewWithSubviewClippingEnabled(newPiece(rowCount, piece), list.allChildrenCount) + } + rowCount++ + } + + fun randomChild(): View = + checkNotNull( + list.getChildAtWithSubviewClippingEnabled(random.nextInt(list.allChildrenCount)) + ) + + repeat(150) { addRow() } + val attached = mutableListOf>() + var scrolls = 0 + var bandUpdates = 0 + var bandSizes = 0L + var children = 0L + var position = 0 + // Focus and animations last a few steps, as they do in an app. + var clearAt = Int.MAX_VALUE + repeat(250) { step -> + if (step >= clearAt) { + list.focusedChild?.let { list.clearChildFocus(it) } + for (i in 0 until list.allChildrenCount) list + .getChildAtWithSubviewClippingEnabled(i) + ?.clearAnimation() + clearAt = Int.MAX_VALUE + } + val bandBefore = list.clippingBandForTesting + val bandUpdatesBefore = bandBefore?.bandUpdateCount ?: 0 + when (random.nextInt(20)) { + in 0..8 -> { + position = (position + random.nextInt(600) - 250).coerceIn(-200, rowCount * ROW_SIZE) + scrolling.scrollTo(position) + scrolls++ + } + 9 -> { + // A jump, as scrollToIndex does. + position = random.nextInt(rowCount * ROW_SIZE) + scrolling.scrollTo(position) + scrolls++ + } + 10 -> addRow() + 11 -> { + if (random.nextBoolean()) { + // A row anywhere, sometimes out of order. + list.addViewWithSubviewClippingEnabled( + newPiece(random.nextInt(rowCount + 1), 0), + random.nextInt(list.allChildrenCount + 1), + ) + } else { + // A row mounted before its layout, laid out on a later step. + val view = View(context) + view.id = nextId++ + list.addViewWithSubviewClippingEnabled(view, list.allChildrenCount) + } + } + 12 -> + if (list.allChildrenCount > 1) list.removeViewWithSubviewClippingEnabled(randomChild()) + 13 -> layoutPiece(randomChild(), random.nextInt(rowCount + 1), 0) + 14 -> { + // A row grows, as when its content changes. + val child = randomChild() + if (horizontal) child.layout(child.left, 0, child.right + 50, 500) + else child.layout(20, child.top, 480, child.bottom + 50) + } + 15 -> scrolling.container.updateClippingRect(setOf(randomChild().id)) + 16 -> { + if (list.childCount > 0) { + val child = list.getChildAt(random.nextInt(list.childCount)) + list.requestChildFocus(child, child) + clearAt = step + 3 + } + } + 17 -> { + val child = + if (list.childCount > 0 && random.nextBoolean()) + list.getChildAt(random.nextInt(list.childCount)) + else randomChild() + child.startAnimation(AlphaAnimation(0f, 1f).apply { duration = 1000 }) + clearAt = step + 3 + } + 18 -> { + // The list moves in its container without a scroll. + if (horizontal) list.layout(random.nextInt(10), 0, 1_000_000, 500) + else list.layout(0, random.nextInt(10), 500, 1_000_000) + } + else -> { + list.removeClippedSubviews = false + list.removeClippedSubviews = true + } + } + val band = list.clippingBandForTesting + // The band never finds attached children outside it, which would mean a missed invalidation. + assertThat(band?.state) + .describedAs("$layout seed $seed step $step") + .isNotEqualTo(ClippingBand.State.DISABLED) + if ( + band != null && band.bandUpdateCount > (if (band === bandBefore) bandUpdatesBefore else 0) + ) { + bandUpdates++ + bandSizes += band.lastBandSize + children += list.allChildrenCount + } + attached.add(attached(list)) + } + return Steps(attached, scrolls, bandUpdates, bandSizes, children) + } + + private fun addRows(parent: ReactViewGroup, count: Int): List = + (0 until count).map { i -> + val row = child(i + 1, 0, i * ROW_SIZE, 500, (i + 1) * ROW_SIZE) + parent.addViewWithSubviewClippingEnabled(row, i) + row + } + + private fun child(id: Int, left: Int, top: Int, right: Int, bottom: Int): View { + val view = View(context) + view.id = id + view.layout(left, top, right, bottom) + return view + } + + /** A clipping view in a parent, so that its children's layout changes update it. */ + private fun newClippingParent(): ReactViewGroup { + val host = FrameLayout(context) + val parent = ReactViewGroup(context) + host.addView(parent) + parent.layout(0, 0, 100_000, 100_000) + parent.removeClippedSubviews = true + return parent + } + + private fun newScrollingList(horizontal: Boolean): ScrollingList { + val host = FrameLayout(context) + val container = ReactViewGroup(context) + host.addView(container) + container.layout(0, 0, 500, 500) + container.removeClippedSubviews = true + val list = ReactViewGroup(context) + if (horizontal) list.layout(0, 0, 1_000_000, 500) else list.layout(0, 0, 500, 1_000_000) + list.removeClippedSubviews = true + container.addViewWithSubviewClippingEnabled(list, 0) + return ScrollingList(container, list) + } + + private fun band(parent: ReactViewGroup): ClippingBand = + checkNotNull(parent.clippingBandForTesting) + + private fun attached(parent: ReactViewGroup): List = + (0 until parent.childCount).map { parent.getChildAt(it).id } + + private companion object { + const val ROW_SIZE = 100 + } +}