Merge "Do not add padding left/right when cell layout border spacing exists." into sc-dev
diff --git a/quickstep/src/com/android/launcher3/QuickstepTransitionManager.java b/quickstep/src/com/android/launcher3/QuickstepTransitionManager.java
index 36322ce..26d407f 100644
--- a/quickstep/src/com/android/launcher3/QuickstepTransitionManager.java
+++ b/quickstep/src/com/android/launcher3/QuickstepTransitionManager.java
@@ -214,8 +214,9 @@
         }
     };
 
+    // Pairs of window starting type and starting window background color for starting tasks
     // Will never be larger than MAX_NUM_TASKS
-    private LinkedHashMap<Integer, Integer> mTypeForTaskId;
+    private LinkedHashMap<Integer, Pair<Integer, Integer>> mTaskStartParams;
 
     public QuickstepTransitionManager(Context context) {
         mLauncher = Launcher.cast(Launcher.getLauncher(context));
@@ -232,9 +233,9 @@
         mLauncher.addOnDeviceProfileChangeListener(this);
 
         if (supportsSSplashScreen()) {
-            mTypeForTaskId = new LinkedHashMap<Integer, Integer>(MAX_NUM_TASKS) {
+            mTaskStartParams = new LinkedHashMap<Integer, Pair<Integer, Integer>>(MAX_NUM_TASKS) {
                 @Override
-                protected boolean removeEldestEntry(Entry<Integer, Integer> entry) {
+                protected boolean removeEldestEntry(Entry<Integer, Pair<Integer, Integer>> entry) {
                     return size() > MAX_NUM_TASKS;
                 }
             };
@@ -420,15 +421,6 @@
         return bounds;
     }
 
-    private int getOpeningTaskId(RemoteAnimationTargetCompat[] appTargets) {
-        for (RemoteAnimationTargetCompat target : appTargets) {
-            if (target.mode == MODE_OPENING) {
-                return target.taskId;
-            }
-        }
-        return -1;
-    }
-
     public void setRemoteAnimationProvider(final RemoteAnimationProvider animationProvider,
             CancellationSignal cancellationSignal) {
         mRemoteAnimationProvider = animationProvider;
@@ -595,10 +587,12 @@
 
         final boolean hasSplashScreen;
         if (supportsSSplashScreen()) {
-            int taskId = getOpeningTaskId(appTargets);
-            int type = mTypeForTaskId.getOrDefault(taskId, STARTING_WINDOW_TYPE_NONE);
-            mTypeForTaskId.remove(taskId);
-            hasSplashScreen = type == STARTING_WINDOW_TYPE_SPLASH_SCREEN;
+            int taskId = openingTargets.getFirstAppTargetTaskId();
+            Pair<Integer, Integer> defaultParams = Pair.create(STARTING_WINDOW_TYPE_NONE, 0);
+            Pair<Integer, Integer> taskParams =
+                    mTaskStartParams.getOrDefault(taskId, defaultParams);
+            mTaskStartParams.remove(taskId);
+            hasSplashScreen = taskParams.first == STARTING_WINDOW_TYPE_SPLASH_SCREEN;
         } else {
             hasSplashScreen = false;
         }
@@ -799,18 +793,30 @@
         final RectF widgetBackgroundBounds = new RectF();
         final Rect appWindowCrop = new Rect();
         final Matrix matrix = new Matrix();
+        RemoteAnimationTargets openingTargets = new RemoteAnimationTargets(appTargets,
+                wallpaperTargets, nonAppTargets, MODE_OPENING);
+
+        RemoteAnimationTargetCompat openingTarget = openingTargets.getFirstAppTarget();
+        int fallbackBackgroundColor = 0;
+        if (openingTarget != null && supportsSSplashScreen()) {
+            fallbackBackgroundColor = mTaskStartParams.containsKey(openingTarget.taskId)
+                    ? mTaskStartParams.get(openingTarget.taskId).second : 0;
+            mTaskStartParams.remove(openingTarget.taskId);
+        }
+        if (fallbackBackgroundColor == 0) {
+            fallbackBackgroundColor =
+                    FloatingWidgetView.getDefaultBackgroundColor(mLauncher, openingTarget);
+        }
 
         final float finalWindowRadius = mDeviceProfile.isMultiWindowMode
                 ? 0 : getWindowCornerRadius(mLauncher.getResources());
         final FloatingWidgetView floatingView = FloatingWidgetView.getFloatingWidgetView(mLauncher,
                 v, widgetBackgroundBounds,
                 new Size(windowTargetBounds.width(), windowTargetBounds.height()),
-                finalWindowRadius, appTargetsAreTranslucent);
+                finalWindowRadius, appTargetsAreTranslucent, fallbackBackgroundColor);
         final float initialWindowRadius = supportsRoundedCornersOnWindows(mLauncher.getResources())
                 ? floatingView.getInitialCornerRadius() : 0;
 
-        RemoteAnimationTargets openingTargets = new RemoteAnimationTargets(appTargets,
-                wallpaperTargets, nonAppTargets, MODE_OPENING);
         SurfaceTransactionApplier surfaceApplier = new SurfaceTransactionApplier(floatingView);
         openingTargets.addReleaseCheck(surfaceApplier);
 
@@ -1434,8 +1440,8 @@
         }
 
         @Override
-        public void onTaskLaunching(int taskId, int supportedType) {
-            mTransitionManager.mTypeForTaskId.put(taskId, supportedType);
+        public void onTaskLaunching(int taskId, int supportedType, int color) {
+            mTransitionManager.mTaskStartParams.put(taskId, Pair.create(supportedType, color));
         }
     }
 }
diff --git a/quickstep/src/com/android/quickstep/AbsSwipeUpHandler.java b/quickstep/src/com/android/quickstep/AbsSwipeUpHandler.java
index 88db274..8f42993 100644
--- a/quickstep/src/com/android/quickstep/AbsSwipeUpHandler.java
+++ b/quickstep/src/com/android/quickstep/AbsSwipeUpHandler.java
@@ -117,6 +117,7 @@
 import com.android.systemui.shared.system.RemoteAnimationTargetCompat;
 import com.android.systemui.shared.system.TaskInfoCompat;
 import com.android.systemui.shared.system.TaskStackChangeListener;
+import com.android.systemui.shared.system.TaskStackChangeListeners;
 
 import java.util.ArrayList;
 import java.util.function.Consumer;
@@ -1071,7 +1072,8 @@
     }
 
     protected abstract HomeAnimationFactory createHomeAnimationFactory(
-            ArrayList<IBinder> launchCookies, long duration, boolean isTargetTranslucent);
+            ArrayList<IBinder> launchCookies, long duration, boolean isTargetTranslucent,
+            boolean appCanEnterPip, RemoteAnimationTargetCompat runningTaskTarget);
 
     private final TaskStackChangeListener mActivityRestartListener = new TaskStackChangeListener() {
         @Override
@@ -1082,7 +1084,7 @@
                 // Since this is an edge case, just cancel and relaunch with default activity
                 // options (since we don't know if there's an associated app icon to launch from)
                 endRunningWindowAnim(true /* cancel */);
-                ActivityManagerWrapper.getInstance().unregisterTaskStackListener(
+                TaskStackChangeListeners.getInstance().unregisterTaskStackListener(
                         mActivityRestartListener);
                 ActivityManagerWrapper.getInstance().startActivityFromRecents(task.taskId, null);
             }
@@ -1097,7 +1099,7 @@
         // If we are transitioning to launcher, then listen for the activity to be restarted while
         // the transition is in progress
         if (mGestureState.getEndTarget().isLauncher) {
-            ActivityManagerWrapper.getInstance().registerTaskStackListener(
+            TaskStackChangeListeners.getInstance().registerTaskStackListener(
                     mActivityRestartListener);
 
             mParallelRunningAnim = mActivityInterface.getParallelAnimationToLauncher(
@@ -1116,13 +1118,15 @@
                     ? runningTaskTarget.taskInfo.launchCookies
                     : new ArrayList<>();
             boolean isTranslucent = runningTaskTarget != null && runningTaskTarget.isTranslucent;
-            HomeAnimationFactory homeAnimFactory =
-                    createHomeAnimationFactory(cookies, duration, isTranslucent);
-            mIsSwipingPipToHome = homeAnimFactory.supportSwipePipToHome()
+            boolean appCanEnterPip = !mDeviceState.isPipActive()
                     && runningTaskTarget != null
                     && runningTaskTarget.taskInfo.pictureInPictureParams != null
                     && TaskInfoCompat.isAutoEnterPipEnabled(
                             runningTaskTarget.taskInfo.pictureInPictureParams);
+            HomeAnimationFactory homeAnimFactory =
+                    createHomeAnimationFactory(cookies, duration, isTranslucent, appCanEnterPip,
+                            runningTaskTarget);
+            mIsSwipingPipToHome = homeAnimFactory.supportSwipePipToHome() && appCanEnterPip;
             if (mIsSwipingPipToHome) {
                 mSwipePipToHomeAnimator = getSwipePipToHomeAnimator(
                         homeAnimFactory, runningTaskTarget, start);
@@ -1398,7 +1402,8 @@
         }
 
         mActivityInitListener.unregister();
-        ActivityManagerWrapper.getInstance().unregisterTaskStackListener(mActivityRestartListener);
+        TaskStackChangeListeners.getInstance().unregisterTaskStackListener(
+                mActivityRestartListener);
         mTaskSnapshot = null;
     }
 
diff --git a/quickstep/src/com/android/quickstep/FallbackSwipeHandler.java b/quickstep/src/com/android/quickstep/FallbackSwipeHandler.java
index 2d81429..fd44e02 100644
--- a/quickstep/src/com/android/quickstep/FallbackSwipeHandler.java
+++ b/quickstep/src/com/android/quickstep/FallbackSwipeHandler.java
@@ -129,7 +129,8 @@
 
     @Override
     protected HomeAnimationFactory createHomeAnimationFactory(ArrayList<IBinder> launchCookies,
-            long duration, boolean isTargetTranslucent) {
+            long duration, boolean isTargetTranslucent, boolean appCanEnterPip,
+            RemoteAnimationTargetCompat runningTaskTarget) {
         mActiveAnimationFactory = new FallbackHomeAnimationFactory(duration);
         ActivityOptions options = ActivityOptions.makeCustomAnimation(mContext, 0, 0);
         Intent intent = new Intent(mGestureState.getHomeIntent());
diff --git a/quickstep/src/com/android/quickstep/LauncherSwipeHandlerV2.java b/quickstep/src/com/android/quickstep/LauncherSwipeHandlerV2.java
index 1bae1c5..47d94ba 100644
--- a/quickstep/src/com/android/quickstep/LauncherSwipeHandlerV2.java
+++ b/quickstep/src/com/android/quickstep/LauncherSwipeHandlerV2.java
@@ -20,6 +20,9 @@
 import static com.android.launcher3.LauncherState.NORMAL;
 import static com.android.launcher3.Utilities.boundToRange;
 import static com.android.launcher3.Utilities.dpToPx;
+import static com.android.launcher3.Utilities.mapBoundToRange;
+import static com.android.launcher3.anim.Interpolators.EXAGGERATED_EASE;
+import static com.android.launcher3.anim.Interpolators.LINEAR;
 import static com.android.launcher3.config.FeatureFlags.PROTOTYPE_APP_CLOSE;
 import static com.android.launcher3.model.data.ItemInfo.NO_MATCHING_ID;
 import static com.android.launcher3.views.FloatingIconView.SHAPE_PROGRESS_DURATION;
@@ -65,6 +68,7 @@
 import com.android.quickstep.views.TaskView;
 import com.android.systemui.plugins.ResourceProvider;
 import com.android.systemui.shared.system.InputConsumerController;
+import com.android.systemui.shared.system.RemoteAnimationTargetCompat;
 
 import java.util.ArrayList;
 
@@ -84,7 +88,8 @@
 
     @Override
     protected HomeAnimationFactory createHomeAnimationFactory(ArrayList<IBinder> launchCookies,
-            long duration, boolean isTargetTranslucent) {
+            long duration, boolean isTargetTranslucent, boolean appCanEnterPip,
+            RemoteAnimationTargetCompat runningTaskTarget) {
         if (mActivity == null) {
             mStateCallback.addChangeListener(STATE_LAUNCHER_PRESENT | STATE_HANDLER_INVALIDATED,
                     isPresent -> mRecentsView.startHome());
@@ -103,12 +108,12 @@
         mActivity.getRootView().setForceHideBackArrow(true);
         mActivity.setHintUserWillBeActive();
 
-        if (!canUseWorkspaceView) {
+        if (!canUseWorkspaceView || appCanEnterPip) {
             return new LauncherHomeAnimationFactory();
         }
         if (workspaceView instanceof LauncherAppWidgetHostView) {
             return createWidgetHomeAnimationFactory((LauncherAppWidgetHostView) workspaceView,
-                    isTargetTranslucent);
+                    isTargetTranslucent, runningTaskTarget);
         }
         return createIconHomeAnimationFactory(workspaceView);
     }
@@ -169,15 +174,19 @@
     }
 
     private HomeAnimationFactory createWidgetHomeAnimationFactory(
-            LauncherAppWidgetHostView hostView, boolean isTargetTranslucent) {
-
+            LauncherAppWidgetHostView hostView, boolean isTargetTranslucent,
+            RemoteAnimationTargetCompat runningTaskTarget) {
+        final float floatingWidgetAlpha = isTargetTranslucent ? 0 : 1;
         RectF backgroundLocation = new RectF();
         Rect crop = new Rect();
         mTaskViewSimulator.getCurrentCropRect().roundOut(crop);
         Size windowSize = new Size(crop.width(), crop.height());
+        int fallbackBackgroundColor =
+                FloatingWidgetView.getDefaultBackgroundColor(mContext, runningTaskTarget);
         FloatingWidgetView floatingWidgetView = FloatingWidgetView.getFloatingWidgetView(mActivity,
                 hostView, backgroundLocation, windowSize,
-                mTaskViewSimulator.getCurrentCornerRadius(), isTargetTranslucent);
+                mTaskViewSimulator.getCurrentCornerRadius(), isTargetTranslucent,
+                fallbackBackgroundColor);
 
         return new FloatingViewHomeAnimationFactory(floatingWidgetView) {
 
@@ -207,12 +216,20 @@
             }
 
             @Override
-            public void update(@Nullable AppCloseConfig config, RectF currentRect,
-                    float progress, float radius) {
+            public void update(@Nullable AppCloseConfig config, RectF currentRect, float progress,
+                    float radius) {
                 super.update(config, currentRect, progress, radius);
-                floatingWidgetView.update(currentRect, 1 /* floatingWidgetAlpha */,
-                        config != null ? config.getFgAlpha() : 1f /* foregroundAlpha */,
-                        0 /* fallbackBackgroundAlpha */, 1 - progress);
+                final float fallbackBackgroundAlpha =
+                        1 - mapBoundToRange(progress, 0.8f, 1, 0, 1, EXAGGERATED_EASE);
+                final float foregroundAlpha =
+                        mapBoundToRange(progress, 0.5f, 1, 0, 1, EXAGGERATED_EASE);
+                floatingWidgetView.update(currentRect, floatingWidgetAlpha, foregroundAlpha,
+                        fallbackBackgroundAlpha, 1 - progress);
+            }
+
+            @Override
+            protected float getWindowAlpha(float progress) {
+                return 1 - mapBoundToRange(progress, 0, 0.5f, 0, 1, LINEAR);
             }
         };
     }
diff --git a/quickstep/src/com/android/quickstep/RecentTasksList.java b/quickstep/src/com/android/quickstep/RecentTasksList.java
index 3302da0..3080f04 100644
--- a/quickstep/src/com/android/quickstep/RecentTasksList.java
+++ b/quickstep/src/com/android/quickstep/RecentTasksList.java
@@ -33,6 +33,7 @@
 import com.android.systemui.shared.system.ActivityManagerWrapper;
 import com.android.systemui.shared.system.KeyguardManagerCompat;
 import com.android.systemui.shared.system.TaskStackChangeListener;
+import com.android.systemui.shared.system.TaskStackChangeListeners;
 
 import java.util.ArrayList;
 import java.util.Collections;
@@ -66,7 +67,7 @@
         mKeyguardManager = keyguardManager;
         mChangeId = 1;
         mActivityManagerWrapper = activityManagerWrapper;
-        mActivityManagerWrapper.registerTaskStackListener(this);
+        TaskStackChangeListeners.getInstance().registerTaskStackListener(this);
     }
 
     @VisibleForTesting
diff --git a/quickstep/src/com/android/quickstep/RecentsActivity.java b/quickstep/src/com/android/quickstep/RecentsActivity.java
index 6852642..0e85ec3 100644
--- a/quickstep/src/com/android/quickstep/RecentsActivity.java
+++ b/quickstep/src/com/android/quickstep/RecentsActivity.java
@@ -353,7 +353,8 @@
     public void startHome() {
         if (LIVE_TILE.get()) {
             RecentsView recentsView = getOverviewPanel();
-            recentsView.switchToScreenshotAndFinishAnimationToRecents(this::startHomeInternal);
+            recentsView.switchToScreenshot(() -> recentsView.finishRecentsAnimation(true,
+                    this::startHomeInternal));
         } else {
             startHomeInternal();
         }
diff --git a/quickstep/src/com/android/quickstep/RecentsAnimationDeviceState.java b/quickstep/src/com/android/quickstep/RecentsAnimationDeviceState.java
index fa37901..444d77a 100644
--- a/quickstep/src/com/android/quickstep/RecentsAnimationDeviceState.java
+++ b/quickstep/src/com/android/quickstep/RecentsAnimationDeviceState.java
@@ -15,6 +15,8 @@
  */
 package com.android.quickstep;
 
+import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
+import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
 import static android.content.Intent.ACTION_USER_UNLOCKED;
 
 import static com.android.launcher3.util.DisplayController.CHANGE_ALL;
@@ -41,6 +43,7 @@
 import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING_OCCLUDED;
 
 import android.app.ActivityManager;
+import android.app.ActivityTaskManager;
 import android.content.BroadcastReceiver;
 import android.content.ComponentName;
 import android.content.Context;
@@ -50,6 +53,7 @@
 import android.graphics.Region;
 import android.net.Uri;
 import android.os.Process;
+import android.os.RemoteException;
 import android.os.SystemProperties;
 import android.os.UserManager;
 import android.provider.Settings;
@@ -75,6 +79,8 @@
 import com.android.systemui.shared.system.QuickStepContract;
 import com.android.systemui.shared.system.QuickStepContract.SystemUiStateFlags;
 import com.android.systemui.shared.system.SystemGestureExclusionListenerCompat;
+import com.android.systemui.shared.system.TaskStackChangeListener;
+import com.android.systemui.shared.system.TaskStackChangeListeners;
 
 import java.io.PrintWriter;
 import java.util.ArrayList;
@@ -96,6 +102,8 @@
     private final DisplayController mDisplayController;
     private final int mDisplayId;
     private final RotationTouchHelper mRotationTouchHelper;
+    private final TaskStackChangeListener mPipListener;
+    private final List<ComponentName> mGestureBlockedActivities;
 
     private final ArrayList<Runnable> mOnDestroyActions = new ArrayList<>();
 
@@ -106,9 +114,11 @@
     private final Region mDeferredGestureRegion = new Region();
     private boolean mAssistantAvailable;
     private float mAssistantVisibility;
+    private boolean mIsUserSetupComplete;
     private boolean mIsOneHandedModeEnabled;
     private boolean mIsSwipeToNotificationEnabled;
     private final boolean mIsOneHandedModeSupported;
+    private boolean mPipIsActive;
 
     private boolean mIsUserUnlocked;
     private final ArrayList<Runnable> mUserUnlockedActions = new ArrayList<>();
@@ -125,10 +135,6 @@
     private Region mExclusionRegion;
     private SystemGestureExclusionListenerCompat mExclusionListener;
 
-    private final List<ComponentName> mGestureBlockedActivities;
-
-    private boolean mIsUserSetupComplete;
-
     public RecentsAnimationDeviceState(Context context) {
         this(context, false);
     }
@@ -204,7 +210,6 @@
             mIsOneHandedModeEnabled = false;
         }
 
-
         Uri swipeBottomNotificationUri =
                 Settings.Secure.getUriFor(ONE_HANDED_SWIPE_BOTTOM_TO_NOTIFICATION_ENABLED);
         SettingsCache.OnChangeListener onChangeListener =
@@ -220,6 +225,27 @@
             settingsCache.register(setupCompleteUri, userSetupChangeListener);
             runOnDestroy(() -> settingsCache.unregister(setupCompleteUri, userSetupChangeListener));
         }
+
+        try {
+            mPipIsActive = ActivityTaskManager.getService().getRootTaskInfo(
+                    WINDOWING_MODE_PINNED, ACTIVITY_TYPE_UNDEFINED) != null;
+        } catch (RemoteException e) {
+            // Do nothing
+        }
+        mPipListener = new TaskStackChangeListener() {
+            @Override
+            public void onActivityPinned(String packageName, int userId, int taskId, int stackId) {
+                mPipIsActive = true;
+            }
+
+            @Override
+            public void onActivityUnpinned() {
+                mPipIsActive = false;
+            }
+        };
+        TaskStackChangeListeners.getInstance().registerTaskStackListener(mPipListener);
+        runOnDestroy(() ->
+                TaskStackChangeListeners.getInstance().unregisterTaskStackListener(mPipListener));
     }
 
     private void runOnDestroy(Runnable action) {
@@ -579,6 +605,10 @@
         return mIsSwipeToNotificationEnabled;
     }
 
