Merge "Import translations. DO NOT MERGE ANYWHERE" into sc-v2-dev
diff --git a/quickstep/src/com/android/launcher3/uioverrides/DeviceFlag.java b/quickstep/src/com/android/launcher3/uioverrides/DeviceFlag.java
index c115bbb..c46809a 100644
--- a/quickstep/src/com/android/launcher3/uioverrides/DeviceFlag.java
+++ b/quickstep/src/com/android/launcher3/uioverrides/DeviceFlag.java
@@ -17,21 +17,17 @@
 package com.android.launcher3.uioverrides;
 
 import android.annotation.TargetApi;
-import android.content.Context;
 import android.os.Build;
 import android.provider.DeviceConfig;
 
 import com.android.launcher3.config.FeatureFlags.DebugFlag;
 
-import java.util.ArrayList;
-
 @TargetApi(Build.VERSION_CODES.P)
 public class DeviceFlag extends DebugFlag {
 
     public static final String NAMESPACE_LAUNCHER = "launcher";
 
     private final boolean mDefaultValueInCode;
-    ArrayList<Runnable> mListeners;
 
     public DeviceFlag(String key, boolean defaultValue, String description) {
         super(key, getDeviceValue(key, defaultValue), description);
@@ -44,53 +40,11 @@
     }
 
     @Override
-    public void initialize(Context context) {
-        super.initialize(context);
-        if (mListeners == null) {
-            mListeners = new ArrayList<>();
-            registerDeviceConfigChangedListener(context);
-        }
-    }
-
-    @Override
-    public void addChangeListener(Context context, Runnable r) {
-        if (mListeners == null) {
-            initialize(context);
-        }
-        mListeners.add(r);
-    }
-
-    @Override
-    public void removeChangeListener(Runnable r) {
-        if (mListeners == null) {
-            return;
-        }
-        mListeners.remove(r);
-    }
-
-    @Override
     public boolean get() {
         // Override this method in order to let Robolectric ShadowDeviceFlag to stub it.
         return super.get();
     }
 
-    private void registerDeviceConfigChangedListener(Context context) {
-        DeviceConfig.addOnPropertiesChangedListener(
-                NAMESPACE_LAUNCHER,
-                context.getMainExecutor(),
-                properties -> {
-                    if (!NAMESPACE_LAUNCHER.equals(properties.getNamespace())
-                            || !properties.getKeyset().contains(key)) {
-                        return;
-                    }
-                    defaultValue = getDeviceValue(key, mDefaultValueInCode);
-                    initialize(context);
-                    for (Runnable r: mListeners) {
-                        r.run();
-                    }
-                });
-    }
-
     protected static boolean getDeviceValue(String key, boolean defaultValue) {
         return DeviceConfig.getBoolean(NAMESPACE_LAUNCHER, key, defaultValue);
     }
diff --git a/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewTouchController.java b/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewTouchController.java
index 180af0b..051485a 100644
--- a/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewTouchController.java
+++ b/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewTouchController.java
@@ -34,7 +34,6 @@
 import com.android.launcher3.anim.AnimatorPlaybackController;
 import com.android.launcher3.anim.Interpolators;
 import com.android.launcher3.anim.PendingAnimation;
-import com.android.launcher3.config.FeatureFlags;
 import com.android.launcher3.touch.BaseSwipeDetector;
 import com.android.launcher3.touch.PagedOrientationHandler;
 import com.android.launcher3.touch.SingleAxisSwipeDetector;
@@ -158,26 +157,21 @@
                         mTaskBeingDragged = view;
                         int upDirection = mRecentsView.getPagedOrientationHandler()
                                 .getUpDirection(mIsRtl);
-                        if (!SysUINavigationMode.getMode(mActivity).hasGestures || (
-                                mActivity.getDeviceProfile().isTablet
-                                        && FeatureFlags.ENABLE_OVERVIEW_GRID.get())) {
-                            // Don't allow swipe down to open if we don't support swipe up
-                            // to enter overview, or when grid layout is enabled.
-                            directionsToDetectScroll = upDirection;
-                            mAllowGoingUp = true;
-                            mAllowGoingDown = false;
-                        } else {
-                            // The task can be dragged up to dismiss it,
-                            // and down to open if it's the current page.
-                            mAllowGoingUp = true;
-                            if (i == mRecentsView.getCurrentPage()) {
-                                mAllowGoingDown = true;
-                                directionsToDetectScroll = DIRECTION_BOTH;
-                            } else {
-                                mAllowGoingDown = false;
-                                directionsToDetectScroll = upDirection;
-                            }
-                        }
+
+                        // The task can be dragged up to dismiss it
+                        mAllowGoingUp = true;
+
+                        // The task can be dragged down to open it if:
+                        // - It's the current page
+                        // - We support gestures to enter overview
+                        // - It's the focused task if in grid view
+                        // - The task is snapped
+                        mAllowGoingDown = i == mRecentsView.getCurrentPage()
+                                && SysUINavigationMode.getMode(mActivity).hasGestures
+                                && (!mRecentsView.showAsGrid() || mTaskBeingDragged.isFocusedTask())
+                                && mRecentsView.isTaskSnapped(i);
+
+                        directionsToDetectScroll = mAllowGoingDown ? DIRECTION_BOTH : upDirection;
                         break;
                     }
                 }
