Merge "Make all tasks in intermediate carousel have the same size" into sc-v2-dev
diff --git a/quickstep/src/com/android/launcher3/BaseQuickstepLauncher.java b/quickstep/src/com/android/launcher3/BaseQuickstepLauncher.java
index 8a7d01b..fc1556e 100644
--- a/quickstep/src/com/android/launcher3/BaseQuickstepLauncher.java
+++ b/quickstep/src/com/android/launcher3/BaseQuickstepLauncher.java
@@ -37,6 +37,7 @@
 import android.os.CancellationSignal;
 import android.os.IBinder;
 import android.view.View;
+import android.window.SplashScreen;
 
 import androidx.annotation.Nullable;
 
@@ -428,6 +429,7 @@
             ActivityOptionsCompat.setLauncherSourceInfo(
                     activityOptions.options, mLastTouchUpTime);
         }
+        activityOptions.options.setSplashscreenStyle(SplashScreen.SPLASH_SCREEN_STYLE_ICON);
         addLaunchCookie(item, activityOptions.options);
         return activityOptions;
     }
diff --git a/quickstep/src/com/android/quickstep/RecentsActivity.java b/quickstep/src/com/android/quickstep/RecentsActivity.java
index d43bb24..6852642 100644
--- a/quickstep/src/com/android/quickstep/RecentsActivity.java
+++ b/quickstep/src/com/android/quickstep/RecentsActivity.java
@@ -40,6 +40,7 @@
 import android.os.Looper;
 import android.view.SurfaceControl.Transaction;
 import android.view.View;
+import android.window.SplashScreen;
 
 import androidx.annotation.Nullable;
 
@@ -222,9 +223,11 @@
                 wrapper, RECENTS_LAUNCH_DURATION,
                 RECENTS_LAUNCH_DURATION - STATUS_BAR_TRANSITION_DURATION
                         - STATUS_BAR_TRANSITION_PRE_DELAY);
-        return new ActivityOptionsWrapper(
+        final ActivityOptionsWrapper activityOptions = new ActivityOptionsWrapper(
                 ActivityOptionsCompat.makeRemoteAnimation(adapterCompat),
                 onEndCallback);
+        activityOptions.options.setSplashscreenStyle(SplashScreen.SPLASH_SCREEN_STYLE_ICON);
+        return activityOptions;
     }
 
     /**
diff --git a/quickstep/src/com/android/quickstep/TaskShortcutFactory.java b/quickstep/src/com/android/quickstep/TaskShortcutFactory.java
index 4ec1c15..a078bf3 100644
--- a/quickstep/src/com/android/quickstep/TaskShortcutFactory.java
+++ b/quickstep/src/com/android/quickstep/TaskShortcutFactory.java
@@ -30,6 +30,7 @@
 import android.os.Handler;
 import android.os.Looper;
 import android.view.View;
+import android.window.SplashScreen;
 
 import com.android.launcher3.BaseDraggingActivity;
 import com.android.launcher3.DeviceProfile;
@@ -165,6 +166,9 @@
             dismissTaskMenuView(mTarget);
 
             ActivityOptions options = mFactory.makeLaunchOptions(mTarget);
+            if (options != null) {
+                options.setSplashscreenStyle(SplashScreen.SPLASH_SCREEN_STYLE_ICON);
+            }
             if (options != null
                     && ActivityManagerWrapper.getInstance().startActivityFromRecents(taskId,
                             options)) {
diff --git a/quickstep/src/com/android/quickstep/util/TaskViewSimulator.java b/quickstep/src/com/android/quickstep/util/TaskViewSimulator.java
index b15bbf3..0e6ce87 100644
--- a/quickstep/src/com/android/quickstep/util/TaskViewSimulator.java
+++ b/quickstep/src/com/android/quickstep/util/TaskViewSimulator.java
@@ -256,8 +256,8 @@
 
         float fullScreenProgress = Utilities.boundToRange(this.fullScreenProgress.value, 0, 1);
         mCurrentFullscreenParams.setProgress(
-                fullScreenProgress, recentsViewScale.value, mTaskRect.width(), mDp,
-                mPositionHelper);
+                fullScreenProgress, recentsViewScale.value, /*taskViewScale=*/1f, mTaskRect.width(),
+                mDp, mPositionHelper);
 
         // Apply thumbnail matrix
         RectF insets = mCurrentFullscreenParams.mCurrentDrawnInsets;
diff --git a/quickstep/src/com/android/quickstep/views/TaskView.java b/quickstep/src/com/android/quickstep/views/TaskView.java
index 1a2a556..8ed6c14 100644
--- a/quickstep/src/com/android/quickstep/views/TaskView.java
+++ b/quickstep/src/com/android/quickstep/views/TaskView.java
@@ -1298,6 +1298,7 @@
         mCurrentFullscreenParams.setProgress(
                 mFullscreenProgress,
                 getRecentsView().getScaleX(),
+                getScaleX(),
                 getWidth(), mActivity.getDeviceProfile(),
                 previewPositionHelper);
     }
@@ -1434,8 +1435,8 @@
         /**
          * Sets the progress in range [0, 1]
          */
