1 /*
2  * 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 android.tools.rules
18 
19 import android.tools.ScenarioBuilder
20 import android.tools.traces.io.ResultWriter
21 import android.tools.traces.monitors.PerfettoTraceMonitor
22 import android.tools.traces.monitors.TraceMonitor
23 import android.tools.traces.monitors.view.ViewTraceMonitor
24 import android.tools.traces.monitors.wm.LegacyShellTransitionTraceMonitor
25 import android.tools.traces.monitors.wm.LegacyWmTransitionTraceMonitor
26 import android.tools.traces.monitors.wm.WindowManagerTraceMonitor
27 import kotlin.io.path.createTempDirectory
28 import kotlin.io.path.name
29 import org.junit.rules.TestRule
30 import org.junit.runner.Description
31 import org.junit.runners.model.Statement
32 
33 class StopAllTracesRule : TestRule {
applynull34     override fun apply(base: Statement?, description: Description?): Statement {
35         return object : Statement() {
36             override fun evaluate() {
37                 PerfettoTraceMonitor.stopAllSessions()
38                 LegacyShellTransitionTraceMonitor().stopIfEnabled()
39                 LegacyWmTransitionTraceMonitor().stopIfEnabled()
40                 WindowManagerTraceMonitor().stopIfEnabled()
41                 ViewTraceMonitor().stopIfEnabled()
42 
43                 base?.evaluate()
44             }
45         }
46     }
47 
48     companion object {
TraceMonitornull49         private fun TraceMonitor.stopIfEnabled() {
50             if (!isEnabled) {
51                 return
52             }
53             val resultWriter =
54                 ResultWriter()
55                     .forScenario(
56                         ScenarioBuilder().forClass(kotlin.io.path.createTempFile().name).build()
57                     )
58                     .withOutputDir(createTempDirectory().toFile())
59                     .setRunComplete()
60             stop(resultWriter)
61         }
62     }
63 }
64