From 1dc8a1f3ca9bc7ac61858e03f64894a682ab84ec Mon Sep 17 00:00:00 2001 From: Sunny Goyal Date: Thu, 16 Nov 2017 11:12:42 -0800 Subject: [PATCH] Batching MotionEvents and processing them on the UI thread Change-Id: I2dc972af8360e719db743740074893bac0213ded --- quickstep/libs/sysui_shared.jar | Bin 93200 -> 93195 bytes .../android/quickstep/MotionEventQueue.java | 93 ++++++++++++++++++ .../NavBarSwipeInteractionHandler.java | 74 +++----------- .../quickstep/TouchInteractionService.java | 12 ++- 4 files changed, 115 insertions(+), 64 deletions(-) create mode 100644 quickstep/src/com/android/quickstep/MotionEventQueue.java diff --git a/quickstep/libs/sysui_shared.jar b/quickstep/libs/sysui_shared.jar index fa0e0f358f8ef4886c3b897d8b34880ffb1074eb..906969826598dc6939f5f01dcef6a6fbc009d795 100644 GIT binary patch delta 2065 zcmY+Fc~BEq9LMwH2$4e|$R&!12^pY386i-0Op1yk2pjGr5u)6YODQ-iM1i7~QG^I< zN7PCk(T-N|iHn0(iX*lbm5K@ub`Z~Er8t(>tEAnxFJ)-{*w6m1@B8iVz1{2^G_4sl zwWPw0O=j@~0s(Kirp|J)5qk~$g1xrg6#)x6-xz%9J_XFsHSvY?jVQ20l#!hY8`9MY zgHRLS$`s#gor2f|D>QBq_`fm-lxro%8K_S9lB3q?Gn|3`a!%w(xd<$=oh)%T!z}l` z%*T`ko-oH8m8~*jsnZTi>3y*<8&!s6PA#G9E1%gI57zYII50=@h?+aXE#W&qE6PynKYFELR6a9f}aw(ZH%(OEGqMxo}`oS zHlu42!2-Q1AK}KqESV z$^(0G4SMuEo_^|t)gXB4bGXU`RqXf zmXUQhYT*4(zjvaO^sv}04~^KSS#nhR7T8)F;0)IW75pw z{8S{}3jX1Y)-GRK<_~7|?;My`8|dYROX;Qbo-CNl{49bMc!-RX2h8J?WSu0R&i8~l z+VCrKo3j3U=X>7AX(mnnjQ2iJ=^nD8s>030)P8)ZxGhDu;l9XT+vsR&t>6)RSDrF2KR^L)I?`Z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97|xYG_C7w|^<-97_)6)E}< z9C>}+@s@)YHq1oUQp6j2i~k_K;~a1%YCXuX{5yJ9UKB9k9z*i`J;ms`7$kVuOY*Mm Jfe@CQ`ya&mIb;9; diff --git a/quickstep/src/com/android/quickstep/MotionEventQueue.java b/quickstep/src/com/android/quickstep/MotionEventQueue.java new file mode 100644 index 0000000000..e3c3a1b893 --- /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 mConsumer; + + public MotionEventQueue(Choreographer choreographer, Consumer 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 { + + 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 dc7d648180..e03a2ff60f 100644 --- a/quickstep/src/com/android/quickstep/NavBarSwipeInteractionHandler.java +++ b/quickstep/src/com/android/quickstep/NavBarSwipeInteractionHandler.java @@ -28,11 +28,7 @@ import android.graphics.Rect; 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.recents.model.Task.TaskKey; 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 @@ public class NavBarSwipeInteractionHandler extends InternalStateHandler implemen // 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 @@ public class NavBarSwipeInteractionHandler extends InternalStateHandler implemen 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 @@ public class NavBarSwipeInteractionHandler extends InternalStateHandler implemen 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 @@ public class NavBarSwipeInteractionHandler extends InternalStateHandler implemen float shift = hotseatHeight == 0 ? 0 : translation / hotseatHeight; mCurrentShift.updateValue(shift); } - - if (mTouchEnded) { - if (mTouchEndHandled) { - return; - } - mTouchEndHandled = true; - animateToFinalShift(); - } } @UiThread @@ -301,25 +250,30 @@ public class NavBarSwipeInteractionHandler extends InternalStateHandler implemen } @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 b57a417785..ff26fb39c1 100644 --- a/quickstep/src/com/android/quickstep/TouchInteractionService.java +++ b/quickstep/src/com/android/quickstep/TouchInteractionService.java @@ -42,6 +42,7 @@ import android.view.WindowManager; 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 @@ public class TouchInteractionService extends Service { @Override public void onMotionEvent(MotionEvent ev) { - handleMotionEvent(ev); + mEventQueue.queue(ev); } @Override @@ -76,7 +77,7 @@ public class TouchInteractionService extends Service { 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 @@ public class TouchInteractionService extends Service { sRecentsTaskLoader.startLoader(this); } - mChoreographer = Choreographer.getInstance(); mMainThreadExecutor = new MainThreadExecutor(); + mEventQueue = new MotionEventQueue(Choreographer.getInstance(), this::handleMotionEvent); } @Override @@ -203,7 +204,7 @@ public class TouchInteractionService extends Service { 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 @@ public class TouchInteractionService extends Service { 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 @@ public class TouchInteractionService extends Service { } catch (RemoteException e) { Log.e(TAG, "Error capturing snapshot", e); return null; + } finally { + TraceHelper.endSection("TaskSnapshot"); } } }