Batching MotionEvents and processing them on the UI thread

Change-Id: I2dc972af8360e719db743740074893bac0213ded
diff --git a/quickstep/libs/sysui_shared.jar b/quickstep/libs/sysui_shared.jar
index fa0e0f3..9069698 100644
--- a/quickstep/libs/sysui_shared.jar
+++ b/quickstep/libs/sysui_shared.jar
Binary files differ
diff --git a/quickstep/src/com/android/quickstep/MotionEventQueue.java b/quickstep/src/com/android/quickstep/MotionEventQueue.java
new file mode 100644
index 0000000..e3c3a1b
--- /dev/null
+++ b/quickstep/src/com/android/quickstep/MotionEventQueue.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.quickstep;
+
+import static android.view.MotionEvent.ACTION_CANCEL;
+import static android.view.MotionEvent.ACTION_MOVE;
+
+import android.view.Choreographer;
+import android.view.MotionEvent;
+
+import com.android.systemui.shared.system.ChoreographerCompat;
+
+import java.util.ArrayList;
+import java.util.function.Consumer;
+
+/**
+ * Helper class for batching input events
+ */
+public class MotionEventQueue implements Runnable {
+
+    // We use two arrays and swap the current index when one array is being consumed
+    private final EventArray[] mArrays = new EventArray[] {new EventArray(), new EventArray()};
+    private int mCurrentIndex = 0;
+
+    private final Choreographer mChoreographer;
+    private final Consumer<MotionEvent> mConsumer;
+
+    public MotionEventQueue(Choreographer choreographer, Consumer<MotionEvent> consumer) {
+        mChoreographer = choreographer;
+        mConsumer = consumer;
+    }
+
+    public void queue(MotionEvent event) {
+        synchronized (mArrays) {
+            EventArray array = mArrays[mCurrentIndex];
+            if (array.isEmpty()) {
+                ChoreographerCompat.postInputFrame(mChoreographer, this);
+            }
+
+            int eventAction = event.getAction();
+            if (eventAction == ACTION_MOVE && array.lastEventAction == ACTION_MOVE) {
+                // Replace and recycle the last event
+                array.set(array.size() - 1, event).recycle();
+            } else {
+                array.add(event);
+                array.lastEventAction = eventAction;
+            }
+        }
+    }
+
+    @Override
+    public void run() {
+        EventArray array = swapAndGetCurrentArray();
+        int size = array.size();
+        for (int i = 0; i < size; i++) {
+            MotionEvent event = array.get(i);
+            mConsumer.accept(event);
+            event.recycle();
+        }
+        array.clear();
+        array.lastEventAction = ACTION_CANCEL;
+    }
+
+    private EventArray swapAndGetCurrentArray() {
+        synchronized (mArrays) {
+            EventArray current = mArrays[mCurrentIndex];
+            mCurrentIndex = mCurrentIndex ^ 1;
+            return current;
+        }
+    }
+
+    private static class EventArray extends ArrayList<MotionEvent> {
+
+        public int lastEventAction = ACTION_CANCEL;
+
+        public EventArray() {
+            super(4);
+        }
+    }
+}
diff --git a/quickstep/src/com/android/quickstep/NavBarSwipeInteractionHandler.java b/quickstep/src/com/android/quickstep/NavBarSwipeInteractionHandler.java
index dc7d648..e03a2ff 100644
--- a/quickstep/src/com/android/quickstep/NavBarSwipeInteractionHandler.java
+++ b/quickstep/src/com/android/quickstep/NavBarSwipeInteractionHandler.java
@@ -28,11 +28,7 @@
 import android.os.Build;
 import android.os.Handler;
 import android.os.UserHandle;
-import android.support.annotation.BinderThread;
 import android.support.annotation.UiThread;
-import android.util.DisplayMetrics;
-import android.view.Choreographer;
-import android.view.Choreographer.FrameCallback;
 import android.view.View;
 import android.view.ViewTreeObserver.OnPreDrawListener;
 