-        public void setProgress(float fullscreenProgress, float parentScale, int previewWidth,
-                DeviceProfile dp, PreviewPositionHelper pph) {
+        public void setProgress(float fullscreenProgress, float parentScale, float taskViewScale,
+                int previewWidth, DeviceProfile dp, PreviewPositionHelper pph) {
             RectF insets = pph.getInsetsToDrawInFullscreen();
 
             float currentInsetsLeft = insets.left * fullscreenProgress;
@@ -1446,7 +1447,7 @@
 
             mCurrentDrawnCornerRadius =
                     Utilities.mapRange(fullscreenProgress, mCornerRadius, fullscreenCornerRadius)
-                            / parentScale;
+                            / parentScale / taskViewScale;
 
             // We scaled the thumbnail to fit the content (excluding insets) within task view width.
             // Now that we are drawing left/right insets again, we need to scale down to fit them.
diff --git a/res/values-v31/colors.xml b/res/values-v31/colors.xml
index 7b37001..a9721a4 100644
--- a/res/values-v31/colors.xml
+++ b/res/values-v31/colors.xml
@@ -37,4 +37,6 @@
 
     <color name="wallpaper_popup_scrim">@android:color/system_neutral1_900</color>
 
+    <color name="folder_dot_color">@android:color/system_accent2_50</color>
+
 </resources>
diff --git a/res/values/colors.xml b/res/values/colors.xml
index c2b07e0..7aab4fa 100644
--- a/res/values/colors.xml
+++ b/res/values/colors.xml
@@ -59,6 +59,8 @@
     <color name="folder_hint_text_color_light">#FFF</color>
     <color name="folder_hint_text_color_dark">#FF000000</color>
 
+    <color name="folder_dot_color">?attr/colorPrimary</color>
+
     <color name="text_color_primary_dark">#FFFFFFFF</color>
     <color name="text_color_secondary_dark">#FFFFFFFF</color>
     <color name="text_color_tertiary_dark">#CCFFFFFF</color>
diff --git a/res/values/styles.xml b/res/values/styles.xml
index 86dcf4c..571377c 100644
--- a/res/values/styles.xml
+++ b/res/values/styles.xml
@@ -47,7 +47,7 @@
         <item name="workspaceKeyShadowColor">#89000000</item>
         <item name="workspaceStatusBarScrim">@drawable/workspace_bg</item>
         <item name="widgetsTheme">@style/WidgetContainerTheme</item>
-        <item name="folderDotColor">?android:attr/colorPrimary</item>
+        <item name="folderDotColor">@color/folder_dot_color</item>
         <item name="folderFillColor">?android:attr/colorBackgroundFloating</item>
         <item name="folderIconBorderColor">?android:attr/colorPrimary</item>
         <item name="folderTextColor">?android:attr/textColorPrimary</item>
@@ -86,7 +86,7 @@
         <item name="workspaceKeyShadowColor">@android:color/transparent</item>
         <item name="isWorkspaceDarkText">true</item>
         <item name="workspaceStatusBarScrim">@null</item>
-        <item name="folderDotColor">#FF464646</item>
+        <item name="folderDotColor">@color/folder_dot_color</item>
         <item name="folderFillColor">?android:attr/colorBackgroundFloating</item>
         <item name="folderIconBorderColor">#FF80868B</item>
         <item name="folderTextColor">?attr/workspaceTextColor</item>
@@ -108,7 +108,7 @@
         <item name="popupColorSecondary">@color/popup_color_secondary_dark</item>
         <item name="popupColorTertiary">@color/popup_color_tertiary_dark</item>
         <item name="widgetsTheme">@style/WidgetContainerTheme.Dark</item>
-        <item name="folderDotColor">?android:attr/colorPrimary</item>
+        <item name="folderDotColor">@color/folder_dot_color</item>
         <item name="folderFillColor">?android:attr/colorBackgroundFloating</item>
         <item name="folderIconBorderColor">?android:attr/colorPrimary</item>
         <item name="folderTextColor">?android:attr/textColorPrimary</item>
diff --git a/robolectric_tests/src/com/android/launcher3/widget/LauncherAppWidgetProviderInfoTest.java b/robolectric_tests/src/com/android/launcher3/widget/LauncherAppWidgetProviderInfoTest.java
index d18138f..c7286e5 100644
--- a/robolectric_tests/src/com/android/launcher3/widget/LauncherAppWidgetProviderInfoTest.java
+++ b/robolectric_tests/src/com/android/launcher3/widget/LauncherAppWidgetProviderInfoTest.java
@@ -40,6 +40,8 @@
 public final class LauncherAppWidgetProviderInfoTest {
 
     private static final int CELL_SIZE = 50;
+    private static final int NUM_OF_COLS = 4;
+    private static final int NUM_OF_ROWS = 5;
 
     private Context mContext;
 
@@ -76,6 +78,33 @@
     }
 
     @Test
+    public void
+            initSpans_minWidthLargerThanGridColumns_shouldInitializeSpansToAtMostTheGridColumns() {
+        LauncherAppWidgetProviderInfo info = new LauncherAppWidgetProviderInfo();
+        info.minWidth = CELL_SIZE * (NUM_OF_COLS + 1);
+        info.minHeight = 20;
+        InvariantDeviceProfile idp = createIDP();
+
+        info.initSpans(mContext, idp);
+
+        assertThat(info.spanX).isEqualTo(NUM_OF_COLS);
+        assertThat(info.spanY).isEqualTo(1);
+    }
+
+    @Test
+    public void initSpans_minHeightLargerThanGridRows_shouldInitializeSpansToAtMostTheGridRows() {
+        LauncherAppWidgetProviderInfo info = new LauncherAppWidgetProviderInfo();
+        info.minWidth = 20;
+        info.minHeight = 50 * (NUM_OF_ROWS + 1);
+        InvariantDeviceProfile idp = createIDP();
+
+        info.initSpans(mContext, idp);
+
+        assertThat(info.spanX).isEqualTo(1);
+        assertThat(info.spanY).isEqualTo(NUM_OF_ROWS);
+    }
+
+    @Test
     public void initSpans_minResizeWidthUnspecified_shouldInitializeMinSpansToOne() {
         LauncherAppWidgetProviderInfo info = new LauncherAppWidgetProviderInfo();
         InvariantDeviceProfile idp = createIDP();
@@ -153,6 +182,49 @@
         assertThat(info.minSpanY).isEqualTo(3);
     }
 
+    @Test
+    public void isMinSizeFulfilled_minWidthAndHeightWithinGridSize_shouldReturnTrue() {
+        LauncherAppWidgetProviderInfo info = new LauncherAppWidgetProviderInfo();
+        info.minWidth = 80;
+        info.minHeight = 80;
+        info.minResizeWidth = 50;
+        info.minResizeHeight = 50;
+        InvariantDeviceProfile idp = createIDP();
+
+        info.initSpans(mContext, idp);
+
+        assertThat(info.isMinSizeFulfilled()).isTrue();
+    }
+
+    @Test
+    public void
+            isMinSizeFulfilled_minWidthAndMinResizeWidthExceededGridColumns_shouldReturnFalse() {
+        LauncherAppWidgetProviderInfo info = new LauncherAppWidgetProviderInfo();
+        info.minWidth = CELL_SIZE * (NUM_OF_COLS + 2);
+        info.minHeight = 80;
+        info.minResizeWidth = CELL_SIZE * (NUM_OF_COLS + 1);
+        info.minResizeHeight = 50;
+        InvariantDeviceProfile idp = createIDP();
+
+        info.initSpans(mContext, idp);
+
+        assertThat(info.isMinSizeFulfilled()).isFalse();
+    }
+
+    @Test
+    public void isMinSizeFulfilled_minHeightAndMinResizeHeightExceededGridRows_shouldReturnFalse() {
+        LauncherAppWidgetProviderInfo info = new LauncherAppWidgetProviderInfo();
+        info.minWidth = 80;
+        info.minHeight = CELL_SIZE * (NUM_OF_ROWS + 2);
+        info.minResizeWidth = 50;
+        info.minResizeHeight = CELL_SIZE * (NUM_OF_ROWS + 1);
+        InvariantDeviceProfile idp = createIDP();
+
+        info.initSpans(mContext, idp);
+
+        assertThat(info.isMinSizeFulfilled()).isFalse();
+    }
+
     private InvariantDeviceProfile createIDP() {
         DeviceProfile profile = Mockito.mock(DeviceProfile.class);
         doAnswer(i -> {
@@ -163,6 +235,8 @@
 
         InvariantDeviceProfile idp = new InvariantDeviceProfile();
         idp.supportedProfiles.add(profile);
+        idp.numColumns = NUM_OF_COLS;
+        idp.numRows = NUM_OF_ROWS;
         return idp;
     }
 
diff --git a/src/com/android/launcher3/AppWidgetResizeFrame.java b/src/com/android/launcher3/AppWidgetResizeFrame.java
index 5d9797f..74ac8c2 100644
--- a/src/com/android/launcher3/AppWidgetResizeFrame.java
+++ b/src/com/android/launcher3/AppWidgetResizeFrame.java
@@ -4,7 +4,6 @@
 
 import static com.android.launcher3.LauncherAnimUtils.LAYOUT_HEIGHT;
 import static com.android.launcher3.LauncherAnimUtils.LAYOUT_WIDTH;
-import static com.android.launcher3.Utilities.ATLEAST_S;
 import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_WIDGET_RESIZE_COMPLETED;
 import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_WIDGET_RESIZE_STARTED;
 import static com.android.launcher3.views.BaseDragLayer.LAYOUT_X;
@@ -13,18 +12,12 @@
 import android.animation.AnimatorSet;
 import android.animation.ObjectAnimator;
 import android.animation.PropertyValuesHolder;
-import android.appwidget.AppWidgetHostView;
-import android.appwidget.AppWidgetManager;
 import android.appwidget.AppWidgetProviderInfo;
-import android.content.ComponentName;
 import android.content.Context;
-import android.graphics.Point;
 import android.graphics.Rect;
 import android.graphics.drawable.Drawable;
 import android.graphics.drawable.GradientDrawable;
-import android.os.Bundle;
 import android.util.AttributeSet;
-import android.util.SizeF;
 import android.view.KeyEvent;
 import android.view.MotionEvent;
 import android.view.View;
@@ -39,10 +32,10 @@
 import com.android.launcher3.util.PendingRequestArgs;
 import com.android.launcher3.widget.LauncherAppWidgetHostView;
 import com.android.launcher3.widget.LauncherAppWidgetProviderInfo;
+import com.android.launcher3.widget.util.WidgetSizes;
 
 import java.util.ArrayList;
 import java.util.List;
-import java.util.stream.Collectors;
 
 public class AppWidgetResizeFrame extends AbstractFloatingView implements View.OnKeyListener {
     private static final int SNAP_DURATION = 150;
@@ -415,90 +408,12 @@
             mRunningHInc += hSpanDelta;
 
             if (!onDismiss) {
-                updateWidgetSizeRanges(mWidgetView, mLauncher, spanX, spanY);
+                WidgetSizes.updateWidgetSizeRanges(mWidgetView, mLauncher, spanX, spanY);
             }
         }
         mWidgetView.requestLayout();
     }
 
-    public static void updateWidgetSizeRanges(
-            AppWidgetHostView widgetView, Context context, int spanX, int spanY) {
-        List<SizeF> sizes = getWidgetSizes(context, spanX, spanY);
-        if (ATLEAST_S) {
-            widgetView.updateAppWidgetSize(new Bundle(), sizes);
-        } else {
-            Rect bounds = getMinMaxSizes(sizes);
-            widgetView.updateAppWidgetSize(new Bundle(), bounds.left, bounds.top, bounds.right,
-                    bounds.bottom);
-        }
-    }
-
-    /** Returns the list of sizes for a widget of given span, in dp. */
-    public static ArrayList<SizeF> getWidgetSizes(Context context, int spanX, int spanY) {
-        ArrayList<SizeF> sizes = new ArrayList<>(2);
-        final float density = context.getResources().getDisplayMetrics().density;
-        Point cellSize = new Point();
-
-        for (DeviceProfile profile : LauncherAppState.getIDP(context).supportedProfiles) {
-            final float hBorderSpacing = (spanX - 1) * profile.cellLayoutBorderSpacingPx;
-            final float vBorderSpacing = (spanY - 1) * profile.cellLayoutBorderSpacingPx;
-            profile.getCellSize(cellSize);
-            sizes.add(new SizeF(
-                    ((spanX * cellSize.x) + hBorderSpacing) / density,
-                    ((spanY * cellSize.y) + vBorderSpacing) / density));
-        }
-        return sizes;
-    }
-
-    /**
-     * Returns the bundle to be used as the default options for a widget with provided size
-     */
-    public static Bundle getWidgetSizeOptions(
-            Context context, ComponentName provider, int spanX, int spanY) {
-        ArrayList<SizeF> sizes = getWidgetSizes(context, spanX, spanY);
-        Rect padding = getDefaultPaddingForWidget(context, provider, null);
-        float density = context.getResources().getDisplayMetrics().density;
-        float xPaddingDips = (padding.left + padding.right) / density;
-        float yPaddingDips = (padding.top + padding.bottom) / density;
-
-        ArrayList<SizeF> paddedSizes = sizes.stream()
-                .map(size -> new SizeF(
-                        Math.max(0.f, size.getWidth() - xPaddingDips),
-                        Math.max(0.f, size.getHeight() - yPaddingDips)))
-                .collect(Collectors.toCollection(ArrayList::new));
-
-        Rect rect = AppWidgetResizeFrame.getMinMaxSizes(paddedSizes);
-        Bundle options = new Bundle();
-        options.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, rect.left);
-        options.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT, rect.top);
-        options.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH, rect.right);
-        options.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT, rect.bottom);
-        options.putParcelableArrayList(AppWidgetManager.OPTION_APPWIDGET_SIZES, paddedSizes);
-        return options;
-    }
-
-    /**
-     * Returns the min and max widths and heights given a list of sizes, in dp.
-     *
-     * @param sizes List of sizes to get the min/max from.
-     * @return A rectangle with the left (resp. top) is used for the min width (resp. height) and
-     * the right (resp. bottom) for the max. The returned rectangle is set with 0s if the list is
-     * empty.
-     */
-    private static Rect getMinMaxSizes(List<SizeF> sizes) {
-        if (sizes.isEmpty()) {
-            return new Rect();
-        } else {
-            SizeF first = sizes.get(0);
-            Rect result = new Rect((int) first.getWidth(), (int) first.getHeight(),
-                    (int) first.getWidth(), (int) first.getHeight());
-            for (int i = 1; i < sizes.size(); i++) {
-                result.union((int) sizes.get(i).getWidth(), (int) sizes.get(i).getHeight());
-            }
-            return result;
-        }
-    }
-
     @Override
     protected void onDetachedFromWindow() {
         super.onDetachedFromWindow();
diff --git a/src/com/android/launcher3/WidgetPreviewLoader.java b/src/com/android/launcher3/WidgetPreviewLoader.java
index c7323d0..ff3584a 100644
--- a/src/com/android/launcher3/WidgetPreviewLoader.java
+++ b/src/com/android/launcher3/WidgetPreviewLoader.java
@@ -27,10 +27,10 @@
 import android.os.CancellationSignal;
 import android.os.Process;
 import android.os.UserHandle;
-import android.util.ArrayMap;
 import android.util.Log;
 import android.util.LongSparseArray;
 import android.util.Pair;
+import android.util.Size;
 
 import androidx.annotation.Nullable;
 
@@ -50,6 +50,7 @@
 import com.android.launcher3.widget.LauncherAppWidgetProviderInfo;
 import com.android.launcher3.widget.WidgetCell;
 import com.android.launcher3.widget.WidgetManagerHelper;
+import com.android.launcher3.widget.util.WidgetSizes;
 
 import java.util.ArrayList;
 import java.util.Collections;
@@ -79,9 +80,6 @@
     private final UserCache mUserCache;
     private final CacheDb mDb;
 
-    private final UserHandle mMyUser = Process.myUserHandle();
-    private final ArrayMap<UserHandle, Bitmap> mUserBadges = new ArrayMap<>();
-
     public WidgetPreviewLoader(Context context, IconCache iconCache) {
         mContext = context;
         mIconCache = iconCache;
@@ -366,9 +364,9 @@
             previewHeight = drawable.getIntrinsicHeight();
         } else {
             DeviceProfile dp = launcher.getDeviceProfile();
-            int tileSize = Math.min(dp.cellWidthPx, dp.cellHeightPx);
-            previewWidth = tileSize * spanX;
-            previewHeight = tileSize * spanY;
+            Size widgetSize = WidgetSizes.getWidgetSizePx(dp, spanX, spanY);
+            previewWidth = widgetSize.getWidth();
+            previewHeight = widgetSize.getHeight();
         }
 
         // Scale to fit width only - let the widget preview be clipped in the
diff --git a/src/com/android/launcher3/Workspace.java b/src/com/android/launcher3/Workspace.java
index 9a8f3dd..fdc69a7 100644
--- a/src/com/android/launcher3/Workspace.java
+++ b/src/com/android/launcher3/Workspace.java
@@ -117,6 +117,7 @@
 import com.android.launcher3.widget.PendingAppWidgetHostView;
 import com.android.launcher3.widget.WidgetManagerHelper;
 import com.android.launcher3.widget.dragndrop.AppWidgetHostViewDragListener;
+import com.android.launcher3.widget.util.WidgetSizes;
 import com.android.systemui.plugins.shared.LauncherOverlayManager.LauncherOverlay;
 
 import java.util.ArrayList;
@@ -1858,7 +1859,7 @@
                     item.spanX = resultSpan[0];
                     item.spanY = resultSpan[1];
                     AppWidgetHostView awhv = (AppWidgetHostView) cell;
-                    AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, resultSpan[0],
+                    WidgetSizes.updateWidgetSizeRanges(awhv, mLauncher, resultSpan[0],
                             resultSpan[1]);
                 }
 