diff --git a/quickstep/src/com/android/quickstep/AbsSwipeUpHandler.java b/quickstep/src/com/android/quickstep/AbsSwipeUpHandler.java
index bda2b77..9180bd0 100644
--- a/quickstep/src/com/android/quickstep/AbsSwipeUpHandler.java
+++ b/quickstep/src/com/android/quickstep/AbsSwipeUpHandler.java
@@ -539,7 +539,7 @@
             @Override
             public void onMotionPauseDetected() {
                 mHasMotionEverBeenPaused = true;
-                maybeUpdateRecentsAttachedState(true/* animate */, true/* moveFocusedTask */);
+                maybeUpdateRecentsAttachedState();
                 performHapticFeedback();
             }
 
@@ -550,24 +550,18 @@
         };
     }
 
-    private void maybeUpdateRecentsAttachedState() {
+    public void maybeUpdateRecentsAttachedState() {
         maybeUpdateRecentsAttachedState(true /* animate */);
     }
 
-    private void maybeUpdateRecentsAttachedState(boolean animate) {
-        maybeUpdateRecentsAttachedState(animate, false /* moveFocusedTask */);
-    }
-
     /**
      * Determines whether to show or hide RecentsView. The window is always
      * synchronized with its corresponding TaskView in RecentsView, so if
      * RecentsView is shown, it will appear to be attached to the window.
      *
      * Note this method has no effect unless the navigation mode is NO_BUTTON.
-     * @param animate whether to animate when attaching RecentsView
-     * @param moveFocusedTask whether to move focused task to front when attaching
      */
-    private void maybeUpdateRecentsAttachedState(boolean animate, boolean moveFocusedTask) {
+    private void maybeUpdateRecentsAttachedState(boolean animate) {
         if (!mDeviceState.isFullyGesturalNavMode() || mRecentsView == null) {
             return;
         }
@@ -586,12 +580,6 @@
         } else {
             recentsAttachedToAppWindow = mHasMotionEverBeenPaused || mIsLikelyToStartNewTask;
         }
-        if (moveFocusedTask && !mAnimationFactory.hasRecentsEverAttachedToAppWindow()
-                && recentsAttachedToAppWindow) {
-            // Only move focused task if RecentsView has never been attached before, to avoid
-            // TaskView jumping to new position as we move the tasks.
-            mRecentsView.moveFocusedTaskToFront();
-        }
         mAnimationFactory.setRecentsAttachedToAppWindow(recentsAttachedToAppWindow, animate);
 
         // Reapply window transform throughout the attach animation, as the animation affects how
diff --git a/quickstep/src/com/android/quickstep/BaseActivityInterface.java b/quickstep/src/com/android/quickstep/BaseActivityInterface.java
index 389509f..1412b1a 100644
--- a/quickstep/src/com/android/quickstep/BaseActivityInterface.java
+++ b/quickstep/src/com/android/quickstep/BaseActivityInterface.java
@@ -396,10 +396,6 @@
         default boolean isRecentsAttachedToAppWindow() {
             return false;
         }
-
-        default boolean hasRecentsEverAttachedToAppWindow() {
-            return false;
-        }
     }
 
     class DefaultAnimationFactory implements AnimationFactory {
@@ -409,7 +405,6 @@
         private final Consumer<AnimatorControllerWithResistance> mCallback;
 
         private boolean mIsAttachedToWindow;
-        private boolean mHasEverAttachedToWindow;
 
         DefaultAnimationFactory(Consumer<AnimatorControllerWithResistance> callback) {
             mCallback = callback;
@@ -463,9 +458,6 @@
             }
             mIsAttachedToWindow = attached;
             RecentsView recentsView = mActivity.getOverviewPanel();
-            if (attached) {
-                mHasEverAttachedToWindow = true;
-            }
             Animator fadeAnim = mActivity.getStateManager()
                     .createStateElementAnimation(INDEX_RECENTS_FADE_ANIM, attached ? 1 : 0);
 
@@ -495,11 +487,6 @@
             return mIsAttachedToWindow;
         }
 
-        @Override
-        public boolean hasRecentsEverAttachedToAppWindow() {
-            return mHasEverAttachedToWindow;
-        }
-
         protected void createBackgroundToOverviewAnim(ACTIVITY_TYPE activity, PendingAnimation pa) {
             //  Scale down recents from being full screen to being in overview.
             RecentsView recentsView = activity.getOverviewPanel();
diff --git a/quickstep/src/com/android/quickstep/views/FloatingWidgetBackgroundView.java b/quickstep/src/com/android/quickstep/views/FloatingWidgetBackgroundView.java
index 65dba33..1548268 100644
--- a/quickstep/src/com/android/quickstep/views/FloatingWidgetBackgroundView.java
+++ b/quickstep/src/com/android/quickstep/views/FloatingWidgetBackgroundView.java
@@ -72,14 +72,20 @@
             mForegroundProperties.init(
                     mOriginalForeground.getConstantState().newDrawable().mutate());
             setForeground(mForegroundProperties.mDrawable);
-            mSourceView.setForeground(null);
+            Drawable clipPlaceholder =
+                    mOriginalForeground.getConstantState().newDrawable().mutate();
+            clipPlaceholder.setAlpha(0);
+            mSourceView.setForeground(clipPlaceholder);
         }
         if (isSupportedDrawable(backgroundView.getBackground())) {
             mOriginalBackground = backgroundView.getBackground();
             mBackgroundProperties.init(
                     mOriginalBackground.getConstantState().newDrawable().mutate());
             setBackground(mBackgroundProperties.mDrawable);
-            mSourceView.setBackground(null);
+            Drawable clipPlaceholder =
+                    mOriginalBackground.getConstantState().newDrawable().mutate();
+            clipPlaceholder.setAlpha(0);
+            mSourceView.setBackground(clipPlaceholder);
         } else if (mOriginalForeground == null) {
             mFallbackDrawable.setColor(fallbackBackgroundColor);
             setBackground(mFallbackDrawable);
diff --git a/quickstep/src/com/android/quickstep/views/RecentsView.java b/quickstep/src/com/android/quickstep/views/RecentsView.java
index 9d10b54..6844f9f 100644
--- a/quickstep/src/com/android/quickstep/views/RecentsView.java
+++ b/quickstep/src/com/android/quickstep/views/RecentsView.java
@@ -912,8 +912,8 @@
             TaskViewUtils.composeRecentsLaunchAnimator(anim, taskView, apps, wallpaper, nonApps,
                     true /* launcherClosing */, mActivity.getStateManager(), this,
                     getDepthController());
-            anim.start();
         }
+        anim.start();
     }
 
     private void updateTaskStartIndex(View affectingView) {
@@ -949,6 +949,16 @@
                 && taskEnd <= end);
     }
 