@@ -52,10 +48,8 @@
 import com.android.systemui.shared.system.ActivityManagerWrapper;
 import com.android.systemui.shared.system.WindowManagerWrapper;
 
-import java.util.concurrent.atomic.AtomicBoolean;
-
 @TargetApi(Build.VERSION_CODES.O)
-public class NavBarSwipeInteractionHandler extends InternalStateHandler implements FrameCallback {
+public class NavBarSwipeInteractionHandler extends InternalStateHandler {
 
     private static final int STATE_LAUNCHER_READY = 1 << 0;
     private static final int STATE_RECENTS_DELAY_COMPLETE = 1 << 1;
@@ -90,9 +84,6 @@
     // animated to 1, so allow for a smooth transition.
     private final AnimatedFloat mActivityMultiplier = new AnimatedFloat(this::updateFinalShift);
 
-    private final Choreographer mChoreographer;
-    private final AtomicBoolean mFrameScheduled = new AtomicBoolean(false);
-
     private final int mRunningTaskId;
     private final Context mContext;
 
@@ -106,18 +97,12 @@
 
     private boolean mLauncherReady;
     private boolean mTouchEndHandled;
+    private float mCurrentDisplacement;
 
     private Bitmap mTaskSnapshot;
 
-    // These are updated on the binder thread, and eventually picked up on doFrame
-    private volatile float mCurrentDisplacement;
-    private volatile float mEndVelocity;
-    private volatile boolean mTouchEnded = false;
-
-    NavBarSwipeInteractionHandler(
-            RunningTaskInfo runningTaskInfo, Choreographer choreographer, Context context) {
+    NavBarSwipeInteractionHandler(RunningTaskInfo runningTaskInfo, Context context) {
         mRunningTaskId = runningTaskInfo.id;
-        mChoreographer = choreographer;
         mContext = context;
         WindowManagerWrapper.getInstance().getStableInsets(mStableInsets);
 
@@ -196,37 +181,9 @@
         mRecentsView.setVisibility(View.GONE);
     }
 
-    /**
-     * This is updated on the binder thread and is picked up on the UI thread during the next
-     * scheduled frame.
-     * TODO: Instead of continuously scheduling frames, post the motion events to UI thread
-     * (can ignore all continuous move events until the last move).
-     */
-    @BinderThread
+    @UiThread
     public void updateDisplacement(float displacement) {
         mCurrentDisplacement = displacement;
-        scheduleFrameIfNeeded();
-    }
-
-    @BinderThread
-    public void endTouch(float endVelocity) {
-        mEndVelocity = endVelocity;
-        mTouchEnded = true;
-        scheduleFrameIfNeeded();
-    }
-
-    private void scheduleFrameIfNeeded() {
-        boolean alreadyScheduled = mFrameScheduled.getAndSet(true);
-        if (!alreadyScheduled) {
-            // TODO: Here we might end up scheduling one additional frame in some race conditions.
-            // This can be avoided by synchronising postFrameCallback as well
-            mChoreographer.postFrameCallback(this);
-        }
-    }
-
-    @Override
-    public void doFrame(long l) {
-        mFrameScheduled.set(false);
         executeFrameUpdate();
     }
 
@@ -238,14 +195,6 @@
             float shift = hotseatHeight == 0 ? 0 : translation / hotseatHeight;
             mCurrentShift.updateValue(shift);
         }
-
-        if (mTouchEnded) {
-            if (mTouchEndHandled) {
-                return;
-            }
-            mTouchEndHandled = true;
-            animateToFinalShift();
-        }
     }
 
     @UiThread
@@ -301,25 +250,30 @@
     }
 
     @UiThread
