-
-
Notifications
You must be signed in to change notification settings - Fork 476
Expand file tree
/
Copy pathPixelCopyStrategyTest.kt
More file actions
512 lines (434 loc) · 17.8 KB
/
Copy pathPixelCopyStrategyTest.kt
File metadata and controls
512 lines (434 loc) · 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
package io.sentry.android.replay.screenshot
import android.app.Activity
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.Rect
import android.graphics.RectF
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.PixelCopy
import android.view.SurfaceView
import android.view.View
import android.view.Window
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.LinearLayout.LayoutParams
import android.widget.TextView
import androidx.test.ext.junit.runners.AndroidJUnit4
import io.sentry.SentryOptions
import io.sentry.android.replay.ExecutorProvider
import io.sentry.android.replay.ScreenshotRecorderCallback
import io.sentry.android.replay.ScreenshotRecorderConfig
import io.sentry.android.replay.util.DebugOverlayDrawable
import io.sentry.android.replay.util.MainLooperHandler
import java.util.concurrent.Future
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import org.junit.runner.RunWith
import org.mockito.kotlin.any
import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.doAnswer
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.robolectric.Robolectric.buildActivity
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
import org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
import org.robolectric.shadows.ShadowPixelCopy
@Config(shadows = [ShadowPixelCopy::class], sdk = [30])
@GraphicsMode(GraphicsMode.Mode.NATIVE)
@RunWith(AndroidJUnit4::class)
class PixelCopyStrategyTest {
private class Fixture {
val options = SentryOptions()
val callback = mock<ScreenshotRecorderCallback>()
val debugOverlayDrawable = mock<DebugOverlayDrawable>()
val config = ScreenshotRecorderConfig(100, 100, 1f, 1f, 1, 1000)
val contentChangedMarked = AtomicBoolean(false)
fun getSut(executor: ScheduledExecutorService = mock()): PixelCopyStrategy {
return PixelCopyStrategy(
object : ExecutorProvider {
override fun getExecutor(): ScheduledExecutorService = executor
override fun getMainLooperHandler(): MainLooperHandler = MainLooperHandler()
override fun getBackgroundHandler(): Handler = mock()
},
callback,
options,
config,
debugOverlayDrawable,
markContentChanged = { contentChangedMarked.set(true) },
)
}
/** Executor mock that runs submitted tasks synchronously on the calling thread. */
fun inlineExecutor(): ScheduledExecutorService {
return mock {
doAnswer {
(it.arguments[0] as Runnable).run()
null // submit(Runnable) returns Future<?>; returning Unit breaks the cast
}
.whenever(mock)
.submit(any<Runnable>())
}
}
}
private val fixture = Fixture()
@BeforeTest
fun setup() {
System.setProperty("robolectric.areWindowsMarkedVisible", "true")
System.setProperty("robolectric.pixelCopyRenderMode", "hardware")
DeferredWindowPixelCopyShadow.reset()
}
@Test
fun `when strategy is closed, lastCaptureSuccessful returns false`() {
val strategy = fixture.getSut()
strategy.close()
assertFalse(strategy.lastCaptureSuccessful())
}
@Test
fun `when close is called while executor task is running, does not crash with recycled bitmap`() {
val activity = buildActivity(SimpleActivity::class.java).setup()
shadowOf(Looper.getMainLooper()).idle()
var strategy: PixelCopyStrategy? = null
val failure = AtomicReference<Throwable>()
// Custom executor that closes the strategy before executing tasks
val executorThatClosesFirst = mock<ScheduledExecutorService>()
whenever(executorThatClosesFirst.submit(any<Runnable>())).doAnswer {
val task = it.getArgument<Runnable>(0)
strategy?.close()
try {
task.run()
} catch (e: Throwable) {
// PixelCopyStrategy swallows the exception, so we have to capture it here and rethrow later
failure.set(e)
}
null
}
strategy = fixture.getSut(executor = executorThatClosesFirst)
strategy.capture(activity.get().findViewById(android.R.id.content))
shadowOf(Looper.getMainLooper()).idle()
if (failure.get() != null) throw failure.get()
}
@Test
@Config(shadows = [DeferredWindowPixelCopyShadow::class])
fun `capture drops frame while PixelCopy is in flight`() {
val activity = buildActivity(SimpleActivity::class.java).setup()
shadowOf(Looper.getMainLooper()).idle()
val root = activity.get().findViewById<View>(android.R.id.content)
val strategy = fixture.getSut(executor = fixture.inlineExecutor())
strategy.capture(root)
strategy.capture(root)
assertTrue(fixture.contentChangedMarked.get())
DeferredWindowPixelCopyShadow.flush()
shadowOf(Looper.getMainLooper()).idle()
verify(fixture.callback).onScreenshotRecorded(any<Bitmap>())
strategy.capture(root)
DeferredWindowPixelCopyShadow.flush()
shadowOf(Looper.getMainLooper()).idle()
verify(fixture.callback, times(2)).onScreenshotRecorded(any<Bitmap>())
}
@Test
@Config(shadows = [DeferredWindowPixelCopyShadow::class])
fun `capture drops frame while masking is in flight`() {
val activity = buildActivity(SimpleActivity::class.java).setup()
shadowOf(Looper.getMainLooper()).idle()
val root = activity.get().findViewById<View>(android.R.id.content)
val tasks = mutableListOf<Runnable>()
val executor = mock<ScheduledExecutorService>()
whenever(executor.submit(any<Runnable>())).doAnswer {
tasks += it.getArgument<Runnable>(0)
mock<Future<*>>()
}
val strategy = fixture.getSut(executor)
strategy.capture(root)
DeferredWindowPixelCopyShadow.flush()
shadowOf(Looper.getMainLooper()).idle()
strategy.capture(root)
DeferredWindowPixelCopyShadow.flush()
shadowOf(Looper.getMainLooper()).idle()
assertEquals(1, tasks.size)
tasks.removeAt(0).run()
strategy.capture(root)
DeferredWindowPixelCopyShadow.flush()
shadowOf(Looper.getMainLooper()).idle()
assertEquals(1, tasks.size)
}
@Test
@Config(shadows = [DeferredWindowPixelCopyShadow::class])
fun `emitLastScreenshot skips while frame is in flight`() {
val activity = buildActivity(SimpleActivity::class.java).setup()
shadowOf(Looper.getMainLooper()).idle()
val root = activity.get().findViewById<View>(android.R.id.content)
val strategy = fixture.getSut(executor = fixture.inlineExecutor())
captureStableFrame(strategy, root)
strategy.capture(root)
strategy.emitLastScreenshot()
verify(fixture.callback).onScreenshotRecorded(any<Bitmap>())
DeferredWindowPixelCopyShadow.flush()
shadowOf(Looper.getMainLooper()).idle()
verify(fixture.callback, times(2)).onScreenshotRecorded(any<Bitmap>())
}
@Test
@Config(shadows = [DeferredWindowPixelCopyShadow::class])
fun `close defers cleanup until PixelCopy completes`() {
val activity = buildActivity(SimpleActivity::class.java).setup()
shadowOf(Looper.getMainLooper()).idle()
val root = activity.get().findViewById<View>(android.R.id.content)
val executor = mock<ScheduledExecutorService>()
val strategy = fixture.getSut(executor)
strategy.capture(root)
strategy.close()
verify(executor, never()).submit(any<Runnable>())
DeferredWindowPixelCopyShadow.flush()
shadowOf(Looper.getMainLooper()).idle()
verify(executor).submit(any<Runnable>())
}
@Test
@Config(shadows = [DeferredWindowPixelCopyShadow::class])
fun `capture skips the first unstable PixelCopy result`() {
val activity = buildActivity(SimpleActivity::class.java).setup()
shadowOf(Looper.getMainLooper()).idle()
val root = activity.get().findViewById<View>(android.R.id.content)
val strategy = fixture.getSut(executor = fixture.inlineExecutor())
captureUnstableFrame(strategy, root)
assertFalse(strategy.lastCaptureSuccessful())
verify(fixture.callback, never()).onScreenshotRecorded(any<Bitmap>())
}
@Test
@Config(shadows = [DeferredWindowPixelCopyShadow::class])
fun `capture emits the second consecutive unstable PixelCopy result`() {
val activity = buildActivity(SimpleActivity::class.java).setup()
shadowOf(Looper.getMainLooper()).idle()
val root = activity.get().findViewById<View>(android.R.id.content)
val strategy = fixture.getSut(executor = fixture.inlineExecutor())
captureUnstableFrame(strategy, root)
captureUnstableFrame(strategy, root)
assertTrue(strategy.lastCaptureSuccessful())
verify(fixture.callback).onScreenshotRecorded(any<Bitmap>())
}
@Test
@Config(shadows = [DeferredWindowPixelCopyShadow::class])
fun `capture keeps emitting after entering continuous instability mode`() {
val activity = buildActivity(SimpleActivity::class.java).setup()
shadowOf(Looper.getMainLooper()).idle()
val root = activity.get().findViewById<View>(android.R.id.content)
val strategy = fixture.getSut(executor = fixture.inlineExecutor())
captureUnstableFrame(strategy, root)
captureUnstableFrame(strategy, root)
captureUnstableFrame(strategy, root)
assertTrue(strategy.lastCaptureSuccessful())
verify(fixture.callback, times(2)).onScreenshotRecorded(any<Bitmap>())
}
@Test
@Config(shadows = [DeferredWindowPixelCopyShadow::class])
fun `stable capture resets the unstable PixelCopy counter`() {
val activity = buildActivity(SimpleActivity::class.java).setup()
shadowOf(Looper.getMainLooper()).idle()
val root = activity.get().findViewById<View>(android.R.id.content)
val strategy = fixture.getSut(executor = fixture.inlineExecutor())
captureUnstableFrame(strategy, root)
captureUnstableFrame(strategy, root)
captureStableFrame(strategy, root)
captureUnstableFrame(strategy, root)
assertFalse(strategy.lastCaptureSuccessful())
verify(fixture.callback, times(2)).onScreenshotRecorded(any<Bitmap>())
}
@Test
fun `capture does not call markContentChanged when option is disabled`() {
val activity = buildActivity(ActivityWithSurfaceView::class.java).setup()
shadowOf(Looper.getMainLooper()).idle()
// Default: isCaptureSurfaceViews = false
val strategy = fixture.getSut(executor = fixture.inlineExecutor())
strategy.capture(activity.get().findViewById(android.R.id.content))
shadowOf(Looper.getMainLooper()).idle()
assertFalse(fixture.contentChangedMarked.get())
assertTrue(strategy.lastCaptureSuccessful())
val screenshot = argumentCaptor<Bitmap>()
verify(fixture.callback).onScreenshotRecorded(screenshot.capture())
assertEquals(Bitmap.Config.RGB_565, screenshot.firstValue.config)
}
@Test
fun `capture re-arms contentChanged when option is enabled and SurfaceView is present`() {
val activity = buildActivity(ActivityWithSurfaceView::class.java).setup()
shadowOf(Looper.getMainLooper()).idle()
fixture.options.sessionReplay.isCaptureSurfaceViews = true
val strategy = fixture.getSut(executor = fixture.inlineExecutor())
strategy.capture(activity.get().findViewById(android.R.id.content))
shadowOf(Looper.getMainLooper()).idle()
assertTrue(fixture.contentChangedMarked.get())
}
@Test
fun `capture completes when SurfaceView surface is not valid`() {
// In Robolectric the SurfaceView holder surface is not valid — this exercises the
// `surfaceView.holder.surface.isValid == false` branch: each SurfaceView skips its
// PixelCopy and onCaptureComplete still fires, eventually running the compositor and
// callback.
val activity = buildActivity(ActivityWithSurfaceView::class.java).setup()
shadowOf(Looper.getMainLooper()).idle()
fixture.options.sessionReplay.isCaptureSurfaceViews = true
val strategy = fixture.getSut(executor = fixture.inlineExecutor())
strategy.capture(activity.get().findViewById(android.R.id.content))
shadowOf(Looper.getMainLooper()).idle()
assertTrue(strategy.lastCaptureSuccessful())
val screenshot = argumentCaptor<Bitmap>()
verify(fixture.callback).onScreenshotRecorded(screenshot.capture())
assertEquals(Bitmap.Config.ARGB_8888, screenshot.firstValue.config)
}
@Test
fun `compositeSurfaceViewInto draws source behind existing destination with DST_OVER`() {
// Destination ("Window capture"): 100x100, opaque red in the top half,
// fully transparent in the bottom half (the "hole" where the SurfaceView sits).
val dest = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888)
val destCanvas = Canvas(dest)
destCanvas.drawColor(Color.RED)
val clearPaint = Paint().apply { xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR) }
destCanvas.drawRect(0f, 50f, 100f, 100f, clearPaint)
// Source ("SurfaceView capture"): 100x50, solid blue — matches the hole.
val source = Bitmap.createBitmap(100, 50, Bitmap.Config.ARGB_8888)
source.eraseColor(Color.BLUE)
val dstOverPaint = Paint().apply { xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OVER) }
compositeSurfaceViewInto(
destCanvas = destCanvas,
destPaint = dstOverPaint,
tmpSrc = Rect(),
tmpDst = RectF(),
sourceBitmap = source,
sourceX = 0,
sourceY = 50,
windowX = 0,
windowY = 0,
scaleFactorX = 1f,
scaleFactorY = 1f,
)
// Top region: still red (DST_OVER must not overwrite existing opaque pixels).
assertEquals(Color.RED, dest.getPixel(50, 10))
assertEquals(Color.RED, dest.getPixel(50, 49))
// Bottom region: now blue (source filled the transparent hole).
assertEquals(Color.BLUE, dest.getPixel(50, 50))
assertEquals(Color.BLUE, dest.getPixel(99, 99))
}
@Test
fun `compositeSurfaceViewInto respects scale factors and window offset`() {
// Destination is 50x50 (scaled recording), fully transparent.
val dest = Bitmap.createBitmap(50, 50, Bitmap.Config.ARGB_8888)
val destCanvas = Canvas(dest)
// Source is 40x40, solid green; its on-screen location is (20, 20).
val source = Bitmap.createBitmap(40, 40, Bitmap.Config.ARGB_8888)
source.eraseColor(Color.GREEN)
val dstOverPaint = Paint().apply { xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OVER) }
compositeSurfaceViewInto(
destCanvas = destCanvas,
destPaint = dstOverPaint,
tmpSrc = Rect(),
tmpDst = RectF(),
sourceBitmap = source,
sourceX = 20,
sourceY = 20,
windowX = 10, // window is at (10, 10)
windowY = 10,
scaleFactorX = 0.5f, // 0.5x scale → destination coords halve
scaleFactorY = 0.5f,
)
// Expected destination rect: ((20-10)*0.5, (20-10)*0.5) = (5, 5), size 40*0.5 = 20x20
// → occupies pixels [5..25) × [5..25). Check inside, on the edge, and just outside.
assertEquals(Color.GREEN, dest.getPixel(5, 5))
assertEquals(Color.GREEN, dest.getPixel(15, 15))
assertEquals(Color.GREEN, dest.getPixel(24, 24))
// Just outside the rect — still transparent.
assertEquals(0, dest.getPixel(4, 4))
assertEquals(0, dest.getPixel(25, 25))
}
private fun captureUnstableFrame(strategy: PixelCopyStrategy, root: View) {
strategy.capture(root)
strategy.onContentChanged()
DeferredWindowPixelCopyShadow.flush()
shadowOf(Looper.getMainLooper()).idle()
}
private fun captureStableFrame(strategy: PixelCopyStrategy, root: View) {
strategy.capture(root)
DeferredWindowPixelCopyShadow.flush()
shadowOf(Looper.getMainLooper()).idle()
}
}
@Implements(PixelCopy::class)
class DeferredWindowPixelCopyShadow {
companion object {
private val pendingCallbacks = mutableListOf<() -> Unit>()
fun reset() {
pendingCallbacks.clear()
}
fun flush() {
val callbacks = pendingCallbacks.toList()
pendingCallbacks.clear()
callbacks.forEach { it.invoke() }
}
@JvmStatic
@Implementation
@Suppress("UNUSED_PARAMETER")
fun request(
_source: Window,
_dest: Bitmap,
listener: PixelCopy.OnPixelCopyFinishedListener,
listenerThread: Handler,
) {
pendingCallbacks.add {
listenerThread.post { listener.onPixelCopyFinished(PixelCopy.SUCCESS) }
}
}
}
}
private class SimpleActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val linearLayout =
LinearLayout(this).apply {
setBackgroundColor(android.R.color.white)
orientation = LinearLayout.VERTICAL
layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
}
val textView =
TextView(this).apply {
text = "Hello, World!"
layoutParams = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
}
linearLayout.addView(textView)
setContentView(linearLayout)
}
}
private class ActivityWithSurfaceView : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val root =
FrameLayout(this).apply {
setBackgroundColor(android.R.color.white)
layoutParams =
FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT,
)
}
root.addView(
TextView(this).apply {
text = "Overlay"
layoutParams = FrameLayout.LayoutParams(200, 50)
}
)
root.addView(SurfaceView(this).apply { layoutParams = FrameLayout.LayoutParams(200, 200) })
setContentView(root)
}
}