+    public boolean isPipActive() {
+        return mPipIsActive;
+    }
+
     public RotationTouchHelper getRotationTouchHelper() {
         return mRotationTouchHelper;
     }
@@ -596,6 +626,7 @@
         pw.println("  isOneHandedModeEnabled=" + mIsOneHandedModeEnabled);
         pw.println("  isSwipeToNotificationEnabled=" + mIsSwipeToNotificationEnabled);
         pw.println("  deferredGestureRegion=" + mDeferredGestureRegion);
+        pw.println("  pipIsActive=" + mPipIsActive);
         mRotationTouchHelper.dump(pw);
     }
 }
diff --git a/quickstep/src/com/android/quickstep/RecentsModel.java b/quickstep/src/com/android/quickstep/RecentsModel.java
index 2eb9dd8..1e82c8c 100644
--- a/quickstep/src/com/android/quickstep/RecentsModel.java
+++ b/quickstep/src/com/android/quickstep/RecentsModel.java
@@ -39,6 +39,7 @@
 import com.android.systemui.shared.system.ActivityManagerWrapper;
 import com.android.systemui.shared.system.KeyguardManagerCompat;
 import com.android.systemui.shared.system.TaskStackChangeListener;
+import com.android.systemui.shared.system.TaskStackChangeListeners;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -75,7 +76,7 @@
         mIconCache = new TaskIconCache(context, RECENTS_MODEL_EXECUTOR, iconProvider);
         mThumbnailCache = new TaskThumbnailCache(context, RECENTS_MODEL_EXECUTOR);
 
-        ActivityManagerWrapper.getInstance().registerTaskStackListener(this);
+        TaskStackChangeListeners.getInstance().registerTaskStackListener(this);
         iconProvider.registerIconChangeListener(this, MAIN_EXECUTOR.getHandler());
     }
 
diff --git a/quickstep/src/com/android/quickstep/RemoteAnimationTargets.java b/quickstep/src/com/android/quickstep/RemoteAnimationTargets.java
index edc3ab2..c032889 100644
--- a/quickstep/src/com/android/quickstep/RemoteAnimationTargets.java
+++ b/quickstep/src/com/android/quickstep/RemoteAnimationTargets.java
@@ -85,6 +85,17 @@
         return null;
     }
 
