1 package com.android.launcher3.util;
2 
3 import android.os.SystemClock;
4 import android.util.Log;
5 
6 import com.android.launcher3.tapl.LauncherInstrumentation;
7 
8 import org.junit.Assert;
9 
10 import java.util.function.Supplier;
11 
12 /**
13  * A utility class for waiting for a condition to be true.
14  */
15 public class Wait {
16 
17     private static final long DEFAULT_SLEEP_MS = 200;
18 
atMost(String message, Condition condition, long timeout, LauncherInstrumentation launcher)19     public static void atMost(String message, Condition condition, long timeout,
20             LauncherInstrumentation launcher) {
21         atMost(() -> message, condition, timeout, DEFAULT_SLEEP_MS, launcher);
22     }
23 
atMost(Supplier<String> message, Condition condition, long timeout, LauncherInstrumentation launcher)24     public static void atMost(Supplier<String> message, Condition condition, long timeout,
25             LauncherInstrumentation launcher) {
26         atMost(message, condition, timeout, DEFAULT_SLEEP_MS, launcher);
27     }
28 
atMost(Supplier<String> message, Condition condition, long timeout, long sleepMillis, LauncherInstrumentation launcher)29     public static void atMost(Supplier<String> message, Condition condition, long timeout,
30             long sleepMillis,
31             LauncherInstrumentation launcher) {
32         final long startTime = SystemClock.uptimeMillis();
33         long endTime = startTime + timeout;
34         Log.d("Wait", "atMost: " + startTime + " - " + endTime);
35         while (SystemClock.uptimeMillis() < endTime) {
36             try {
37                 if (condition.isTrue()) {
38                     return;
39                 }
40             } catch (Throwable t) {
41                 throw new RuntimeException(t);
42             }
43             SystemClock.sleep(sleepMillis);
44         }
45 
46         // Check once more before returning false.
47         try {
48             if (condition.isTrue()) {
49                 return;
50             }
51         } catch (Throwable t) {
52             throw new RuntimeException(t);
53         }
54         Log.d("Wait", "atMost: timed out: " + SystemClock.uptimeMillis());
55         launcher.checkForAnomaly();
56         Assert.fail(message.get());
57     }
58 
59     /**
60      * Interface representing a generic condition
61      */
62     public interface Condition {
63 
isTrue()64         boolean isTrue() throws Throwable;
65     }
66 }
67