• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2017 Google Inc.
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  *     https://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 traceviewer.ui
18 
19 import java.awt.event.ActionListener
20 import javax.swing.Timer
21 
animatenull22 fun animate(start: Double, end: Double, setter: (Double) -> Unit) {
23     AnimationPulse.register(Animator(start, end, setter))
24 }
25 
26 class Animator(val start: Double, val end: Double, val setter: (Double) -> Unit, val duration: Int = 150) {
27     val startTime: Long = System.currentTimeMillis()
28 
animatenull29     fun animate(now: Long): Boolean {
30         val frac = maxOf(0f, minOf(1f, (now - startTime).toFloat() / duration.toFloat()))
31         val value: Double = ((end - start) * frac) + start
32         setter(value)
33         return frac >= 1f
34     }
35 }
36 
37 object AnimationPulse {
38     private val animators = mutableListOf<Animator>()
39 
registernull40     fun register(animator: Animator) {
41         animators.add(animator)
42         if (animators.size == 1) {
43             animationTimer.restart()
44         }
45     }
46 
<lambda>null47     private val animationPulse: ActionListener = ActionListener {
48         val now = System.currentTimeMillis()
49         animators.removeIf { it.animate(now) }
50         if (animators.isNotEmpty()) {
51             animationTimer.restart()
52         }
53     }
54 
55     private val animationTimer = Timer(15, animationPulse)
56 }