+    /** Returns the first opening app target. */
+    public RemoteAnimationTargetCompat getFirstAppTarget() {
+        return apps.length > 0 ? apps[0] : null;
+    }
+
+    /** Returns the task id of the first opening app target, or -1 if none is found. */
+    public int getFirstAppTargetTaskId() {
+        RemoteAnimationTargetCompat target = getFirstAppTarget();
+        return target == null ? -1 : target.taskId;
+    }
+
     public boolean isAnimatingHome() {
         for (RemoteAnimationTargetCompat target : unfilteredApps) {
             if (target.activityType == RemoteAnimationTargetCompat.ACTIVITY_TYPE_HOME) {
diff --git a/quickstep/src/com/android/quickstep/RotationTouchHelper.java b/quickstep/src/com/android/quickstep/RotationTouchHelper.java
index fc7a3df..678b176 100644
--- a/quickstep/src/com/android/quickstep/RotationTouchHelper.java
+++ b/quickstep/src/com/android/quickstep/RotationTouchHelper.java
@@ -38,6 +38,7 @@
 import com.android.systemui.shared.system.ActivityManagerWrapper;
 import com.android.systemui.shared.system.QuickStepContract;
 import com.android.systemui.shared.system.TaskStackChangeListener;
+import com.android.systemui.shared.system.TaskStackChangeListeners;
 
 import java.io.PrintWriter;
 import java.util.ArrayList;
@@ -178,14 +179,14 @@
     }
 
     private void setupOrientationSwipeHandler() {
-        ActivityManagerWrapper.getInstance().registerTaskStackListener(mFrozenTaskListener);
-        mOnDestroyFrozenTaskRunnable = () -> ActivityManagerWrapper.getInstance()
+        TaskStackChangeListeners.getInstance().registerTaskStackListener(mFrozenTaskListener);
+        mOnDestroyFrozenTaskRunnable = () -> TaskStackChangeListeners.getInstance()
                 .unregisterTaskStackListener(mFrozenTaskListener);
         runOnDestroy(mOnDestroyFrozenTaskRunnable);
     }
 
     private void destroyOrientationSwipeHandlerCallback() {
-        ActivityManagerWrapper.getInstance().unregisterTaskStackListener(mFrozenTaskListener);
+        TaskStackChangeListeners.getInstance().unregisterTaskStackListener(mFrozenTaskListener);
         mOnDestroyActions.remove(mOnDestroyFrozenTaskRunnable);
     }
 
diff --git a/quickstep/src/com/android/quickstep/SwipeUpAnimationLogic.java b/quickstep/src/com/android/quickstep/SwipeUpAnimationLogic.java
index b79e934..4495455 100644
--- a/quickstep/src/com/android/quickstep/SwipeUpAnimationLogic.java
+++ b/quickstep/src/com/android/quickstep/SwipeUpAnimationLogic.java
@@ -181,6 +181,24 @@
         public boolean supportSwipePipToHome() {
             return false;
         }
+
+        /**
+         * @param progress The progress of the animation to the home screen.
+         * @return The current alpha to set on the animating app window.
+         */
+        protected float getWindowAlpha(float progress) {
+            // Alpha interpolates between [1, 0] between progress values [start, end]
+            final float start = 0f;
+            final float end = 0.85f;
+
+            if (progress <= start) {
+                return 1f;
+            }
+            if (progress >= end) {
+                return 0f;
+            }
+            return Utilities.mapToRange(progress, start, end, 1, 0, ACCEL_1_5);
+        }
     }
 
     /**
@@ -236,24 +254,6 @@
         return anim;
     }
 
-    /**
-     * @param progress The progress of the animation to the home screen.
-     * @return The current alpha to set on the animating app window.
-     */
-    protected float getWindowAlpha(float progress) {
-        // Alpha interpolates between [1, 0] between progress values [start, end]
-        final float start = 0f;
-        final float end = 0.85f;
-
-        if (progress <= start) {
-            return 1f;
-        }
-        if (progress >= end) {
-            return 0f;
-        }
-        return Utilities.mapToRange(progress, start, end, 1, 0, ACCEL_1_5);
-    }
-
     protected class SpringAnimationRunner extends AnimationSuccessListener
             implements RectFSpringAnim.OnUpdateListener, BuilderProxy {
 
@@ -292,7 +292,7 @@
 
             mMatrix.setRectToRect(mCropRectF, mWindowCurrentRect, ScaleToFit.FILL);
             float cornerRadius = Utilities.mapRange(progress, mStartRadius, mEndRadius);
-            float alpha = getWindowAlpha(progress);
+            float alpha = mAnimationFactory.getWindowAlpha(progress);
             if (config != null && PROTOTYPE_APP_CLOSE.get()) {
                 alpha = config.getWindowAlpha();
                 cornerRadius = config.getCornerRadius();
diff --git a/quickstep/src/com/android/quickstep/TaskAnimationManager.java b/quickstep/src/com/android/quickstep/TaskAnimationManager.java
index 29ddde0..9731bf1 100644
--- a/quickstep/src/com/android/quickstep/TaskAnimationManager.java
+++ b/quickstep/src/com/android/quickstep/TaskAnimationManager.java
@@ -39,6 +39,7 @@
 import com.android.systemui.shared.system.RemoteAnimationTargetCompat;
 import com.android.systemui.shared.system.RemoteTransitionCompat;
 import com.android.systemui.shared.system.TaskStackChangeListener;
+import com.android.systemui.shared.system.TaskStackChangeListeners;
 
 public class TaskAnimationManager implements RecentsAnimationCallbacks.RecentsAnimationListener {
     public static final boolean ENABLE_SHELL_TRANSITIONS =
@@ -58,7 +59,7 @@
         public void onActivityRestartAttempt(ActivityManager.RunningTaskInfo task,
                 boolean homeTaskVisible, boolean clearedTask, boolean wasVisible) {
             if (mLastGestureState == null) {
-                ActivityManagerWrapper.getInstance().unregisterTaskStackListener(
+                TaskStackChangeListeners.getInstance().unregisterTaskStackListener(
                         mLiveTileRestartListener);
                 return;
             }
@@ -68,7 +69,7 @@
                 RecentsView recentsView = activityInterface.getCreatedActivity().getOverviewPanel();
                 if (recentsView != null) {
                     recentsView.launchSideTaskInLiveTileModeForRestartedApp(task.taskId);
-                    ActivityManagerWrapper.getInstance().unregisterTaskStackListener(
+                    TaskStackChangeListeners.getInstance().unregisterTaskStackListener(
                             mLiveTileRestartListener);
                 }
             }
@@ -197,7 +198,7 @@
     }
 
     public void enableLiveTileRestartListener() {
-        ActivityManagerWrapper.getInstance().registerTaskStackListener(mLiveTileRestartListener);
+        TaskStackChangeListeners.getInstance().registerTaskStackListener(mLiveTileRestartListener);
     }
 
     /**
@@ -241,7 +242,7 @@
             mLiveTileCleanUpHandler.run();
             mLiveTileCleanUpHandler = null;
         }
-        ActivityManagerWrapper.getInstance().unregisterTaskStackListener(mLiveTileRestartListener);
+        TaskStackChangeListeners.getInstance().unregisterTaskStackListener(mLiveTileRestartListener);
 
         // Release all the target leashes
         if (mTargets != null) {
diff --git a/quickstep/src/com/android/quickstep/interaction/GestureSandboxActivity.java b/quickstep/src/com/android/quickstep/interaction/GestureSandboxActivity.java
index c3b342b..cf523d0 100644
--- a/quickstep/src/com/android/quickstep/interaction/GestureSandboxActivity.java
+++ b/quickstep/src/com/android/quickstep/interaction/GestureSandboxActivity.java
@@ -29,8 +29,6 @@
 import com.android.launcher3.R;
 import com.android.quickstep.interaction.TutorialController.TutorialType;
 
-import java.util.ArrayDeque;
-import java.util.Deque;
 import java.util.List;
 
 /** Shows the gesture interactive sandbox in full screen mode. */
@@ -39,8 +37,9 @@
     private static final String LOG_TAG = "GestureSandboxActivity";
 
     private static final String KEY_TUTORIAL_STEPS = "tutorial_steps";
+    private static final String KEY_CURRENT_STEP = "current_step";
 
-    private Deque<TutorialType> mTutorialSteps;
+    private TutorialType[] mTutorialSteps;
     private TutorialType mCurrentTutorialStep;
     private TutorialFragment mFragment;
 
@@ -55,9 +54,7 @@
 
         Bundle args = savedInstanceState == null ? getIntent().getExtras() : savedInstanceState;
         mTutorialSteps = getTutorialSteps(args);
-        mCurrentStep = 1;
-        mNumSteps = mTutorialSteps.size();
-        mCurrentTutorialStep = mTutorialSteps.pop();
+        mCurrentTutorialStep = mTutorialSteps[mCurrentStep - 1];
         mFragment = TutorialFragment.newInstance(mCurrentTutorialStep);
         getSupportFragmentManager().beginTransaction()
                 .add(R.id.gesture_tutorial_fragment_container, mFragment)
@@ -88,12 +85,13 @@
     @Override
     protected void onSaveInstanceState(@NonNull Bundle savedInstanceState) {
         savedInstanceState.putStringArray(KEY_TUTORIAL_STEPS, getTutorialStepNames());
+        savedInstanceState.putInt(KEY_CURRENT_STEP, mCurrentStep);
         super.onSaveInstanceState(savedInstanceState);
     }
 
     /** Returns true iff there aren't anymore tutorial types to display to the user. */
     public boolean isTutorialComplete() {
-        return mTutorialSteps.isEmpty();
+        return mCurrentStep >= mNumSteps;
     }
 
     public int getCurrentStep() {
@@ -121,7 +119,7 @@
             mFragment.closeTutorial();
             return;
         }
-        mCurrentTutorialStep = mTutorialSteps.pop();
+        mCurrentTutorialStep = mTutorialSteps[mCurrentStep];
         mFragment = TutorialFragment.newInstance(mCurrentTutorialStep);
         getSupportFragmentManager().beginTransaction()
             .replace(R.id.gesture_tutorial_fragment_container, mFragment)
@@ -131,10 +129,9 @@
     }
 
     private String[] getTutorialStepNames() {
-        String[] tutorialStepNames = new String[mTutorialSteps.size() + 1];
+        String[] tutorialStepNames = new String[mTutorialSteps.length];
 
-        int i = 1;
-        tutorialStepNames[0] = mCurrentTutorialStep.name();
+        int i = 0;
         for (TutorialType tutorialStep : mTutorialSteps) {
             tutorialStepNames[i++] = tutorialStep.name();
         }
@@ -142,25 +139,28 @@
         return tutorialStepNames;
     }
 
-    private Deque<TutorialType> getTutorialSteps(Bundle extras) {
-        Deque<TutorialType> defaultSteps = new ArrayDeque<>();
-        defaultSteps.push(TutorialType.RIGHT_EDGE_BACK_NAVIGATION);
+    private TutorialType[] getTutorialSteps(Bundle extras) {
+        TutorialType[] defaultSteps = new TutorialType[] {TutorialType.LEFT_EDGE_BACK_NAVIGATION};
 
         if (extras == null || !extras.containsKey(KEY_TUTORIAL_STEPS)) {
             return defaultSteps;
         }
 
         String[] tutorialStepNames = extras.getStringArray(KEY_TUTORIAL_STEPS);
+        int currentStep = extras.getInt(KEY_CURRENT_STEP, -1);
 
         if (tutorialStepNames == null) {
             return defaultSteps;
         }
 
-        Deque<TutorialType> tutorialSteps = new ArrayDeque<>();
-        for (String tutorialStepName : tutorialStepNames) {
-            tutorialSteps.addLast(TutorialType.valueOf(tutorialStepName));
+        TutorialType[] tutorialSteps = new TutorialType[tutorialStepNames.length];
+        for (int i = 0; i < tutorialStepNames.length; i++) {
+            tutorialSteps[i] = TutorialType.valueOf(tutorialStepNames[i]);
         }
 
+        mCurrentStep = Math.max(currentStep, 1);
+        mNumSteps = tutorialSteps.length;
+
         return tutorialSteps;
     }
 
diff --git a/quickstep/src/com/android/quickstep/interaction/TutorialController.java b/quickstep/src/com/android/quickstep/interaction/TutorialController.java
index c9da609..dfe0c72 100644
--- a/quickstep/src/com/android/quickstep/interaction/TutorialController.java
+++ b/quickstep/src/com/android/quickstep/interaction/TutorialController.java
@@ -58,6 +58,7 @@
 
     private static final int FEEDBACK_ANIMATION_MS = 250;
     private static final int RIPPLE_VISIBLE_MS = 300;
+    private static final int GESTURE_ANIMATION_DELAY_MS = 1500;
 
     final TutorialFragment mTutorialFragment;
     TutorialType mTutorialType;
@@ -65,6 +66,7 @@
 
     final TextView mCloseButton;
     final ViewGroup mFeedbackView;
+    final TextView mFeedbackTitleView;
     final ImageView mFeedbackVideoView;
     final ImageView mGestureVideoView;
     final RelativeLayout mFakeLauncherView;
@@ -80,6 +82,12 @@
 
     protected boolean mGestureCompleted = false;
 
+    // These runnables  should be used when posting callbacks to their views and cleared from their
+    // views before posting new callbacks.
+    private final Runnable mTitleViewCallback;
+    @Nullable private Runnable mFeedbackViewCallback;
+    @Nullable private Runnable mFeedbackVideoViewCallback;
+
     TutorialController(TutorialFragment tutorialFragment, TutorialType tutorialType) {
         mTutorialFragment = tutorialFragment;
         mTutorialType = tutorialType;
@@ -89,6 +97,8 @@
         mCloseButton = rootView.findViewById(R.id.gesture_tutorial_fragment_close_button);
         mCloseButton.setOnClickListener(button -> showSkipTutorialDialog());
         mFeedbackView = rootView.findViewById(R.id.gesture_tutorial_fragment_feedback_view);
+        mFeedbackTitleView = mFeedbackView.findViewById(
+                R.id.gesture_tutorial_fragment_feedback_title);
         mFeedbackVideoView = rootView.findViewById(R.id.gesture_tutorial_feedback_video);
         mGestureVideoView = rootView.findViewById(R.id.gesture_tutorial_gesture_video);
         mFakeLauncherView = rootView.findViewById(R.id.gesture_tutorial_fake_launcher_view);
@@ -103,6 +113,9 @@
         mTutorialStepView =
                 rootView.findViewById(R.id.gesture_tutorial_fragment_feedback_tutorial_step);
         mSkipTutorialDialog = createSkipTutorialDialog();
+
+        mTitleViewCallback = () -> mFeedbackTitleView.sendAccessibilityEvent(
+                AccessibilityEvent.TYPE_VIEW_FOCUSED);
     }
 
     private void showSkipTutorialDialog() {
@@ -169,7 +182,7 @@
             playFeedbackVideo(tutorialAnimation, gestureAnimation, () -> {
                 mFeedbackView.setTranslationY(0);
                 title.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
-            });
+            }, true);
         }
     }
 
@@ -192,15 +205,17 @@
                 isGestureSuccessful
                         ? R.string.gesture_tutorial_nice : R.string.gesture_tutorial_try_again,
                 subtitleResId,
-                isGestureSuccessful);
+                isGestureSuccessful,
+                false);
     }
 
     void showFeedback(
             int titleResId,
             int subtitleResId,
-            boolean isGestureSuccessful) {
-        TextView title = mFeedbackView.findViewById(R.id.gesture_tutorial_fragment_feedback_title);
-        title.setText(titleResId);
+            boolean isGestureSuccessful,
+            boolean useGestureAnimationDelay) {
+        mFeedbackTitleView.setText(titleResId);
+        mFeedbackTitleView.removeCallbacks(mTitleViewCallback);
         TextView subtitle =
                 mFeedbackView.findViewById(R.id.gesture_tutorial_fragment_feedback_subtitle);
         subtitle.setText(subtitleResId);
@@ -221,11 +236,8 @@
                             .setDuration(FEEDBACK_ANIMATION_MS)
                             .translationY(0)
                             .start();
-                    title.postDelayed(
-                            () -> title.sendAccessibilityEvent(
-                                    AccessibilityEvent.TYPE_VIEW_FOCUSED),
-                            FEEDBACK_ANIMATION_MS);
-                });
+                    mFeedbackTitleView.postDelayed(mTitleViewCallback, FEEDBACK_ANIMATION_MS);
+                }, useGestureAnimationDelay);
                 return;
             } else {
                 mTutorialFragment.releaseFeedbackVideoView();
@@ -237,10 +249,7 @@
                 .setDuration(FEEDBACK_ANIMATION_MS)
                 .translationY(0)
                 .start();
-        title.postDelayed(
-                () -> title.sendAccessibilityEvent(
-                        AccessibilityEvent.TYPE_VIEW_FOCUSED),
-                FEEDBACK_ANIMATION_MS);
+        mFeedbackTitleView.postDelayed(mTitleViewCallback, FEEDBACK_ANIMATION_MS);
     }
 
     void hideFeedback(boolean releaseFeedbackVideo) {
@@ -254,7 +263,8 @@
     private void playFeedbackVideo(
             @NonNull AnimatedVectorDrawable tutorialAnimation,
             @NonNull AnimatedVectorDrawable gestureAnimation,
-            @NonNull Runnable onStartRunnable) {
+            @NonNull Runnable onStartRunnable,
+            boolean useGestureAnimationDelay) {
 
         if (tutorialAnimation.isRunning()) {
             tutorialAnimation.reset();
@@ -270,7 +280,9 @@
                     gestureAnimation.stop();
                 }
 
-                onStartRunnable.run();
+                if (!useGestureAnimationDelay) {
+                    onStartRunnable.run();
+                }
             }
 
             @Override
@@ -284,8 +296,28 @@
             }
         });
 