@@ -2532,8 +2533,7 @@
                     ((PendingAddWidgetInfo) pendingInfo).boundWidget : null;
 
             if (finalView != null && updateWidgetSize) {
-                AppWidgetResizeFrame.updateWidgetSizeRanges(finalView, mLauncher, item.spanX,
-                        item.spanY);
+                WidgetSizes.updateWidgetSizeRanges(finalView, mLauncher, item.spanX, item.spanY);
             }
 
             int animationStyle = ANIMATE_INTO_POSITION_AND_DISAPPEAR;
diff --git a/src/com/android/launcher3/accessibility/LauncherAccessibilityDelegate.java b/src/com/android/launcher3/accessibility/LauncherAccessibilityDelegate.java
index 2b36f19..9faac5b 100644
--- a/src/com/android/launcher3/accessibility/LauncherAccessibilityDelegate.java
+++ b/src/com/android/launcher3/accessibility/LauncherAccessibilityDelegate.java
@@ -21,7 +21,6 @@
 import android.view.accessibility.AccessibilityNodeInfo;
 import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
 
-import com.android.launcher3.AppWidgetResizeFrame;
 import com.android.launcher3.BubbleTextView;
 import com.android.launcher3.ButtonDropTarget;
 import com.android.launcher3.CellLayout;