+    /**
+     * Returns true if the task is snapped.
+     *
+     * @param taskIndex the index of the task
+     */
+    public boolean isTaskSnapped(int taskIndex) {
+        return getScrollForPage(taskIndex + mTaskViewStartIndex)
+                == getPagedOrientationHandler().getPrimaryScroll(this);
+    }
+
     public TaskView getTaskView(int taskId) {
         for (int i = 0; i < getTaskViewCount(); i++) {
             TaskView taskView = getTaskViewAt(i);
@@ -1111,35 +1121,6 @@
         }
     }
 
-    /**
-     * Moves the focused task to the front of the carousel in tablets, to minimize animation
-     * required to focus the task in grid.
-     */
-    public void moveFocusedTaskToFront() {
-        if (!(mActivity.getDeviceProfile().isTablet && FeatureFlags.ENABLE_OVERVIEW_GRID.get())) {
-            return;
-        }
-
-        TaskView focusedTaskView = getFocusedTaskView();
-        if (focusedTaskView == null) {
-            return;
-        }
-
-        if (indexOfChild(focusedTaskView) != mCurrentPage) {
-            return;
-        }
-
-        int primaryScroll = mOrientationHandler.getPrimaryScroll(this);
-        int currentPageScroll = getScrollForPage(mCurrentPage);
-        mCurrentPageScrollDiff = primaryScroll - currentPageScroll;
-
-        removeView(focusedTaskView);
-        addView(focusedTaskView, mTaskViewStartIndex);
-        setCurrentPage(0);
-
-        updateGridProperties();
-    }
-
     protected void applyLoadPlan(ArrayList<Task> tasks) {
         if (mPendingAnimation != null) {
             mPendingAnimation.addEndListener(success -> applyLoadPlan(tasks));
diff --git a/src/com/android/launcher3/PagedView.java b/src/com/android/launcher3/PagedView.java
index 1555e98..20f5f9b 100644
--- a/src/com/android/launcher3/PagedView.java
+++ b/src/com/android/launcher3/PagedView.java
@@ -1087,26 +1087,25 @@
 
     protected float getScrollProgress(int screenCenter, View v, int page) {
         final int halfScreenSize = getMeasuredWidth() / 2;
-
         int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
-        int count = getChildCount();
+        int panelCount = getPanelCount();
+        int pageCount = getChildCount();
 
-        final int totalDistance;
-
-        int adjacentPage = page + 1;
+        int adjacentPage = page + panelCount;
         if ((delta < 0 && !mIsRtl) || (delta > 0 && mIsRtl)) {
-            adjacentPage = page - 1;
+            adjacentPage = page - panelCount;
         }
 
-        if (adjacentPage < 0 || adjacentPage > count - 1) {
-            totalDistance = v.getMeasuredWidth() + mPageSpacing;
+        final int totalDistance;
+        if (adjacentPage < 0 || adjacentPage > pageCount - 1) {
+            totalDistance = (v.getMeasuredWidth() + mPageSpacing) * panelCount;
         } else {
             totalDistance = Math.abs(getScrollForPage(adjacentPage) - getScrollForPage(page));
         }
 
         float scrollProgress = delta / (totalDistance * 1.0f);
         scrollProgress = Math.min(scrollProgress, MAX_SCROLL_PROGRESS);
-        scrollProgress = Math.max(scrollProgress, - MAX_SCROLL_PROGRESS);
+        scrollProgress = Math.max(scrollProgress, -MAX_SCROLL_PROGRESS);
         return scrollProgress;
     }
 
@@ -1649,7 +1648,7 @@
 
     public boolean scrollLeft() {
         if (getNextPage() > 0) {
-            snapToPage(getNextPage() - 1);
+            snapToPage(getNextPage() - getPanelCount());
             return true;
         }
         return mAllowOverScroll;
@@ -1657,7 +1656,7 @@
 
     public boolean scrollRight() {
         if (getNextPage() < getChildCount() - 1) {
-            snapToPage(getNextPage() + 1);
+            snapToPage(getNextPage() + getPanelCount());
             return true;
         }
         return mAllowOverScroll;
diff --git a/src/com/android/launcher3/allapps/AllAppsContainerView.java b/src/com/android/launcher3/allapps/AllAppsContainerView.java
index 516af59..d2c71b2 100644
--- a/src/com/android/launcher3/allapps/AllAppsContainerView.java
+++ b/src/com/android/launcher3/allapps/AllAppsContainerView.java
@@ -477,10 +477,6 @@
         } else {
             mAH[AdapterHolder.MAIN].setup(findViewById(R.id.apps_list_view), null);
             mAH[AdapterHolder.WORK].recyclerView = null;
-            if (mWorkModeSwitch != null) {
-                ((ViewGroup) mWorkModeSwitch.getParent()).removeView(mWorkModeSwitch);
-                mWorkModeSwitch = null;
-            }
         }
         setupHeader();
 
@@ -532,7 +528,7 @@
 
     @Override
     public void onActivePageChanged(int currentActivePage) {
-        mHeader.setMainActive(currentActivePage == 0);
+        mHeader.setMainActive(currentActivePage == AdapterHolder.MAIN);
         if (mAH[currentActivePage].recyclerView != null) {
             mAH[currentActivePage].recyclerView.bindFastScrollbar();
         }
@@ -541,6 +537,14 @@
             mWorkModeSwitch.setWorkTabVisible(currentActivePage == AdapterHolder.WORK
                     && mAllAppsStore.hasModelFlag(
                     FLAG_HAS_SHORTCUT_PERMISSION | FLAG_QUIET_MODE_CHANGE_PERMISSION));
+
+            if (currentActivePage == AdapterHolder.WORK) {
+                if (mWorkModeSwitch.getParent() == null) {
+                    addView(mWorkModeSwitch);
+                }
+            } else {
+                removeView(mWorkModeSwitch);
+            }
         }
     }
 
diff --git a/src/com/android/launcher3/config/FeatureFlags.java b/src/com/android/launcher3/config/FeatureFlags.java
index 1fe50f8..1779ddb 100644
--- a/src/com/android/launcher3/config/FeatureFlags.java
+++ b/src/com/android/launcher3/config/FeatureFlags.java
@@ -295,7 +295,7 @@
     public static class BooleanFlag {
 
         public final String key;
-        public boolean defaultValue;
+        public final boolean defaultValue;
 
         public BooleanFlag(String key, boolean defaultValue) {
             this.key = key;
@@ -314,16 +314,12 @@
         protected StringBuilder appendProps(StringBuilder src) {
             return src.append(key).append(", defaultValue=").append(defaultValue);
         }
-
-        public void addChangeListener(Context context, Runnable r) { }
-
-        public void removeChangeListener(Runnable r) {}
     }
 
     public static class DebugFlag extends BooleanFlag {
 
         public final String description;
-        private boolean mCurrentValue;
+        protected boolean mCurrentValue;
 
         public DebugFlag(String key, boolean defaultValue, String description) {
             super(key, defaultValue);
diff --git a/src/com/android/launcher3/dragndrop/AddItemActivity.java b/src/com/android/launcher3/dragndrop/AddItemActivity.java
index 55be4a4..6bd6261 100644
--- a/src/com/android/launcher3/dragndrop/AddItemActivity.java
+++ b/src/com/android/launcher3/dragndrop/AddItemActivity.java
@@ -189,10 +189,18 @@
         if (appWidgetHostView != null) {
             bounds = new Rect();
             appWidgetHostView.getSourceVisualDragBounds(bounds);
-            bounds.offset(appWidgetHostView.getLeft() - (int) mLastTouchPos.x,
-                    appWidgetHostView.getTop() - (int) mLastTouchPos.y);
-            listener = new PinItemDragListener(mRequest, bounds,
-                    appWidgetHostView.getMeasuredWidth(), appWidgetHostView.getMeasuredWidth());
+            float appWidgetHostViewScale = mWidgetCell.getAppWidgetHostViewScale();
+            int xOffset =
+                    appWidgetHostView.getLeft() - (int) (mLastTouchPos.x * appWidgetHostViewScale);
+            int yOffset = appWidgetHostView.getTop()
+                    - (int) (mLastTouchPos.y * mWidgetCell.getAppWidgetHostViewScale());
+            bounds.offset(xOffset, yOffset);
+            listener = new PinItemDragListener(
+                    mRequest,
+                    bounds,
+                    appWidgetHostView.getMeasuredWidth(),
+                    appWidgetHostView.getMeasuredWidth(),
+                    appWidgetHostView.getScaleX());
         } else {
             bounds = img.getBitmapBounds();
             bounds.offset(img.getLeft() - (int) mLastTouchPos.x,
diff --git a/src/com/android/launcher3/dragndrop/PinItemDragListener.java b/src/com/android/launcher3/dragndrop/PinItemDragListener.java
index 2bdf8a0..af43ae8 100644
--- a/src/com/android/launcher3/dragndrop/PinItemDragListener.java
+++ b/src/com/android/launcher3/dragndrop/PinItemDragListener.java
@@ -48,12 +48,19 @@
 
     private final PinItemRequest mRequest;
     private final CancellationSignal mCancelSignal;
+    private final float mPreviewScale;
 
     public PinItemDragListener(PinItemRequest request, Rect previewRect,
             int previewBitmapWidth, int previewViewWidth) {
+        this(request, previewRect, previewBitmapWidth, previewViewWidth, /* previewScale= */ 1f);
+    }
+
+    public PinItemDragListener(PinItemRequest request, Rect previewRect,
+            int previewBitmapWidth, int previewViewWidth, float previewScale) {
         super(previewRect, previewBitmapWidth, previewViewWidth);
         mRequest = request;
         mCancelSignal = new CancellationSignal();
+        mPreviewScale = previewScale;
     }
 
     @Override
@@ -98,7 +105,7 @@
 
         PendingItemDragHelper dragHelper = new PendingItemDragHelper(view);
         if (mRequest.getRequestType() == PinItemRequest.REQUEST_TYPE_APPWIDGET) {
-            dragHelper.setRemoteViewsPreview(getPreview(mRequest));
+            dragHelper.setRemoteViewsPreview(getPreview(mRequest), mPreviewScale);
         }
         return dragHelper;
     }
diff --git a/src/com/android/launcher3/widget/BaseWidgetSheet.java b/src/com/android/launcher3/widget/BaseWidgetSheet.java
index adc7ba0..ee44174 100644
--- a/src/com/android/launcher3/widget/BaseWidgetSheet.java
+++ b/src/com/android/launcher3/widget/BaseWidgetSheet.java
@@ -176,7 +176,9 @@
         }
 
         PendingItemDragHelper dragHelper = new PendingItemDragHelper(v);
-        dragHelper.setRemoteViewsPreview(v.getRemoteViewsPreview());
+        // RemoteViews are being rendered in AppWidgetHostView in WidgetCell. And thus, the scale of
+        // RemoteViews is equivalent to the AppWidgetHostView scale.
+        dragHelper.setRemoteViewsPreview(v.getRemoteViewsPreview(), v.getAppWidgetHostViewScale());
         dragHelper.setAppWidgetHostViewPreview(v.getAppWidgetHostViewPreview());
 
         if (image.getDrawable() != null) {
diff --git a/src/com/android/launcher3/widget/PendingItemDragHelper.java b/src/com/android/launcher3/widget/PendingItemDragHelper.java
index cea4de7..a4003d4 100644
--- a/src/com/android/launcher3/widget/PendingItemDragHelper.java
+++ b/src/com/android/launcher3/widget/PendingItemDragHelper.java
@@ -22,6 +22,7 @@
 import android.graphics.Point;
 import android.graphics.Rect;
 import android.graphics.drawable.Drawable;
+import android.util.Size;
 import android.view.View;
 import android.view.View.MeasureSpec;
 import android.widget.RemoteViews;
@@ -41,6 +42,7 @@
 import com.android.launcher3.icons.LauncherIcons;
 import com.android.launcher3.icons.RoundDrawableWrapper;
 import com.android.launcher3.widget.dragndrop.AppWidgetHostViewDragListener;
+import com.android.launcher3.widget.util.WidgetSizes;
 
 /**
  * Extension of {@link DragPreviewProvider} with logic specific to pending widgets/shortcuts
@@ -54,6 +56,7 @@
     private int[] mEstimatedCellSize;
 
     @Nullable private RemoteViews mRemoteViewsPreview;
+    private float mRemoteViewsPreviewScale = 1f;
     @Nullable private NavigableAppWidgetHostView mAppWidgetHostViewPreview;
     private final float mEnforcedRoundedCornersForWidget;
 
@@ -68,8 +71,10 @@
      * Sets a {@link RemoteViews} which shows an app widget preview provided by app developers in
      * the pin widget flow.
      */
-    public void setRemoteViewsPreview(@Nullable RemoteViews remoteViewsPreview) {
+    public void setRemoteViewsPreview(@Nullable RemoteViews remoteViewsPreview,
+            float previewScale) {
         mRemoteViewsPreview = remoteViewsPreview;
+        mRemoteViewsPreviewScale = previewScale;
     }
 
     /** Sets a {@link NavigableAppWidgetHostView} which shows a preview layout of an app widget. */
@@ -120,13 +125,14 @@
                 mAppWidgetHostViewPreview.setPadding(padding.left, padding.top, padding.right,
                         padding.bottom);
                 mAppWidgetHostViewPreview.updateAppWidget(/* remoteViews= */ mRemoteViewsPreview);
-                int width =
-                        deviceProfile.cellWidthPx * mAddInfo.spanX + padding.left + padding.right;
-                int height =
-                        deviceProfile.cellHeightPx * mAddInfo.spanY + padding.top + padding.bottom;
+                Size widgetSizes = WidgetSizes.getWidgetPaddedSizePx(launcher,
+                        mAddInfo.componentName, deviceProfile, mAddInfo.spanX, mAddInfo.spanY);
                 mAppWidgetHostViewPreview.measure(
-                        MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
-                        MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
+                        MeasureSpec.makeMeasureSpec(widgetSizes.getWidth(), MeasureSpec.EXACTLY),
+                        MeasureSpec.makeMeasureSpec(widgetSizes.getHeight(), MeasureSpec.EXACTLY));
+                mAppWidgetHostViewPreview.setClipChildren(false);
+                mAppWidgetHostViewPreview.setClipToPadding(false);
+                mAppWidgetHostViewPreview.setScaleToFit(mRemoteViewsPreviewScale);
             }
             if (mAppWidgetHostViewPreview != null) {
                 previewSizeBeforeScale[0] = mAppWidgetHostViewPreview.getMeasuredWidth();
diff --git a/src/com/android/launcher3/widget/WidgetCell.java b/src/com/android/launcher3/widget/WidgetCell.java
index edcab4e..0c9a15a 100644
--- a/src/com/android/launcher3/widget/WidgetCell.java
+++ b/src/com/android/launcher3/widget/WidgetCell.java
@@ -46,6 +46,7 @@
 import com.android.launcher3.BaseActivity;
 import com.android.launcher3.CheckLongPressHelper;
 import com.android.launcher3.DeviceProfile;
+import com.android.launcher3.Launcher;
 import com.android.launcher3.R;
 import com.android.launcher3.icons.FastBitmapDrawable;
 import com.android.launcher3.icons.RoundDrawableWrapper;
@@ -127,6 +128,7 @@
 
     private RemoteViews mRemoteViewsPreview;
     private NavigableAppWidgetHostView mAppWidgetHostViewPreview;
+    private float mAppWidgetHostViewScale = 1f;
     private int mSourceContainer = CONTAINER_WIDGETS_TRAY;
 
     public WidgetCell(Context context) {
@@ -177,6 +179,11 @@
         return mRemoteViewsPreview;
     }
 
+    /** Returns the app widget host view scale, which is a value between [0f, 1f]. */
+    public float getAppWidgetHostViewScale() {
+        return mAppWidgetHostViewScale;
+    }
+
     /**
      * Called to clear the view and free attached resources. (e.g., {@link Bitmap}
      */
@@ -202,6 +209,7 @@
             mWidgetImageContainer.removeView(mAppWidgetHostViewPreview);
         }
         mAppWidgetHostViewPreview = null;
+        mAppWidgetHostViewScale = 1f;
         mItem = null;
     }
 
@@ -242,12 +250,7 @@
 
     private void applyPreviewOnAppWidgetHostView(WidgetItem item) {
         if (mRemoteViewsPreview != null) {
-            mAppWidgetHostViewPreview = new NavigableAppWidgetHostView(getContext()) {
-                @Override
-                protected boolean shouldAllowDirectClick() {
-                    return false;
-                }
-            };
+            mAppWidgetHostViewPreview = createAppWidgetHostView(getContext());
             setAppWidgetHostViewPreview(mAppWidgetHostViewPreview, item.widgetInfo,
                     mRemoteViewsPreview);
             return;
@@ -255,10 +258,15 @@
 
         if (!item.hasPreviewLayout()) return;
 
-        mAppWidgetHostViewPreview = new LauncherAppWidgetHostView(getContext());
+        Context context = getContext();
+        // If the context is a Launcher activity, DragView will show mAppWidgetHostViewPreview as
+        // a preview during drag & drop. And thus, we should use LauncherAppWidgetHostView, which
+        // supports applying local color extraction during drag & drop.
+        mAppWidgetHostViewPreview = isLauncherContext(context)
+                ? new LauncherAppWidgetHostView(context)
+                : createAppWidgetHostView(context);
         LauncherAppWidgetProviderInfo launcherAppWidgetProviderInfo =
-                LauncherAppWidgetProviderInfo.fromProviderInfo(getContext(),
-                        item.widgetInfo.clone());
+                LauncherAppWidgetProviderInfo.fromProviderInfo(context, item.widgetInfo.clone());
         // A hack to force the initial layout to be the preview layout since there is no API for
         // rendering a preview layout for work profile apps yet. For non-work profile layout, a
         // proper solution is to use RemoteViews(PackageName, LayoutId).
@@ -364,8 +372,8 @@
                 if (shouldScale) {
                     setNoClip(mWidgetImageContainer);
                     setNoClip(mAppWidgetHostViewPreview);
-                    float previewLayoutScale = computeWidgetPreviewScale();
-                    mAppWidgetHostViewPreview.setScaleToFit(previewLayoutScale);
+                    mAppWidgetHostViewScale = computeWidgetPreviewScale();
+                    mAppWidgetHostViewPreview.setScaleToFit(mAppWidgetHostViewScale);
                 }
             }
             FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
@@ -431,6 +439,24 @@
         return "";
     }
 
+    private static NavigableAppWidgetHostView createAppWidgetHostView(Context context) {
+        return new NavigableAppWidgetHostView(context) {
+            @Override
+            protected boolean shouldAllowDirectClick() {
+                return false;
+            }
+        };
+    }
+
+    private static boolean isLauncherContext(Context context) {
+        try {
+            Launcher.getLauncher(context);
+            return true;
+        } catch (Exception e) {
+            return false;
+        }
+    }
+
     @Override
     public CharSequence getAccessibilityClassName() {
         return WidgetCell.class.getName();