diff --git a/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AutomationCommandHandler.java b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AutomationCommandHandler.java index 4b1868f965..7e1f63eb75 100644 --- a/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AutomationCommandHandler.java +++ b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AutomationCommandHandler.java @@ -57,59 +57,165 @@ private static final class InputDispatch { boolean attempted; } + /** + * The budget of a host that sends none: a provider-supplied helper can be newer than its host, and + * an older host waits 30 s for input, less the 5 s answer margin. It never affords a retry. + */ + private static final long OLDER_HOST_BUDGET_MS = 25_000; + + /** The framework's accessibility interaction timeout, AccessibilityInteractionClient. */ + private static final long TEXT_ENTRY_RESERVE_MS = 5_000; + + /** The command deadline left too little time for the next step, so it was not started. */ + static final class InputBudgetExhausted extends IllegalStateException { + InputBudgetExhausted(String message) { + super(message); + } + } + + /** Refuses text entry the deadline cannot fit, after a focus tap that may have used the budget. */ + static void requireTextEntryTime(long deadline, long now) { + if (deadline - now < TEXT_ENTRY_RESERVE_MS) { + throw new InputBudgetExhausted("Fill text was not entered: too little time left after focus"); + } + } + private static void input(UiAutomation automation, JSONObject input, InputDispatch dispatch) throws Exception { + // The host's remaining time for this command bounds every retry decision. + long deadline = + SystemClock.uptimeMillis() + input.optLong("budgetMs", OLDER_HOST_BUDGET_MS); switch (input.getString("kind")) { case "tap": - tap(automation, input.getDouble("x"), input.getDouble("y"), dispatch); + tap(automation, input.getDouble("x"), input.getDouble("y"), dispatch, deadline); return; case "key": - key(automation, input.getInt("keyCode"), dispatch); + key(automation, input.getInt("keyCode"), dispatch, deadline); return; case "fill": - fill(automation, input.getInt("x"), input.getInt("y"), input.getString("text"), dispatch); + fill(automation, input.getInt("x"), input.getInt("y"), input.getString("text"), dispatch, + deadline); return; default: throw new IllegalArgumentException("Unknown input kind"); } } - private static void tap(UiAutomation automation, double x, double y, InputDispatch dispatch) { + private static void tap( + UiAutomation automation, double x, double y, InputDispatch dispatch, long deadline) { if (Double.isNaN(x) || Double.isInfinite(x) || Double.isNaN(y) || Double.isInfinite(y) || x < 0 || y < 0) { throw new IllegalArgumentException("Invalid tap coordinates"); } - long down = SystemClock.uptimeMillis(); - touch(automation, down, MotionEvent.ACTION_DOWN, (float) x, (float) y, dispatch); - touch(automation, down, MotionEvent.ACTION_UP, (float) x, (float) y, dispatch); + dispatch.attempted = true; + PressSequence.requireDispatched(PressSequence.run(new TouchPress(automation, (float) x, (float) y), deadline), "Touch"); } - private static void touch(UiAutomation automation, long down, int action, float x, float y, InputDispatch dispatch) { - MotionEvent event = MotionEvent.obtain(down, SystemClock.uptimeMillis(), action, x, y, 0); - event.setSource(InputDevice.SOURCE_TOUCHSCREEN); - try { - dispatch.attempted = true; - if (!automation.injectInputEvent(event, true)) { - throw new IllegalStateException("Touch injection was refused"); - } - } finally { - event.recycle(); + private static void key(UiAutomation automation, int code, InputDispatch dispatch, long deadline) { + if (code < 0 || code > KeyEvent.getMaxKeyCode()) throw new IllegalArgumentException("Invalid key code"); + dispatch.attempted = true; + PressSequence.requireDispatched(PressSequence.run(new KeyPress(automation, code), deadline), "Key"); + } + + private abstract static class Press implements PressSequence.Injections { + final UiAutomation automation; + + Press(UiAutomation automation) { + this.automation = automation; + } + + @Override + public long now() { + return SystemClock.uptimeMillis(); + } + + @Override + public boolean skipsAnimationWait() { + return UiAutomationInputDispatcher.skipsAnimationWait(); + } + + @Override + public boolean awaitAnimations() { + return UiAutomationInputDispatcher.awaitAnimations(automation); } } - private static void key(UiAutomation automation, int code, InputDispatch dispatch) { - if (code < 0 || code > KeyEvent.getMaxKeyCode()) throw new IllegalArgumentException("Invalid key code"); - long down = SystemClock.uptimeMillis(); - for (int action : new int[] {KeyEvent.ACTION_DOWN, KeyEvent.ACTION_UP}) { - KeyEvent event = new KeyEvent(down, SystemClock.uptimeMillis(), action, code, 0, 0, - KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, InputDevice.SOURCE_KEYBOARD); - dispatch.attempted = true; - if (!automation.injectInputEvent(event, true)) { - throw new IllegalStateException("Key injection was refused"); + private static final class TouchPress extends Press { + private final float x; + private final float y; + + TouchPress(UiAutomation automation, float x, float y) { + super(automation); + this.x = x; + this.y = y; + } + + @Override + public boolean start(long downTime) { + return inject(MotionEvent.ACTION_DOWN, downTime, 0, true); + } + + @Override + public boolean end(long downTime) { + return inject(MotionEvent.ACTION_UP, downTime, 0, true); + } + + /** Not awaited: a window that received a timed-out DOWN may not finish handling the cancel. */ + @Override + public void releaseRefusedStart(long downTime) { + inject(MotionEvent.ACTION_CANCEL, downTime, MotionEvent.FLAG_CANCELED, false); + } + + private boolean inject(int action, long downTime, int flags, boolean waitForDispatch) { + MotionEvent event = TouchEvents.obtain( + downTime, SystemClock.uptimeMillis(), action, new float[] {x}, new float[] {y}, flags); + try { + return UiAutomationInputDispatcher.inject(automation, event, waitForDispatch); + } finally { + event.recycle(); } } } - private static void fill(UiAutomation automation, int x, int y, String text, InputDispatch dispatch) { + private static final class KeyPress extends Press { + private final int code; + + KeyPress(UiAutomation automation, int code) { + super(automation); + this.code = code; + } + + @Override + public boolean start(long downTime) { + return inject(KeyEvent.ACTION_DOWN, downTime, 0, true); + } + + @Override + public boolean end(long downTime) { + return inject(KeyEvent.ACTION_UP, downTime, 0, true); + } + + /** + * Android releases an interrupted key with an ACTION_UP that carries FLAG_CANCELED; receivers + * take no action on a canceled up. Not awaited, like the touch cancel. + */ + @Override + public void releaseRefusedStart(long downTime) { + inject(KeyEvent.ACTION_UP, downTime, KeyEvent.FLAG_CANCELED, false); + } + + private boolean inject(int action, long downTime, int flags, boolean waitForDispatch) { + return UiAutomationInputDispatcher.inject( + automation, event(action, downTime, flags), waitForDispatch); + } + + private KeyEvent event(int action, long downTime, int flags) { + return new KeyEvent(downTime, SystemClock.uptimeMillis(), action, code, 0, 0, + KeyCharacterMap.VIRTUAL_KEYBOARD, 0, flags, InputDevice.SOURCE_KEYBOARD); + } + } + + private static void fill( + UiAutomation automation, int x, int y, String text, InputDispatch dispatch, long deadline) { AccessibilityNodeInfo target = null; try { for (AccessibilityWindowInfo window : automation.getWindows()) { @@ -134,7 +240,8 @@ private static void fill(UiAutomation automation, int x, int y, String text, Inp } } if (target == null) throw new IllegalStateException("No editable field at the fill point"); - tap(automation, x, y, dispatch); + tap(automation, x, y, dispatch, deadline); + requireTextEntryTime(deadline, SystemClock.uptimeMillis()); if (!target.refresh()) throw new IllegalStateException("Fill target disappeared after focus"); if (!target.isFocused() && !target.performAction(AccessibilityNodeInfo.ACTION_FOCUS)) { throw new IllegalStateException("Field focus was refused"); diff --git a/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/PressSequence.java b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/PressSequence.java new file mode 100644 index 0000000000..0c7fbf23dd --- /dev/null +++ b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/PressSequence.java @@ -0,0 +1,94 @@ +package com.callstack.agentdevice.snapshothelper; + +/** + * Sequences one tap or key press: a start event, then an end event with the same down time. + * + *
Every refused start is released before anything else is decided: the verifier and the policy + * record a start even when the dispatcher drops it, and a start refused by the injection timeout + * was delivered. Without the framework's animation wait, a start is often refused only because a + * transition leaves nothing able to receive it, so it is retried once after the animation sync, + * with a fresh down time, when the host's deadline still has room for that retry. + */ +final class PressSequence { + /** + * The room a retry decision reserves: the framework's animation-sync cap + * ({@code WindowManagerService.ANIMATION_COMPLETED_TIMEOUT_MS}) plus the retried start's injection + * deadline ({@code InputManagerService.INJECTION_TIMEOUT_MILLIS}). The end is not reserved: it + * blocks only while the app does not finish handling it, which a press without a retry meets the + * same way, and a 60 s press request could never reserve a second 30 s deadline. + */ + static final long RETRY_WORST_CASE_MS = 5_000 + 30_000; + + /** Builds and injects the platform events of one press. */ + interface Injections { + long now(); + + /** Whether {@link #start} skips the framework's animation wait on this runtime. */ + boolean skipsAnimationWait(); + + boolean start(long downTime); + + boolean end(long downTime); + + /** Releases a refused start that has this down time; the receiver may hold it. */ + void releaseRefusedStart(long downTime); + + /** Waits for the framework's animation sync; false when the runtime cannot wait separately. */ + boolean awaitAnimations(); + } + + enum Outcome { + DISPATCHED, + START_REFUSED, + END_REFUSED, + ANIMATION_SYNC_UNAVAILABLE, + } + + private PressSequence() {} + + /** Runs one press that must answer by {@code deadline}, on the {@link Injections#now} clock. */ + static Outcome run(Injections injections, long deadline) { + long downTime = injections.now(); + if (!injections.start(downTime)) { + release(injections, downTime); + if (!injections.skipsAnimationWait() + || deadline - injections.now() < RETRY_WORST_CASE_MS) { + return Outcome.START_REFUSED; + } + if (!injections.awaitAnimations()) return Outcome.ANIMATION_SYNC_UNAVAILABLE; + downTime = injections.now(); + if (!injections.start(downTime)) { + release(injections, downTime); + return Outcome.START_REFUSED; + } + } + // A refused end gets no cancel. The verifier records an event before the dispatcher drops it, + // so the press is closed there and a cancel would be inconsistent. The dispatcher drops an end + // only when no pointer or focus is still down, after it cancelled the receiving window itself + // ("touched window was removed", "focus left window"). A timed-out end was already enqueued, + // so the live window still receives it. + return injections.end(downTime) ? Outcome.DISPATCHED : Outcome.END_REFUSED; + } + + /** Turns an outcome into the helper's response: a typed exception for each failed press. */ + static void requireDispatched(Outcome outcome, String kind) { + switch (outcome) { + case DISPATCHED: + return; + case ANIMATION_SYNC_UNAVAILABLE: + throw new UnsupportedOperationException( + kind + " injection was refused and this runtime cannot wait for animations to retry it"); + case START_REFUSED: + case END_REFUSED: + throw new IllegalStateException(kind + " injection was refused"); + } + } + + private static void release(Injections injections, long downTime) { + try { + injections.releaseRefusedStart(downTime); + } catch (RuntimeException ignored) { + // The refused start stays the reported outcome. + } + } +} diff --git a/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/TouchEvents.java b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/TouchEvents.java new file mode 100644 index 0000000000..d1630cbe3d --- /dev/null +++ b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/TouchEvents.java @@ -0,0 +1,31 @@ +package com.callstack.agentdevice.snapshothelper; + +import android.view.InputDevice; +import android.view.MotionEvent; + +/** Builds the touchscreen finger events that taps and touch plans inject. */ +final class TouchEvents { + private TouchEvents() {} + + /** One pointer per coordinate pair; pointer ids follow the array order. */ + static MotionEvent obtain( + long downTime, long eventTime, int action, float[] x, float[] y, int flags) { + int count = x.length; + MotionEvent.PointerProperties[] properties = new MotionEvent.PointerProperties[count]; + MotionEvent.PointerCoords[] coords = new MotionEvent.PointerCoords[count]; + for (int index = 0; index < count; index += 1) { + properties[index] = new MotionEvent.PointerProperties(); + properties[index].id = index; + properties[index].toolType = MotionEvent.TOOL_TYPE_FINGER; + coords[index] = new MotionEvent.PointerCoords(); + coords[index].x = x[index]; + coords[index].y = y[index]; + coords[index].pressure = 1.0f; + coords[index].size = 1.0f; + } + MotionEvent event = MotionEvent.obtain(downTime, eventTime, action, count, properties, coords, + 0, 0, 1.0f, 1.0f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, flags); + event.setSource(InputDevice.SOURCE_TOUCHSCREEN); + return event; + } +} diff --git a/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/TouchPlanInjector.java b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/TouchPlanInjector.java index 315205cb7a..76413e0f49 100644 --- a/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/TouchPlanInjector.java +++ b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/TouchPlanInjector.java @@ -2,7 +2,6 @@ import android.app.UiAutomation; import android.os.SystemClock; -import android.view.InputDevice; import android.view.MotionEvent; /** Injects a validated touch plan through UiAutomation with real-time sample pacing. */ @@ -104,37 +103,7 @@ private static void injectCancel( private static MotionEvent motionEvent( long downTime, long eventTime, int action, PointerState pointers) { - MotionEvent.PointerProperties[] properties = - new MotionEvent.PointerProperties[pointers.count]; - MotionEvent.PointerCoords[] coords = new MotionEvent.PointerCoords[pointers.count]; - for (int index = 0; index < pointers.count; index += 1) { - properties[index] = new MotionEvent.PointerProperties(); - properties[index].id = index; - properties[index].toolType = MotionEvent.TOOL_TYPE_FINGER; - coords[index] = new MotionEvent.PointerCoords(); - coords[index].x = pointers.x[index]; - coords[index].y = pointers.y[index]; - coords[index].pressure = 1.0f; - coords[index].size = 1.0f; - } - MotionEvent event = - MotionEvent.obtain( - downTime, - eventTime, - action, - pointers.count, - properties, - coords, - 0, - 0, - 1.0f, - 1.0f, - 0, - 0, - InputDevice.SOURCE_TOUCHSCREEN, - 0); - event.setSource(InputDevice.SOURCE_TOUCHSCREEN); - return event; + return TouchEvents.obtain(downTime, eventTime, action, pointers.x, pointers.y, 0); } private static final class PointerState { diff --git a/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/UiAutomationInputDispatcher.java b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/UiAutomationInputDispatcher.java index 791edf083d..104413cfe2 100644 --- a/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/UiAutomationInputDispatcher.java +++ b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/UiAutomationInputDispatcher.java @@ -6,14 +6,16 @@ import java.lang.reflect.Method; /** - * Dispatches planned input without the framework's global animation synchronization. + * Dispatches input without the framework's global animation synchronization. * - *
The public two-argument overload waits for global animations before every event. Android's - * three-argument test API separates that policy from synchronous input dispatch, but the SDK stub - * hides the method, so the helper resolves it from the runtime framework. + *
The public two-argument overload waits for global animations before a gesture's first event
+ * and after its last one, up to five seconds each. Android's three-argument test API separates that
+ * policy from synchronous input dispatch, but the SDK stub hides the method, so the helper resolves
+ * it from the runtime framework.
*/
final class UiAutomationInputDispatcher {
private static volatile Method injectWithoutAnimationWait = findInjectWithoutAnimationWait();
+ private static volatile Method syncInputTransactions = findSyncInputTransactions();
private UiAutomationInputDispatcher() {}
@@ -32,6 +34,30 @@ static boolean inject(UiAutomation automation, InputEvent event, boolean waitFor
}
}
+ /** Whether injection skips the framework's animation wait on this runtime. */
+ static boolean skipsAnimationWait() {
+ return injectWithoutAnimationWait != null;
+ }
+
+ /**
+ * Waits for the framework's animation sync. Returns false when the runtime does not expose or
+ * permit the separate sync.
+ */
+ static boolean awaitAnimations(UiAutomation automation) {
+ Method method = syncInputTransactions;
+ if (method == null) return false;
+ try {
+ method.invoke(automation);
+ return true;
+ } catch (IllegalAccessException | IllegalArgumentException error) {
+ syncInputTransactions = null;
+ return false;
+ } catch (InvocationTargetException error) {
+ rethrowCause(error.getCause());
+ throw new AssertionError("Unreachable");
+ }
+ }
+
private static Method findInjectWithoutAnimationWait() {
try {
return UiAutomation.class.getMethod(
@@ -41,6 +67,14 @@ private static Method findInjectWithoutAnimationWait() {
}
}
+ private static Method findSyncInputTransactions() {
+ try {
+ return UiAutomation.class.getMethod("syncInputTransactions");
+ } catch (NoSuchMethodException | SecurityException error) {
+ return null;
+ }
+ }
+
private static void rethrowCause(Throwable cause) {
if (cause instanceof RuntimeException) throw (RuntimeException) cause;
if (cause instanceof Error) throw (Error) cause;
diff --git a/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/FillTextEntryTimeTest.java b/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/FillTextEntryTimeTest.java
new file mode 100644
index 0000000000..1aa9467942
--- /dev/null
+++ b/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/FillTextEntryTimeTest.java
@@ -0,0 +1,27 @@
+package com.callstack.agentdevice.snapshothelper;
+
+public final class FillTextEntryTimeTest {
+ private FillTextEntryTimeTest() {}
+
+ static void run() {
+ entersTextWhenTheAccessibilityTimeoutStillFits();
+ refusesTextEntryWithATypedBudgetRefusalWhenItNoLongerFits();
+ }
+
+ private static void entersTextWhenTheAccessibilityTimeoutStillFits() {
+ AutomationCommandHandler.requireTextEntryTime(15_000, 10_000);
+ }
+
+ private static void refusesTextEntryWithATypedBudgetRefusalWhenItNoLongerFits() {
+ try {
+ AutomationCommandHandler.requireTextEntryTime(14_999, 10_000);
+ } catch (AutomationCommandHandler.InputBudgetExhausted refusal) {
+ String expected = "Fill text was not entered: too little time left after focus";
+ if (!expected.equals(refusal.getMessage())) {
+ throw new AssertionError("Expected " + expected + ", got " + refusal.getMessage());
+ }
+ return;
+ }
+ throw new AssertionError("Expected the text entry to be refused");
+ }
+}
diff --git a/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/PressSequenceTest.java b/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/PressSequenceTest.java
new file mode 100644
index 0000000000..56de9feeba
--- /dev/null
+++ b/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/PressSequenceTest.java
@@ -0,0 +1,190 @@
+package com.callstack.agentdevice.snapshothelper;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+public final class PressSequenceTest {
+ private static final long ROOM = PressSequence.RETRY_WORST_CASE_MS;
+ /** A deadline far enough away that it never limits the press. */
+ private static final long OPEN = Long.MAX_VALUE / 2;
+
+ private PressSequenceTest() {}
+
+ static void run() {
+ endsWithTheStartDownTime();
+ releasesARefusedStartAndRetriesItAfterTheSyncWithAFreshDownTime();
+ retriesWhenTheDeadlineLeavesExactlyRoomForTheRetry();
+ releasesWithoutRetryingWhenTheDeadlineLeavesNoRoomForTheRetry();
+ releasesWithoutRetryingAStartRefusedLateInTheBudget();
+ releasesAStartRefusedAgainAfterTheSync();
+ doesNotCancelARefusedEnd();
+ releasesAndFailsADroppedStartAtOnceWhenInjectionWaitsForAnimations();
+ reportsAnUnavailableAnimationSyncApartFromARefusal();
+ retriesWhenTheReleaseThrows();
+ failsARefusedPressAsARefusal();
+ failsAnUnavailableSyncAsUnsupported();
+ }
+
+ private static void endsWithTheStartDownTime() {
+ FakeInjections injections = new FakeInjections(accepted());
+ expect(PressSequence.run(injections, OPEN), PressSequence.Outcome.DISPATCHED);
+ expect(injections.calls, "start 1", "end 1");
+ }
+
+ private static void releasesARefusedStartAndRetriesItAfterTheSyncWithAFreshDownTime() {
+ FakeInjections injections = new FakeInjections(refusedAfter(0), accepted());
+ expect(PressSequence.run(injections, OPEN), PressSequence.Outcome.DISPATCHED);
+ expect(injections.calls, "start 1", "release 1", "sync", "start 3", "end 3");
+ }
+
+ private static void retriesWhenTheDeadlineLeavesExactlyRoomForTheRetry() {
+ FakeInjections injections = new FakeInjections(refusedAfter(0), accepted());
+ expect(PressSequence.run(injections, 2 + ROOM), PressSequence.Outcome.DISPATCHED);
+ expect(injections.calls, "start 1", "release 1", "sync", "start 3", "end 3");
+ }
+
+ private static void releasesWithoutRetryingWhenTheDeadlineLeavesNoRoomForTheRetry() {
+ FakeInjections injections = new FakeInjections(refusedAfter(0), accepted());
+ expect(PressSequence.run(injections, 1 + ROOM), PressSequence.Outcome.START_REFUSED);
+ expect(injections.calls, "start 1", "release 1");
+ }
+
+ private static void releasesWithoutRetryingAStartRefusedLateInTheBudget() {
+ FakeInjections injections = new FakeInjections(refusedAfter(30_000), accepted());
+ expect(PressSequence.run(injections, 40_000), PressSequence.Outcome.START_REFUSED);
+ expect(injections.calls, "start 1", "release 1");
+ }
+
+ private static void releasesAStartRefusedAgainAfterTheSync() {
+ FakeInjections injections = new FakeInjections(refusedAfter(0), refusedAfter(0));
+ expect(PressSequence.run(injections, OPEN), PressSequence.Outcome.START_REFUSED);
+ expect(injections.calls, "start 1", "release 1", "sync", "start 3", "release 3");
+ }
+
+ private static void doesNotCancelARefusedEnd() {
+ FakeInjections injections = new FakeInjections(accepted());
+ injections.endAccepted = false;
+ expect(PressSequence.run(injections, OPEN), PressSequence.Outcome.END_REFUSED);
+ expect(injections.calls, "start 1", "end 1");
+ }
+
+ private static void releasesAndFailsADroppedStartAtOnceWhenInjectionWaitsForAnimations() {
+ FakeInjections injections = new FakeInjections(refusedAfter(0), accepted());
+ injections.skipsAnimationWait = false;
+ expect(PressSequence.run(injections, OPEN), PressSequence.Outcome.START_REFUSED);
+ expect(injections.calls, "start 1", "release 1");
+ }
+
+ private static void reportsAnUnavailableAnimationSyncApartFromARefusal() {
+ FakeInjections injections = new FakeInjections(refusedAfter(0), accepted());
+ injections.syncAvailable = false;
+ expect(PressSequence.run(injections, OPEN), PressSequence.Outcome.ANIMATION_SYNC_UNAVAILABLE);
+ expect(injections.calls, "start 1", "release 1", "sync");
+ }
+
+ private static void retriesWhenTheReleaseThrows() {
+ FakeInjections injections = new FakeInjections(refusedAfter(0), accepted());
+ injections.releaseThrows = true;
+ expect(PressSequence.run(injections, OPEN), PressSequence.Outcome.DISPATCHED);
+ expect(injections.calls, "start 1", "release 1", "sync", "start 3", "end 3");
+ }
+
+ private static void failsARefusedPressAsARefusal() {
+ FakeInjections injections = new FakeInjections(refusedAfter(0), refusedAfter(0));
+ expectFailure(injections, IllegalStateException.class, "Key injection was refused");
+ }
+
+ private static void failsAnUnavailableSyncAsUnsupported() {
+ FakeInjections injections = new FakeInjections(refusedAfter(0), accepted());
+ injections.syncAvailable = false;
+ expectFailure(injections, UnsupportedOperationException.class,
+ "Key injection was refused and this runtime cannot wait for animations to retry it");
+ }
+
+ private static void expectFailure(
+ FakeInjections injections, Class extends RuntimeException> type, String message) {
+ try {
+ PressSequence.requireDispatched(PressSequence.run(injections, OPEN), "Key");
+ } catch (RuntimeException error) {
+ if (error.getClass() != type || !message.equals(error.getMessage())) {
+ throw new AssertionError("Expected " + type.getName() + ": " + message + ", got " + error);
+ }
+ return;
+ }
+ throw new AssertionError("Expected " + type.getName() + ", but the press dispatched");
+ }
+
+ /** A start the framework accepts at once. */
+ private static long accepted() {
+ return -1;
+ }
+
+ /** A start the framework refuses after this many milliseconds. */
+ private static long refusedAfter(long elapsedMs) {
+ return elapsedMs;
+ }
+
+ private static void expect(PressSequence.Outcome actual, PressSequence.Outcome expected) {
+ if (actual != expected) throw new AssertionError("Expected " + expected + ", got " + actual);
+ }
+
+ private static void expect(List