package link.roadio.riff.ui import android.graphics.Bitmap import android.os.Handler import android.os.Looper import android.os.SystemClock import android.view.InputDevice import android.view.MotionEvent import android.view.PixelCopy import android.view.ViewTreeObserver import android.view.WindowManager import android.view.accessibility.AccessibilityNodeInfo import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.displayCutout import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.systemBars import androidx.compose.foundation.layout.union import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Rect import androidx.compose.ui.layout.boundsInWindow import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import androidx.core.view.doOnLayout import androidx.test.core.app.ActivityScenario import androidx.test.platform.app.InstrumentationRegistry import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test import java.io.File import java.util.concurrent.CountDownLatch import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicReference import kotlin.math.roundToInt import android.graphics.Rect as AndroidRect /** Public platform capture/input APIs keep this regression independent of Espresso hidden APIs. */ class BatchStatusRenderingInstrumentedTest { private val instrumentation = InstrumentationRegistry.getInstrumentation() private val rootBounds = AtomicReference(Rect.Zero) private val screenOffset = AtomicReference(0 to 0) private val actions = LinkedBlockingQueue() @Volatile private var density = 1f private var fontScale by mutableStateOf(1f) private var direction by mutableStateOf(LayoutDirection.Ltr) private val firstMessage = "Analyzing audio: 15 / 100 tracks | 1.0 tracks/s [64 pkts]" private var state by mutableStateOf( PlayerUiState( screen = PlayerScreen.MAIN, root = BrowserItem( "root", "Fixture", BrowserKind.ROOT, children = HierarchyRoot.entries.map { BrowserItem(it.categoryId, it.label, BrowserKind.CATEGORY, it.icon) }, ), nowPlaying = NowPlayingUiState(), indexerStatus = firstMessage, ), ) @Test fun batchDigitsPaintWithoutShiftingControlsOrTakingInput() { instrumentation.uiAutomation.waitForIdle(100, 5_000) ActivityScenario.launch(ComponentActivity::class.java).use { scenario -> scenario.onActivity { activity -> activity.setTurnScreenOn(true) activity.setShowWhenLocked(true) activity.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) activity.setContent { BoxWithConstraints( Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.systemBars.union(WindowInsets.displayCutout)), ) { density = minOf(1f, constraints.maxWidth / 1400f, constraints.maxHeight / 1650f) CompositionLocalProvider( LocalDensity provides Density(density, fontScale), LocalLayoutDirection provides direction, ) { Box( Modifier.size(1200.dp, 800.dp).onGloballyPositioned { rootBounds.set(it.boundsInWindow()) }, ) { PlayerComposeUi( state, UiConfig.fromUserText("{}"), CalibrationSessionState(), activity, dispatch = { actions.offer(it) }, ) } } } } } val readyDeadline = SystemClock.uptimeMillis() + 10_000L while (rootBounds.get().width <= 0f && SystemClock.uptimeMillis() < readyDeadline) { instrumentation.waitForIdleSync() SystemClock.sleep(16) } assertTrue("Compose root must be laid out", rootBounds.get().width > 0f) val before = capture(scenario) save("initial", before) val albumBefore = labelBounds("Albums") assertDecorative(firstMessage) scenario.onActivity { state = state.copy(indexerStatus = firstMessage.replace("[64 pkts]", "[1 pkts]")) } val after = capture(scenario) assertEquals(albumBefore, labelBounds("Albums")) val cropBefore = statusDigits(before) val cropAfter = statusDigits(after) assertFalse("The changed packet digit must paint inside the status viewport", cropBefore.sameAs(cropAfter)) save("batch-4", before) save("batch-1", after) save("digit-4", cropBefore) save("digit-1", cropAfter) tapStatus() assertDecorative(state.indexerStatus) scenario.onActivity { fontScale = 2f direction = LayoutDirection.Rtl } save("rtl-font-2", capture(scenario)) assertDecorative(state.indexerStatus) tapStatus() } } private fun capture(scenario: ActivityScenario): Bitmap { val done = CountDownLatch(1) val result = AtomicReference() val status = AtomicInteger(PixelCopy.ERROR_UNKNOWN) scenario.onActivity { activity -> val view = activity.window.decorView view.doOnLayout { val onScreen = IntArray(2) val inWindow = IntArray(2) view.getLocationOnScreen(onScreen) view.getLocationInWindow(inWindow) screenOffset.set(onScreen[0] - inWindow[0] to onScreen[1] - inWindow[1]) val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888) val once = AtomicBoolean() val listener = object : ViewTreeObserver.OnDrawListener { override fun onDraw() { if (!once.compareAndSet(false, true)) return view.post { view.viewTreeObserver.removeOnDrawListener(this) PixelCopy.request( activity.window, bitmap, { code -> status.set(code) result.set(bitmap) done.countDown() }, Handler(Looper.getMainLooper()), ) } } } view.viewTreeObserver.addOnDrawListener(listener) view.postInvalidateOnAnimation() } } assertTrue("Window must draw", done.await(10, TimeUnit.SECONDS)) assertEquals(PixelCopy.SUCCESS, status.get()) return requireNotNull(result.get()) } private fun statusDigits(bitmap: Bitmap): Bitmap { val bounds = rootBounds.get() val left = (bounds.left + 420 * density).roundToInt().coerceIn(0, bitmap.width - 1) val right = (bounds.left + 940 * density).roundToInt().coerceIn(left + 1, bitmap.width) val top = bounds.top.roundToInt().coerceIn(0, bitmap.height - 1) val bottom = (bounds.top + 30 * density).roundToInt().coerceIn(top + 1, bitmap.height) return Bitmap.createBitmap(bitmap, left, top, right - left, bottom - top) } private fun activeRoot(): AccessibilityNodeInfo { instrumentation.uiAutomation.waitForIdle(100, 5_000) return requireNotNull(instrumentation.uiAutomation.rootInActiveWindow) } private fun find( node: AccessibilityNodeInfo, predicate: (AccessibilityNodeInfo) -> Boolean, ): AccessibilityNodeInfo? { if (predicate(node)) return node for (index in 0 until node.childCount) { val child = node.getChild(index) ?: continue find(child, predicate)?.let { return it } } return null } private fun labelBounds(label: String): AndroidRect { val deadline = SystemClock.uptimeMillis() + 5_000L do { val node = find(activeRoot()) { it.text?.toString() == label || it.contentDescription?.toString() == label } if (node != null) return AndroidRect().also(node::getBoundsInScreen) SystemClock.sleep(100) } while (SystemClock.uptimeMillis() < deadline) error("Accessible control was not exported: $label") } private fun assertDecorative(message: String) { assertTrue(find(activeRoot()) { it.text?.toString() == message || it.contentDescription?.toString() == message } == null) } private fun tapStatus() { assertTrue(actions.isEmpty()) val bounds = rootBounds.get() val x = bounds.left + screenOffset.get().first + 2 * density val y = bounds.top + screenOffset.get().second + 12 * density val started = SystemClock.uptimeMillis() MotionEvent.obtain(started, started, MotionEvent.ACTION_DOWN, x, y, 0).useEvent { assertTrue(instrumentation.uiAutomation.injectInputEvent(it, true)) } SystemClock.sleep(40) MotionEvent.obtain(started, SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, x, y, 0).useEvent { assertTrue(instrumentation.uiAutomation.injectInputEvent(it, true)) } assertEquals(PlayerUiAction.TogglePlaybackSurface, actions.poll(5, TimeUnit.SECONDS)) assertTrue(actions.isEmpty()) } private fun MotionEvent.useEvent(block: (MotionEvent) -> Unit) { try { source = InputDevice.SOURCE_TOUCHSCREEN block(this) } finally { recycle() } } private fun save( name: String, bitmap: Bitmap, ) { val directory = File(instrumentation.targetContext.filesDir, "batch-status-public").apply { mkdirs() } File(directory, "$name.png").outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) } } }