-        tutorialAnimation.start();
-        mFeedbackVideoView.setVisibility(View.VISIBLE);
+        if (mFeedbackViewCallback != null) {
+            mFeedbackVideoView.removeCallbacks(mFeedbackViewCallback);
+            mFeedbackViewCallback = null;
+        }
+        if (mFeedbackVideoViewCallback != null) {
+            mFeedbackVideoView.removeCallbacks(mFeedbackVideoViewCallback);
+            mFeedbackVideoViewCallback = null;
+        }
+        if (useGestureAnimationDelay) {
+            mFeedbackViewCallback = onStartRunnable;
+            mFeedbackVideoViewCallback = () -> {
+                mFeedbackVideoView.setVisibility(View.VISIBLE);
+                tutorialAnimation.start();
+            };
+
+            mFeedbackVideoView.setVisibility(View.GONE);
+            mFeedbackView.post(mFeedbackViewCallback);
+            mFeedbackVideoView.postDelayed(mFeedbackVideoViewCallback, GESTURE_ANIMATION_DELAY_MS);
+        } else {
+            mFeedbackVideoView.setVisibility(View.VISIBLE);
+            tutorialAnimation.start();
+        }
     }
 
     void setRippleHotspot(float x, float y) {
diff --git a/quickstep/src/com/android/quickstep/interaction/TutorialFragment.java b/quickstep/src/com/android/quickstep/interaction/TutorialFragment.java
index ec26022..da0fc66 100644
--- a/quickstep/src/com/android/quickstep/interaction/TutorialFragment.java
+++ b/quickstep/src/com/android/quickstep/interaction/TutorialFragment.java
@@ -170,7 +170,8 @@
             Integer introTileStringResId = mTutorialController.getIntroductionTitle();
             Integer introSubtitleResId = mTutorialController.getIntroductionSubtitle();
             if (introTileStringResId != null && introSubtitleResId != null) {
-                mTutorialController.showFeedback(introTileStringResId, introSubtitleResId, false);
+                mTutorialController.showFeedback(
+                        introTileStringResId, introSubtitleResId, false, true);
                 mIntroductionShown = true;
             }
         }
