• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 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.uirendering.cts.util;
18 
19 import static org.junit.Assert.assertFalse;
20 import static org.junit.Assert.assertTrue;
21 
22 import android.view.animation.AnimationUtils;
23 
24 import java.util.concurrent.ExecutionException;
25 import java.util.concurrent.ExecutorService;
26 import java.util.concurrent.Executors;
27 import java.util.concurrent.Future;
28 
29 public class MockVsyncHelper {
30 
31     private static ExecutorService sExecutor = Executors.newSingleThreadExecutor();
32     private static Future<Thread> sExecutorThread;
33 
34     static {
35         // We can't wait on the future here because the lambda cannot be executed until
36         // the class has finished loading
37         sExecutorThread = sExecutor.submit(() -> {
38             AnimationUtils.lockAnimationClock(16);
39             return Thread.currentThread();
40         });
41     }
42 
isOnExecutorThread()43     private static boolean isOnExecutorThread() {
44         try {
45             return Thread.currentThread().equals(sExecutorThread.get());
46         } catch (InterruptedException | ExecutionException e) {
47             throw new RuntimeException(e);
48         }
49     }
50 
nextFrame()51     public static void nextFrame() {
52         assertTrue("nextFrame() must be called inside #unOnVsyncThread block",
53                 isOnExecutorThread());
54         AnimationUtils.lockAnimationClock(AnimationUtils.currentAnimationTimeMillis() + 16);
55     }
56 
runOnVsyncThread(CallableVoid callable)57     public static void runOnVsyncThread(CallableVoid callable) {
58         assertFalse("Cannot runOnVsyncThread inside #runOnVsyncThread block",
59                 isOnExecutorThread());
60         try {
61             sExecutor.submit(() -> {
62                 callable.call();
63                 return (Void) null;
64             }).get();
65         } catch (InterruptedException e) {
66             Thread.currentThread().interrupt();
67         } catch (ExecutionException e) {
68             SneakyThrow.sneakyThrow(e.getCause() != null ? e.getCause() : e);
69         }
70     }
71 
72     public interface CallableVoid {
call()73         void call() throws Exception;
74     }
75 }
76