summaryrefslogtreecommitdiff
path: root/libraries/screenshot/src/main/java/platform/test/screenshot/DeviceEmulationRule.kt
blob: b49f1aae7e8a0eabd16d581ced4b0c58a361320b (plain)
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
/*
 * Copyright 2022 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package platform.test.screenshot

import android.app.UiAutomation
import android.app.UiModeManager
import android.content.Context
import android.os.Build
import android.os.UserHandle
import android.view.Display
import android.view.WindowManagerGlobal
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement

/**
 * Rule to be added to a screenshot test to simulate a device with the given [spec].
 *
 * This rule takes care of setting up the environment by:
 * - emulating a display size and density, taking the device orientation into account.
 * - setting the test app in dark/light mode.
 *
 * Important: This rule should usually be the first rule in your test, so that all the display and
 * app reconfiguration happens *before* your test starts doing any work, like launching an Activity.
 *
 * @see DeviceEmulationSpec
 */
class DeviceEmulationRule(private val spec: DeviceEmulationSpec) : TestRule {

    private val instrumentation = InstrumentationRegistry.getInstrumentation()
    private val uiAutomation = instrumentation.uiAutomation
    private val isRoblectric = Build.FINGERPRINT.contains("robolectric")

    override fun apply(base: Statement, description: Description): Statement {
        // The statement which calls beforeTest() before running the test and afterTest()
        // afterwards.
        return object : Statement() {
            override fun evaluate() {
                try {
                    beforeTest()
                    base.evaluate()
                } finally {
                    afterTest()
                }
            }
        }
    }

    private fun beforeTest() {
        // Emulate the display size and density.
        val display = spec.display
        val density = display.densityDpi
        val (width, height) = getEmulatedDisplaySize()

        if (isRoblectric) {
            // For Robolectric tests use RuntimeEnvironment.setQualifiers until wm is shadowed
            // b/275751037  to address this issue.
            val runtimeEnvironment = Class.forName("org.robolectric.RuntimeEnvironment")
            val setQualifiers =
                runtimeEnvironment.getDeclaredMethod("setQualifiers", String::class.java)
            val qualifier = "w${width}dp-h${height}dp-${density}dpi"
            setQualifiers.invoke(null, qualifier)
        } else {
            // Make sure that we are in natural orientation (rotation 0) before we set the screen size
            uiAutomation.setRotation(UiAutomation.ROTATION_FREEZE_0)

            val wm = WindowManagerGlobal.getWindowManagerService()
            wm.setForcedDisplayDensityForUser(
                Display.DEFAULT_DISPLAY,
                density,
                UserHandle.myUserId()
            )
            wm.setForcedDisplaySize(Display.DEFAULT_DISPLAY, width, height)

            // Force the dark/light theme.
            val uiModeManager =
                InstrumentationRegistry.getInstrumentation()
                    .targetContext
                    .getSystemService(Context.UI_MODE_SERVICE) as UiModeManager
            uiModeManager.setApplicationNightMode(
                if (spec.isDarkTheme) {
                    UiModeManager.MODE_NIGHT_YES
                } else {
                    UiModeManager.MODE_NIGHT_NO
                }
            )
            // Make sure that all devices are in touch mode to avoid screenshot differences
            // in focused elements when in keyboard mode
            instrumentation.setInTouchMode(true)
        }
    }

    /** Get the emulated display size for [spec]. */
    private fun getEmulatedDisplaySize(): Pair<Int, Int> {
        val display = spec.display
        val isPortraitNaturalPosition = display.width < display.height
        return if (spec.isLandscape == isPortraitNaturalPosition) {
            display.height to display.width
        } else {
            display.width to display.height
        }
    }

    private fun afterTest() {
        // Reset the density and display size.
        if (isRoblectric) {
            return
        }

        val wm = WindowManagerGlobal.getWindowManagerService()
        wm.clearForcedDisplayDensityForUser(Display.DEFAULT_DISPLAY, UserHandle.myUserId())
        wm.clearForcedDisplaySize(Display.DEFAULT_DISPLAY)

        // Reset the dark/light theme.
        val uiModeManager =
            InstrumentationRegistry.getInstrumentation()
                .targetContext
                .getSystemService(Context.UI_MODE_SERVICE) as UiModeManager
        uiModeManager.setApplicationNightMode(UiModeManager.MODE_NIGHT_AUTO)

        instrumentation.resetInTouchMode()

        // Unfreeze locked rotation
        uiAutomation.setRotation(UiAutomation.ROTATION_UNFREEZE)
    }
}

/** The specification of a device display to be used in a screenshot test. */
data class DisplaySpec(
    val name: String,
    val width: Int,
    val height: Int,
    val densityDpi: Int,
)

/** The specification of a device emulation. */
data class DeviceEmulationSpec(
    val display: DisplaySpec,
    val isDarkTheme: Boolean = false,
    val isLandscape: Boolean = false,
) {
    companion object {
        /**
         * Return a list of [DeviceEmulationSpec] for each of the [displays].
         *
         * If [isDarkTheme] is null, this will create a spec for both light and dark themes, for
         * each of the orientation.
         *
         * If [isLandscape] is null, this will create a spec for both portrait and landscape, for
         * each of the light/dark themes.
         */
        fun forDisplays(
            vararg displays: DisplaySpec,
            isDarkTheme: Boolean? = null,
            isLandscape: Boolean? = null,
        ): List<DeviceEmulationSpec> {
            return displays.flatMap { display ->
                buildList {
                    fun addDisplay(isLandscape: Boolean) {
                        if (isDarkTheme != true) {
                            add(DeviceEmulationSpec(display, isDarkTheme = false, isLandscape))
                        }

                        if (isDarkTheme != false) {
                            add(DeviceEmulationSpec(display, isDarkTheme = true, isLandscape))
                        }
                    }

                    if (isLandscape != true) {
                        addDisplay(isLandscape = false)
                    }

                    if (isLandscape != false) {
                        addDisplay(isLandscape = true)
                    }
                }
            }
        }
    }

    override fun toString(): String = buildString {
        // This string is appended to PNGs stored in the device, so let's keep it simple.
        append(display.name)
        if (isDarkTheme) append("_dark")
        if (isLandscape) append("_landscape")
    }
}