@@ -252,7 +253,7 @@
     @Override
     public void onResume() {
         super.onResume();
-        if (mFragmentStopped) {
+        if (mFragmentStopped && mTutorialController != null) {
             mTutorialController.showFeedback();
             mFragmentStopped = false;
         } else {
diff --git a/quickstep/src/com/android/quickstep/interaction/TutorialStepIndicator.java b/quickstep/src/com/android/quickstep/interaction/TutorialStepIndicator.java
index eda6158..d880d74 100644
--- a/quickstep/src/com/android/quickstep/interaction/TutorialStepIndicator.java
+++ b/quickstep/src/com/android/quickstep/interaction/TutorialStepIndicator.java
@@ -23,6 +23,7 @@
 import android.widget.LinearLayout;
 
 import androidx.appcompat.content.res.AppCompatResources;
+import androidx.core.graphics.ColorUtils;
 
 import com.android.launcher3.R;
 import com.android.launcher3.Utilities;
@@ -86,6 +87,8 @@
         for (int i = mTotalSteps; i < getChildCount(); i++) {
             removeViewAt(i);
         }
+        int stepIndicatorColor = GraphicsUtils.getAttrColor(
+                getContext(), android.R.attr.textColorPrimary);
         for (int i = 0; i < mTotalSteps; i++) {
             Drawable pageIndicatorPillDrawable = AppCompatResources.getDrawable(
                     getContext(), R.drawable.tutorial_step_indicator_pill);
@@ -104,13 +107,10 @@
             }
             if (pageIndicatorPillDrawable != null) {
                 if (i < mCurrentStep) {
-                    pageIndicatorPillDrawable.setTint(
-                            GraphicsUtils.getAttrColor(getContext(),
-                                    android.R.attr.textColorPrimary));
+                    pageIndicatorPillDrawable.setTint(stepIndicatorColor);
                 } else {
                     pageIndicatorPillDrawable.setTint(
-                            GraphicsUtils.getAttrColor(getContext(),
-                                    android.R.attr.textColorPrimaryInverse));
+                            ColorUtils.setAlphaComponent(stepIndicatorColor, 0x22));
                 }
             }
         }
diff --git a/quickstep/src/com/android/quickstep/util/MotionPauseDetector.java b/quickstep/src/com/android/quickstep/util/MotionPauseDetector.java
index 8151d41..1ed2da3 100644
--- a/quickstep/src/com/android/quickstep/util/MotionPauseDetector.java
+++ b/quickstep/src/com/android/quickstep/util/MotionPauseDetector.java
@@ -121,7 +121,7 @@
         mForcePauseTimeout.setAlarm(mMakePauseHarderToTrigger
                 ? HARDER_TRIGGER_TIMEOUT
                 : FORCE_PAUSE_TIMEOUT);
-        float newVelocity = mVelocityProvider.addMotionEvent(ev, pointerIndex);
+        float newVelocity = mVelocityProvider.addMotionEvent(ev, ev.getPointerId(pointerIndex));
         if (mPreviousVelocity != null) {
             checkMotionPaused(newVelocity, mPreviousVelocity, ev.getEventTime());
         }
diff --git a/quickstep/src/com/android/quickstep/util/SwipePipToHomeAnimator.java b/quickstep/src/com/android/quickstep/util/SwipePipToHomeAnimator.java
index 3631130..1062652 100644
--- a/quickstep/src/com/android/quickstep/util/SwipePipToHomeAnimator.java
+++ b/quickstep/src/com/android/quickstep/util/SwipePipToHomeAnimator.java
@@ -121,6 +121,15 @@
         mDestinationBoundsAnimation.set(mDestinationBounds);
         mSurfaceTransactionHelper = new PipSurfaceTransactionHelper(cornerRadius);
 
+        if (sourceRectHint != null && (sourceRectHint.width() < destinationBounds.width()
+                || sourceRectHint.height() < destinationBounds.height())) {
+            // This is a situation in which the source hint rect on at least one axis is smaller
+            // than the destination bounds, which presents a problem because we would have to scale
+            // up that axis to fit the bounds. So instead, just fallback to the non-source hint
+            // animation in this case.
+            sourceRectHint = null;
+        }
+
         if (sourceRectHint == null) {
             mSourceHintRectInsets = null;
 
diff --git a/quickstep/src/com/android/quickstep/views/FloatingWidgetBackgroundView.java b/quickstep/src/com/android/quickstep/views/FloatingWidgetBackgroundView.java
index 9ea2369..65dba33 100644
--- a/quickstep/src/com/android/quickstep/views/FloatingWidgetBackgroundView.java
+++ b/quickstep/src/com/android/quickstep/views/FloatingWidgetBackgroundView.java
@@ -27,7 +27,6 @@
 import android.view.ViewOutlineProvider;
 import android.widget.RemoteViews.RemoteViewOutlineProvider;
 
-import com.android.launcher3.util.Themes;
 import com.android.launcher3.widget.LauncherAppWidgetHostView;
 import com.android.launcher3.widget.RoundedCornerEnforcement;
 
@@ -62,7 +61,8 @@
         setClipToOutline(true);
     }
 
-    void init(LauncherAppWidgetHostView hostView, View backgroundView, float finalRadius) {
+    void init(LauncherAppWidgetHostView hostView, View backgroundView, float finalRadius,
+            int fallbackBackgroundColor) {
         mFinalRadius = finalRadius;
         mSourceView = backgroundView;
         mInitialOutlineRadius = getOutlineRadius(hostView, backgroundView);
@@ -81,7 +81,7 @@
             setBackground(mBackgroundProperties.mDrawable);
             mSourceView.setBackground(null);
         } else if (mOriginalForeground == null) {
-            mFallbackDrawable.setColor(Themes.getColorBackground(backgroundView.getContext()));
+            mFallbackDrawable.setColor(fallbackBackgroundColor);
             setBackground(mFallbackDrawable);
             mIsUsingFallback = true;
         }
diff --git a/quickstep/src/com/android/quickstep/views/FloatingWidgetView.java b/quickstep/src/com/android/quickstep/views/FloatingWidgetView.java
index 0012dd8..22ce942 100644
--- a/quickstep/src/com/android/quickstep/views/FloatingWidgetView.java
+++ b/quickstep/src/com/android/quickstep/views/FloatingWidgetView.java
@@ -34,10 +34,12 @@
 import com.android.launcher3.R;
 import com.android.launcher3.Utilities;
 import com.android.launcher3.dragndrop.DragLayer;
+import com.android.launcher3.util.Themes;
 import com.android.launcher3.views.FloatingView;
 import com.android.launcher3.views.ListenerView;
 import com.android.launcher3.widget.LauncherAppWidgetHostView;
 import com.android.launcher3.widget.RoundedCornerEnforcement;
+import com.android.systemui.shared.system.RemoteAnimationTargetCompat;
 
 /** A view that mimics an App Widget through a launch animation. */
 @TargetApi(Build.VERSION_CODES.S)
@@ -148,7 +150,7 @@
 
     private void init(DragLayer dragLayer, LauncherAppWidgetHostView originalView,
             RectF widgetBackgroundPosition, Size windowSize, float windowCornerRadius,
-            boolean appTargetIsTranslucent) {
+            boolean appTargetIsTranslucent, int fallbackBackgroundColor) {
         mAppWidgetView = originalView;
         mAppWidgetView.beginDeferringUpdates();
         mBackgroundPosition = widgetBackgroundPosition;
@@ -163,7 +165,8 @@
         getRelativePosition(mAppWidgetBackgroundView, dragLayer, mBackgroundPosition);
         getRelativePosition(mAppWidgetBackgroundView, mAppWidgetView, mBackgroundOffset);
         if (!mAppTargetIsTranslucent) {
-            mBackgroundView.init(mAppWidgetView, mAppWidgetBackgroundView, windowCornerRadius);
+            mBackgroundView.init(mAppWidgetView, mAppWidgetBackgroundView, windowCornerRadius,
+                    fallbackBackgroundColor);
             // Layout call before GhostView creation so that the overlaid view isn't clipped
             layout(0, 0, windowSize.getWidth(), windowSize.getHeight());
             mForegroundOverlayView = GhostView.addGhost(mAppWidgetView, this);
@@ -274,7 +277,8 @@
      */
     public static FloatingWidgetView getFloatingWidgetView(Launcher launcher,
             LauncherAppWidgetHostView originalView, RectF widgetBackgroundPosition,
-            Size windowSize, float windowCornerRadius, boolean appTargetsAreTranslucent) {
+            Size windowSize, float windowCornerRadius, boolean appTargetsAreTranslucent,
+            int fallbackBackgroundColor) {
         final DragLayer dragLayer = launcher.getDragLayer();
         ViewGroup parent = (ViewGroup) dragLayer.getParent();
         FloatingWidgetView floatingView =
@@ -282,11 +286,22 @@
         floatingView.recycle();
 
         floatingView.init(dragLayer, originalView, widgetBackgroundPosition, windowSize,
-                windowCornerRadius, appTargetsAreTranslucent);
+                windowCornerRadius, appTargetsAreTranslucent, fallbackBackgroundColor);
         parent.addView(floatingView);
         return floatingView;
     }
 
+    /**
+     * Extract a background color from a target's task description, or fall back to the given
+     * context's theme background color.
+     */
+    public static int getDefaultBackgroundColor(
+            Context context, RemoteAnimationTargetCompat target) {
+        return (target != null && target.taskInfo.taskDescription != null)
+                ? target.taskInfo.taskDescription.getBackgroundColor()
+                : Themes.getColorBackground(context);
+    }
+
     private static void getRelativePosition(View descendant, View ancestor, RectF position) {
         float[] points = new float[]{0, 0, descendant.getWidth(), descendant.getHeight()};
         Utilities.getDescendantCoordRelativeToAncestor(descendant, ancestor, points,
diff --git a/quickstep/src/com/android/quickstep/views/RecentsView.java b/quickstep/src/com/android/quickstep/views/RecentsView.java
index 7991614..df7f8b5 100644
--- a/quickstep/src/com/android/quickstep/views/RecentsView.java
+++ b/quickstep/src/com/android/quickstep/views/RecentsView.java
@@ -2357,7 +2357,8 @@
             public void accept(Boolean success) {
                 if (LIVE_TILE.get() && mEnableDrawingLiveTile && taskView.isRunningTask()
                         && success) {
-                    finishRecentsAnimation(true /* toHome */, () -> onEnd(success));
+                    finishRecentsAnimation(true /* toRecents */, false /* shouldPip */,
+                            () -> onEnd(success));
                 } else {
                     onEnd(success);
                 }
@@ -2368,7 +2369,8 @@
                 if (success) {
                     if (shouldRemoveTask) {
                         if (taskView.getTask() != null) {
-                            switchToScreenshotAndFinishAnimationToRecents(() -> {
+                            finishRecentsAnimation(true /* toRecents */, false /* shouldPip */,
+                                    () -> {
                                 UI_HELPER_EXECUTOR.getHandler().postDelayed(() ->
                                         ActivityManagerWrapper.getInstance().removeTask(
                                                 taskView.getTask().key.id),
@@ -2478,7 +2480,7 @@
         mPendingAnimation.addEndListener(isSuccess -> {
             if (isSuccess) {
                 // Remove all the task views now
-                switchToScreenshotAndFinishAnimationToRecents(() -> {
+                finishRecentsAnimation(true /* toRecents */, false /* shouldPip */, () -> {
                     UI_HELPER_EXECUTOR.getHandler().postDelayed(
                             ActivityManagerWrapper.getInstance()::removeAllRecentTasks,
                             REMOVE_TASK_WAIT_FOR_APP_STOP_MS);
@@ -2639,7 +2641,9 @@
     protected void onConfigurationChanged(Configuration newConfig) {
         super.onConfigurationChanged(newConfig);
         if (LIVE_TILE.get() && mEnableDrawingLiveTile && newConfig.orientation != mOrientation) {
-            switchToScreenshotAndFinishAnimationToRecents(this::updateRecentsRotation);
+            switchToScreenshot(
+                    () -> finishRecentsAnimation(true /* toRecents */, false /* showPip */,
+                            this::updateRecentsRotation));
             mEnableDrawingLiveTile = false;
         } else {
             updateRecentsRotation();
@@ -3632,10 +3636,6 @@
         }
     }
 
-    public void switchToScreenshotAndFinishAnimationToRecents(Runnable onFinishRunnable) {
-        switchToScreenshot(() -> finishRecentsAnimation(true /* toRecents */, onFinishRunnable));
-    }
-
     /**
      * Switch the current running task view to static snapshot mode,
      * capturing the snapshot at the same time.
diff --git a/res/color/all_apps_tab_bg.xml b/res/color-night-v31/all_apps_tab_background_selected.xml
similarity index 76%
copy from res/color/all_apps_tab_bg.xml
copy to res/color-night-v31/all_apps_tab_background_selected.xml
index e59e8d2..b7c9ff6 100644
--- a/res/color/all_apps_tab_bg.xml
+++ b/res/color-night-v31/all_apps_tab_background_selected.xml
@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 The Android Open Source Project
+<!-- Copyright (C) 2021 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.
@@ -13,7 +13,6 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<selector xmlns:android="http://schemas.android.com/apk/res/android"
-        xmlns:androidprv="http://schemas.android.com/apk/prv/res/android">
-    <item android:color="?androidprv:attr/colorAccentPrimary"/>
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:color="@android:color/system_accent2_100"/>
 </selector>
\ No newline at end of file
diff --git a/res/color/all_apps_tab_bg.xml b/res/color-night-v31/all_apps_tab_text.xml
similarity index 75%
copy from res/color/all_apps_tab_bg.xml
copy to res/color-night-v31/all_apps_tab_text.xml
index e59e8d2..83237b4 100644
--- a/res/color/all_apps_tab_bg.xml
+++ b/res/color-night-v31/all_apps_tab_text.xml
@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 The Android Open Source Project
+<!-- Copyright (C) 2021 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.
@@ -13,7 +13,7 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<selector xmlns:android="http://schemas.android.com/apk/res/android"
-        xmlns:androidprv="http://schemas.android.com/apk/prv/res/android">
-    <item android:color="?androidprv:attr/colorAccentPrimary"/>
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:color="@android:color/system_neutral1_50" android:state_selected="true"/>
+    <item android:color="@android:color/system_neutral2_700"/>
 </selector>
\ No newline at end of file
diff --git a/res/color/all_apps_tab_bg.xml b/res/color-night-v31/all_apps_tabs_background.xml
similarity index 76%
copy from res/color/all_apps_tab_bg.xml
copy to res/color-night-v31/all_apps_tabs_background.xml
index e59e8d2..b396f33 100644
--- a/res/color/all_apps_tab_bg.xml
+++ b/res/color-night-v31/all_apps_tabs_background.xml
@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 The Android Open Source Project
+<!-- Copyright (C) 2021 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.
@@ -13,7 +13,6 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<selector xmlns:android="http://schemas.android.com/apk/res/android"
-        xmlns:androidprv="http://schemas.android.com/apk/prv/res/android">
-    <item android:color="?androidprv:attr/colorAccentPrimary"/>
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:color="@android:color/system_neutral2_100"/>
 </selector>
\ No newline at end of file
diff --git a/res/color/all_apps_tab_bg.xml b/res/color-night/all_apps_tab_background_selected.xml
similarity index 76%
copy from res/color/all_apps_tab_bg.xml
copy to res/color-night/all_apps_tab_background_selected.xml
index e59e8d2..b22bc8b 100644
--- a/res/color/all_apps_tab_bg.xml
+++ b/res/color-night/all_apps_tab_background_selected.xml
@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 The Android Open Source Project
+<!-- Copyright (C) 2021 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.
@@ -13,7 +13,6 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<selector xmlns:android="http://schemas.android.com/apk/res/android"
-        xmlns:androidprv="http://schemas.android.com/apk/prv/res/android">
-    <item android:color="?androidprv:attr/colorAccentPrimary"/>
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:color="#BFEBE3"/>
 </selector>
\ No newline at end of file
diff --git a/res/color/all_apps_tab_bg.xml b/res/color-night/all_apps_tab_text.xml
similarity index 76%
copy from res/color/all_apps_tab_bg.xml
copy to res/color-night/all_apps_tab_text.xml
index e59e8d2..183af01 100644
--- a/res/color/all_apps_tab_bg.xml
+++ b/res/color-night/all_apps_tab_text.xml
@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 The Android Open Source Project
+<!-- Copyright (C) 2021 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.
@@ -13,7 +13,7 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<selector xmlns:android="http://schemas.android.com/apk/res/android"
-        xmlns:androidprv="http://schemas.android.com/apk/prv/res/android">
-    <item android:color="?androidprv:attr/colorAccentPrimary"/>
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:color="#F0F0F0" android:state_selected="true"/>
+    <item android:color="#464646"/>
 </selector>
\ No newline at end of file
diff --git a/res/color/all_apps_tab_bg.xml b/res/color-night/all_apps_tabs_background.xml
similarity index 76%
copy from res/color/all_apps_tab_bg.xml
copy to res/color-night/all_apps_tabs_background.xml
index e59e8d2..c0c1621 100644
--- a/res/color/all_apps_tab_bg.xml
+++ b/res/color-night/all_apps_tabs_background.xml
@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 The Android Open Source Project
+<!-- Copyright (C) 2021 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.
@@ -13,7 +13,6 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<selector xmlns:android="http://schemas.android.com/apk/res/android"
-        xmlns:androidprv="http://schemas.android.com/apk/prv/res/android">
-    <item android:color="?androidprv:attr/colorAccentPrimary"/>
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:color="#E2E2E2"/>
 </selector>
\ No newline at end of file
diff --git a/res/color/all_apps_tab_bg.xml b/res/color-v31/all_apps_tab_background_selected.xml
similarity index 76%
copy from res/color/all_apps_tab_bg.xml
copy to res/color-v31/all_apps_tab_background_selected.xml
index e59e8d2..dac8fa2 100644
--- a/res/color/all_apps_tab_bg.xml
+++ b/res/color-v31/all_apps_tab_background_selected.xml
@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 The Android Open Source Project
+<!-- Copyright (C) 2021 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.
@@ -13,7 +13,6 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<selector xmlns:android="http://schemas.android.com/apk/res/android"
-        xmlns:androidprv="http://schemas.android.com/apk/prv/res/android">
-    <item android:color="?androidprv:attr/colorAccentPrimary"/>
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:color="@android:color/system_accent1_100"/>
 </selector>
\ No newline at end of file
diff --git a/res/color/all_apps_tab_bg.xml b/res/color-v31/all_apps_tab_text.xml
similarity index 75%
copy from res/color/all_apps_tab_bg.xml
copy to res/color-v31/all_apps_tab_text.xml
index e59e8d2..c3520a7 100644
--- a/res/color/all_apps_tab_bg.xml
+++ b/res/color-v31/all_apps_tab_text.xml
@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 The Android Open Source Project
+<!-- Copyright (C) 2021 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.
@@ -13,7 +13,7 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<selector xmlns:android="http://schemas.android.com/apk/res/android"
-        xmlns:androidprv="http://schemas.android.com/apk/prv/res/android">
-    <item android:color="?androidprv:attr/colorAccentPrimary"/>
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:color="@android:color/system_neutral1_900" android:state_selected="true"/>
+    <item android:color="@android:color/system_neutral2_700"/>
 </selector>
\ No newline at end of file
diff --git a/res/color/all_apps_tab_bg.xml b/res/color-v31/all_apps_tabs_background.xml
similarity index 76%
copy from res/color/all_apps_tab_bg.xml
copy to res/color-v31/all_apps_tabs_background.xml
index e59e8d2..30757b0 100644
--- a/res/color/all_apps_tab_bg.xml
+++ b/res/color-v31/all_apps_tabs_background.xml
@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 The Android Open Source Project
+<!-- Copyright (C) 2021 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.
@@ -13,7 +13,6 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<selector xmlns:android="http://schemas.android.com/apk/res/android"
-        xmlns:androidprv="http://schemas.android.com/apk/prv/res/android">
-    <item android:color="?androidprv:attr/colorAccentPrimary"/>
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:color="@android:color/system_neutral1_500" android:lStar="97" />
 </selector>
\ No newline at end of file
diff --git a/res/color/all_apps_tab_bg.xml b/res/color/all_apps_tab_background_selected.xml
similarity index 83%
rename from res/color/all_apps_tab_bg.xml
rename to res/color/all_apps_tab_background_selected.xml
index e59e8d2..5cb9bd8 100644
--- a/res/color/all_apps_tab_bg.xml
+++ b/res/color/all_apps_tab_background_selected.xml
@@ -13,7 +13,6 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<selector xmlns:android="http://schemas.android.com/apk/res/android"
-        xmlns:androidprv="http://schemas.android.com/apk/prv/res/android">
-    <item android:color="?androidprv:attr/colorAccentPrimary"/>
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:color="#8DF5E3"/>
 </selector>
\ No newline at end of file
diff --git a/res/color/all_apps_tab_text.xml b/res/color/all_apps_tab_text.xml
index 2db0fb5..dace380 100644
--- a/res/color/all_apps_tab_text.xml
+++ b/res/color/all_apps_tab_text.xml
@@ -14,6 +14,6 @@
      limitations under the License.
 -->
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
-    <item android:color="@android:color/black" android:state_selected="true"/>
-    <item android:color="?android:attr/textColorTertiary"/>
+    <item android:color="#1B1B1B" android:state_selected="true"/>
+    <item android:color="#464646"/>
 </selector>
\ No newline at end of file
diff --git a/res/color/all_apps_tab_bg.xml b/res/color/all_apps_tabs_background.xml
similarity index 77%
copy from res/color/all_apps_tab_bg.xml
copy to res/color/all_apps_tabs_background.xml
index e59e8d2..a4b7d1f 100644
--- a/res/color/all_apps_tab_bg.xml
+++ b/res/color/all_apps_tabs_background.xml
@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 The Android Open Source Project
+<!-- Copyright (C) 2021 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.
@@ -13,7 +13,6 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<selector xmlns:android="http://schemas.android.com/apk/res/android"
-        xmlns:androidprv="http://schemas.android.com/apk/prv/res/android">
-    <item android:color="?androidprv:attr/colorAccentPrimary"/>
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:color="#F6F6F6"/>
 </selector>
\ No newline at end of file
diff --git a/res/drawable/all_apps_tabs_background.xml b/res/drawable/all_apps_tabs_background.xml
index a345dd3..4e95315 100644
--- a/res/drawable/all_apps_tabs_background.xml
+++ b/res/drawable/all_apps_tabs_background.xml
@@ -13,14 +13,12 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:androidprv="http://schemas.android.com/apk/prv/res/android">
+<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
     <item
         android:top="@dimen/all_apps_tabs_vertical_padding"
-        android:bottom="@dimen/all_apps_tabs_vertical_padding
-">
+        android:bottom="@dimen/all_apps_tabs_vertical_padding">
         <shape android:shape="rectangle">
-            <solid android:color="?androidprv:attr/colorSurface" />
+            <solid android:color="@color/all_apps_tabs_background" />
             <corners android:radius="@dimen/all_apps_header_pill_corner_radius" />
         </shape>
     </item>
diff --git a/res/drawable/work_apps_toggle_background.xml b/res/drawable/work_apps_toggle_background.xml
new file mode 100644
index 0000000..a04d269
--- /dev/null
+++ b/res/drawable/work_apps_toggle_background.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2021 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.
+-->
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:state_enabled="false">
+        <shape android:shape="rectangle">
+            <corners android:radius="@dimen/work_fab_radius" />
+            <solid android:color="?android:attr/colorControlHighlight" />
+            <padding android:left="@dimen/work_fab_radius" android:right="@dimen/work_fab_radius" />
+        </shape>
+    </item>
+    <item>
+        <shape android:shape="rectangle">
+            <corners android:radius="@dimen/work_fab_radius" />
+            <solid android:color="?android:attr/colorAccent" />
+            <padding android:left="@dimen/work_fab_radius" android:right="@dimen/work_fab_radius" />
+        </shape>
+    </item>
+</selector>
diff --git a/res/layout/work_mode_fab.xml b/res/layout/work_mode_fab.xml
new file mode 100644
index 0000000..21f269f
--- /dev/null
+++ b/res/layout/work_mode_fab.xml
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
+<com.android.launcher3.allapps.WorkModeSwitch
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/work_mode_toggle"
+    android:layout_alignParentBottom="true"
+    android:layout_alignParentEnd="true"
+    android:layout_height="@dimen/work_fab_height"
+    android:layout_width="wrap_content"
+    android:gravity="center"
+    android:includeFontPadding="false"
+    android:drawableTint="@android:color/white"
+    android:textColor="@android:color/white"
+    android:background="@drawable/work_apps_toggle_background"
+    android:drawablePadding="16dp"
+    android:drawableStart="@drawable/ic_corp_off"
+    android:elevation="10dp"
+    android:layout_marginBottom="@dimen/work_fab_margin"
+    android:layout_marginEnd="@dimen/work_fab_margin"
+    android:text="@string/work_apps_pause_btn_text" />
\ No newline at end of file
diff --git a/res/layout/work_mode_switch.xml b/res/layout/work_mode_switch.xml
index 31953c7..538a180 100644
--- a/res/layout/work_mode_switch.xml
+++ b/res/layout/work_mode_switch.xml
@@ -1,5 +1,4 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 The Android Open Source Project
+<?xml version="1.0" encoding="utf-8"?><!-- 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.
@@ -13,8 +12,7 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<com.android.launcher3.allapps.WorkModeSwitch
-    xmlns:android="http://schemas.android.com/apk/res/android"
+<com.android.launcher3.allapps.WorkModeSwitch xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     style="@style/PrimaryHeadline"
@@ -35,5 +33,4 @@
     android:paddingBottom="@dimen/work_profile_footer_padding"
     android:paddingLeft="@dimen/work_profile_footer_padding"
     android:paddingRight="@dimen/work_profile_footer_padding"
-    android:paddingTop="@dimen/work_profile_footer_padding"
-/>
+    android:paddingTop="@dimen/work_profile_footer_padding" />
diff --git a/res/layout/work_profile_edu.xml b/res/layout/work_profile_edu.xml
deleted file mode 100644
index c3c7010..0000000
--- a/res/layout/work_profile_edu.xml
+++ /dev/null
@@ -1,61 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?><!-- Copyright (C) 2020 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.
--->
-<com.android.launcher3.views.WorkEduView xmlns:android="http://schemas.android.com/apk/res/android"
-    android:layout_width="match_parent"
-    android:layout_height="wrap_content"
-    android:layout_gravity="bottom"
-    android:gravity="bottom"
-    android:orientation="vertical">
-
-    <View
-        android:layout_width="match_parent"
-        android:layout_height="32dp"
-        android:background="@drawable/bottom_sheet_top_border"
-        android:backgroundTint="?attr/eduHalfSheetBGColor" />
-
-    <LinearLayout
-        android:id="@+id/view_wrapper"
-        android:layout_width="match_parent"
-        android:layout_height="wrap_content"
-        android:background="?attr/eduHalfSheetBGColor"
-        android:orientation="vertical"
-        android:paddingLeft="@dimen/bottom_sheet_edu_padding"
-        android:paddingRight="@dimen/bottom_sheet_edu_padding">
-
-        <TextView
-            android:id="@+id/content_text"
-            style="@style/TextHeadline"
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:layout_marginTop="48dp"
-            android:layout_marginBottom="48dp"
-            android:gravity="center"
-            android:text="@string/work_profile_edu_personal_apps"
-            android:textAlignment="center"
-            android:textColor="@android:color/white"
-            android:textSize="20sp" />
-
-        <Button
-            android:id="@+id/proceed"
-            android:layout_width="wrap_content"
-            android:layout_height="48dp"
-            android:layout_gravity="end"
-            android:background="?android:attr/selectableItemBackground"
-            android:gravity="center"
-            android:text="@string/work_profile_edu_next"
-            android:textAlignment="center"
-            android:textColor="@android:color/white" />
-    </LinearLayout>
-</com.android.launcher3.views.WorkEduView>
\ No newline at end of file
diff --git a/res/values/dimens.xml b/res/values/dimens.xml
index 29a8016..06bdd49 100644
--- a/res/values/dimens.xml
+++ b/res/values/dimens.xml
@@ -116,6 +116,10 @@
 
     <dimen name="all_apps_divider_margin_vertical">8dp</dimen>
 
+<!-- Floating action button inside work tab to toggle work profile -->
+    <dimen name="work_fab_height">48dp</dimen>
+    <dimen name="work_fab_radius">24dp</dimen>
+    <dimen name="work_fab_margin">18dp</dimen>
     <dimen name="work_profile_footer_padding">20dp</dimen>
     <dimen name="work_profile_footer_text_size">16sp</dimen>
 
diff --git a/res/values/strings.xml b/res/values/strings.xml
index ee0b64a..9cfe69a 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -388,37 +388,30 @@
 
     <!-- This string is in the work profile tab when a user has All Apps open on their phone. This is a label for a toggle to turn the work profile on and off. "Work profile" means a separate profile on a user's phone that's specifically for their work apps and managed by their company. "Work" is used as an adjective.-->
     <string name="work_profile_toggle_label">Work profile</string>
-    <!--- User onboarding title for personal apps -->
-    <string name="work_profile_edu_personal_apps">Personal data is separate &amp; hidden from work apps</string>
     <!--- User onboarding title for work profile apps -->
-    <string name="work_profile_edu_work_apps">Work apps &amp; data are visible to your IT admin</string>
-    <!-- Action label to proceed to the next work profile edu section-->
-    <string name="work_profile_edu_next">Next</string>
+    <string name="work_profile_edu_work_apps">Work apps are badged andare visible to your IT admin</string>
     <!-- Action label to finish work profile edu-->
     <string name="work_profile_edu_accept">Got it</string>
 
     <!--- heading shown when user opens work apps tab while work apps are paused -->
-    <string name="work_apps_paused_title">Work profile is paused</string>
+    <string name="work_apps_paused_title">Work apps are off</string>
     <!--- body shown when user opens work apps tab while work apps are paused -->
-    <string name="work_apps_paused_body">Work apps can’t send you notifications, use your battery, or access your location</string>
+    <string name="work_apps_paused_body">Your work apps can’t send you notifications, use your battery, or access your location</string>
     <!-- content description for paused work apps list -->
-    <string name="work_apps_paused_content_description">Work profile is paused. Work apps can’t send you notifications, use your battery, or access your location</string>
+    <string name="work_apps_paused_content_description">Work apps are off. Your work apps can’t send you notifications, use your battery, or access your location</string>
     <!-- string shown in educational banner about work profile -->
     <string name="work_apps_paused_edu_banner">Work apps are badged and visible to your IT admin</string>
     <!-- button string shown to dismiss work tab education -->
     <string name="work_apps_paused_edu_accept">Got it</string>
 
     <!-- button string shown pause work profile -->
-    <string name="work_apps_pause_btn_text">Pause work apps</string>
+    <string name="work_apps_pause_btn_text">Turn off work apps</string>
     <!-- button string shown enable work profile -->
-    <string name="work_apps_enable_btn_text">Turn on</string>
+    <string name="work_apps_enable_btn_text">Turn on work apps</string>
 
     <!-- A hint shown in launcher settings develop options filter box -->
     <string name="developer_options_filter_hint">Filter</string>
 
-    <!-- A tip shown pointing at work toggle -->
-    <string name="work_switch_tip">Pause work apps and notifications</string>
-
     <!-- Failed action error message: e.g. Failed: Pause -->
     <string name="remote_action_failed">Failed: <xliff:g id="what" example="Pause">%1$s</xliff:g></string>
 </resources>
diff --git a/src/com/android/launcher3/Utilities.java b/src/com/android/launcher3/Utilities.java
index cb9e1f3..a2d86bc 100644
--- a/src/com/android/launcher3/Utilities.java
+++ b/src/com/android/launcher3/Utilities.java
@@ -397,6 +397,13 @@
         return mapRange(interpolator.getInterpolation(progress), toMin, toMax);
     }
 
+    /** Bounds t between a lower and upper bound and maps the result to a range. */
+    public static float mapBoundToRange(float t, float lowerBound, float upperBound,
+            float toMin, float toMax, Interpolator interpolator) {
+        return mapToRange(boundToRange(t, lowerBound, upperBound), lowerBound, upperBound,
+                toMin, toMax, interpolator);
+    }
+
     public static float getProgress(float current, float min, float max) {
         return Math.abs(current - min) / Math.abs(max - min);
     }
diff --git a/src/com/android/launcher3/Workspace.java b/src/com/android/launcher3/Workspace.java
index 17c8edc..2e1cc58 100644
--- a/src/com/android/launcher3/Workspace.java
+++ b/src/com/android/launcher3/Workspace.java
@@ -1922,6 +1922,11 @@
                     CellLayout layout = (CellLayout) cell.getParent().getParent();
                     layout.markCellsAsOccupiedForView(cell);
                 }
+            } else {
+                // When drag is cancelled, reattach content view back to its original parent.
+                if (mDragInfo.cell instanceof LauncherAppWidgetHostView) {
+                    d.dragView.detachContentView(/* reattachToPreviousParent= */ true);
+                }
             }
 
             final CellLayout parent = (CellLayout) cell.getParent().getParent();
diff --git a/src/com/android/launcher3/allapps/AllAppsContainerView.java b/src/com/android/launcher3/allapps/AllAppsContainerView.java
index 681f5e7..7249aaf 100644
--- a/src/com/android/launcher3/allapps/AllAppsContainerView.java
+++ b/src/com/android/launcher3/allapps/AllAppsContainerView.java
@@ -228,7 +228,7 @@
     }
 
     private void resetWorkProfile() {
-        mWorkModeSwitch.update(!mAllAppsStore.hasModelFlag(FLAG_QUIET_MODE_ENABLED));
+        mWorkModeSwitch.updateCurrentState(!mAllAppsStore.hasModelFlag(FLAG_QUIET_MODE_ENABLED));
         mAH[AdapterHolder.WORK].setupOverlay();
         mAH[AdapterHolder.WORK].applyPadding();
     }
@@ -482,7 +482,7 @@
     private void setupWorkToggle() {
         if (Utilities.ATLEAST_P) {
             mWorkModeSwitch = (WorkModeSwitch) mLauncher.getLayoutInflater().inflate(
-                    R.layout.work_mode_switch, this, false);
+                    R.layout.work_mode_fab, this, false);
             this.addView(mWorkModeSwitch);
             mWorkModeSwitch.setInsets(mInsets);
             mWorkModeSwitch.post(this::resetWorkProfile);
diff --git a/src/com/android/launcher3/allapps/LauncherAllAppsContainerView.java b/src/com/android/launcher3/allapps/LauncherAllAppsContainerView.java
index 16ae250..1eb726c 100644
--- a/src/com/android/launcher3/allapps/LauncherAllAppsContainerView.java
+++ b/src/com/android/launcher3/allapps/LauncherAllAppsContainerView.java
@@ -25,7 +25,6 @@
 import com.android.launcher3.Launcher;
 import com.android.launcher3.LauncherState;
 import com.android.launcher3.statemanager.StateManager.StateListener;
-import com.android.launcher3.views.WorkEduView;
 
 /**
  * AllAppsContainerView with launcher specific callbacks
@@ -88,13 +87,6 @@
     @Override
     public void onActivePageChanged(int currentActivePage) {
         super.onActivePageChanged(currentActivePage);
-        if (mUsingTabs) {
-            if (currentActivePage == AdapterHolder.WORK) {
-                WorkEduView.showWorkEduIfNeeded(mLauncher);
-            } else {
-                mWorkTabListener = WorkEduView.showEduFlowIfNeeded(mLauncher, mWorkTabListener);
-            }
-        }
     }
 
     @Override
diff --git a/src/com/android/launcher3/allapps/WorkModeSwitch.java b/src/com/android/launcher3/allapps/WorkModeSwitch.java
index 4567ee6..c22cd63 100644
--- a/src/com/android/launcher3/allapps/WorkModeSwitch.java
+++ b/src/com/android/launcher3/allapps/WorkModeSwitch.java
@@ -15,108 +15,61 @@
  */
 package com.android.launcher3.allapps;
 
+import static com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR;
+
 import android.content.Context;
-import android.content.SharedPreferences;
 import android.graphics.Rect;
-import android.os.AsyncTask;
+import android.os.Build;
 import android.os.Process;
 import android.os.UserHandle;
 import android.os.UserManager;
 import android.util.AttributeSet;
-import android.view.MotionEvent;
-import android.view.ViewConfiguration;
-import android.widget.Switch;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+
+import androidx.annotation.RequiresApi;
 
 import com.android.launcher3.Insettable;
 import com.android.launcher3.R;
 import com.android.launcher3.Utilities;
 import com.android.launcher3.pm.UserCache;
-import com.android.launcher3.views.ArrowTipView;
-
-import java.lang.ref.WeakReference;
 
 /**
  * Work profile toggle switch shown at the bottom of AllApps work tab
  */
-public class WorkModeSwitch extends Switch implements Insettable {
-
-    private static final int WORK_TIP_THRESHOLD = 2;
-    public static final String KEY_WORK_TIP_COUNTER = "worked_tip_counter";
+public class WorkModeSwitch extends Button implements Insettable, View.OnClickListener {
 
     private Rect mInsets = new Rect();
-
-    private final float[] mTouch = new float[2];
-    private int mTouchSlop;
+    private boolean mWorkEnabled;
 
     public WorkModeSwitch(Context context) {
-        super(context);
-        init();
+        this(context, null, 0);
     }
 
     public WorkModeSwitch(Context context, AttributeSet attrs) {
-        super(context, attrs);
-        init();
+        this(context, attrs, 0);
     }
 
     public WorkModeSwitch(Context context, AttributeSet attrs, int defStyleAttr) {
         super(context, attrs, defStyleAttr);
-        init();
-    }
-
-    private void init() {
-        ViewConfiguration viewConfiguration = ViewConfiguration.get(getContext());
-        mTouchSlop = viewConfiguration.getScaledTouchSlop();
     }
 
     @Override
-    public void setChecked(boolean checked) { }
-
-    @Override
-    public void toggle() {
-        // don't show tip if user uses toggle
-        Utilities.getPrefs(getContext()).edit().putInt(KEY_WORK_TIP_COUNTER, -1).apply();
-        trySetQuietModeEnabledToAllProfilesAsync(isChecked());
-    }
-
-    /**
-     * Sets the enabled or disabled state of the button
-     * @param isChecked
-     */
-    public void update(boolean isChecked) {
-        super.setChecked(isChecked);
-        setCompoundDrawablesRelativeWithIntrinsicBounds(
-                isChecked ? R.drawable.ic_corp : R.drawable.ic_corp_off, 0, 0, 0);
-        setEnabled(true);
-    }
-
-    @Override
-    public boolean onTouchEvent(MotionEvent ev) {
-        if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) {
-            mTouch[0] = ev.getX();
-            mTouch[1] = ev.getY();
-        } else if (ev.getActionMasked() == MotionEvent.ACTION_MOVE) {
-            if (Math.abs(mTouch[0] - ev.getX()) > mTouchSlop
-                    || Math.abs(mTouch[1] - ev.getY()) > mTouchSlop) {
-                int action = ev.getAction();
-                ev.setAction(MotionEvent.ACTION_CANCEL);
-                super.onTouchEvent(ev);
-                ev.setAction(action);
-                return false;
-            }
-        }
-        return super.onTouchEvent(ev);
-    }
-
-    private void trySetQuietModeEnabledToAllProfilesAsync(boolean enabled) {
-        new SetQuietModeEnabledAsyncTask(enabled, new WeakReference<>(this)).execute();
+    protected void onFinishInflate() {
+        super.onFinishInflate();
+        setOnClickListener(this);
     }
 
     @Override
     public void setInsets(Rect insets) {
         int bottomInset = insets.bottom - mInsets.bottom;
         mInsets.set(insets);
-        setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(),
-                getPaddingBottom() + bottomInset);
+        ViewGroup.MarginLayoutParams marginLayoutParams =
+                (ViewGroup.MarginLayoutParams) getLayoutParams();
+        if (marginLayoutParams != null) {
+            marginLayoutParams.bottomMargin = bottomInset + marginLayoutParams.bottomMargin;
+        }
     }
 
     /**
@@ -125,78 +78,44 @@
     public void setWorkTabVisible(boolean workTabVisible) {
         clearAnimation();
         if (workTabVisible) {
+            setEnabled(true);
             setVisibility(VISIBLE);
             setAlpha(0);
             animate().alpha(1).start();
-            showTipIfNeeded();
         } else {
             animate().alpha(0).withEndAction(() -> this.setVisibility(GONE)).start();
         }
     }
 
-    private static final class SetQuietModeEnabledAsyncTask
-            extends AsyncTask<Void, Void, Boolean> {
-
-        private final boolean enabled;
-        private final WeakReference<WorkModeSwitch> switchWeakReference;
-
-        SetQuietModeEnabledAsyncTask(boolean enabled,
-                                     WeakReference<WorkModeSwitch> switchWeakReference) {
-            this.enabled = enabled;
-            this.switchWeakReference = switchWeakReference;
-        }
-
-        @Override
-        protected void onPreExecute() {
-            super.onPreExecute();
-            WorkModeSwitch workModeSwitch = switchWeakReference.get();
-            if (workModeSwitch != null) {
-                workModeSwitch.setEnabled(false);
-            }
-        }
-
-        @Override
-        protected Boolean doInBackground(Void... voids) {
-            WorkModeSwitch workModeSwitch = switchWeakReference.get();
-            if (workModeSwitch == null || !Utilities.ATLEAST_P) {
-                return false;
-            }
-
-            Context context = workModeSwitch.getContext();
-            UserManager userManager = context.getSystemService(UserManager.class);
-            boolean showConfirm = false;
-            for (UserHandle userProfile : UserCache.INSTANCE.get(context).getUserProfiles()) {
-                if (Process.myUserHandle().equals(userProfile)) {
-                    continue;
-                }
-                showConfirm |= !userManager.requestQuietModeEnabled(enabled, userProfile);
-            }
-            return showConfirm;
-        }
-
-        @Override
-        protected void onPostExecute(Boolean showConfirm) {
-            if (showConfirm) {
-                WorkModeSwitch workModeSwitch = switchWeakReference.get();
-                if (workModeSwitch != null) {
-                    workModeSwitch.setEnabled(true);
-                }
-            }
+    @Override
+    public void onClick(View view) {
+        if (Utilities.ATLEAST_P) {
+            setEnabled(false);
+            UI_HELPER_EXECUTOR.post(() -> setToState(!mWorkEnabled));
         }
     }
 
     /**
-     * Shows a work tip on the Nth work tab open
+     * Sets the enabled or disabled state of the button
      */
-    public void showTipIfNeeded() {
-        Context context = getContext();
-        SharedPreferences prefs = Utilities.getPrefs(context);
-        int tipCounter = prefs.getInt(KEY_WORK_TIP_COUNTER, WORK_TIP_THRESHOLD);
-        if (tipCounter < 0) return;
-        if (tipCounter == 0) {
-            new ArrowTipView(context)
-                    .show(context.getString(R.string.work_switch_tip), getTop());
+    public void updateCurrentState(boolean active) {
+        mWorkEnabled = active;
+        setEnabled(true);
+        setCompoundDrawablesRelativeWithIntrinsicBounds(
+                active ? R.drawable.ic_corp_off : R.drawable.ic_corp, 0, 0, 0);
+        setText(active ? R.string.work_apps_pause_btn_text : R.string.work_apps_enable_btn_text);
+    }
+
+    @RequiresApi(Build.VERSION_CODES.P)
+    protected Boolean setToState(boolean toState) {
+        UserManager userManager = getContext().getSystemService(UserManager.class);
+        boolean showConfirm = false;
+        for (UserHandle userProfile : UserCache.INSTANCE.get(getContext()).getUserProfiles()) {
+            if (Process.myUserHandle().equals(userProfile)) {
+                continue;
+            }
+            showConfirm |= !userManager.requestQuietModeEnabled(!toState, userProfile);
         }
-        prefs.edit().putInt(KEY_WORK_TIP_COUNTER, tipCounter - 1).apply();
+        return showConfirm;
     }
 }
diff --git a/src/com/android/launcher3/views/RecyclerViewFastScroller.java b/src/com/android/launcher3/views/RecyclerViewFastScroller.java
index e607ab3..f49d1b5 100644
--- a/src/com/android/launcher3/views/RecyclerViewFastScroller.java
+++ b/src/com/android/launcher3/views/RecyclerViewFastScroller.java
@@ -28,6 +28,7 @@
 import android.graphics.Point;
 import android.graphics.Rect;
 import android.graphics.RectF;
+import android.os.Build;
 import android.util.AttributeSet;
 import android.util.Property;
 import android.view.MotionEvent;
@@ -37,6 +38,7 @@
 import android.widget.TextView;
 
 import androidx.annotation.Nullable;
+import androidx.annotation.RequiresApi;
 import androidx.recyclerview.widget.RecyclerView;
 
 import com.android.launcher3.BaseRecyclerView;
@@ -342,16 +344,21 @@
             // swiping very close to the thumb area (not just within it's bound)
             // will also prevent back gesture
             SYSTEM_GESTURE_EXCLUSION_RECT.get(0).offset(mThumbDrawOffset.x, mThumbDrawOffset.y);
-            SYSTEM_GESTURE_EXCLUSION_RECT.get(0).left = SYSTEM_GESTURE_EXCLUSION_RECT.get(0).right
-                    - mSystemGestureInsets.right;
+            if (Utilities.ATLEAST_Q) {
+                SYSTEM_GESTURE_EXCLUSION_RECT.get(0).left =
+                        SYSTEM_GESTURE_EXCLUSION_RECT.get(0).right - mSystemGestureInsets.right;
+            }
             setSystemGestureExclusionRects(SYSTEM_GESTURE_EXCLUSION_RECT);
         }
         canvas.restoreToCount(saveCount);
     }
 
     @Override
+    @RequiresApi(Build.VERSION_CODES.Q)
     public WindowInsets onApplyWindowInsets(WindowInsets insets) {
-        mSystemGestureInsets = insets.getSystemGestureInsets();
+        if (Utilities.ATLEAST_Q) {
+            mSystemGestureInsets = insets.getSystemGestureInsets();
+        }
         return super.onApplyWindowInsets(insets);
     }
 
diff --git a/src/com/android/launcher3/views/WorkEduView.java b/src/com/android/launcher3/views/WorkEduView.java
deleted file mode 100644
index 6be0c23..0000000
--- a/src/com/android/launcher3/views/WorkEduView.java
+++ /dev/null
@@ -1,230 +0,0 @@
-/*
- * Copyright (C) 2020 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.launcher3.views;
-
-
-import android.animation.Animator;
-import android.animation.ObjectAnimator;
-import android.animation.PropertyValuesHolder;
-import android.content.Context;
-import android.graphics.Rect;
-import android.util.AttributeSet;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.widget.Button;
-import android.widget.TextView;
-
-import androidx.annotation.Nullable;
-
-import com.android.launcher3.Insettable;
-import com.android.launcher3.Launcher;
-import com.android.launcher3.LauncherState;
-import com.android.launcher3.R;
-import com.android.launcher3.allapps.AllAppsContainerView;
-import com.android.launcher3.allapps.AllAppsPagedView;
-import com.android.launcher3.anim.AnimationSuccessListener;
-import com.android.launcher3.anim.Interpolators;
-import com.android.launcher3.statemanager.StateManager.StateListener;
-
-/**
- * On boarding flow for users right after setting up work profile
- */
-public class WorkEduView extends AbstractSlideInView<Launcher>
-        implements Insettable, StateListener<LauncherState> {
-
-    private static final int DEFAULT_CLOSE_DURATION = 200;
-    public static final String KEY_WORK_EDU_STEP = "showed_work_profile_edu";
-    public static final String KEY_LEGACY_WORK_EDU_SEEN = "showed_bottom_user_education";
-
-    private static final int WORK_EDU_NOT_STARTED = 0;
-    private static final int WORK_EDU_PERSONAL_APPS = 1;
-    private static final int WORK_EDU_WORK_APPS = 2;
-
-    protected static final int FINAL_SCRIM_BG_COLOR = 0x88000000;
-
-
-    private Rect mInsets = new Rect();
-    private View mViewWrapper;
-    private Button mProceedButton;
-    private TextView mContentText;
-
-    private int mNextWorkEduStep = WORK_EDU_PERSONAL_APPS;
-
-
-    public WorkEduView(Context context, AttributeSet attr) {
-        this(context, attr, 0);
-    }
-
-    public WorkEduView(Context context, AttributeSet attrs,
-            int defStyleAttr) {
-        super(context, attrs, defStyleAttr);
-        mContent = this;
-    }
-
-    @Override
-    protected void handleClose(boolean animate) {
-        mActivityContext.getSharedPrefs().edit()
-                .putInt(KEY_WORK_EDU_STEP, mNextWorkEduStep).apply();
-        handleClose(true, DEFAULT_CLOSE_DURATION);
-    }
-
-    @Override
-    protected void onCloseComplete() {
-        super.onCloseComplete();
-        mActivityContext.getStateManager().removeStateListener(this);
-    }
-
-    @Override
-    protected boolean isOfType(int type) {
-        return (type & TYPE_ON_BOARD_POPUP) != 0;
-    }
-
-    @Override
-    protected void onFinishInflate() {
-        super.onFinishInflate();
-        mViewWrapper = findViewById(R.id.view_wrapper);
-        mProceedButton = findViewById(R.id.proceed);
-        mContentText = findViewById(R.id.content_text);
-
-        // make sure layout does not shrink when we change the text
-        mContentText.post(() -> mContentText.setMinLines(mContentText.getLineCount()));
-
-        mProceedButton.setOnClickListener(view -> {
-            if (getAllAppsPagedView() != null) {
-                getAllAppsPagedView().snapToPage(AllAppsContainerView.AdapterHolder.WORK);
-            }
-            goToWorkTab(true);
-        });
-    }
-
-    private void goToWorkTab(boolean animate) {
-        mProceedButton.setText(R.string.work_profile_edu_accept);
-        if (animate) {
-            ObjectAnimator animator = ObjectAnimator.ofFloat(mContentText, ALPHA, 0);
-            animator.addListener(new AnimationSuccessListener() {
-                @Override
-                public void onAnimationSuccess(Animator animator) {
-                    mContentText.setText(
-                            mActivityContext.getString(R.string.work_profile_edu_work_apps));
-                    ObjectAnimator.ofFloat(mContentText, ALPHA, 1).start();
-                }
-            });
-            animator.start();
-        } else {
-            mContentText.setText(mActivityContext.getString(R.string.work_profile_edu_work_apps));
-        }
-        mNextWorkEduStep = WORK_EDU_WORK_APPS;
-        mProceedButton.setOnClickListener(v -> handleClose(true));
-    }
-
-    @Override
-    public void setInsets(Rect insets) {
-        int leftInset = insets.left - mInsets.left;
-        int rightInset = insets.right - mInsets.right;
-        int bottomInset = insets.bottom - mInsets.bottom;
-        mInsets.set(insets);
-        setPadding(leftInset, getPaddingTop(), rightInset, 0);
-        mViewWrapper.setPaddingRelative(mViewWrapper.getPaddingStart(),
-                mViewWrapper.getPaddingTop(), mViewWrapper.getPaddingEnd(), bottomInset);
-    }
-
-    private void show() {
-        attachToContainer();
-        animateOpen();
-        mActivityContext.getStateManager().addStateListener(this);
-    }
-
-    @Override
-    protected int getScrimColor(Context context) {
-        return FINAL_SCRIM_BG_COLOR;
-    }
-
-    private void goToFirstPage() {
-        if (getAllAppsPagedView() != null) {
-            getAllAppsPagedView().snapToPageImmediately(AllAppsContainerView.AdapterHolder.MAIN);
-        }
-    }
-
-    private void animateOpen() {
-        if (mIsOpen || mOpenCloseAnimator.isRunning()) {
-            return;
-        }
-        mIsOpen = true;
-        mOpenCloseAnimator.setValues(
-                PropertyValuesHolder.ofFloat(TRANSLATION_SHIFT, TRANSLATION_SHIFT_OPENED));
-        mOpenCloseAnimator.setInterpolator(Interpolators.FAST_OUT_SLOW_IN);
-        mOpenCloseAnimator.start();
-    }
-
-    private AllAppsPagedView getAllAppsPagedView() {
-        View v = mActivityContext.getAppsView().getContentView();
-        return (v instanceof AllAppsPagedView) ? (AllAppsPagedView) v : null;
-    }
-
-    /**
-     * Checks if user has not seen onboarding UI yet and shows it when user navigates to all apps
-     */
-    public static StateListener<LauncherState> showEduFlowIfNeeded(Launcher launcher,
-            @Nullable StateListener<LauncherState> oldListener) {
-        if (oldListener != null) {
-            launcher.getStateManager().removeStateListener(oldListener);
-        }
-        if (hasSeenLegacyEdu(launcher) || launcher.getSharedPrefs().getInt(KEY_WORK_EDU_STEP,
-                WORK_EDU_NOT_STARTED) != WORK_EDU_NOT_STARTED) {
-            return null;
-        }
-
-        StateListener<LauncherState> listener = new StateListener<LauncherState>() {
-            @Override
-            public void onStateTransitionComplete(LauncherState finalState) {
-                if (finalState != LauncherState.ALL_APPS) return;
-                LayoutInflater layoutInflater = LayoutInflater.from(launcher);
-                WorkEduView v = (WorkEduView) layoutInflater.inflate(
-                        R.layout.work_profile_edu, launcher.getDragLayer(),
-                        false);
-                v.show();
-                v.goToFirstPage();
-                launcher.getStateManager().removeStateListener(this);
-            }
-        };
-        launcher.getStateManager().addStateListener(listener);
-        return listener;
-    }
-
-    /**
-     * Shows work apps edu if user had dismissed full edu flow
-     */
-    public static void showWorkEduIfNeeded(Launcher launcher) {
-        if (hasSeenLegacyEdu(launcher) || launcher.getSharedPrefs().getInt(KEY_WORK_EDU_STEP,
-                WORK_EDU_NOT_STARTED) != WORK_EDU_PERSONAL_APPS) {
-            return;
-        }
-        LayoutInflater layoutInflater = LayoutInflater.from(launcher);
-        WorkEduView v = (WorkEduView) layoutInflater.inflate(
-                R.layout.work_profile_edu, launcher.getDragLayer(), false);
-        v.show();
-        v.goToWorkTab(false);
-    }
-
-    private static boolean hasSeenLegacyEdu(Launcher launcher) {
-        return launcher.getSharedPrefs().getBoolean(KEY_LEGACY_WORK_EDU_SEEN, false);
-    }
-
-    @Override
-    public void onStateTransitionComplete(LauncherState finalState) {
-        close(false);
-    }
-}
diff --git a/src/com/android/launcher3/widget/LauncherAppWidgetHost.java b/src/com/android/launcher3/widget/LauncherAppWidgetHost.java
index d745754..6dc6971 100644
--- a/src/com/android/launcher3/widget/LauncherAppWidgetHost.java
+++ b/src/com/android/launcher3/widget/LauncherAppWidgetHost.java
@@ -25,15 +25,20 @@
 import android.content.ActivityNotFoundException;
 import android.content.Context;
 import android.content.Intent;
+import android.os.Bundle;
 import android.os.Handler;
 import android.util.SparseArray;
 import android.widget.Toast;
 
+import androidx.annotation.Nullable;
+
 import com.android.launcher3.BaseActivity;
+import com.android.launcher3.BaseDraggingActivity;
 import com.android.launcher3.LauncherAppState;
 import com.android.launcher3.R;
 import com.android.launcher3.Utilities;
 import com.android.launcher3.model.WidgetsModel;
+import com.android.launcher3.model.data.ItemInfo;
 import com.android.launcher3.testing.TestLogging;
 import com.android.launcher3.testing.TestProtocol;
 import com.android.launcher3.widget.custom.CustomWidgetManager;
@@ -292,8 +297,13 @@
         activity.startActivityForResult(intent, requestCode);
     }
 
-
-    public void startConfigActivity(BaseActivity activity, int widgetId, int requestCode) {
+    /**
+     * Launches an app widget's configuration activity.
+     * @param activity The activity from which to launch the configuration activity
+     * @param widgetId The id of the bound app widget to be configured
+     * @param requestCode An optional request code to be returned with the result
+     */
+    public void startConfigActivity(BaseDraggingActivity activity, int widgetId, int requestCode) {
         if (WidgetsModel.GO_DISABLE_WIDGETS) {
             sendActionCancelled(activity, requestCode);
             return;
@@ -301,13 +311,27 @@
 
         try {
             TestLogging.recordEvent(TestProtocol.SEQUENCE_MAIN, "start: startConfigActivity");
-            startAppWidgetConfigureActivityForResult(activity, widgetId, 0, requestCode, null);
+            startAppWidgetConfigureActivityForResult(activity, widgetId, 0, requestCode,
+                    getConfigurationActivityOptions(activity, widgetId));
         } catch (ActivityNotFoundException | SecurityException e) {
             Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
             sendActionCancelled(activity, requestCode);
         }
     }
 
+    /**
+     * Returns an {@link android.app.ActivityOptions} bundle from the {code activity} for launching
+     * the configuration of the {@code widgetId} app widget, or null of options cannot be produced.
+     */
+    @Nullable
+    private Bundle getConfigurationActivityOptions(BaseDraggingActivity activity, int widgetId) {
+        LauncherAppWidgetHostView view = mViews.get(widgetId);
+        if (view == null) return null;
+        Object tag = view.getTag();
+        if (!(tag instanceof ItemInfo)) return null;
+        return activity.getActivityLaunchOptions(view, (ItemInfo) tag).toBundle();
+    }
+
     private void sendActionCancelled(final BaseActivity activity, final int requestCode) {
         new Handler().post(() -> activity.onActivityResult(requestCode, RESULT_CANCELED, null));
     }
diff --git a/src/com/android/launcher3/widget/picker/WidgetsListAdapter.java b/src/com/android/launcher3/widget/picker/WidgetsListAdapter.java
index 150bd99..e89aea7 100644
--- a/src/com/android/launcher3/widget/picker/WidgetsListAdapter.java
+++ b/src/com/android/launcher3/widget/picker/WidgetsListAdapter.java
@@ -298,6 +298,12 @@
         scrollToPositionAndMaintainOffset(positionForPackageUserKey, topForPackageUserKey);
     }
 
+    /** Returns the position of the currently expanded header, or empty if it's not present. */
+    public OptionalInt getSelectedHeaderPosition() {
+        if (mWidgetsContentVisiblePackageUserKey == null) return OptionalInt.empty();
+        return getPositionForPackageUserKey(mWidgetsContentVisiblePackageUserKey);
+    }
+
     /**
      * Returns the position of {@code key} in {@link #mVisibleEntries}, or  empty if it's not
      * present.
diff --git a/src/com/android/launcher3/widget/picker/WidgetsListLayoutManager.java b/src/com/android/launcher3/widget/picker/WidgetsListLayoutManager.java
new file mode 100644
index 0000000..2b7f544
--- /dev/null
+++ b/src/com/android/launcher3/widget/picker/WidgetsListLayoutManager.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2021 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.launcher3.widget.picker;
+
+import android.content.Context;
+
+import androidx.annotation.Nullable;
+import androidx.recyclerview.widget.LinearLayoutManager;
+import androidx.recyclerview.widget.RecyclerView;
+
+import com.android.launcher3.widget.picker.SearchAndRecommendationsScrollController.OnContentChangeListener;
+
+/**
+ * A layout manager for the {@link WidgetsRecyclerView}.
+ *
+ * {@link #setOnContentChangeListener(OnContentChangeListener)} can be used to register a callback
+ * for when the content of the layout manager has changed, following measurement and animation.
+ */
+public final class WidgetsListLayoutManager extends LinearLayoutManager {
+    @Nullable
+    private OnContentChangeListener mOnContentChangeListener;
+
+    public WidgetsListLayoutManager(Context context) {
+        super(context);
+    }
+
+    @Override
+    public void onLayoutCompleted(RecyclerView.State state) {
+        super.onLayoutCompleted(state);
+        if (mOnContentChangeListener != null) {
+            mOnContentChangeListener.onContentChanged();
+        }
+    }
+
+    public void setOnContentChangeListener(@Nullable OnContentChangeListener listener) {
+        mOnContentChangeListener = listener;
+    }
+}
diff --git a/src/com/android/launcher3/widget/picker/WidgetsRecyclerView.java b/src/com/android/launcher3/widget/picker/WidgetsRecyclerView.java
index 090362b..3ee8b33 100644
--- a/src/com/android/launcher3/widget/picker/WidgetsRecyclerView.java
+++ b/src/com/android/launcher3/widget/picker/WidgetsRecyclerView.java
@@ -23,7 +23,6 @@
 import android.view.View;
 import android.widget.TableLayout;
 
-import androidx.annotation.NonNull;
 import androidx.annotation.Nullable;
 import androidx.recyclerview.widget.LinearLayoutManager;
 import androidx.recyclerview.widget.RecyclerView;
@@ -53,6 +52,7 @@
     private HeaderViewDimensionsProvider mHeaderViewDimensionsProvider;
     private int mLastVisibleWidgetContentTableHeight = 0;
     private int mWidgetHeaderHeight = 0;
+    private final int mCollapsedHeaderBottomMarginSize;
     @Nullable private OnContentChangeListener mOnContentChangeListener;
 
     public WidgetsRecyclerView(Context context) {
@@ -71,6 +71,10 @@
 
         ActivityContext activity = ActivityContext.lookupContext(getContext());
         DeviceProfile grid = activity.getDeviceProfile();
+
+        // The bottom margin used when the header is not expanded.
+        mCollapsedHeaderBottomMarginSize =
+                getResources().getDimensionPixelSize(R.dimen.widget_list_entry_bottom_margin);
     }
 
     @Override
@@ -78,7 +82,9 @@
         super.onFinishInflate();
         // create a layout manager with Launcher's context so that scroll position
         // can be preserved during screen rotation.
-        setLayoutManager(new LinearLayoutManager(getContext()));
+        WidgetsListLayoutManager layoutManager = new WidgetsListLayoutManager(getContext());
+        layoutManager.setOnContentChangeListener(mOnContentChangeListener);
+        setLayoutManager(layoutManager);
     }
 
     @Override
@@ -87,22 +93,6 @@
         mAdapter = (WidgetsListAdapter) adapter;
     }
 
-    @Override
-    public void onChildAttachedToWindow(@NonNull View child) {
-        super.onChildAttachedToWindow(child);
-        if (mOnContentChangeListener != null) {
-            mOnContentChangeListener.onContentChanged();
-        }
-    }
-
-    @Override
-    public void onChildDetachedFromWindow(@NonNull View child) {
-        super.onChildDetachedFromWindow(child);
-        if (mOnContentChangeListener != null) {
-            mOnContentChangeListener.onContentChanged();
-        }
-    }
-
     /**
      * Maps the touch (from 0..1) to the adapter position that should be visible.
      */
@@ -182,10 +172,7 @@
                     && mLastVisibleWidgetContentTableHeight == 0
                     && view.getMeasuredHeight() > 0) {
                 // This assumes all header views are of the same height.
-                RecyclerView.LayoutParams layoutParams =
-                        (RecyclerView.LayoutParams) view.getLayoutParams();
-                mWidgetHeaderHeight = view.getMeasuredHeight() + layoutParams.topMargin
-                    + layoutParams.bottomMargin;
+                mWidgetHeaderHeight = view.getMeasuredHeight();
             }
         }
 
@@ -266,6 +253,10 @@
 
     public void setOnContentChangeListener(@Nullable OnContentChangeListener listener) {
         mOnContentChangeListener = listener;
+        WidgetsListLayoutManager layoutManager = (WidgetsListLayoutManager) getLayoutManager();
+        if (layoutManager != null) {
+            layoutManager.setOnContentChangeListener(listener);
+        }
     }
 
     /**
@@ -279,12 +270,17 @@
         if (untilIndex > mAdapter.getItems().size()) {
             untilIndex = mAdapter.getItems().size();
         }
+        int expandedHeaderPosition = mAdapter.getSelectedHeaderPosition().orElse(-1);
         int totalItemsHeight = 0;
         for (int i = 0; i < untilIndex; i++) {
             WidgetsListBaseEntry entry = mAdapter.getItems().get(i);
             if (entry instanceof WidgetsListHeaderEntry
                     || entry instanceof WidgetsListSearchHeaderEntry) {
                 totalItemsHeight += mWidgetHeaderHeight;
+                if (expandedHeaderPosition != i) {
+                    // If the header is collapsed, include the bottom margin it will use.
+                    totalItemsHeight += mCollapsedHeaderBottomMarginSize;
+                }
             } else if (entry instanceof WidgetsListContentEntry) {
                 totalItemsHeight += mLastVisibleWidgetContentTableHeight;
             } else {
diff --git a/src/com/android/launcher3/workprofile/PersonalWorkSlidingTabStrip.java b/src/com/android/launcher3/workprofile/PersonalWorkSlidingTabStrip.java
index 59ada7b..b35c75b 100644
--- a/src/com/android/launcher3/workprofile/PersonalWorkSlidingTabStrip.java
+++ b/src/com/android/launcher3/workprofile/PersonalWorkSlidingTabStrip.java
@@ -59,7 +59,8 @@
                 R.dimen.all_apps_header_pill_corner_radius);
 
         mSelectedIndicatorPaint = new Paint();
-        mSelectedIndicatorPaint.setColor(context.getColor(R.color.all_apps_tab_bg));
+        mSelectedIndicatorPaint.setColor(
+                context.getColor(R.color.all_apps_tab_background_selected));
 
         mIsRtl = Utilities.isRtl(getResources());
     }