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.traces.wm
18 
19 import android.tools.Timestamp
20 import android.tools.Trace
21 
22 data class TransitionsTrace(override val entries: Collection<Transition>) : Trace<Transition> {
asCompressednull23     fun asCompressed(): TransitionsTrace {
24         val transitionById = mutableMapOf<Int, Transition>()
25 
26         for (transition in this.entries) {
27             require(transition.id != 0) { "Requires non-null transition id" }
28             val accumulatedTransition = transitionById[transition.id]
29             if (accumulatedTransition == null) {
30                 transitionById[transition.id] = transition
31             } else {
32                 transitionById[transition.id] =
33                     Transition.mergePartialTransitions(accumulatedTransition, transition)
34             }
35         }
36 
37         val sortedCompressedTransitions =
38             transitionById.values.sortedWith(compareBy { it.timestamp })
39 
40         return TransitionsTrace(sortedCompressedTransitions)
41     }
42 
slicenull43     override fun slice(startTimestamp: Timestamp, endTimestamp: Timestamp): TransitionsTrace {
44         require(startTimestamp.hasElapsedTimestamp && endTimestamp.hasElapsedTimestamp)
45         return sliceElapsed(startTimestamp.elapsedNanos, endTimestamp.elapsedNanos)
46     }
47 
sliceElapsednull48     private fun sliceElapsed(from: Long, to: Long): TransitionsTrace {
49         return TransitionsTrace(
50             this.entries
51                 .dropWhile { it.sendTime.elapsedNanos < from }
52                 .dropLastWhile { it.createTime.elapsedNanos > to }
53         )
54     }
55 }
56