diff --git a/.nx/version-plans/version-plan-1792417333384.md b/.nx/version-plans/version-plan-1792417333384.md new file mode 100644 index 00000000..f1cf8378 --- /dev/null +++ b/.nx/version-plans/version-plan-1792417333384.md @@ -0,0 +1,5 @@ +--- +__default__: minor +--- + +On Android 8 and later, `screen.screenshot()` captures what a TextureView or a SurfaceView shows, such as a GPU-rendered canvas, a video or a camera preview, instead of transparent pixels. An on-screen capture now copies what the window shows, so effects only the GPU renderer draws, such as elevation shadows and `filter` blurs, appear in it, and an Android baseline recorded without them needs recording again; a capture whose copy fails, or whose window is not shown, as while the screen is off, resolves `null` instead of a different image. An element under a scale or rotation transform is captured in the box it covers on the screen, as on iOS. An element partly off the screen, scaled to nothing or detached from the window is still drawn by itself, at its scroll offset, so a TextureView or a SurfaceView in it still comes out transparent; on Android 8.0 and 8.1 a window with elevation is drawn from its view tree, as before, with its SurfaceViews behind it; and a SurfaceView set above its window with `setZOrderOnTop` is still left out. diff --git a/apps/playground/android/app/src/main/java/com/harnessplayground/MainApplication.kt b/apps/playground/android/app/src/main/java/com/harnessplayground/MainApplication.kt index d0632ee7..34e2696e 100644 --- a/apps/playground/android/app/src/main/java/com/harnessplayground/MainApplication.kt +++ b/apps/playground/android/app/src/main/java/com/harnessplayground/MainApplication.kt @@ -15,6 +15,7 @@ class MainApplication : Application(), ReactApplication { packageList = PackageList(this).packages.apply { add(PlaygroundCrashPackage()) + add(PaintedSurfacesPackage()) }, ) } diff --git a/apps/playground/android/app/src/main/java/com/harnessplayground/PaintedSurfacesPackage.kt b/apps/playground/android/app/src/main/java/com/harnessplayground/PaintedSurfacesPackage.kt new file mode 100644 index 00000000..38309686 --- /dev/null +++ b/apps/playground/android/app/src/main/java/com/harnessplayground/PaintedSurfacesPackage.kt @@ -0,0 +1,206 @@ +package com.harnessplayground + +import android.content.Context +import android.graphics.Color +import android.graphics.Paint +import android.graphics.SurfaceTexture +import android.media.MediaPlayer +import android.view.SurfaceHolder +import android.view.SurfaceView +import android.view.TextureView +import android.view.View +import com.facebook.react.ReactPackage +import com.facebook.react.bridge.ReactApplicationContext +import com.facebook.react.uimanager.PixelUtil +import com.facebook.react.uimanager.SimpleViewManager +import com.facebook.react.uimanager.ThemedReactContext +import com.facebook.react.uimanager.ViewManager +import com.facebook.react.uimanager.annotations.ReactProp + +// Views whose pixels live on a surface of their own, as a GPU-rendered view's +// do. Each fills its surface from the CPU or a decoder and labels itself once +// that frame is what it shows. + +class SolidColorTextureView(context: Context) : + TextureView(context), + TextureView.SurfaceTextureListener { + init { + surfaceTextureListener = this + } + + override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) { + val canvas = lockCanvas() ?: return + canvas.drawColor(Color.RED) + unlockCanvasAndPost(canvas) + } + + override fun onSurfaceTextureUpdated(surface: SurfaceTexture) { + contentDescription = PAINTED_LABEL + } + + override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {} + + override fun onSurfaceTextureDestroyed(surface: SurfaceTexture) = true + + companion object { + const val PAINTED_LABEL = "texture-view-painted" + } +} + +class SolidColorSurfaceView(context: Context) : + SurfaceView(context), + SurfaceHolder.Callback { + init { + holder.addCallback(this) + } + + override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) { + val canvas = holder.lockCanvas() ?: return + canvas.drawColor(Color.BLUE) + holder.unlockCanvasAndPost(canvas) + contentDescription = PAINTED_LABEL + } + + override fun surfaceCreated(holder: SurfaceHolder) {} + + override fun surfaceDestroyed(holder: SurfaceHolder) {} + + companion object { + const val PAINTED_LABEL = "surface-view-painted" + } +} + +// Blue on its left half and yellow on its right, so a capture shows which part +// of the frame it copied and at what scale. +class SplitColorSurfaceView(context: Context) : + SurfaceView(context), + SurfaceHolder.Callback { + init { + holder.addCallback(this) + } + + override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) { + val canvas = holder.lockCanvas() ?: return + canvas.drawColor(Color.BLUE) + canvas.drawRect(width / 2f, 0f, width.toFloat(), height.toFloat(), Paint().apply { color = Color.YELLOW }) + holder.unlockCanvasAndPost(canvas) + contentDescription = PAINTED_LABEL + } + + override fun surfaceCreated(holder: SurfaceHolder) {} + + override fun surfaceDestroyed(holder: SurfaceHolder) {} + + companion object { + const val PAINTED_LABEL = "split-surface-view-painted" + } +} + +// A video whose 320 x 180 frame, blue on its left half and yellow on its right, +// is larger than the view: the decoder queues buffers at the frame's size and +// the screen shows them scaled to the view, as a video player's do. +class SplitColorVideoView(context: Context) : + SurfaceView(context), + SurfaceHolder.Callback { + private var player: MediaPlayer? = null + + init { + holder.addCallback(this) + } + + override fun surfaceCreated(holder: SurfaceHolder) { + player = + MediaPlayer.create(context, R.raw.split_color)?.apply { + setDisplay(holder) + setOnInfoListener { _, what, _ -> + if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) { + this@SplitColorVideoView.contentDescription = PAINTED_LABEL + } + false + } + start() + } + } + + override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {} + + override fun surfaceDestroyed(holder: SurfaceHolder) { + player?.release() + player = null + } + + companion object { + const val PAINTED_LABEL = "split-video-painted" + } +} + +// Moves the window's root view down while it is mounted, as an app's slide or +// shake effect does, and puts it back when it is unmounted. +class RootShiftView(context: Context) : View(context) { + private var shiftedRoot: View? = null + + var rootTranslationY = 0f + set(value) { + field = value + shiftedRoot?.translationY = value + } + + override fun onAttachedToWindow() { + super.onAttachedToWindow() + shiftedRoot = rootView.also { root -> root.translationY = rootTranslationY } + } + + override fun onDetachedFromWindow() { + shiftedRoot?.translationY = 0f + shiftedRoot = null + super.onDetachedFromWindow() + } +} + +class SolidColorTextureViewManager : SimpleViewManager() { + override fun getName() = "SolidColorTextureView" + + override fun createViewInstance(context: ThemedReactContext) = SolidColorTextureView(context) +} + +class SolidColorSurfaceViewManager : SimpleViewManager() { + override fun getName() = "SolidColorSurfaceView" + + override fun createViewInstance(context: ThemedReactContext) = SolidColorSurfaceView(context) +} + +class SplitColorSurfaceViewManager : SimpleViewManager() { + override fun getName() = "SplitColorSurfaceView" + + override fun createViewInstance(context: ThemedReactContext) = SplitColorSurfaceView(context) +} + +class SplitColorVideoViewManager : SimpleViewManager() { + override fun getName() = "SplitColorVideoView" + + override fun createViewInstance(context: ThemedReactContext) = SplitColorVideoView(context) +} + +class RootShiftViewManager : SimpleViewManager() { + override fun getName() = "RootShiftView" + + override fun createViewInstance(context: ThemedReactContext) = RootShiftView(context) + + @ReactProp(name = "rootTranslationY") + fun setRootTranslationY(view: RootShiftView, value: Float) { + view.rootTranslationY = PixelUtil.toPixelFromDIP(value) + } +} + +class PaintedSurfacesPackage : ReactPackage { + override fun createViewManagers( + reactContext: ReactApplicationContext, + ): List> = + listOf( + SolidColorTextureViewManager(), + SolidColorSurfaceViewManager(), + SplitColorSurfaceViewManager(), + SplitColorVideoViewManager(), + RootShiftViewManager(), + ) +} diff --git a/apps/playground/android/app/src/main/res/raw/split_color.mp4 b/apps/playground/android/app/src/main/res/raw/split_color.mp4 new file mode 100644 index 00000000..79d48822 Binary files /dev/null and b/apps/playground/android/app/src/main/res/raw/split_color.mp4 differ diff --git a/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/element-clipped-out.png b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/element-clipped-out.png new file mode 100644 index 00000000..12dbbeff Binary files /dev/null and b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/element-clipped-out.png differ diff --git a/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/element-scaled-to-nothing.png b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/element-scaled-to-nothing.png new file mode 100644 index 00000000..d58458dc Binary files /dev/null and b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/element-scaled-to-nothing.png differ diff --git a/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/element-scrolled-off-screen.png b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/element-scrolled-off-screen.png new file mode 100644 index 00000000..b6bd382e Binary files /dev/null and b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/element-scrolled-off-screen.png differ diff --git a/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/element-under-moved-root.png b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/element-under-moved-root.png new file mode 100644 index 00000000..a5e1bf38 Binary files /dev/null and b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/element-under-moved-root.png differ diff --git a/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/element-under-nested-rotations.png b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/element-under-nested-rotations.png new file mode 100644 index 00000000..12dbbeff Binary files /dev/null and b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/element-under-nested-rotations.png differ diff --git a/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/region-past-window-edge.png b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/region-past-window-edge.png new file mode 100644 index 00000000..918bafba Binary files /dev/null and b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/region-past-window-edge.png differ diff --git a/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/surface-view-blue.png b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/surface-view-blue.png new file mode 100644 index 00000000..b6bd382e Binary files /dev/null and b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/surface-view-blue.png differ diff --git a/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/surface-view-enlarged.png b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/surface-view-enlarged.png new file mode 100644 index 00000000..88fcf88b Binary files /dev/null and b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/surface-view-enlarged.png differ diff --git a/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/surface-view-fractional-scale.png b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/surface-view-fractional-scale.png new file mode 100644 index 00000000..421015df Binary files /dev/null and b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/surface-view-fractional-scale.png differ diff --git a/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/surface-view-half-pixel-translation.png b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/surface-view-half-pixel-translation.png new file mode 100644 index 00000000..96977b60 Binary files /dev/null and b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/surface-view-half-pixel-translation.png differ diff --git a/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/surface-view-right-half.png b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/surface-view-right-half.png new file mode 100644 index 00000000..af526ed3 Binary files /dev/null and b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/surface-view-right-half.png differ diff --git a/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/surface-view-scaled.png b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/surface-view-scaled.png new file mode 100644 index 00000000..5ccaedfd Binary files /dev/null and b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/surface-view-scaled.png differ diff --git a/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/surfaces-overlapped.png b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/surfaces-overlapped.png new file mode 100644 index 00000000..2e92629e Binary files /dev/null and b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/surfaces-overlapped.png differ diff --git a/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/texture-view-red.png b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/texture-view-red.png new file mode 100644 index 00000000..a8b07f23 Binary files /dev/null and b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/texture-view-red.png differ diff --git a/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/video-surface-view.png b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/video-surface-view.png new file mode 100644 index 00000000..4a179c92 Binary files /dev/null and b/apps/playground/src/__tests__/normal/ui/__image_snapshots__/android/video-surface-view.png differ diff --git a/apps/playground/src/__tests__/normal/ui/surfaces.android.harness.tsx b/apps/playground/src/__tests__/normal/ui/surfaces.android.harness.tsx new file mode 100644 index 00000000..ed018686 --- /dev/null +++ b/apps/playground/src/__tests__/normal/ui/surfaces.android.harness.tsx @@ -0,0 +1,373 @@ +import { createRef } from 'react'; +import { describe, test, render, expect, waitFor } from 'react-native-harness'; +import { Dimensions, ScrollView, View } from 'react-native'; +import { screen } from '@react-native-harness/ui'; + +import { + RootShiftView, + SolidColorSurfaceView, + SolidColorTextureView, + SplitColorSurfaceView, + SplitColorVideoView, +} from '../../../native/PaintedSurfaces'; + +describe('Screenshot of views drawn on a surface of their own', () => { + test('shows what a TextureView and a SurfaceView display', async () => { + await render( + + + + + ); + await screen.findByAccessibilityLabel('texture-view-painted'); + await screen.findByAccessibilityLabel('surface-view-painted'); + + const textureView = await screen.findByTestId('texture-view'); + await expect(await screen.screenshot(textureView)).toMatchImageSnapshot({ + name: 'texture-view-red', + }); + + const surfaceView = await screen.findByTestId('surface-view'); + await expect(await screen.screenshot(surfaceView)).toMatchImageSnapshot({ + name: 'surface-view-blue', + }); + }); + + test('places a SurfaceView at its offset, under the views drawn over it', async () => { + await render( + + + + + + + + ); + await screen.findByAccessibilityLabel('texture-view-painted'); + await screen.findByAccessibilityLabel('surface-view-painted'); + + const surfaces = await screen.findByTestId('surfaces'); + await expect(await screen.screenshot(surfaces)).toMatchImageSnapshot({ + name: 'surfaces-overlapped', + }); + }); + + test('draws a SurfaceView under a scale transform at the size the screen shows it', async () => { + await render( + + + + + + ); + await screen.findByAccessibilityLabel('split-surface-view-painted'); + + const scaledSurface = await screen.findByTestId('scaled-surface'); + await expect(await screen.screenshot(scaledSurface)).toMatchImageSnapshot({ + name: 'surface-view-scaled', + }); + }); + + test('copies only the part of a SurfaceView inside the captured region', async () => { + await render( + + + + + + + ); + await screen.findByAccessibilityLabel('split-surface-view-painted'); + + const rightHalf = await screen.findByTestId('right-half'); + await expect(await screen.screenshot(rightHalf)).toMatchImageSnapshot({ + name: 'surface-view-right-half', + }); + }); + + test('draws a SurfaceView under a fractional scale into the box the screen shows it in', async () => { + await render( + + + + + + ); + await screen.findByAccessibilityLabel('split-surface-view-painted'); + + const scaledSurface = await screen.findByTestId( + 'fractionally-scaled-surface' + ); + await expect(await screen.screenshot(scaledSurface)).toMatchImageSnapshot({ + name: 'surface-view-fractional-scale', + }); + }); + + test('draws a SurfaceView under a half-pixel translation into the box the screen shows it in', async () => { + await render( + + + + + + ); + await screen.findByAccessibilityLabel('split-surface-view-painted'); + + const translatedSurface = await screen.findByTestId( + 'half-pixel-translated-surface' + ); + await expect( + await screen.screenshot(translatedSurface) + ).toMatchImageSnapshot({ + name: 'surface-view-half-pixel-translation', + }); + }); + + test('draws a SurfaceView under an enlarging scale into the box the screen shows it in', async () => { + await render( + + + + + + ); + await screen.findByAccessibilityLabel('split-surface-view-painted'); + + const enlargedSurface = await screen.findByTestId('enlarged-surface'); + await expect(await screen.screenshot(enlargedSurface)).toMatchImageSnapshot( + { + name: 'surface-view-enlarged', + } + ); + }); + + test('copies a video frame larger than its SurfaceView at the size the screen shows it', async () => { + await render( + + + + ); + await screen.findByAccessibilityLabel('split-video-painted'); + + const videoSurface = await screen.findByTestId('video-surface'); + await expect(await screen.screenshot(videoSurface)).toMatchImageSnapshot({ + name: 'video-surface-view', + }); + }); + + test('captures the window while a SurfaceView is scaled to nothing', async () => { + await render( + + + + + + ); + await screen.findByAccessibilityLabel('split-surface-view-painted'); + + expect(await screen.screenshot()).not.toBeNull(); + }); +}); + +describe('Screenshot of an element by the box it covers on the screen', () => { + test('draws an element scaled to nothing as the element draws itself', async () => { + await render( + + + + ); + + const scaledToNothing = await screen.findByTestId('scaled-to-nothing'); + await expect(await screen.screenshot(scaledToNothing)).toMatchImageSnapshot( + { name: 'element-scaled-to-nothing' } + ); + }); + + test("captures an element where it is drawn when the window's root view moves", async () => { + await render( + + + + + ); + + const underMovedRoot = await screen.findByTestId('under-moved-root'); + await expect(await screen.screenshot(underMovedRoot)).toMatchImageSnapshot({ + name: 'element-under-moved-root', + }); + }); + + test('captures an element under nested rotations in the box it covers on the screen', async () => { + await render( + + + + + + ); + + const counterRotated = await screen.findByTestId('counter-rotated'); + await expect(await screen.screenshot(counterRotated)).toMatchImageSnapshot({ + name: 'element-under-nested-rotations', + }); + }); + + test('draws an element clipped out of the view tree as the element draws itself', async () => { + const clippingTree = (top: number) => ( + + + + + + ); + const { rerender } = await render(clippingTree(0)); + const clipped = await screen.findByTestId('clipped'); + await rerender(clippingTree(200)); + await waitFor(() => expect(screen.queryByTestId('clipped')).toBeNull()); + + await expect(await screen.screenshot(clipped)).toMatchImageSnapshot({ + name: 'element-clipped-out', + }); + }); + + test('draws a scrolled element partly off the screen at its scroll offset', async () => { + const scrollView = createRef(); + let onScrolledToBlue: () => void = () => undefined; + const scrolledToBlue = new Promise((resolve) => { + onScrolledToBlue = resolve; + }); + await render( + + { + if (nativeEvent.contentOffset.x >= 95.5) { + onScrolledToBlue(); + } + }} + style={{ + position: 'absolute', + top: 96, + left: -48, + width: 96, + height: 96, + }} + > + + + + + ); + scrollView.current?.scrollTo({ x: 96, animated: false }); + await scrolledToBlue; + + const scrolledOffScreen = await screen.findByTestId('scrolled-off-screen'); + await expect( + await screen.screenshot(scrolledOffScreen) + ).toMatchImageSnapshot({ name: 'element-scrolled-off-screen' }); + }); +}); + +describe('Screenshot of a region past the edge of the window', () => { + test('leaves the part off the window transparent', async () => { + await render( + + + + ); + + const { height } = Dimensions.get('window'); + await expect( + await screen.screenshot({ + x: -24, + y: height / 2 - 24, + width: 48, + height: 48, + }) + ).toMatchImageSnapshot({ name: 'region-past-window-edge' }); + }); +}); diff --git a/apps/playground/src/native/PaintedSurfaces.ts b/apps/playground/src/native/PaintedSurfaces.ts new file mode 100644 index 00000000..49c84621 --- /dev/null +++ b/apps/playground/src/native/PaintedSurfaces.ts @@ -0,0 +1,23 @@ +import { requireNativeComponent } from 'react-native'; +import type { ViewProps } from 'react-native'; + +// Android only: see PaintedSurfacesPackage.kt. +export const SolidColorTextureView = requireNativeComponent( + 'SolidColorTextureView' +); + +export const SolidColorSurfaceView = requireNativeComponent( + 'SolidColorSurfaceView' +); + +export const SplitColorSurfaceView = requireNativeComponent( + 'SplitColorSurfaceView' +); + +export const SplitColorVideoView = requireNativeComponent( + 'SplitColorVideoView' +); + +export const RootShiftView = requireNativeComponent< + ViewProps & { rootTranslationY: number } +>('RootShiftView'); diff --git a/packages/ui/android/src/main/java/com/harnessui/UIHelperImpl.kt b/packages/ui/android/src/main/java/com/harnessui/UIHelperImpl.kt index d904960e..5be47519 100644 --- a/packages/ui/android/src/main/java/com/harnessui/UIHelperImpl.kt +++ b/packages/ui/android/src/main/java/com/harnessui/UIHelperImpl.kt @@ -3,12 +3,23 @@ package com.harnessui import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas +import android.graphics.Matrix +import android.graphics.Paint +import android.graphics.PorterDuff +import android.graphics.PorterDuffXfermode import android.graphics.Rect +import android.graphics.RectF +import android.os.Build import android.os.Handler import android.os.Looper import android.os.SystemClock import android.util.Log import android.view.MotionEvent +import android.view.PixelCopy +import android.view.SurfaceView +import android.view.View +import android.view.ViewGroup +import android.view.Window import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputMethodManager import android.widget.EditText @@ -24,6 +35,8 @@ import java.io.ByteArrayOutputStream import java.nio.ByteBuffer import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit +import kotlin.math.floor +import kotlin.math.min import kotlin.math.roundToInt /** @@ -37,6 +50,8 @@ class UIHelperImpl( private const val TAG = "HarnessUI" private const val TAP_DURATION_MS = 50L // Duration between touch down and up private const val EVENT_PROCESSING_DELAY_MS = 10L // Delay after touch up for React Native to process the event + private const val GEOMETRY_FUDGE_FACTOR = 0.0656f // How far the renderer widens a box it snaps to pixels + private const val COPY_ATTEMPTS = 4 // Requests of a copy the renderer abandons at its 500 ms buffer fence wait } private val mainHandler = Handler(Looper.getMainLooper()) @@ -251,7 +266,8 @@ class UIHelperImpl( return@runOnUiThread } - val root = activity.window.decorView.rootView + val window = activity.window + val root = window.decorView.rootView val density = root.resources.displayMetrics.density try { @@ -276,96 +292,400 @@ class UIHelperImpl( return@runOnUiThread } - val location = IntArray(2) - targetView.getLocationOnScreen(location) - val viewRect = Rect(location[0], location[1], location[0] + width, location[1] + height) + val viewRect = rectInWindow(targetView) val rootRect = Rect(0, 0, root.width, root.height) - val isFullyOnScreen = rootRect.contains(viewRect) - val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) - val canvas = Canvas(bitmap) - - if (isFullyOnScreen) { + if (targetView.isAttachedToWindow && !viewRect.isEmpty && rootRect.contains(viewRect)) { Log.i(TAG, "View $nativeId is fully on screen. Using screen-based screenshotting.") - // Translate canvas to capture the view from the root view hierarchy - canvas.translate(-location[0].toFloat(), -location[1].toFloat()) - root.draw(canvas) + captureWindowRegion(window, viewRect, promise) } else { - Log.i(TAG, "View $nativeId is partially/fully off screen. Using direct view render.") - // Draw the specific view directly - targetView.draw(canvas) + Log.i(TAG, "View $nativeId is not fully on screen. Using direct view render.") + promise.resolve(encodePng(drawView(targetView))) } - - val outputStream = ByteArrayOutputStream() - bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream) - val pngBytes = outputStream.toByteArray() - bitmap.recycle() - - val base64String = android.util.Base64.encodeToString(pngBytes, android.util.Base64.NO_WRAP) - promise.resolve(base64String) return@runOnUiThread } - // Determine capture dimensions - val captureX: Int - val captureY: Int - val captureWidth: Int - val captureHeight: Int - // Check if bounds are provided and have non-zero dimensions - val hasBounds = bounds != null && bounds.getDouble("width") > 0 && bounds.getDouble("height") > 0 - - if (hasBounds) { - // Convert dp to px, rounding each edge (not the size) so the region covers the same - // pixels React Native lays out for a view with these bounds. - val boundsX = bounds!!.getDouble("x") - val boundsY = bounds.getDouble("y") - val left = (boundsX * density).roundToInt() - val top = (boundsY * density).roundToInt() - val right = ((boundsX + bounds.getDouble("width")) * density).roundToInt() - val bottom = ((boundsY + bounds.getDouble("height")) * density).roundToInt() - captureX = left - captureY = top - captureWidth = right - left - captureHeight = bottom - top - Log.i(TAG, "Capturing region: x=$captureX y=$captureY w=$captureWidth h=$captureHeight") - } else { - captureX = 0 - captureY = 0 - captureWidth = root.width - captureHeight = root.height - Log.i(TAG, "Capturing full window: w=$captureWidth h=$captureHeight") - } + val region = + if (bounds != null && bounds.getDouble("width") > 0 && bounds.getDouble("height") > 0) { + // Convert dp to px, rounding each edge (not the size) so the region covers the same + // pixels React Native lays out for a view with these bounds. + val boundsX = bounds.getDouble("x") + val boundsY = bounds.getDouble("y") + val left = (boundsX * density).roundToInt() + val top = (boundsY * density).roundToInt() + val right = ((boundsX + bounds.getDouble("width")) * density).roundToInt() + val bottom = ((boundsY + bounds.getDouble("height")) * density).roundToInt() + Log.i(TAG, "Capturing region: x=$left y=$top w=${right - left} h=${bottom - top}") + Rect(left, top, right, bottom) + } else { + Log.i(TAG, "Capturing full window: w=${root.width} h=${root.height}") + Rect(0, 0, root.width, root.height) + } - // Create bitmap and canvas - val bitmap = Bitmap.createBitmap(captureWidth, captureHeight, Bitmap.Config.ARGB_8888) - val canvas = Canvas(bitmap) + captureWindowRegion(window, region, promise) + } catch (e: Exception) { + Log.e(TAG, "Screenshot capture failed", e) + promise.resolve(null) + } + } + } + + // A software draw of the view tree leaves out pixels a view keeps on a surface of its own: a TextureView draws + // nothing into a software canvas, and a SurfaceView's content lives on a separate surface behind the window, which + // leaves a transparent hole over it. PixelCopy reads the window's surface, which the TextureViews render into, and + // each SurfaceView's surface, each at the latest frame it holds when its copy runs. A SurfaceView set above its + // window with setZOrderOnTop punches no hole, so it stays hidden: before Android 16 only hidden API tells one + // apart, and the SDK this module compiles against by default predates getCompositionOrder(). + private fun captureWindowRegion( + window: Window, + region: Rect, + promise: Promise, + ) { + val decorView = window.decorView + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { + promise.resolve(encodePng(drawWindowRegion(decorView, region))) + return + } + // A window that is not shown, as while the screen is off, has nothing on the screen to copy. + if (!decorView.isShown) { + Log.e(TAG, "Screenshot capture failed: the window is not shown") + promise.resolve(null) + return + } + + // PixelCopy stretches a source rect that runs past the window over the whole bitmap, so only the part on the + // window is copied, and placed at its offset in the region. + val copiedRegion = Rect(0, 0, decorView.width, decorView.height) + if (!copiedRegion.intersect(region)) { + promise.resolve(encodePng(drawWindowRegion(decorView, region))) + return + } - // Translate canvas if capturing a specific region - canvas.translate(-captureX.toFloat(), -captureY.toFloat()) + val surfaceViews = + collectSurfaceViews(decorView).filter { surfaceView -> + !surfaceView.rect.isEmpty && Rect.intersects(copiedRegion, surfaceView.rect) + } + val surfaceLayers = arrayOfNulls(surfaceViews.size) + var windowSource: WindowSource = WindowSource.ViewTree + var copyFailure: String? = null + var pendingCopies = surfaceViews.size + 1 - // Draw the view hierarchy - root.draw(canvas) + fun failCopy(reason: String) { + copyFailure = copyFailure ?: reason + } - // Convert to PNG bytes - val outputStream = ByteArrayOutputStream() - bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream) - val pngBytes = outputStream.toByteArray() + fun onCopyFinished() { + pendingCopies -= 1 + if (pendingCopies > 0) { + return + } + val layers = surfaceLayers.filterNotNull() - // Clean up - bitmap.recycle() + fun abandon() { + when (val source = windowSource) { + is WindowSource.Copy -> source.pixels.recycle() + WindowSource.ViewTree -> Unit + } + layers.forEach { layer -> layer.pixels.recycle() } + promise.resolve(null) + } - // Return as Base64 string for efficiency - val base64String = android.util.Base64.encodeToString(pngBytes, android.util.Base64.NO_WRAP) - Log.i(TAG, "Screenshot captured successfully (${pngBytes.size} bytes)") - promise.resolve(base64String) + val failure = copyFailure + if (failure != null) { + Log.e(TAG, "Screenshot capture failed: $failure") + abandon() + return + } + var screenshot: Bitmap? = null + try { + screenshot = + when (val source = windowSource) { + is WindowSource.Copy -> placeInRegion(source.pixels, copiedRegion, region) + WindowSource.ViewTree -> drawWindowRegion(decorView, region) + } + drawBehind(screenshot, layers, Rect(copiedRegion).apply { offset(-region.left, -region.top) }) + promise.resolve(encodePng(screenshot)) } catch (e: Exception) { Log.e(TAG, "Screenshot capture failed", e) - promise.resolve(null) + screenshot?.recycle() + abandon() + } + } + + // Before Android 9, PixelCopy does not offset the rect it is given by the window's surface insets, which a + // window with elevation has, so such a window's view tree is drawn instead. + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P && decorView.z > 0f) { + onCopyFinished() + } else { + val windowPixels = Bitmap.createBitmap(copiedRegion.width(), copiedRegion.height(), Bitmap.Config.ARGB_8888) + val copyWindow = { listener: PixelCopy.OnPixelCopyFinishedListener -> + PixelCopy.request(window, Rect(copiedRegion), windowPixels, listener, mainHandler) + } + requestCopy(copyWindow) { outcome -> + when (outcome) { + is CopyOutcome.Finished -> + if (outcome.result == PixelCopy.SUCCESS) { + windowSource = WindowSource.Copy(windowPixels) + } else { + windowPixels.recycle() + failCopy("PixelCopy of the window failed with result ${outcome.result}") + } + is CopyOutcome.SourceGone -> { + windowPixels.recycle() + failCopy("PixelCopy cannot read the window, which has no surface: ${outcome.error.message}") + } + } + onCopyFinished() + } + } + + // A SurfaceView's buffer can differ in size from its view, as a video decoder's does, and the screen shows it + // scaled to the view's box, so the whole buffer is copied, at no more than the view's own size, and drawn into + // the box. + surfaceViews.forEachIndexed { index, surfaceView -> + val pixels = + Bitmap.createBitmap( + min(surfaceView.rect.width(), surfaceView.view.width), + min(surfaceView.rect.height(), surfaceView.view.height), + Bitmap.Config.ARGB_8888, + ) + val box = Rect(surfaceView.rect).apply { offset(-region.left, -region.top) } + val copySurface = { listener: PixelCopy.OnPixelCopyFinishedListener -> + PixelCopy.request(surfaceView.view, pixels, listener, mainHandler) + } + requestCopy(copySurface) { outcome -> + when (outcome) { + is CopyOutcome.Finished -> + when (val result = outcome.result) { + PixelCopy.SUCCESS -> surfaceLayers[index] = SurfaceLayer(pixels, box) + // A surface with no frame yet, one that is gone and a protected one hold nothing a copy can + // read, so they add no layer. + PixelCopy.ERROR_SOURCE_NO_DATA, PixelCopy.ERROR_SOURCE_INVALID -> pixels.recycle() + else -> { + failCopy("PixelCopy of a SurfaceView failed with result $result") + pixels.recycle() + } + } + is CopyOutcome.SourceGone -> { + Log.w(TAG, "PixelCopy cannot read a SurfaceView, whose surface is gone", outcome.error) + pixels.recycle() + } + } + onCopyFinished() } } } + private sealed interface WindowSource { + class Copy(val pixels: Bitmap) : WindowSource + + object ViewTree : WindowSource + } + + private sealed interface CopyOutcome { + class Finished(val result: Int) : CopyOutcome + + class SourceGone(val error: IllegalArgumentException) : CopyOutcome + } + + // The renderer abandons a copy whose source buffer is still being drawn when its fence wait ends (ERROR_TIMEOUT), + // so a slow GPU gets the copy requested again, up to COPY_ATTEMPTS times, before it counts as failed. + private fun requestCopy( + request: (PixelCopy.OnPixelCopyFinishedListener) -> Unit, + attempt: Int = 1, + onOutcome: (CopyOutcome) -> Unit, + ) { + try { + request( + PixelCopy.OnPixelCopyFinishedListener { result -> + if (result == PixelCopy.ERROR_TIMEOUT && attempt < COPY_ATTEMPTS) { + requestCopy(request, attempt + 1, onOutcome) + } else { + onOutcome(CopyOutcome.Finished(result)) + } + }, + ) + } catch (e: IllegalArgumentException) { + onOutcome(CopyOutcome.SourceGone(e)) + } + } + + private fun drawView(view: View): Bitmap = + drawRegion(Rect(0, 0, view.width, view.height)) { canvas -> drawScrolled(view, canvas) } + + // The window's view tree drawn in software where the window shows it, through the root view's transform and the + // window's pan and cut at the window's edges, so the region and the SurfaceViews' boxes line up with it. + private fun drawWindowRegion( + rootView: View, + region: Rect, + ): Bitmap = + drawRegion(region) { canvas -> + canvas.clipRect(0, 0, rootView.width, rootView.height) + canvas.concat(viewToWindow(rootView)) + drawScrolled(rootView, canvas) + } + + // A view draws its content in its scrolled space, which the parent's draw otherwise translates it into. + private fun drawScrolled( + view: View, + canvas: Canvas, + ) { + canvas.translate(-view.scrollX.toFloat(), -view.scrollY.toFloat()) + view.draw(canvas) + } + + private fun drawRegion( + region: Rect, + draw: (Canvas) -> Unit, + ): Bitmap { + val bitmap = Bitmap.createBitmap(region.width(), region.height(), Bitmap.Config.ARGB_8888) + try { + val canvas = Canvas(bitmap) + canvas.translate(-region.left.toFloat(), -region.top.toFloat()) + draw(canvas) + } catch (e: Exception) { + bitmap.recycle() + throw e + } + return bitmap + } + + private fun placeInRegion( + pixels: Bitmap, + pixelsRegion: Rect, + region: Rect, + ): Bitmap { + if (pixelsRegion == region) { + return pixels + } + val bitmap = Bitmap.createBitmap(region.width(), region.height(), Bitmap.Config.ARGB_8888) + Canvas(bitmap).drawBitmap( + pixels, + (pixelsRegion.left - region.left).toFloat(), + (pixelsRegion.top - region.top).toFloat(), + null, + ) + pixels.recycle() + return bitmap + } + + // Each layer goes behind what is drawn already, so the layers are drawn last to first, stacking the SurfaceViews in + // the order of the view tree. The screen stacks a media overlay above the others, which no public API reports + // before Android 16, and the rest in the order their surfaces were created, which no API reports. Nothing is drawn + // outside the window's part of the region. + private fun drawBehind( + screenshot: Bitmap, + layers: List, + windowPart: Rect, + ) { + val canvas = Canvas(screenshot) + canvas.clipRect(windowPart) + val behind = Paint(Paint.FILTER_BITMAP_FLAG).apply { xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OVER) } + layers.asReversed().forEach { layer -> + canvas.drawBitmap(layer.pixels, null, layer.box, behind) + layer.pixels.recycle() + } + } + + private class SurfaceLayer( + val pixels: Bitmap, + val box: Rect, + ) + + private class SurfaceViewInWindow( + val view: SurfaceView, + val rect: Rect, + ) + + private fun collectSurfaceViews( + view: View, + found: MutableList = mutableListOf(), + ): List { + when { + view.visibility != View.VISIBLE -> Unit + view is SurfaceView -> + if (view.width > 0 && view.height > 0 && view.holder.surface.isValid) { + found.add(SurfaceViewInWindow(view, rectInWindow(view))) + } + view is ViewGroup -> + for (index in 0 until view.childCount) { + collectSurfaceViews(view.getChildAt(index), found) + } + } + return found + } + + // A view's own space mapped into the window through its own and its ancestors' transforms, composed into one as + // the renderer composes them, then the pan the window applies to all of its views. + private fun viewToWindow(view: View): Matrix { + val transform = Matrix() + var current = view + while (true) { + transform.postConcat(current.matrix) + transform.postTranslate(current.left.toFloat(), current.top.toFloat()) + val parent = current.parent as? View ?: break + transform.postTranslate(-parent.scrollX.toFloat(), -parent.scrollY.toFloat()) + current = parent + } + // The root view's location in the window is its own corner, already composed above, rounded to whole pixels, + // plus the pan. + val rootLocation = IntArray(2) + current.getLocationInWindow(rootLocation) + val rootCorner = floatArrayOf(0f, 0f).also { corner -> current.matrix.mapPoints(corner) } + transform.postTranslate( + (rootLocation[0] - (rootCorner[0] + current.left).roundToInt()).toFloat(), + (rootLocation[1] - (rootCorner[1] + current.top).roundToInt()).toFloat(), + ) + return transform + } + + // The box a view covers in the window, as UIKit's convertRect:toView: gives it, rounded as the renderer rounds the + // box it shows a SurfaceView's surface in: snapped to pixel boundaries under translation alone, outward under any + // other transform. A box with no area stays empty whatever its rounding would give. + private fun rectInWindow(view: View): Rect { + val transform = viewToWindow(view) + val bounds = RectF(0f, 0f, view.width.toFloat(), view.height.toFloat()).also { rect -> transform.mapRect(rect) } + return when { + bounds.isEmpty -> Rect() + isTranslation(transform) -> snapToPixelBoundaries(bounds) + else -> Rect().also { rect -> bounds.roundOut(rect) } + } + } + + // As the renderer snaps a box under translation alone: to the nearest pixel, and from Android 10 + // (Rect::snapGeometryToPixelBoundaries) with an edge within GEOMETRY_FUDGE_FACTOR of a half pixel going outward. + private fun snapToPixelBoundaries(bounds: RectF): Rect { + val fudge = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) GEOMETRY_FUDGE_FACTOR else 0f + return Rect( + floor(bounds.left + 0.5f - fudge).toInt(), + floor(bounds.top + 0.5f - fudge).toInt(), + floor(bounds.right + 0.5f + fudge).toInt(), + floor(bounds.bottom + 0.5f + fudge).toInt(), + ) + } + + private fun isTranslation(matrix: Matrix): Boolean { + val values = FloatArray(9).also { matrix.getValues(it) } + return values[Matrix.MSCALE_X] == 1f && + values[Matrix.MSCALE_Y] == 1f && + values[Matrix.MSKEW_X] == 0f && + values[Matrix.MSKEW_Y] == 0f && + values[Matrix.MPERSP_0] == 0f && + values[Matrix.MPERSP_1] == 0f + } + + private fun encodePng(bitmap: Bitmap): String { + try { + val outputStream = ByteArrayOutputStream() + bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream) + Log.i(TAG, "Screenshot captured successfully (${outputStream.size()} bytes)") + return android.util.Base64.encodeToString(outputStream.toByteArray(), android.util.Base64.NO_WRAP) + } finally { + bitmap.recycle() + } + } + // ========================================================================= // Text Input // =========================================================================