1 /* 2 * Copyright 2021 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 androidx.window.testing.layout 18 19 import android.app.Activity 20 import androidx.window.layout.WindowMetrics 21 import androidx.window.layout.WindowMetricsCalculator 22 import org.junit.rules.TestRule 23 import org.junit.runner.Description 24 import org.junit.runners.model.Statement 25 26 /** 27 * A [TestRule] that will sub out the actual [WindowMetricsCalculator] with a more simple one that 28 * will support testing independent of the current platform. The fake [WindowMetricsCalculator] that 29 * is used will return the width and height from the [android.util.DisplayMetrics] associated to an 30 * [Activity]. The result of [WindowMetricsCalculator.computeCurrentWindowMetrics] and 31 * [WindowMetricsCalculator.computeMaximumWindowMetrics] will be the same. For accurate results use 32 * the Espresso Test framework with an actual [Activity] and use the actual 33 * [WindowMetricsCalculator]. 34 */ 35 class WindowMetricsCalculatorRule : TestRule { 36 37 private val stubWindowMetricsCalculator = StubWindowMetricsCalculator() 38 private val decorator = StubMetricDecorator(stubWindowMetricsCalculator) 39 applynull40 override fun apply(base: Statement, description: Description): Statement { 41 return object : Statement() { 42 override fun evaluate() { 43 WindowMetricsCalculator.overrideDecorator(decorator) 44 try { 45 base.evaluate() 46 } finally { 47 WindowMetricsCalculator.reset() 48 } 49 } 50 } 51 } 52 53 /** Overrides the window bounds with a new [WindowMetrics]. */ overrideCurrentWindowBoundsnull54 fun overrideCurrentWindowBounds(windowMetrics: WindowMetrics) { 55 stubWindowMetricsCalculator.overrideWindowBounds(windowMetrics.bounds) 56 } 57 58 /** Overrides the window bounds with a new rectangle defined by the specified coordinates. */ overrideCurrentWindowBoundsnull59 fun overrideCurrentWindowBounds(left: Int, top: Int, right: Int, bottom: Int) { 60 stubWindowMetricsCalculator.overrideWindowBounds(left, top, right, bottom) 61 } 62 } 63