1 /*
<lambda>null2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package platform.test.screenshot
18
19 import android.app.Activity
20 import android.app.Dialog
21 import android.graphics.Bitmap
22 import androidx.test.ext.junit.rules.ActivityScenarioRule
23 import java.util.concurrent.TimeUnit
24 import platform.test.screenshot.matchers.BitmapMatcher
25
26 fun <A : Activity> dialogScreenshotTest(
27 activityRule: ActivityScenarioRule<A>,
28 bitmapDiffer: BitmapDiffer,
29 matcher: BitmapMatcher,
30 goldenIdentifier: String,
31 waitForIdle: () -> Unit = {},
32 dialogProvider: (A) -> Dialog,
33 frameLimit: Int = 10,
_null34 checkDialog: (Dialog) -> Boolean = { _ -> false },
35 ) {
36 var dialog: Dialog? = null
activitynull37 activityRule.scenario.onActivity { activity ->
38 dialog =
39 dialogProvider(activity).apply {
40 val window = checkNotNull(window)
41
42 // Make sure that the dialog draws full screen and fits the whole display
43 // instead of the system bars.
44 window.setDecorFitsSystemWindows(false)
45
46 // Disable enter/exit animations.
47 create()
48 window.setWindowAnimations(0)
49
50 // Elevation/shadows is not deterministic when doing hardware rendering, so we
51 // disable it for any view in the hierarchy.
52 window.decorView.removeElevationRecursively()
53
54 // Show the dialog.
55 show()
56 }
57 }
58
59 checkNotNull(dialog)
60
61 // We call onActivity again because it will make sure that our Activity is done measuring,
62 // laying out and drawing its content.
63 var waitForActivity = true
64 var iterCount = 0
65 while (waitForActivity && iterCount < frameLimit) {
<lambda>null66 activityRule.scenario.onActivity { waitForActivity = checkDialog(dialog!!) }
67 iterCount++
68 }
69
70 waitForIdle()
71
72 try {
73 val bitmap = dialog?.toBitmap() ?: error("dialog is null")
74 bitmapDiffer.assertBitmapAgainstGolden(bitmap, goldenIdentifier, matcher)
75 } finally {
76 dialog?.dismiss()
77 }
78 }
79
toBitmapnull80 private fun Dialog.toBitmap(): Bitmap {
81 val window = checkNotNull(window)
82 return window.decorView.captureToBitmapAsync().get(10, TimeUnit.SECONDS)
83 ?: error("timeout while trying to capture view to bitmap for window")
84 }
85