-    private void animateToFinalShift() {
+    public void endTouch(float endVelocity) {
+        if (mTouchEndHandled) {
+            return;
+        }
+        mTouchEndHandled = true;
+
         Resources res = mContext.getResources();
         float flingThreshold = res.getDimension(R.dimen.quickstep_fling_threshold_velocity);
-        boolean isFling = Math.abs(mEndVelocity) > flingThreshold;
+        boolean isFling = Math.abs(endVelocity) > flingThreshold;
 
         long duration = DEFAULT_SWIPE_DURATION;
         final float endShift;
         if (!isFling) {
             endShift = mCurrentShift.value >= MIN_PROGRESS_FOR_OVERVIEW ? 1 : 0;
         } else {
-            endShift = mEndVelocity < 0 ? 1 : 0;
+            endShift = endVelocity < 0 ? 1 : 0;
             float minFlingVelocity = res.getDimension(R.dimen.quickstep_fling_min_velocity);
-            if (Math.abs(mEndVelocity) > minFlingVelocity && mLauncherReady) {
+            if (Math.abs(endVelocity) > minFlingVelocity && mLauncherReady) {
                 float distanceToTravel = (endShift - mCurrentShift.value) * mHotseat.getHeight();
 
                 // we want the page's snap velocity to approximately match the velocity at
                 // which the user flings, so we scale the duration by a value near to the
                 // derivative of the scroll interpolator at zero, ie. 5.
-                duration = 5 * Math.round(1000 * Math.abs(distanceToTravel / mEndVelocity));
+                duration = 5 * Math.round(1000 * Math.abs(distanceToTravel / endVelocity));
             }
         }
 
diff --git a/quickstep/src/com/android/quickstep/TouchInteractionService.java b/quickstep/src/com/android/quickstep/TouchInteractionService.java
index b57a417..ff26fb3 100644
--- a/quickstep/src/com/android/quickstep/TouchInteractionService.java
+++ b/quickstep/src/com/android/quickstep/TouchInteractionService.java
@@ -42,6 +42,7 @@
 
 import com.android.launcher3.MainThreadExecutor;
 import com.android.launcher3.R;
+import com.android.launcher3.util.TraceHelper;
 import com.android.systemui.shared.recents.IOverviewProxy;
 import com.android.systemui.shared.recents.ISystemUiProxy;
 import com.android.systemui.shared.recents.model.RecentsTaskLoadPlan;
@@ -63,7 +64,7 @@
 
         @Override
         public void onMotionEvent(MotionEvent ev) {
-            handleMotionEvent(ev);
+            mEventQueue.queue(ev);
         }
 
         @Override
@@ -76,7 +77,7 @@
     private RunningTaskInfo mRunningTask;
     private Intent mHomeIntent;
     private ComponentName mLauncher;
-    private Choreographer mChoreographer;
+    private MotionEventQueue mEventQueue;
     private MainThreadExecutor mMainThreadExecutor;
 
     private int mDisplayRotation;
@@ -111,8 +112,8 @@
             sRecentsTaskLoader.startLoader(this);
         }
 
-        mChoreographer = Choreographer.getInstance();
         mMainThreadExecutor = new MainThreadExecutor();
+        mEventQueue = new MotionEventQueue(Choreographer.getInstance(), this::handleMotionEvent);
     }
 
     @Override
@@ -203,7 +204,7 @@
     private void startTouchTracking() {
         // Create the shared handler
         final NavBarSwipeInteractionHandler handler =
-                new NavBarSwipeInteractionHandler(mRunningTask, mChoreographer, this);
+                new NavBarSwipeInteractionHandler(mRunningTask, this);
 
         // Preload and start the recents activity on a background thread
         final Context context = this;
@@ -253,6 +254,7 @@
             return null;
         }
 
+        TraceHelper.beginSection("TaskSnapshot");
         // TODO: We are using some hardcoded layers for now, to best approximate the activity layers
         try {
             return mISystemUiProxy.screenshot(new Rect(), mDisplaySize.x, mDisplaySize.y, 0, 100000,
@@ -260,6 +262,8 @@
         } catch (RemoteException e) {
             Log.e(TAG, "Error capturing snapshot", e);
             return null;
+        } finally {
+            TraceHelper.endSection("TaskSnapshot");
         }
     }
 }