@@ -51,6 +50,7 @@
 import com.android.launcher3.views.OptionsPopupView;
 import com.android.launcher3.views.OptionsPopupView.OptionItem;
 import com.android.launcher3.widget.LauncherAppWidgetHostView;
+import com.android.launcher3.widget.util.WidgetSizes;
 
 import java.util.ArrayList;
 import java.util.Collections;
@@ -367,7 +367,7 @@
         }
 
         layout.markCellsAsOccupiedForView(host);
-        AppWidgetResizeFrame.updateWidgetSizeRanges(((LauncherAppWidgetHostView) host), mLauncher,
+        WidgetSizes.updateWidgetSizeRanges(((LauncherAppWidgetHostView) host), mLauncher,
                 info.spanX, info.spanY);
         host.requestLayout();
         mLauncher.getModelWriter().updateItemInDatabase(info);
diff --git a/src/com/android/launcher3/model/data/LauncherAppWidgetInfo.java b/src/com/android/launcher3/model/data/LauncherAppWidgetInfo.java
index 003b3bd..658c6e1 100644
--- a/src/com/android/launcher3/model/data/LauncherAppWidgetInfo.java
+++ b/src/com/android/launcher3/model/data/LauncherAppWidgetInfo.java
@@ -26,13 +26,13 @@
 
 import androidx.annotation.Nullable;
 
-import com.android.launcher3.AppWidgetResizeFrame;
 import com.android.launcher3.Launcher;
 import com.android.launcher3.LauncherSettings;
 import com.android.launcher3.logger.LauncherAtom;
 import com.android.launcher3.util.ContentWriter;
 import com.android.launcher3.widget.LauncherAppWidgetHostView;
 import com.android.launcher3.widget.LauncherAppWidgetProviderInfo;
+import com.android.launcher3.widget.util.WidgetSizes;
 
 /**
  * Represents a widget (either instantiated or about to be) in the Launcher.
@@ -196,7 +196,7 @@
      */
     public void onBindAppWidget(Launcher launcher, AppWidgetHostView hostView) {
         if (!mHasNotifiedInitialWidgetSizeChanged) {
-            AppWidgetResizeFrame.updateWidgetSizeRanges(hostView, launcher, spanX, spanY);
+            WidgetSizes.updateWidgetSizeRanges(hostView, launcher, spanX, spanY);
             mHasNotifiedInitialWidgetSizeChanged = true;
         }
     }
diff --git a/src/com/android/launcher3/qsb/QsbContainerView.java b/src/com/android/launcher3/qsb/QsbContainerView.java
index 22c3f58..23ee251 100644
--- a/src/com/android/launcher3/qsb/QsbContainerView.java
+++ b/src/com/android/launcher3/qsb/QsbContainerView.java
@@ -20,8 +20,6 @@
 import static android.appwidget.AppWidgetManager.EXTRA_APPWIDGET_ID;
 import static android.appwidget.AppWidgetManager.EXTRA_APPWIDGET_PROVIDER;
 
-import static com.android.launcher3.AppWidgetResizeFrame.getWidgetSizeOptions;
-
 import android.app.Activity;
 import android.app.Fragment;
 import android.app.SearchManager;
@@ -49,6 +47,7 @@
 import com.android.launcher3.Utilities;
 import com.android.launcher3.config.FeatureFlags;
 import com.android.launcher3.graphics.FragmentWithPreview;
+import com.android.launcher3.widget.util.WidgetSizes;
 
 /**
  * A frame layout which contains a QSB. This internally uses fragment to bind the view, which
@@ -292,7 +291,8 @@
 
         protected Bundle createBindOptions() {
             InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
-            return getWidgetSizeOptions(getContext(), mWidgetInfo.provider, idp.numColumns, 1);
+            return WidgetSizes.getWidgetSizeOptions(getContext(), mWidgetInfo.provider,
+                    idp.numColumns, 1);
         }
 
         protected View getDefaultView(ViewGroup container, boolean showSetupIcon) {
diff --git a/src/com/android/launcher3/widget/LauncherAppWidgetProviderInfo.java b/src/com/android/launcher3/widget/LauncherAppWidgetProviderInfo.java
index 14108f6..5a29171 100644
--- a/src/com/android/launcher3/widget/LauncherAppWidgetProviderInfo.java
+++ b/src/com/android/launcher3/widget/LauncherAppWidgetProviderInfo.java
@@ -32,13 +32,44 @@
 
     public static final String CLS_CUSTOM_WIDGET_PREFIX = "#custom-widget-";
 
+    /**
+     * The desired number of cells that this widget occupies horizontally in
+     * {@link com.android.launcher3.CellLayout}.
+     */
     public int spanX;
+
+    /**
+     * The desired number of cells that this widget occupies vertically in
+     * {@link com.android.launcher3.CellLayout}.
+     */
     public int spanY;
+
+    /**
+     * The minimum number of cells that this widget can occupy horizontally in
+     * {@link com.android.launcher3.CellLayout}.
+     */
     public int minSpanX;
+
+    /**
+     * The minimum number of cells that this widget can occupy vertically in
+     * {@link com.android.launcher3.CellLayout}.
+     */
     public int minSpanY;
+
+    /**
+     * The maximum number of cells that this widget can occupy horizontally in
+     * {@link com.android.launcher3.CellLayout}.
+     */
     public int maxSpanX;
+
+    /**
+     * The maximum number of cells that this widget can occupy vertically in
+     * {@link com.android.launcher3.CellLayout}.
+     */
     public int maxSpanY;
 
+    private boolean mIsMinSizeFulfilled;
+
     public static LauncherAppWidgetProviderInfo fromProviderInfo(Context context,
             AppWidgetProviderInfo info) {
         final LauncherAppWidgetProviderInfo launcherInfo;
@@ -133,8 +164,20 @@
         this.minSpanY = minSpanY;
         this.maxSpanX = maxSpanX;
         this.maxSpanY = maxSpanY;
-        this.spanX = spanX;
-        this.spanY = spanY;
+        this.mIsMinSizeFulfilled = Math.min(spanX, minSpanX) <= idp.numColumns
+            && Math.min(spanY, minSpanY) <= idp.numRows;
+        // Ensures the default span X and span Y will not exceed the current grid size.
+        this.spanX = Math.min(spanX, idp.numColumns);
+        this.spanY = Math.min(spanY, idp.numRows);
+    }
+
+    /**
+     * Returns {@code true} if the widget's minimum size requirement can be fulfilled in the device
+     * grid setting, {@link InvariantDeviceProfile}, that was passed in
+     * {@link #initSpans(Context, InvariantDeviceProfile)}.
+     */
+    public boolean isMinSizeFulfilled() {
+        return mIsMinSizeFulfilled;
     }
 
     private int getSpanX(Rect widgetPadding, int widgetWidth, int cellSpacing, float cellWidth) {
diff --git a/src/com/android/launcher3/widget/PendingAddWidgetInfo.java b/src/com/android/launcher3/widget/PendingAddWidgetInfo.java
index 3377abb..c04c8dc 100644
--- a/src/com/android/launcher3/widget/PendingAddWidgetInfo.java
+++ b/src/com/android/launcher3/widget/PendingAddWidgetInfo.java
@@ -15,7 +15,6 @@
  */
 package com.android.launcher3.widget;
 
-import static com.android.launcher3.AppWidgetResizeFrame.getWidgetSizeOptions;
 import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_WIDGETS_TRAY;
 
 import android.appwidget.AppWidgetHostView;
@@ -24,6 +23,7 @@
 
 import com.android.launcher3.LauncherSettings;
 import com.android.launcher3.PendingAddItemInfo;
+import com.android.launcher3.widget.util.WidgetSizes;
 
 /**
  * Meta data used for late binding of {@link LauncherAppWidgetProviderInfo}.
@@ -61,6 +61,6 @@
     }
 
     public Bundle getDefaultSizeOptions(Context context) {
-        return getWidgetSizeOptions(context, componentName, spanX, spanY);
+        return WidgetSizes.getWidgetSizeOptions(context, componentName, spanX, spanY);
     }
 }
diff --git a/src/com/android/launcher3/widget/WidgetCell.java b/src/com/android/launcher3/widget/WidgetCell.java
index e1999c9..b1ccfd9 100644
--- a/src/com/android/launcher3/widget/WidgetCell.java
+++ b/src/com/android/launcher3/widget/WidgetCell.java
@@ -21,12 +21,12 @@
 import android.content.Context;
 import android.content.res.Resources;
 import android.graphics.Bitmap;
-import android.graphics.Point;
 import android.graphics.Rect;
 import android.graphics.drawable.Drawable;
 import android.os.CancellationSignal;
 import android.util.AttributeSet;
 import android.util.Log;
+import android.util.Size;
 import android.view.Gravity;
 import android.view.MotionEvent;
 import android.view.View;
@@ -48,6 +48,7 @@
 import com.android.launcher3.icons.FastBitmapDrawable;
 import com.android.launcher3.icons.RoundDrawableWrapper;
 import com.android.launcher3.model.WidgetItem;
+import com.android.launcher3.widget.util.WidgetSizes;
 
 /**
  * Represents the individual cell of the widget inside the widget tray. The preview is drawn
@@ -96,7 +97,7 @@
     protected final BaseActivity mActivity;
     private final CheckLongPressHelper mLongPressHelper;
     private final float mEnforcedCornerRadius;
-    private final int mPreviewPadding;
+    private final int mShortcutPreviewPadding;
 
     private RemoteViews mRemoteViewsPreview;
     private NavigableAppWidgetHostView mAppWidgetHostViewPreview;
@@ -114,14 +115,14 @@
 
         mActivity = BaseActivity.fromContext(context);
         mLongPressHelper = new CheckLongPressHelper(this);
-
         mLongPressHelper.setLongPressTimeoutFactor(1);
+
         setContainerWidth();
         setWillNotDraw(false);
         setClipToPadding(false);
         setAccessibilityDelegate(mActivity.getAccessibilityDelegate());
         mEnforcedCornerRadius = RoundedCornerEnforcement.computeEnforcedRadius(context);
-        mPreviewPadding =
+        mShortcutPreviewPadding =
                 2 * getResources().getDimensionPixelSize(R.dimen.widget_preview_shortcut_padding);
     }
 
@@ -200,6 +201,8 @@
         mWidgetPreviewLoader = loader;
         if (item.activityInfo != null) {
             setTag(new PendingAddShortcutInfo(item.activityInfo));
+            mPreviewWidth += mShortcutPreviewPadding;
+            mPreviewHeight += mShortcutPreviewPadding;
         } else {
             setTag(new PendingAddWidgetInfo(item.widgetInfo));
         }
@@ -251,8 +254,6 @@
         }
         appWidgetHostViewPreview.setPadding(padding.left, padding.top, padding.right,
                 padding.bottom);
-        mPreviewWidth += padding.left + padding.right;
-        mPreviewHeight += padding.top + padding.bottom;
         appWidgetHostViewPreview.updateAppWidget(remoteViews);
     }
 
@@ -299,7 +300,7 @@
             float scale = 1f;
             if (getWidth() > 0 && getHeight() > 0) {
                 // Scale down the preview size if it's wider than the cell.
-                float maxWidth = getWidth() - mPreviewPadding;
+                float maxWidth = getWidth();
                 float previewWidth = drawable.getIntrinsicWidth() * mPreviewScale;
                 scale = Math.min(maxWidth / previewWidth, 1);
             }
@@ -355,11 +356,9 @@
     /** Sets the widget preview image size, in number of cells, and preview scale. */
     public void setPreviewSize(int spanX, int spanY, float previewScale) {
         DeviceProfile deviceProfile = mActivity.getDeviceProfile();
-        Point cellSize = deviceProfile.getCellSize();
-        mPreviewWidth = cellSize.x * spanX + mPreviewPadding
-                + deviceProfile.cellLayoutBorderSpacingPx * (spanX - 1);
-        mPreviewHeight = cellSize.y * spanY + mPreviewPadding
-                + deviceProfile.cellLayoutBorderSpacingPx * (spanY - 1);
+        Size widgetSize = WidgetSizes.getWidgetSizePx(deviceProfile, spanX, spanY);
+        mPreviewWidth = widgetSize.getWidth();
+        mPreviewHeight = widgetSize.getHeight();
         mPreviewScale = previewScale;
     }
 
diff --git a/src/com/android/launcher3/widget/picker/WidgetsRecommendationTableLayout.java b/src/com/android/launcher3/widget/picker/WidgetsRecommendationTableLayout.java
index 62ef4ff..9167d87 100644
--- a/src/com/android/launcher3/widget/picker/WidgetsRecommendationTableLayout.java
+++ b/src/com/android/launcher3/widget/picker/WidgetsRecommendationTableLayout.java
@@ -18,6 +18,7 @@
 import android.content.Context;
 import android.util.AttributeSet;
 import android.util.Log;
+import android.util.Size;
 import android.view.Gravity;
 import android.view.LayoutInflater;
 import android.view.View;
@@ -33,6 +34,7 @@
 import com.android.launcher3.R;
 import com.android.launcher3.model.WidgetItem;
 import com.android.launcher3.widget.WidgetCell;
+import com.android.launcher3.widget.util.WidgetSizes;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -44,7 +46,6 @@
     private static final float MAX_DOWN_SCALE_RATIO = 0.5f;
     private final float mWidgetsRecommendationTableVerticalPadding;
     private final float mWidgetCellTextViewsHeight;
-    private final float mWidgetPreviewPadding;
 
     private float mRecommendationTableMaxHeight = Float.MAX_VALUE;
     @Nullable private OnLongClickListener mWidgetCellOnLongClickListener;
@@ -61,8 +62,6 @@
         mWidgetsRecommendationTableVerticalPadding = 2 * getResources()
                 .getDimensionPixelSize(R.dimen.widget_cell_vertical_padding);
         mWidgetCellTextViewsHeight = 4 * getResources().getDimension(R.dimen.widget_cell_font_size);
-        mWidgetPreviewPadding = 2 * getResources()
-                .getDimensionPixelSize(R.dimen.widget_preview_shortcut_padding);
     }
 
     /** Sets a {@link android.view.View.OnLongClickListener} for all widget cells in this table. */
@@ -149,8 +148,10 @@
             List<WidgetItem> widgetItems = recommendedWidgetsInTable.get(i);
             float rowHeight = 0;
             for (int j = 0; j < widgetItems.size(); j++) {
-                float previewHeight = widgetItems.get(j).spanY * deviceProfile.cellHeightPx
-                        * previewScale + mWidgetPreviewPadding;
+                WidgetItem widgetItem = widgetItems.get(j);
+                Size widgetSize = WidgetSizes.getWidgetSizePx(
+                        deviceProfile, widgetItem.spanX, widgetItem.spanY);
+                float previewHeight = widgetSize.getHeight() * previewScale;
                 rowHeight = Math.max(rowHeight, previewHeight + mWidgetCellTextViewsHeight);
             }
             totalHeight += rowHeight;
diff --git a/src/com/android/launcher3/widget/util/WidgetSizes.java b/src/com/android/launcher3/widget/util/WidgetSizes.java
new file mode 100644
index 0000000..5c8ea72
--- /dev/null
+++ b/src/com/android/launcher3/widget/util/WidgetSizes.java
@@ -0,0 +1,145 @@
+/*
+ * 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.util;
+
+import static android.appwidget.AppWidgetHostView.getDefaultPaddingForWidget;
+
+import static com.android.launcher3.Utilities.ATLEAST_S;
+
+import android.annotation.SuppressLint;
+import android.appwidget.AppWidgetHostView;
+import android.appwidget.AppWidgetManager;
+import android.content.ComponentName;
+import android.content.Context;
+import android.graphics.Point;
+import android.graphics.Rect;
+import android.os.Bundle;
+import android.util.Size;
+import android.util.SizeF;
+
+import androidx.annotation.Nullable;
+
+import com.android.launcher3.DeviceProfile;
+import com.android.launcher3.LauncherAppState;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+/** A utility class for widget sizes related calculations. */
+public final class WidgetSizes {
+
+    /**
+     * Returns the list of all possible sizes, in dp, for a widget of given spans on this device.
+     */
+    public static ArrayList<SizeF> getWidgetSizes(Context context, int spanX, int spanY) {
+        ArrayList<SizeF> sizes = new ArrayList<>(2);
+        final float density = context.getResources().getDisplayMetrics().density;
+        final Point cellSize = new Point();
+
+        for (DeviceProfile profile : LauncherAppState.getIDP(context).supportedProfiles) {
+            Size widgetSizePx = getWidgetSizePx(profile, spanX, spanY, cellSize);
+            sizes.add(new SizeF(widgetSizePx.getWidth() / density,
+                    widgetSizePx.getHeight() / density));
+        }
+        return sizes;
+    }
+
+    /** Returns the size, in pixels, a widget of given spans & {@code profile}. */
+    public static Size getWidgetSizePx(DeviceProfile profile, int spanX, int spanY) {
+        return getWidgetSizePx(profile, spanX, spanY, /* recycledCellSize= */ null);
+    }
+
+    private static Size getWidgetSizePx(DeviceProfile profile, int spanX, int spanY,
+            @Nullable Point recycledCellSize) {
+        final int hBorderSpacing = (spanX - 1) * profile.cellLayoutBorderSpacingPx;
+        final int vBorderSpacing = (spanY - 1) * profile.cellLayoutBorderSpacingPx;
+        if (recycledCellSize == null) {
+            recycledCellSize = new Point();
+        }
+        profile.getCellSize(recycledCellSize);
+        return new Size(((spanX * recycledCellSize.x) + hBorderSpacing),
+                ((spanY * recycledCellSize.y) + vBorderSpacing));
+    }
+
+    /**
+     * Updates a given {@code widgetView} with size, {@code spanX}, {@code spanY}.
+     *
+     * <p>On Android S+, it also updates the given {@code widgetView} with a list of sizes derived
+     * from {@code spanX}, {@code spanY} in all supported device profiles.
+     */
+    @SuppressLint("NewApi") // Already added API check.
+    public static void updateWidgetSizeRanges(AppWidgetHostView widgetView, Context context,
+            int spanX, int spanY) {
+        List<SizeF> sizes = getWidgetSizes(context, spanX, spanY);
+        if (ATLEAST_S) {
+            widgetView.updateAppWidgetSize(new Bundle(), sizes);
+        } else {
+            Rect bounds = getMinMaxSizes(sizes);
+            widgetView.updateAppWidgetSize(new Bundle(), bounds.left, bounds.top, bounds.right,
+                    bounds.bottom);
+        }
+    }
+
+    /**
+     * Returns the bundle to be used as the default options for a widget with provided size.
+     */
+    public static Bundle getWidgetSizeOptions(Context context, ComponentName provider, int spanX,
+            int spanY) {
+        ArrayList<SizeF> sizes = getWidgetSizes(context, spanX, spanY);
+        Rect padding = getDefaultPaddingForWidget(context, provider, null);
+        float density = context.getResources().getDisplayMetrics().density;
+        float xPaddingDips = (padding.left + padding.right) / density;
+        float yPaddingDips = (padding.top + padding.bottom) / density;
+
+        ArrayList<SizeF> paddedSizes = sizes.stream()
+                .map(size -> new SizeF(
+                        Math.max(0.f, size.getWidth() - xPaddingDips),
+                        Math.max(0.f, size.getHeight() - yPaddingDips)))
+                .collect(Collectors.toCollection(ArrayList::new));
+
+        Rect rect = getMinMaxSizes(paddedSizes);
+        Bundle options = new Bundle();
+        options.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, rect.left);
+        options.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT, rect.top);
+        options.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH, rect.right);
+        options.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT, rect.bottom);
+        options.putParcelableArrayList(AppWidgetManager.OPTION_APPWIDGET_SIZES, paddedSizes);
+        return options;
+    }
+
+    /**
+     * Returns the min and max widths and heights given a list of sizes, in dp.
+     *
+     * @param sizes List of sizes to get the min/max from.
+     * @return A rectangle with the left (resp. top) is used for the min width (resp. height) and
+     * the right (resp. bottom) for the max. The returned rectangle is set with 0s if the list is
+     * empty.
+     */
+    private static Rect getMinMaxSizes(List<SizeF> sizes) {
+        if (sizes.isEmpty()) {
+            return new Rect();
+        } else {
+            SizeF first = sizes.get(0);
+            Rect result = new Rect((int) first.getWidth(), (int) first.getHeight(),
+                    (int) first.getWidth(), (int) first.getHeight());
+            for (int i = 1; i < sizes.size(); i++) {
+                result.union((int) sizes.get(i).getWidth(), (int) sizes.get(i).getHeight());
+            }
+            return result;
+        }
+    }
+}
diff --git a/src_shortcuts_overrides/com/android/launcher3/model/WidgetsModel.java b/src_shortcuts_overrides/com/android/launcher3/model/WidgetsModel.java
index be18e54..51c5b12 100644
--- a/src_shortcuts_overrides/com/android/launcher3/model/WidgetsModel.java
+++ b/src_shortcuts_overrides/com/android/launcher3/model/WidgetsModel.java
@@ -254,13 +254,11 @@
                 }
 
                 // Ensure that all widgets we show can be added on a workspace of this size
-                int minSpanX = Math.min(item.widgetInfo.spanX, item.widgetInfo.minSpanX);
-                int minSpanY = Math.min(item.widgetInfo.spanY, item.widgetInfo.minSpanY);
-                if (minSpanX > mIdp.numColumns || minSpanY > mIdp.numRows) {
+                if (!item.widgetInfo.isMinSizeFulfilled()) {
                     if (DEBUG) {
                         Log.d(TAG, String.format(
-                                "Widget %s : (%d X %d) can't fit on this device",
-                                item.componentName, minSpanX, minSpanY));
+                                "Widget %s : can't fit on this device with a grid size: %dx%d",
+                                item.componentName, mIdp.numColumns, mIdp.numRows));
                     }
                     return false;
                 }