Merge "Sanitizing various search container ids and layout names" into ub-launcher3-dorval-polish
diff --git a/res/drawable-hdpi/all_apps_alpha_mask.png b/res/drawable-hdpi/all_apps_alpha_mask.png
new file mode 100755
index 0000000..01e9e56
--- /dev/null
+++ b/res/drawable-hdpi/all_apps_alpha_mask.png
Binary files differ
diff --git a/res/drawable-mdpi/all_apps_alpha_mask.png b/res/drawable-mdpi/all_apps_alpha_mask.png
new file mode 100755
index 0000000..f24e71d
--- /dev/null
+++ b/res/drawable-mdpi/all_apps_alpha_mask.png
Binary files differ
diff --git a/res/drawable-xhdpi/all_apps_alpha_mask.png b/res/drawable-xhdpi/all_apps_alpha_mask.png
new file mode 100755
index 0000000..f479433
--- /dev/null
+++ b/res/drawable-xhdpi/all_apps_alpha_mask.png
Binary files differ
diff --git a/res/drawable-xxhdpi/all_apps_alpha_mask.png b/res/drawable-xxhdpi/all_apps_alpha_mask.png
new file mode 100755
index 0000000..d5facd7
--- /dev/null
+++ b/res/drawable-xxhdpi/all_apps_alpha_mask.png
Binary files differ
diff --git a/res/drawable/all_apps_alpha_mask.png b/res/drawable-xxxhdpi/all_apps_alpha_mask.png
old mode 100644
new mode 100755
similarity index 100%
rename from res/drawable/all_apps_alpha_mask.png
rename to res/drawable-xxxhdpi/all_apps_alpha_mask.png
Binary files differ
diff --git a/res/drawable/gutter_horizontal.xml b/res/drawable/gutter_horizontal.xml
new file mode 100644
index 0000000..95b03df
--- /dev/null
+++ b/res/drawable/gutter_horizontal.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- This "gutter" has a shadow at the top and a subtler shadow on the bottom. -->
+<shape xmlns:android="http://schemas.android.com/apk/res/android">
+    <gradient android:type="linear"
+              android:angle="-90"
+              android:startColor="#ffE0E0E0"
+              android:centerColor="#ffffffff"
+              android:endColor="#ffF5F5F5" />
+</shape>
\ No newline at end of file
diff --git a/res/interpolator/large_folder_preview_item_interpolator.xml b/res/interpolator/large_folder_preview_item_close_interpolator.xml
similarity index 90%
copy from res/interpolator/large_folder_preview_item_interpolator.xml
copy to res/interpolator/large_folder_preview_item_close_interpolator.xml
index dcf0157..d28af63 100644
--- a/res/interpolator/large_folder_preview_item_interpolator.xml
+++ b/res/interpolator/large_folder_preview_item_close_interpolator.xml
@@ -18,7 +18,7 @@
 -->
 
 <pathInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
-    android:controlX1="0"
-    android:controlY1="1"
-    android:controlX2="0"
+    android:controlX1="0.3"
+    android:controlY1="0"
+    android:controlX2="1"
     android:controlY2="1"/>
diff --git a/res/interpolator/large_folder_preview_item_interpolator.xml b/res/interpolator/large_folder_preview_item_open_interpolator.xml
similarity index 96%
rename from res/interpolator/large_folder_preview_item_interpolator.xml
rename to res/interpolator/large_folder_preview_item_open_interpolator.xml
index dcf0157..b5661ab 100644
--- a/res/interpolator/large_folder_preview_item_interpolator.xml
+++ b/res/interpolator/large_folder_preview_item_open_interpolator.xml
@@ -20,5 +20,5 @@
 <pathInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
     android:controlX1="0"
     android:controlY1="1"
-    android:controlX2="0"
+    android:controlX2="0.5"
     android:controlY2="1"/>
diff --git a/res/layout/notification.xml b/res/layout/notification.xml
index 085dfa9..4a02aa1 100644
--- a/res/layout/notification.xml
+++ b/res/layout/notification.xml
@@ -28,6 +28,13 @@
         android:orientation="vertical"
         android:clipChildren="false">
 
+        <View
+            android:id="@+id/gutter_top"
+            android:layout_width="match_parent"
+            android:layout_height="4dp"
+            android:theme="@style/PopupGutter"
+            android:visibility="gone" />
+
         <FrameLayout
             android:id="@+id/header"
             android:layout_width="match_parent"
@@ -35,22 +42,23 @@
             android:paddingStart="@dimen/notification_padding_start"
             android:paddingEnd="@dimen/notification_padding_end"
             android:background="?attr/popupColorPrimary"
-            android:elevation="@dimen/notification_elevation">
+            android:elevation="@dimen/notification_elevation"
+            android:layout_below="@id/gutter_top" >
             <TextView
                 android:id="@+id/notification_text"
                 android:layout_width="wrap_content"
                 android:layout_height="match_parent"
                 android:layout_gravity="start"
-                android:gravity="center_vertical"
+                android:gravity="bottom"
                 android:text="@string/notifications_header"
                 android:textSize="@dimen/notification_header_text_size"
-                android:textColor="?android:attr/textColorSecondary" />
+                android:textColor="?android:attr/textColorPrimary" />
             <TextView
                 android:id="@+id/notification_count"
                 android:layout_width="@dimen/notification_icon_size"
                 android:layout_height="match_parent"
                 android:layout_gravity="end"
-                android:gravity="center"
+                android:gravity="bottom|center_horizontal"
                 android:textSize="@dimen/notification_header_count_text_size"
                 android:fontFamily="sans-serif-medium"
                 android:textColor="?android:attr/textColorPrimary" />
@@ -76,6 +84,14 @@
             android:layout_height="@dimen/notification_footer_height"
             android:layout_below="@id/divider" />
 
+        <View
+            android:id="@+id/gutter_bottom"
+            android:layout_width="match_parent"
+            android:layout_height="4dp"
+            android:theme="@style/PopupGutter"
+            android:visibility="gone"
+            android:layout_below="@id/footer" />
+
     </RelativeLayout>
 
 </com.android.launcher3.notification.NotificationItemView>
diff --git a/res/layout/notification_main.xml b/res/layout/notification_main.xml
index 7a8cf6d..f681e8b 100644
--- a/res/layout/notification_main.xml
+++ b/res/layout/notification_main.xml
@@ -38,7 +38,7 @@
             android:layout_height="wrap_content"
             android:textAlignment="viewStart"
             android:fontFamily="sans-serif"
-            android:textSize="@dimen/notification_main_text_size"
+            android:textSize="@dimen/notification_main_title_size"
             android:textColor="?android:attr/textColorPrimary"
             android:lines="1"
             android:ellipsize="end" />
diff --git a/res/values-ca/strings.xml b/res/values-ca/strings.xml
index 88b02bb..a6821df 100644
--- a/res/values-ca/strings.xml
+++ b/res/values-ca/strings.xml
@@ -77,8 +77,8 @@
     <string name="allow_rotation_desc" msgid="8662546029078692509">"En girar el telèfon"</string>
     <string name="allow_rotation_blocked_desc" msgid="3212602545192996253">"La configuració actual de la pantalla no permet la rotació"</string>
     <string name="icon_badging_title" msgid="874121399231955394">"Punts de notificació"</string>
-    <string name="icon_badging_desc_on" msgid="2627952638544674079">"Activada"</string>
-    <string name="icon_badging_desc_off" msgid="5503319969924580241">"Desactivada"</string>
+    <string name="icon_badging_desc_on" msgid="2627952638544674079">"Activat"</string>
+    <string name="icon_badging_desc_off" msgid="5503319969924580241">"Desactivat"</string>
     <string name="auto_add_shortcuts_label" msgid="8222286205987725611">"Afegeix la icona a la pantalla d\'inici"</string>
     <string name="auto_add_shortcuts_description" msgid="7117251166066978730">"Per a les aplicacions noves"</string>
     <!-- no translation found for icon_shape_override_label (2977264953998281004) -->
diff --git a/res/values-land/dimens.xml b/res/values-land/dimens.xml
index 08073ce..0db0e61 100644
--- a/res/values-land/dimens.xml
+++ b/res/values-land/dimens.xml
@@ -27,8 +27,7 @@
     <!-- Dynamic grid -->
     <dimen name="dynamic_grid_overview_bar_item_width">120dp</dimen>
     <dimen name="dynamic_grid_page_indicator_size">24dp</dimen>
-    <dimen name="dynamic_grid_icon_drawable_padding">8dp</dimen>
-    <dimen name="dynamic_grid_cell_padding_x">8dp</dimen>
+    <dimen name="folder_preview_padding">5dp</dimen>
 
     <!-- Hotseat -->
     <dimen name="dynamic_grid_hotseat_land_left_nav_bar_right_padding">18dp</dimen>
diff --git a/res/values/config.xml b/res/values/config.xml
index fe5af28..e9c62a7 100644
--- a/res/values/config.xml
+++ b/res/values/config.xml
@@ -124,7 +124,7 @@
     <item type="id" name="preview_image_id" />
 
 <!-- Popup items -->
-    <integer name="config_popupOpenCloseDuration">220</integer>
+    <integer name="config_popupOpenCloseDuration">150</integer>
     <integer name="config_popupArrowOpenDuration">80</integer>
     <integer name="config_removeNotificationViewDuration">300</integer>
 
diff --git a/res/values/dimens.xml b/res/values/dimens.xml
index a4dff71..980b714 100644
--- a/res/values/dimens.xml
+++ b/res/values/dimens.xml
@@ -213,6 +213,7 @@
     <dimen name="notification_footer_height">32dp</dimen>
     <dimen name="notification_header_text_size">13sp</dimen>
     <dimen name="notification_header_count_text_size">12sp</dimen>
+    <dimen name="notification_main_title_size">16sp</dimen>
     <dimen name="notification_main_text_size">14sp</dimen>
     <dimen name="notification_icon_size">24dp</dimen>
     <dimen name="notification_footer_icon_size">18dp</dimen>
diff --git a/res/values/styles.xml b/res/values/styles.xml
index 01ae49d..5bdf512 100644
--- a/res/values/styles.xml
+++ b/res/values/styles.xml
@@ -140,6 +140,13 @@
     <style name="PopupItem">
         <item name="android:colorControlHighlight">?attr/popupColorTertiary</item>
     </style>
+    <style name="PopupGutter">
+        <item name="android:backgroundTintMode">multiply</item>
+        <item name="android:backgroundTint">?attr/popupColorSecondary</item>
+        <item name="android:background">@drawable/gutter_horizontal</item>
+        <item name="android:elevation">@dimen/notification_elevation</item>
+        <item name="android:outlineProvider">none</item>
+    </style>
 
     <!-- Drop targets -->
     <style name="DropTargetButtonBase">
diff --git a/src/com/android/launcher3/BubbleTextView.java b/src/com/android/launcher3/BubbleTextView.java
index 6f2c897..aeb82b3 100644
--- a/src/com/android/launcher3/BubbleTextView.java
+++ b/src/com/android/launcher3/BubbleTextView.java
@@ -44,6 +44,7 @@
 import com.android.launcher3.IconCache.ItemInfoUpdateReceiver;
 import com.android.launcher3.badge.BadgeInfo;
 import com.android.launcher3.badge.BadgeRenderer;
+import com.android.launcher3.folder.FolderIcon;
 import com.android.launcher3.folder.FolderIconPreviewVerifier;
 import com.android.launcher3.graphics.DrawableFactory;
 import com.android.launcher3.graphics.HolographicOutlineHelper;
@@ -438,6 +439,13 @@
         super.setTextColor(colors);
     }
 
+    public boolean shouldTextBeVisible() {
+        // Text should be visible everywhere but the hotseat.
+        Object tag = getParent() instanceof FolderIcon ? ((View) getParent()).getTag() : getTag();
+        ItemInfo info = tag instanceof ItemInfo ? (ItemInfo) tag : null;
+        return info == null || info.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT;
+    }
+
     public void setTextVisibility(boolean visible) {
         if (visible) {
             super.setTextColor(mTextColor);
@@ -459,7 +467,8 @@
      * @param fadeIn Whether the text should fade in or fade out.
      */
     public ObjectAnimator createTextAlphaAnimator(boolean fadeIn) {
-        return ObjectAnimator.ofInt(this, TEXT_ALPHA_PROPERTY, fadeIn ? Color.alpha(mTextColor) : 0);
+        int toAlpha = shouldTextBeVisible() && fadeIn ? Color.alpha(mTextColor) : 0;
+        return ObjectAnimator.ofInt(this, TEXT_ALPHA_PROPERTY, toAlpha);
     }
 
     @Override
diff --git a/src/com/android/launcher3/CellLayout.java b/src/com/android/launcher3/CellLayout.java
index d99a30a..42b64ea 100644
--- a/src/com/android/launcher3/CellLayout.java
+++ b/src/com/android/launcher3/CellLayout.java
@@ -606,7 +606,7 @@
         // Hotseat icons - remove text
         if (child instanceof BubbleTextView) {
             BubbleTextView bubbleChild = (BubbleTextView) child;
-            bubbleChild.setTextVisibility(mContainerType != HOTSEAT);
+            bubbleChild.setTextVisibility(bubbleChild.shouldTextBeVisible());
         }
 
         child.setScaleX(mChildScale);
diff --git a/src/com/android/launcher3/DeviceProfile.java b/src/com/android/launcher3/DeviceProfile.java
index dcfb268..eef6510 100644
--- a/src/com/android/launcher3/DeviceProfile.java
+++ b/src/com/android/launcher3/DeviceProfile.java
@@ -344,7 +344,7 @@
         updateFolderCellSize(1f, dm, res);
 
         // Don't let the folder get too close to the edges of the screen.
-        int folderMargin = 4 * edgeMarginPx;
+        int folderMargin = edgeMarginPx;
 
         // Check if the icons fit within the available height.
         float usedHeight = folderCellHeightPx * inv.numFolderRows + folderBottomPanelSize;
@@ -497,7 +497,7 @@
             // In portrait, we want the pages spaced such that there is no
             // overhang of the previous / next page into the current page viewport.
             // We assume symmetrical padding in portrait mode.
-            return Math.max(defaultPageSpacingPx, getWorkspacePadding(null).left + 1);
+            return Math.max(defaultPageSpacingPx, getWorkspacePadding(null).left / 2 + 1);
         }
     }
 
diff --git a/src/com/android/launcher3/FirstFrameAnimatorHelper.java b/src/com/android/launcher3/FirstFrameAnimatorHelper.java
index a51ddd4..3cbc989 100644
--- a/src/com/android/launcher3/FirstFrameAnimatorHelper.java
+++ b/src/com/android/launcher3/FirstFrameAnimatorHelper.java
@@ -23,7 +23,6 @@
 import android.view.View;
 import android.view.ViewPropertyAnimator;
 import android.view.ViewTreeObserver;
-
 import com.android.launcher3.util.Thunk;
 
 /*
@@ -33,10 +32,11 @@
  */
 public class FirstFrameAnimatorHelper extends AnimatorListenerAdapter
     implements ValueAnimator.AnimatorUpdateListener {
+    private static final String TAG = "FirstFrameAnimatorHlpr";
     private static final boolean DEBUG = false;
     private static final int MAX_DELAY = 1000;
     private static final int IDEAL_FRAME_DURATION = 16;
-    private View mTarget;
+    private final View mTarget;
     private long mStartFrame;
     private long mStartTime = -1;
     private boolean mHandlingOnAnimationUpdate;
@@ -77,7 +77,7 @@
                     sGlobalFrameCounter++;
                     if (DEBUG) {
                         long newTime = System.currentTimeMillis();
-                        Log.d("FirstFrameAnimatorHelper", "TICK " + (newTime - mTime));
+                        Log.d(TAG, "TICK " + (newTime - mTime));
                         mTime = newTime;
                     }
                 }
@@ -139,7 +139,7 @@
 
     public void print(ValueAnimator animation) {
         float flatFraction = animation.getCurrentPlayTime() / (float) animation.getDuration();
-        Log.d("FirstFrameAnimatorHelper", sGlobalFrameCounter +
+        Log.d(TAG, sGlobalFrameCounter +
               "(" + (sGlobalFrameCounter - mStartFrame) + ") " + mTarget + " dirty? " +
               mTarget.isDirty() + " " + flatFraction + " " + this + " " + animation);
     }
diff --git a/src/com/android/launcher3/FolderInfo.java b/src/com/android/launcher3/FolderInfo.java
index 21254ab..7959d40 100644
--- a/src/com/android/launcher3/FolderInfo.java
+++ b/src/com/android/launcher3/FolderInfo.java
@@ -45,6 +45,12 @@
      */
     public static final int FLAG_MULTI_PAGE_ANIMATION = 0x00000004;
 
+    /**
+     * The folder items ranks have been updated such that they appear unchanged with the new
+     * permutation display logic.
+     */
+    public static final int FLAG_ITEM_RANKS_UPDATED = 0x00000008;
+
     public int options;
 
     /**
diff --git a/src/com/android/launcher3/IconCache.java b/src/com/android/launcher3/IconCache.java
index 383e6ef..a23a674 100644
--- a/src/com/android/launcher3/IconCache.java
+++ b/src/com/android/launcher3/IconCache.java
@@ -41,7 +41,6 @@
 import android.support.annotation.NonNull;
 import android.text.TextUtils;
 import android.util.Log;
-
 import com.android.launcher3.compat.LauncherAppsCompat;
 import com.android.launcher3.compat.UserManagerCompat;
 import com.android.launcher3.config.FeatureFlags;
@@ -52,7 +51,6 @@
 import com.android.launcher3.util.Provider;
 import com.android.launcher3.util.SQLiteCacheHelper;
 import com.android.launcher3.util.Thunk;
-
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
@@ -91,7 +89,7 @@
 
     private final Context mContext;
     private final PackageManager mPackageManager;
-    private IconProvider mIconProvider;
+    private final IconProvider mIconProvider;
     @Thunk final UserManagerCompat mUserManager;
     private final LauncherAppsCompat mLauncherApps;
     private final HashMap<ComponentKey, CacheEntry> mCache =
@@ -122,7 +120,7 @@
     }
 
     private Drawable getFullResDefaultActivityIcon() {
-        return getFullResIcon(Resources.getSystem(), android.R.mipmap.sym_def_app_icon);
+        return getFullResIcon(Resources.getSystem(), android.R.drawable.sym_def_app_icon);
     }
 
     private Drawable getFullResIcon(Resources resources, int iconId) {
@@ -193,7 +191,7 @@
      * Remove any records for the supplied package name from memory.
      */
     private void removeFromMemCacheLocked(String packageName, UserHandle user) {
-        HashSet<ComponentKey> forDeletion = new HashSet<ComponentKey>();
+        HashSet<ComponentKey> forDeletion = new HashSet<>();
         for (ComponentKey key: mCache.keySet()) {
             if (key.componentName.getPackageName().equals(packageName)
                     && key.user.equals(user)) {
@@ -219,7 +217,6 @@
             }
         } catch (NameNotFoundException e) {
             Log.d(TAG, "Package not found", e);
-            return;
         }
     }
 
@@ -264,7 +261,7 @@
             Set<String> ignorePackages) {
         long userSerial = mUserManager.getSerialNumberForUser(user);
         PackageManager pm = mContext.getPackageManager();
-        HashMap<String, PackageInfo> pkgInfoMap = new HashMap<String, PackageInfo>();
+        HashMap<String, PackageInfo> pkgInfoMap = new HashMap<>();
         for (PackageInfo info : pm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES)) {
             pkgInfoMap.put(info.packageName, info);
         }
@@ -274,7 +271,7 @@
             componentMap.put(app.getComponentName(), app);
         }
 
-        HashSet<Integer> itemsToRemove = new HashSet<Integer>();
+        HashSet<Integer> itemsToRemove = new HashSet<>();
         Stack<LauncherActivityInfo> appsToUpdate = new Stack<>();
 
         Cursor c = null;
@@ -704,7 +701,7 @@
         private final HashMap<String, PackageInfo> mPkgInfoMap;
         private final Stack<LauncherActivityInfo> mAppsToAdd;
         private final Stack<LauncherActivityInfo> mAppsToUpdate;
-        private final HashSet<String> mUpdatedPackages = new HashSet<String>();
+        private final HashSet<String> mUpdatedPackages = new HashSet<>();
 
         @Thunk SerializedIconUpdateTask(long userSerial, HashMap<String, PackageInfo> pkgInfoMap,
                 Stack<LauncherActivityInfo> appsToAdd,
@@ -753,7 +750,7 @@
     }
 
     private static final class IconDB extends SQLiteCacheHelper {
-        private final static int DB_VERSION = 16;
+        private final static int DB_VERSION = 17;
 
         private final static int RELEASE_VERSION = DB_VERSION +
                 (FeatureFlags.LAUNCHER3_DISABLE_ICON_NORMALIZATION ? 0 : 1);
diff --git a/src/com/android/launcher3/LauncherProvider.java b/src/com/android/launcher3/LauncherProvider.java
index 4813571..a4cd191 100644
--- a/src/com/android/launcher3/LauncherProvider.java
+++ b/src/com/android/launcher3/LauncherProvider.java
@@ -56,6 +56,7 @@
 import com.android.launcher3.compat.UserManagerCompat;
 import com.android.launcher3.config.FeatureFlags;
 import com.android.launcher3.dynamicui.ExtractionUtils;
+import com.android.launcher3.folder.FolderPagedView;
 import com.android.launcher3.graphics.IconShapeOverride;
 import com.android.launcher3.logging.FileLog;
 import com.android.launcher3.model.DbDowngradeHelper;
@@ -725,6 +726,87 @@
                         + "';l.profile=" + serial + ";', ';') where itemType = 0;";
                 db.execSQL(sql);
             }
+
+            updateExistingFoldersToMatchPrePermutationLayout(db);
+        }
+
+        /**
+         * We have changed the way we display items in Folders, but we want existing folders to
+         * appear the same.
+         *
+         * To make this change invisible to existing Folders, we need to update the ranks of the
+         * items such that, when displayed using the permutation, the order remains the same.
+         */
+        private void updateExistingFoldersToMatchPrePermutationLayout(SQLiteDatabase db) {
+            InvariantDeviceProfile idp = new InvariantDeviceProfile(mContext);
+            int maxCols = idp.numFolderColumns;
+            int maxRows = idp.numFolderRows;
+
+            try (SQLiteTransaction t = new SQLiteTransaction(db)) {
+                Cursor c = db.query(Favorites.TABLE_NAME,
+                        new String[] {Favorites._ID, Favorites.OPTIONS},
+                        "itemType=" + Favorites.ITEM_TYPE_FOLDER, null, null, null, null);
+
+                // For every Folder
+                while (c.moveToNext()) {
+                    final long folderId = c.getLong(c.getColumnIndexOrThrow(Favorites._ID));
+                    int options = c.getInt(c.getColumnIndexOrThrow(Favorites.OPTIONS));
+
+                    if ((options & FolderInfo.FLAG_ITEM_RANKS_UPDATED) != 0) {
+                        // The folder has already been updated.
+                        continue;
+                    }
+
+                    // For each item in the Folder
+                    Cursor c2 = db.query(Favorites.TABLE_NAME, new String[] {
+                                    Favorites._ID, Favorites.RANK, Favorites.CELLX, Favorites.CELLY,
+                                    Favorites.OPTIONS},
+                            "container=" + folderId, null, null, null, null);
+
+                    int numItemsInFolder = c2.getCount();
+
+                    // Calculate the grid size.
+                    int[] gridXY = new int[2];
+                    FolderPagedView.calculateGridSize(numItemsInFolder, 0, 0, maxCols, maxRows,
+                            maxCols * maxRows, gridXY);
+                    int gridX = gridXY[0];
+                    int gridY = gridXY[1];
+                    int maxItemsPerPage = gridX * gridY;
+
+                    // We create a mapping from the permutation to the original rank (ie. the
+                    // inverse permutation). This is what we'll use to set the folder items so that
+                    // they appear in their original order.
+                    int[] inversion = new int[numItemsInFolder];
+                    for (int i = 0; i < numItemsInFolder; ++i) {
+                        int permutation = FolderPagedView.getReadingOrderPosForRank(i,
+                                maxItemsPerPage, gridX, null);
+                        inversion[permutation] = i;
+                    }
+
+                    // Now we update the ranks of the folder items. Note that cellX/cellY stay the
+                    // same, due to the permutation.
+                    for (int i = 0; i < numItemsInFolder && c2.moveToNext(); ++i) {
+                        final int rank = c2.getInt(c2.getColumnIndexOrThrow(Favorites.RANK));
+
+                        SQLiteStatement updateItem = db.compileStatement(
+                                "UPDATE favorites SET rank=" + inversion[rank] + " WHERE _id=?");
+                        updateItem.bindLong(1, c2.getInt(c2.getColumnIndexOrThrow(Favorites._ID)));
+                        updateItem.executeUpdateDelete();
+                    }
+                    c2.close();
+
+                    // Mark the folder as having been updated.
+                    options |= FolderInfo.FLAG_ITEM_RANKS_UPDATED;
+                    SQLiteStatement updateFolder = db.compileStatement(
+                            "UPDATE favorites SET options=" + options + " WHERE _id=?");
+                    updateFolder.bindLong(1, folderId);
+                    updateFolder.executeUpdateDelete();
+                }
+                c.close();
+                t.commit();
+            } catch (SQLException ex) {
+                Log.w(TAG, "Error updating folder items to match permutation.", ex);
+            }
         }
 
         @Override
diff --git a/src/com/android/launcher3/PagedView.java b/src/com/android/launcher3/PagedView.java
index ed225c9..dcc7a9d 100644
--- a/src/com/android/launcher3/PagedView.java
+++ b/src/com/android/launcher3/PagedView.java
@@ -408,9 +408,10 @@
         if (getChildCount() == 0) {
             return;
         }
+        int prevPage = mCurrentPage;
         mCurrentPage = validateNewPage(currentPage);
         updateCurrentPageScroll();
-        notifyPageSwitchListener();
+        notifyPageSwitchListener(prevPage);
         invalidate();
     }
 
@@ -418,7 +419,7 @@
      * Should be called whenever the page changes. In the case of a scroll, we wait until the page
      * has settled.
      */
-    protected void notifyPageSwitchListener() {
+    protected void notifyPageSwitchListener(int prevPage) {
         updatePageIndicator();
     }
 
@@ -585,9 +586,10 @@
         } else if (mNextPage != INVALID_PAGE && shouldInvalidate) {
             sendScrollAccessibilityEvent();
 
+            int prevPage = mCurrentPage;
             mCurrentPage = validateNewPage(mNextPage);
             mNextPage = INVALID_PAGE;
-            notifyPageSwitchListener();
+            notifyPageSwitchListener(prevPage);
 
             // We don't want to trigger a page end moving unless the page has settled
             // and the user has stopped scrolling
diff --git a/src/com/android/launcher3/WidgetPreviewLoader.java b/src/com/android/launcher3/WidgetPreviewLoader.java
index ad1be7e..a65ea9b 100644
--- a/src/com/android/launcher3/WidgetPreviewLoader.java
+++ b/src/com/android/launcher3/WidgetPreviewLoader.java
@@ -111,7 +111,7 @@
      * sizes (landscape vs portrait).
      */
     private static class CacheDb extends SQLiteCacheHelper {
-        private static final int DB_VERSION = 8;
+        private static final int DB_VERSION = 9;
 
         private static final String TABLE_NAME = "shortcut_and_widget_previews";
         private static final String COLUMN_COMPONENT = "componentName";
diff --git a/src/com/android/launcher3/Workspace.java b/src/com/android/launcher3/Workspace.java
index 70f719c..28070b7 100644
--- a/src/com/android/launcher3/Workspace.java
+++ b/src/com/android/launcher3/Workspace.java
@@ -75,6 +75,7 @@
 import com.android.launcher3.graphics.PreloadIconDrawable;
 import com.android.launcher3.popup.PopupContainerWithArrow;
 import com.android.launcher3.shortcuts.ShortcutDragPreviewProvider;
+import com.android.launcher3.userevent.nano.LauncherLogProto.Action;
 import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
 import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
 import com.android.launcher3.util.ItemInfoMatcher;
@@ -300,6 +301,7 @@
     boolean mScrollInteractionBegan;
     boolean mStartedSendingScrollEvents;
     float mLastOverlayScroll = 0;
+    boolean mOverlayShown = false;
 
     private boolean mForceDrawAdjacentPages = false;
     // Total over scrollX in the overlay direction.
@@ -1405,6 +1407,20 @@
      * The overlay scroll is being controlled locally, just update our overlay effect
      */
     public void onOverlayScrollChanged(float scroll) {
+
+        if (Float.compare(scroll, 1f) == 0) {
+            if (!mOverlayShown) {
+                mLauncher.getUserEventDispatcher().logActionOnContainer(Action.Touch.SWIPE,
+                        Action.Direction.LEFT, ContainerType.WORKSPACE, 0);
+            }
+            mOverlayShown = true;
+        } else if (Float.compare(scroll, 0f) == 0) {
+            if (mOverlayShown) {
+                mLauncher.getUserEventDispatcher().logActionOnContainer(Action.Touch.SWIPE,
+                        Action.Direction.RIGHT, ContainerType.WORKSPACE, -1);
+            }
+            mOverlayShown = false;
+        }
         float offset = 0f;
         float slip = 0f;
 
@@ -1515,9 +1531,13 @@
     }
 
     @Override
-    protected void notifyPageSwitchListener() {
-        super.notifyPageSwitchListener();
-
+    protected void notifyPageSwitchListener(int prevPage) {
+        super.notifyPageSwitchListener(prevPage);
+        if (prevPage != mCurrentPage) {
+            int swipeDirection = (prevPage < mCurrentPage) ? Action.Direction.RIGHT : Action.Direction.LEFT;
+            mLauncher.getUserEventDispatcher().logActionOnContainer(Action.Touch.SWIPE,
+                    swipeDirection, ContainerType.WORKSPACE, prevPage);
+        }
         if (hasCustomContent() && getNextPage() == 0 && !mCustomContentShowing) {
             mCustomContentShowing = true;
             if (mCustomContentCallbacks != null) {
@@ -1867,13 +1887,20 @@
             return;
         }
 
+        ArrayList<Long> prevScreenOrder = (ArrayList<Long>) mScreenOrder.clone();
         mScreenOrder.clear();
         int count = getChildCount();
         for (int i = 0; i < count; i++) {
             CellLayout cl = ((CellLayout) getChildAt(i));
             mScreenOrder.add(getIdForScreen(cl));
         }
-        mLauncher.getUserEventDispatcher().logOverviewReorder();
+
+        for (int i = 0; i < prevScreenOrder.size(); i++) {
+            if (mScreenOrder.get(i) != prevScreenOrder.get(i)) {
+                mLauncher.getUserEventDispatcher().logOverviewReorder();
+                break;
+            }
+        }
         LauncherModel.updateWorkspaceScreenOrder(mLauncher, mScreenOrder);
 
         // Re-enable auto layout transitions for page deletion.
@@ -3792,7 +3819,7 @@
                 ItemInfo info = (ItemInfo) item.getTag();
                 if (recurse && info instanceof FolderInfo && item instanceof FolderIcon) {
                     FolderIcon folder = (FolderIcon) item;
-                    ArrayList<View> folderChildren = folder.getFolder().getItemsInReadingOrder();
+                    ArrayList<View> folderChildren = folder.getFolder().getItemsInRankOrder();
                     // map over all the children in the folder
                     final int childCount = folderChildren.size();
                     for (int childIdx = 0; childIdx < childCount; childIdx++) {
diff --git a/src/com/android/launcher3/accessibility/LauncherAccessibilityDelegate.java b/src/com/android/launcher3/accessibility/LauncherAccessibilityDelegate.java
index 3433533..6cd086b 100644
--- a/src/com/android/launcher3/accessibility/LauncherAccessibilityDelegate.java
+++ b/src/com/android/launcher3/accessibility/LauncherAccessibilityDelegate.java
@@ -369,7 +369,7 @@
 
         Folder folder = Folder.getOpen(mLauncher);
         if (folder != null) {
-            if (!folder.getItemsInReadingOrder().contains(item)) {
+            if (!folder.getItemsInRankOrder().contains(item)) {
                 folder.close(true);
                 folder = null;
             }
diff --git a/src/com/android/launcher3/allapps/AllAppsContainerView.java b/src/com/android/launcher3/allapps/AllAppsContainerView.java
index 7608fe6..4fb0b86 100644
--- a/src/com/android/launcher3/allapps/AllAppsContainerView.java
+++ b/src/com/android/launcher3/allapps/AllAppsContainerView.java
@@ -423,8 +423,9 @@
 
             // We only show the spring animation when at the top or bottom, so we wait until the
             // first or last row is visible to ensure that all animations run in sync.
-            if ((first == 0 && dy < 0) || (last == mAdapter.getItemCount() - 1 && dy > 0)) {
-                mSpringAnimationHandler.animateToFinalPosition(0);
+            boolean scrollUp = dy < 0;
+            if ((first == 0 && scrollUp) || (last == mAdapter.getItemCount() - 1 && dy > 0)) {
+                mSpringAnimationHandler.animateToFinalPosition(0, scrollUp ? 1 : -1);
             }
         }
 
diff --git a/src/com/android/launcher3/allapps/AllAppsGridAdapter.java b/src/com/android/launcher3/allapps/AllAppsGridAdapter.java
index 1054a56..ba4fbe0 100644
--- a/src/com/android/launcher3/allapps/AllAppsGridAdapter.java
+++ b/src/com/android/launcher3/allapps/AllAppsGridAdapter.java
@@ -481,19 +481,17 @@
          *     5 6 7 8 9
          */
         private int getAppPosition(int position, int numPredictedApps, int appsPerRow) {
-            int appPosition = position;
-            int numDividerViews = 1 + (numPredictedApps == 0 ? 0 : 1);
-
-            int allAppsStartAt = numDividerViews + numPredictedApps;
-            if (numDividerViews == 1 || position < allAppsStartAt) {
-                appPosition -= 1;
-            } else {
-                // We cannot assume that the predicted row will always be full.
-                int numPredictedAppsOffset = appsPerRow - numPredictedApps;
-                appPosition = position + numPredictedAppsOffset - numDividerViews;
+            if (position < numPredictedApps) {
+                // Predicted apps are first in the adapter.
+                return position;
             }
 
-            return appPosition;
+            // There is at most 1 divider view between the predicted apps and the alphabetical apps.
+            int numDividerViews = numPredictedApps == 0 ? 0 : 1;
+
+            // This offset takes into consideration an incomplete row of predicted apps.
+            int numPredictedAppsOffset = appsPerRow - numPredictedApps;
+            return position + numPredictedAppsOffset - numDividerViews;
         }
 
         /**
diff --git a/src/com/android/launcher3/allapps/AllAppsRecyclerView.java b/src/com/android/launcher3/allapps/AllAppsRecyclerView.java
index a2bd43d..34421bd 100644
--- a/src/com/android/launcher3/allapps/AllAppsRecyclerView.java
+++ b/src/com/android/launcher3/allapps/AllAppsRecyclerView.java
@@ -511,7 +511,9 @@
                 if (FeatureFlags.LAUNCHER3_PHYSICS) {
                     // We calculate our own velocity to give the springs the desired effect.
                     velocity = y / getDampedOverScroll(getHeight()) * MAX_RELEASE_VELOCITY;
-                    mSpringAnimationHandler.animateToPositionWithVelocity(0, -velocity);
+                    // We want to negate the velocity because we are moving to 0 from -1 due to the
+                    // downward motion. (y-axis -1 is above 0).
+                    mSpringAnimationHandler.animateToPositionWithVelocity(0, -1, -velocity);
                 }
 
                 ObjectAnimator.ofFloat(AllAppsRecyclerView.this,
diff --git a/src/com/android/launcher3/allapps/AllAppsTransitionController.java b/src/com/android/launcher3/allapps/AllAppsTransitionController.java
index 4d112c6..0859e06 100644
--- a/src/com/android/launcher3/allapps/AllAppsTransitionController.java
+++ b/src/com/android/launcher3/allapps/AllAppsTransitionController.java
@@ -228,7 +228,8 @@
                 }
                 mLauncher.showAppsView(true /* animated */, false /* updatePredictedApps */);
                 if (hasSpringAnimationHandler()) {
-                    mSpringAnimationHandler.animateToFinalPosition(0);
+                    // The icons are moving upwards, so we go to 0 from 1. (y-axis 1 is below 0.)
+                    mSpringAnimationHandler.animateToFinalPosition(0 /* pos */, 1 /* startValue */);
                 }
             } else {
                 calculateDuration(velocity, Math.abs(mShiftRange - mAppsView.getTranslationY()));
diff --git a/src/com/android/launcher3/anim/RoundedRectRevealOutlineProvider.java b/src/com/android/launcher3/anim/RoundedRectRevealOutlineProvider.java
index 7c5fa1c..d01b26c 100644
--- a/src/com/android/launcher3/anim/RoundedRectRevealOutlineProvider.java
+++ b/src/com/android/launcher3/anim/RoundedRectRevealOutlineProvider.java
@@ -56,7 +56,7 @@
 
     @Override
     public boolean shouldRemoveElevationDuringAnimation() {
-        return true;
+        return false;
     }
 
     @Override
diff --git a/src/com/android/launcher3/anim/SpringAnimationHandler.java b/src/com/android/launcher3/anim/SpringAnimationHandler.java
index 1efc4e4..3e58adc 100644
--- a/src/com/android/launcher3/anim/SpringAnimationHandler.java
+++ b/src/com/android/launcher3/anim/SpringAnimationHandler.java
@@ -111,16 +111,32 @@
         mShouldComputeVelocity = true;
     }
 
-    public void animateToFinalPosition(float position) {
-        if (DEBUG) Log.d(TAG, "animateToFinalPosition#computeVelocity=" + mShouldComputeVelocity);
+    public void animateToFinalPosition(float position, int startValue) {
+        animateToFinalPosition(position, startValue, mShouldComputeVelocity);
+    }
+
+    /**
+     * @param position The final animation position.
+     * @param startValue < 0 if scrolling from start to end; > 0 if scrolling from end to start
+     *                   The magnitude of the number changes how the spring will move.
+     * @param setVelocity If true, we set the velocity to {@link #mCurrentVelocity} before
+     *                    starting the animation.
+     */
+    private void animateToFinalPosition(float position, int startValue, boolean setVelocity) {
+        if (DEBUG) {
+            Log.d(TAG, "animateToFinalPosition#position=" + position + ", startValue=" + startValue);
+        }
 
         if (mShouldComputeVelocity) {
-            computeVelocity();
-            setStartVelocity(mCurrentVelocity);
+            mCurrentVelocity = computeVelocity();
         }
 
         int size = mAnimations.size();
         for (int i = 0; i < size; ++i) {
+            mAnimations.get(i).setStartValue(startValue);
+            if (setVelocity) {
+                mAnimations.get(i).setStartVelocity(mCurrentVelocity);
+            }
             mAnimations.get(i).animateToFinalPosition(position);
         }
 
@@ -128,15 +144,18 @@
     }
 
     /**
-     * Similar to {@link #animateToFinalPosition(float)}, but used in cases where we want to
+     * Similar to {@link #animateToFinalPosition(float, int)}, but used in cases where we want to
      * manually set the velocity.
      */
-    public void animateToPositionWithVelocity(float position, float velocity) {
-        if (DEBUG) Log.d(TAG, "animateToPosition#velocity=" + velocity);
+    public void animateToPositionWithVelocity(float position, int startValue, float velocity) {
+        if (DEBUG) {
+            Log.d(TAG, "animateToPosition#pos=" + position + ", start=" + startValue
+                    + ", velocity=" + velocity);
+        }
 
-        setStartVelocity(velocity);
+        mCurrentVelocity = velocity;
         mShouldComputeVelocity = false;
-        animateToFinalPosition(position);
+        animateToFinalPosition(position, startValue, true);
     }
 
 
@@ -163,27 +182,20 @@
             mVelocityTracker = null;
         }
         mCurrentVelocity = 0;
+        mShouldComputeVelocity = false;
     }
 
-    private void setStartVelocity(float velocity) {
-        if (DEBUG) Log.d(TAG, "setStartVelocity=" + velocity);
 
-        int size = mAnimations.size();
-        for (int i = 0; i < size; ++i) {
-            mAnimations.get(i).setStartVelocity(velocity);
-        }
-    }
-
-    private void computeVelocity() {
+    private float computeVelocity() {
         getVelocityTracker().computeCurrentVelocity(1000 /* millis */);
 
-        mCurrentVelocity = isVerticalDirection()
+        float velocity = isVerticalDirection()
                 ? getVelocityTracker().getYVelocity()
                 : getVelocityTracker().getXVelocity();
-        mCurrentVelocity *= VELOCITY_DAMPING_FACTOR;
-        mShouldComputeVelocity = false;
+        velocity *= VELOCITY_DAMPING_FACTOR;
 
-        if (DEBUG) Log.d(TAG, "computeVelocity=" + mCurrentVelocity);
+        if (DEBUG) Log.d(TAG, "computeVelocity=" + velocity);
+        return velocity;
     }
 
     private boolean isVerticalDirection() {
@@ -221,7 +233,6 @@
      */
     public static SpringAnimation forView(View view, FloatPropertyCompat property, float finalPos) {
         SpringAnimation spring = new SpringAnimation(view, property, finalPos);
-        spring.setStartValue(1f);
         spring.setSpring(new SpringForce(finalPos));
         return spring;
     }
diff --git a/src/com/android/launcher3/folder/Folder.java b/src/com/android/launcher3/folder/Folder.java
index 3c7c698..f68b394 100644
--- a/src/com/android/launcher3/folder/Folder.java
+++ b/src/com/android/launcher3/folder/Folder.java
@@ -133,7 +133,7 @@
     private final Alarm mOnScrollHintAlarm = new Alarm();
     @Thunk final Alarm mScrollPauseAlarm = new Alarm();
 
-    @Thunk final ArrayList<View> mItemsInReadingOrder = new ArrayList<View>();
+    @Thunk final ArrayList<View> mItemsInRankOrder = new ArrayList<>();
 
     private AnimatorSet mCurrentAnimator;
 
@@ -284,7 +284,7 @@
         if (tag instanceof ShortcutInfo) {
             ShortcutInfo item = (ShortcutInfo) tag;
 
-            mEmptyCellRank = item.rank;
+            mEmptyCellRank = mContent.getReadingOrderPosForRank(item.rank);
             mCurrentDragView = v;
 
             mDragController.addDragListener(this);
@@ -705,7 +705,7 @@
     }
 
     public void beginExternalDrag() {
-        mEmptyCellRank = mContent.allocateRankForNewItem();
+        mEmptyCellRank = mContent.getReadingOrderPosForRank(mContent.allocateRankForNewItem());
         mIsExternalDrag = true;
         mDragInProgress = true;
 
@@ -997,7 +997,7 @@
             ShortcutInfo info = (ShortcutInfo) d.dragInfo;
             View icon = (mCurrentDragView != null && mCurrentDragView.getTag() == info)
                     ? mCurrentDragView : mContent.createNewView(info);
-            ArrayList<View> views = getItemsInReadingOrder();
+            ArrayList<View> views = getItemsInRankOrder();
             views.add(info.rank, icon);
             mContent.arrangeChildren(views, views.size());
             mItemsInvalidated = true;
@@ -1072,7 +1072,7 @@
     }
 
     private void updateItemLocationsInDatabaseBatch() {
-        ArrayList<View> list = getItemsInReadingOrder();
+        ArrayList<View> list = getItemsInRankOrder();
         ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
         for (int i = 0; i < list.size(); i++) {
             View v = list.get(i);
@@ -1231,7 +1231,7 @@
      * otherwise it is ignored.
      */
     public void rearrangeChildren(int itemCount) {
-        ArrayList<View> views = getItemsInReadingOrder();
+        ArrayList<View> views = getItemsInRankOrder();
         mContent.arrangeChildren(views, Math.max(itemCount, views.size()));
         mItemsInvalidated = true;
     }
@@ -1376,24 +1376,20 @@
 
             View currentDragView;
             if (mIsExternalDrag) {
-                currentDragView = mContent.createAndAddViewForRank(si, mEmptyCellRank);
-
                 // Actually move the item in the database if it was an external drag. Call this
                 // before creating the view, so that ShortcutInfo is updated appropriately.
-                mLauncher.getModelWriter().addOrMoveItemInDatabase(
-                        si, mInfo.id, 0, si.cellX, si.cellY);
-
-                // We only need to update the locations if it doesn't get handled in
-                // #onDropCompleted.
-                if (d.dragSource != this) {
-                    updateItemLocationsInDatabaseBatch();
-                }
-                mIsExternalDrag = false;
-            } else {
-                currentDragView = mCurrentDragView;
-                mContent.addViewForRank(currentDragView, si, mEmptyCellRank);
+                mLauncher.getModelWriter().addOrMoveItemInDatabase(si, mInfo.id, 0, si.cellX, si.cellY);
             }
 
+            currentDragView = mIsExternalDrag
+                    ? mContent.createNewView(si)
+                    : mCurrentDragView;
+            mIsExternalDrag = false;
+
+            // Note: addViewForRankDuringDragAndDrop handles rearranging the children.
+            mContent.addViewForRankDuringDragAndDrop(currentDragView, si, mEmptyCellRank);
+            mItemsInvalidated = true;
+
             if (d.dragView.hasDrawn()) {
                 // Temporarily reset the scale such that the animation target gets calculated
                 // correctly.
@@ -1410,9 +1406,6 @@
                 currentDragView.setVisibility(VISIBLE);
             }
 
-            mItemsInvalidated = true;
-            rearrangeChildren();
-
             // Temporarily suppress the listener, as we did all the work already here.
             try (SuppressInfoChanges s = new SuppressInfoChanges()) {
                 mInfo.add(si, false);
@@ -1450,7 +1443,7 @@
         mLauncher.getModelWriter().addOrMoveItemInDatabase(item, mInfo.id, 0, item.cellX,
                 item.cellY);
 
-        ArrayList<View> items = new ArrayList<>(getItemsInReadingOrder());
+        ArrayList<View> items = new ArrayList<>(getItemsInRankOrder());
         items.add(rank, view);
         mContent.arrangeChildren(items, items.size());
         mItemsInvalidated = true;
@@ -1497,24 +1490,34 @@
     public void onTitleChanged(CharSequence title) {
     }
 
-    public ArrayList<View> getItemsInReadingOrder() {
+    public ArrayList<View> getItemsInRankOrder() {
         if (mItemsInvalidated) {
-            mItemsInReadingOrder.clear();
-            mContent.iterateOverItems(new ItemOperator() {
+            mItemsInRankOrder.clear();
+            mItemsInRankOrder.addAll(getItemsInReadingOrder());
+            mItemsInRankOrder.sort(VIEW_RANK_COMPARATOR);
 
-                @Override
-                public boolean evaluate(ItemInfo info, View view) {
-                    mItemsInReadingOrder.add(view);
-                    return false;
-                }
-            });
             mItemsInvalidated = false;
         }
-        return mItemsInReadingOrder;
+        return mItemsInRankOrder;
+    }
+
+    /**
+     * This is an expensive call. Consider using {@link #getItemsInRankOrder()} instead.
+     */
+    public ArrayList<View> getItemsInReadingOrder() {
+        final ArrayList<View> itemsInReadingOrder = new ArrayList<>();
+        mContent.iterateOverItems(new ItemOperator() {
+            @Override
+            public boolean evaluate(ItemInfo info, View view) {
+                itemsInReadingOrder.add(view);
+                return false;
+            }
+        });
+        return itemsInReadingOrder;
     }
 
     public List<BubbleTextView> getItemsOnCurrentPage() {
-        ArrayList<View> allItems = getItemsInReadingOrder();
+        ArrayList<View> allItems = getItemsInRankOrder();
         int currentPage = mContent.getCurrentPage();
         int lastPage = mContent.getPageCount() - 1;
         int totalItemsInFolder = allItems.size();
@@ -1622,6 +1625,13 @@
         }
     };
 
+    public static final Comparator<View> VIEW_RANK_COMPARATOR = new Comparator<View>() {
+        @Override
+        public int compare(View lhs, View rhs) {
+            return ITEM_POS_COMPARATOR.compare((ItemInfo) lhs.getTag(), (ItemInfo) rhs.getTag());
+        }
+    };
+
     /**
      * Temporary resource held while we don't want to handle info changes
      */
diff --git a/src/com/android/launcher3/folder/FolderAnimationManager.java b/src/com/android/launcher3/folder/FolderAnimationManager.java
index 3648c60..7e8d0c7 100644
--- a/src/com/android/launcher3/folder/FolderAnimationManager.java
+++ b/src/com/android/launcher3/folder/FolderAnimationManager.java
@@ -69,7 +69,8 @@
     private final int mDelay;
 
     private final TimeInterpolator mFolderInterpolator;
-    private final TimeInterpolator mLargeFolderPreviewItemInterpolator;
+    private final TimeInterpolator mLargeFolderPreviewItemOpenInterpolator;
+    private final TimeInterpolator mLargeFolderPreviewItemCloseInterpolator;
 
     private final PreviewItemDrawingParams mTmpParams = new PreviewItemDrawingParams(0, 0, 0, 0);
 
@@ -105,8 +106,10 @@
 
         mFolderInterpolator = AnimationUtils.loadInterpolator(mContext,
                 R.interpolator.folder_interpolator);
-        mLargeFolderPreviewItemInterpolator = AnimationUtils.loadInterpolator(mContext,
-                R.interpolator.large_folder_preview_item_interpolator);
+        mLargeFolderPreviewItemOpenInterpolator = AnimationUtils.loadInterpolator(mContext,
+                R.interpolator.large_folder_preview_item_open_interpolator);
+        mLargeFolderPreviewItemCloseInterpolator = AnimationUtils.loadInterpolator(mContext,
+                R.interpolator.large_folder_preview_item_close_interpolator);
     }
 
 
@@ -122,7 +125,7 @@
         final Rect folderIconPos = new Rect();
         float scaleRelativeToDragLayer = mLauncher.getDragLayer()
                 .getDescendantRectRelativeToSelf(mFolderIcon, folderIconPos);
-        float initialSize = (mFolderIcon.mBackground.getRadius() * 2) * scaleRelativeToDragLayer;
+        float initialSize = (mPreviewBackground.getRadius() * 2) * scaleRelativeToDragLayer;
 
         // Match size/scale of icons in the preview
         float previewScale = rule.scaleForItem(0, itemsInPreview.size());
@@ -150,12 +153,11 @@
                 * initialScale);
 
         // Background can have a scaled radius in drag and drop mode.
-        int radiusDiff = mFolderIcon.mBackground.getScaledRadius()
-                - mFolderIcon.mBackground.getRadius();
+        int radiusDiff = mPreviewBackground.getScaledRadius()- mPreviewBackground.getRadius();
 
-        int initialX = folderIconPos.left + mFolderIcon.mBackground.getOffsetX() - paddingOffsetX
+        int initialX = folderIconPos.left + mPreviewBackground.getOffsetX() - paddingOffsetX
                 - previewItemOffsetX + radiusDiff;
-        int initialY = folderIconPos.top + mFolderIcon.mBackground.getOffsetY() - paddingOffsetY
+        int initialY = folderIconPos.top + mPreviewBackground.getOffsetY() - paddingOffsetY
                 + radiusDiff;
         final float xDistance = initialX - lp.x;
         final float yDistance = initialY - lp.y;
@@ -181,7 +183,7 @@
         AnimatorSet a = LauncherAnimUtils.createAnimatorSet();
 
         // Initialize the Folder items' text.
-        PropertyResetListener colorResetListener = new PropertyResetListener(
+        PropertyResetListener colorResetListener = new PropertyResetListener<>(
                 BubbleTextView.TEXT_ALPHA_PROPERTY,
                 Color.alpha(Themes.getAttrColor(mContext, android.R.attr.textColorSecondary)));
         for (BubbleTextView icon : mFolder.getItemsOnCurrentPage()) {
@@ -198,13 +200,19 @@
         play(a, getAnimator(mFolder, SCALE_PROPERTY, initialScale, finalScale));
         play(a, getAnimator(mFolderBackground, "color", initialColor, finalColor));
         play(a, mFolderIcon.mFolderName.createTextAlphaAnimator(!mIsOpening));
-        play(a, new RoundedRectRevealOutlineProvider(initialRadius, finalRadius, startRect,
-                endRect).createRevealAnimator(mFolder, !mIsOpening));
+        RoundedRectRevealOutlineProvider outlineProvider = new RoundedRectRevealOutlineProvider(
+                initialRadius, finalRadius, startRect, endRect) {
+            @Override
+            public boolean shouldRemoveElevationDuringAnimation() {
+                return true;
+            }
+        };
+        play(a, outlineProvider.createRevealAnimator(mFolder, !mIsOpening));
 
         // Animate the elevation midway so that the shadow is not noticeable in the background.
         int midDuration = mDuration / 2;
         Animator z = getAnimator(mFolder, View.TRANSLATION_Z, -mFolder.getElevation(), 0);
-        play(a, z, midDuration, midDuration);
+        play(a, z, mIsOpening ? midDuration : 0, midDuration);
 
         a.addListener(new AnimatorListenerAdapter() {
             @Override
@@ -287,14 +295,15 @@
             if (mFolder.getItemCount() > FolderIcon.NUM_ITEMS_IN_PREVIEW) {
                 // These delays allows the preview items to move as part of the Folder's motion,
                 // and its only necessary for large folders because of differing interpolators.
+                int delay = mIsOpening ? mDelay : mDelay * 2;
                 if (mIsOpening) {
-                    translationX.setStartDelay(mDelay);
-                    translationY.setStartDelay(mDelay);
-                    scaleAnimator.setStartDelay(mDelay);
+                    translationX.setStartDelay(delay);
+                    translationY.setStartDelay(delay);
+                    scaleAnimator.setStartDelay(delay);
                 }
-                translationX.setDuration(translationX.getDuration() - mDelay);
-                translationY.setDuration(translationY.getDuration() - mDelay);
-                scaleAnimator.setDuration(scaleAnimator.getDuration() - mDelay);
+                translationX.setDuration(translationX.getDuration() - delay);
+                translationY.setDuration(translationY.getDuration() - delay);
+                scaleAnimator.setDuration(scaleAnimator.getDuration() - delay);
             }
 
             animatorSet.addListener(new AnimatorListenerAdapter() {
@@ -337,7 +346,9 @@
             // With larger folders, we want the preview items to reach their final positions faster
             // (when opening) and later (when closing) so that they appear aligned with the rest of
             // the folder items when they are both visible.
-            return mLargeFolderPreviewItemInterpolator;
+            return mIsOpening
+                    ? mLargeFolderPreviewItemOpenInterpolator
+                    : mLargeFolderPreviewItemCloseInterpolator;
         }
         return mFolderInterpolator;
     }
diff --git a/src/com/android/launcher3/folder/FolderIcon.java b/src/com/android/launcher3/folder/FolderIcon.java
index 1cc285e..3a0e71f 100644
--- a/src/com/android/launcher3/folder/FolderIcon.java
+++ b/src/com/android/launcher3/folder/FolderIcon.java
@@ -575,7 +575,7 @@
         mPreviewVerifier.setFolderInfo(mFolder.getInfo());
 
         List<BubbleTextView> itemsToDisplay = new ArrayList<>();
-        List<View> allItems = mFolder.getItemsInReadingOrder();
+        List<View> allItems = mFolder.getItemsInRankOrder();
         int numItems = allItems.size();
         for (int rank = 0; rank < numItems; ++rank) {
             if (mPreviewVerifier.isItemInPreview(rank)) {
diff --git a/src/com/android/launcher3/folder/FolderIconPreviewVerifier.java b/src/com/android/launcher3/folder/FolderIconPreviewVerifier.java
index de962b0..d0d8e79 100644
--- a/src/com/android/launcher3/folder/FolderIconPreviewVerifier.java
+++ b/src/com/android/launcher3/folder/FolderIconPreviewVerifier.java
@@ -25,40 +25,15 @@
  */
 public class FolderIconPreviewVerifier {
 
-    private final int mMaxGridCountX;
-    private final int mMaxGridCountY;
-    private final int mMaxItemsPerPage;
-    private final int[] mGridSize = new int[2];
-
-    private int mGridCountX;
-    private boolean mDisplayingUpperLeftQuadrant = false;
-
     public FolderIconPreviewVerifier(InvariantDeviceProfile profile) {
-        mMaxGridCountX = profile.numFolderColumns;
-        mMaxGridCountY = profile.numFolderRows;
-        mMaxItemsPerPage = mMaxGridCountX * mMaxGridCountY;
+        // b/37570804
     }
 
     public void setFolderInfo(FolderInfo info) {
-        int numItemsInFolder = info.contents.size();
-        mDisplayingUpperLeftQuadrant = FeatureFlags.LAUNCHER3_NEW_FOLDER_ANIMATION
-                && !FeatureFlags.LAUNCHER3_LEGACY_FOLDER_ICON
-                && numItemsInFolder > FolderIcon.NUM_ITEMS_IN_PREVIEW;
-
-        if (mDisplayingUpperLeftQuadrant) {
-            FolderPagedView.calculateGridSize(info.contents.size(), 0, 0, mMaxGridCountX,
-                    mMaxGridCountY, mMaxItemsPerPage, mGridSize);
-            mGridCountX = mGridSize[0];
-        }
+        // b/37570804
     }
 
     public boolean isItemInPreview(int rank) {
-        if (mDisplayingUpperLeftQuadrant) {
-            // Returns true iff the icon is in the 2x2 upper left quadrant of the Folder.
-            int col = rank % mGridCountX;
-            int row = rank / mGridCountX;
-            return col < 2 && row < 2;
-        }
         return rank < FolderIcon.NUM_ITEMS_IN_PREVIEW;
     }
 }
diff --git a/src/com/android/launcher3/folder/FolderPagedView.java b/src/com/android/launcher3/folder/FolderPagedView.java
index f62568f..33ac5ba 100644
--- a/src/com/android/launcher3/folder/FolderPagedView.java
+++ b/src/com/android/launcher3/folder/FolderPagedView.java
@@ -201,18 +201,29 @@
     }
 
     public void allocateSpaceForRank(int rank) {
-        ArrayList<View> views = new ArrayList<>(mFolder.getItemsInReadingOrder());
+        ArrayList<View> views = new ArrayList<>(mFolder.getItemsInRankOrder());
         views.add(rank, null);
         arrangeChildren(views, views.size(), false);
     }
 
+    private ArrayList<View> createListWithViewAtPos(ArrayList<View> list, View v, int position) {
+        ArrayList<View> newList = new ArrayList<>(list.size() + 1);
+        newList.addAll(list);
+        newList.add(position, v);
+        return newList;
+    }
+
     /**
-     * Create space for a new item at the end, and returns the rank for that item.
+     * Create space for a new item and returns the rank for that item.
      * Also sets the current page to the last page.
      */
     public int allocateRankForNewItem() {
-        int rank = getItemCount();
-        allocateSpaceForRank(rank);
+        ArrayList<View> rankOrder = mFolder.getItemsInRankOrder();
+        int rank = rankOrder.size();
+
+        ArrayList<View> views = createListWithViewAtPos(rankOrder, null, rank);
+        arrangeChildren(views, views.size(), false);
+
         setCurrentPage(rank / mMaxItemsPerPage);
         return rank;
     }
@@ -229,20 +240,59 @@
      * related attributes. It assumes that {@param item} is already attached to the view.
      */
     public void addViewForRank(View view, ShortcutInfo item, int rank) {
-        int pagePos = rank % mMaxItemsPerPage;
-        int pageNo = rank / mMaxItemsPerPage;
+        updateShortcutInfoWithRank(item, rank);
 
-        item.rank = rank;
-        item.cellX = pagePos % mGridCountX;
-        item.cellY = pagePos / mGridCountX;
+        ArrayList<View> views = createListWithViewAtPos(mFolder.getItemsInRankOrder(), view, rank);
+        arrangeChildren(views, views.size(), false);
+    }
+
+    /**
+     * Similar to {@link #addViewForRank(View, ShortcutInfo, int)}}, but specific to real time
+     * reorder.
+     *
+     * The difference here is that during real time reorder, we are moving the Views in a contained
+     * order.
+     */
+    public void addViewForRankDuringReorder(View view, ShortcutInfo item, int rank) {
+        updateShortcutInfoWithRank(item, rank);
 
         CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
         lp.cellX = item.cellX;
         lp.cellY = item.cellY;
+
+        int pageNo = rank / mMaxItemsPerPage;
         getPageAt(pageNo).addViewToCellLayout(
                 view, -1, mFolder.mLauncher.getViewIdForItem(item), lp, true);
     }
 
+    /**
+     * Similar to {@link #addViewForRank(View, ShortcutInfo, int)}, but specific to drag and drop.
+     *
+     * The difference is that we handle the drag and drop by adjusting the reading order of the
+     * children, rather than based on their rank.
+     */
+    public void addViewForRankDuringDragAndDrop(View view, ShortcutInfo item, int readingRank) {
+        updateShortcutInfoWithRank(item, readingRank);
+
+        ArrayList<View> views = createListWithViewAtPos(mFolder.getItemsInReadingOrder(), view,
+                readingRank);
+
+        int numItems = views.size();
+        ArrayList<View> rankOrder = new ArrayList<>(numItems);
+        for (int i = 0; i < numItems; ++i) {
+            rankOrder.add(views.get(getReadingOrderPosForRank(i)));
+        }
+
+        arrangeChildren(rankOrder, numItems, false);
+    }
+
+    private void updateShortcutInfoWithRank(ShortcutInfo info, int rank) {
+        info.rank = rank;
+        getCellXYPositionForRank(rank, sTmpArray);
+        info.cellX = sTmpArray[0];
+        info.cellY = sTmpArray[1];
+    }
+
     @SuppressLint("InflateParams")
     public View createNewView(ShortcutInfo item) {
         final BubbleTextView textView = (BubbleTextView) mInflater.inflate(
@@ -310,18 +360,19 @@
      * It essentially removes all views from all the pages and then adds them again in appropriate
      * page.
      *
-     * @param list the ordered list of children.
+     * @param rankOrderedList the rank-ordered list of children.
      * @param itemCount if greater than the total children count, empty spaces are left
      * at the end, otherwise it is ignored.
      *
      */
-    public void arrangeChildren(ArrayList<View> list, int itemCount) {
-        arrangeChildren(list, itemCount, true);
+    public void arrangeChildren(ArrayList<View> rankOrderedList, int itemCount) {
+        arrangeChildren(rankOrderedList, itemCount, true);
     }
 
     @SuppressLint("RtlHardcoded")
-    private void arrangeChildren(ArrayList<View> list, int itemCount, boolean saveChanges) {
-        ArrayList<CellLayout> pages = new ArrayList<>();
+    private void arrangeChildren(ArrayList<View> rankOrderedList, int itemCount,
+            boolean saveChanges) {
+        ArrayList<CellLayout> pages = new ArrayList<CellLayout>();
         for (int i = 0; i < getChildCount(); i++) {
             CellLayout page = (CellLayout) getChildAt(i);
             page.removeAllViews();
@@ -339,7 +390,7 @@
                 Launcher.getLauncher(getContext()).getDeviceProfile().inv);
         rank = 0;
         for (int i = 0; i < itemCount; i++) {
-            View v = list.size() > i ? list.get(i) : null;
+            View v = rankOrderedList.size() > i ? rankOrderedList.get(i) : null;
             if (currentPage == null || position >= mMaxItemsPerPage) {
                 // Next page
                 if (pageItr.hasNext()) {
@@ -352,8 +403,10 @@
 
             if (v != null) {
                 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) v.getLayoutParams();
-                newX = position % mGridCountX;
-                newY = position / mGridCountX;
+                getCellXYPositionForRank(rank, sTmpArray);
+                newX = sTmpArray[0];
+                newY = sTmpArray[1];
+
                 ItemInfo info = (ItemInfo) v.getTag();
                 if (info.cellX != newX || info.cellY != newY || info.rank != rank) {
                     info.cellX = newX;
@@ -494,8 +547,8 @@
     }
 
     @Override
-    protected void notifyPageSwitchListener() {
-        super.notifyPageSwitchListener();
+    protected void notifyPageSwitchListener(int prevPage) {
+        super.notifyPageSwitchListener(prevPage);
         if (mFolder != null) {
             mFolder.updateTextViewFocus();
         }
@@ -651,7 +704,7 @@
             if (v != null) {
                 if (pageToAnimate != p) {
                     page.removeView(v);
-                    addViewForRank(v, (ShortcutInfo) v.getTag(), moveStart);
+                    addViewForRankDuringReorder(v, (ShortcutInfo) v.getTag(), moveStart);
                 } else {
                     // Do a fake animation before removing it.
                     final int newRank = moveStart;
@@ -664,14 +717,14 @@
                             mPendingAnimations.remove(v);
                             v.setTranslationX(oldTranslateX);
                             ((CellLayout) v.getParent().getParent()).removeView(v);
-                            addViewForRank(v, (ShortcutInfo) v.getTag(), newRank);
+                            addViewForRankDuringReorder(v, (ShortcutInfo) v.getTag(), newRank);
                         }
                     };
                     v.animate()
-                        .translationXBy((direction > 0 ^ mIsRtl) ? -v.getWidth() : v.getWidth())
-                        .setDuration(REORDER_ANIMATION_DURATION)
-                        .setStartDelay(0)
-                        .withEndAction(endAction);
+                            .translationXBy((direction > 0 ^ mIsRtl) ? -v.getWidth() : v.getWidth())
+                            .setDuration(REORDER_ANIMATION_DURATION)
+                            .setStartDelay(0)
+                            .withEndAction(endAction);
                     mPendingAnimations.put(v, endAction);
                 }
             }
@@ -701,4 +754,102 @@
     public int itemsPerPage() {
         return mMaxItemsPerPage;
     }
+
+    public int getReadingOrderPosForRank(int rank) {
+        return getReadingOrderPosForRank(rank, mMaxItemsPerPage, mGridCountX, sTmpArray);
+    }
+
+    /**
+     * Returns the reading order position for a given rank.
+     *
+     * ie. For the permutation below, rank 0 returns 0, rank 1 returns 1, rank 4 returns 2,
+     *                                rank 2 returns 3, rank 3 returns 4, rank 5 returns 5.
+     *
+     *     R0 R1 R4
+     *     R2 R3 R5
+     *
+     * @param outXY If notnull, we also return the cell X/Y position.
+     */
+    public static int getReadingOrderPosForRank(int rank, int maxItemsPerPage, int gridX,
+            int[] outXY) {
+        outXY = outXY == null ? sTmpArray : outXY;
+        getCellXYPositionForRank(rank, maxItemsPerPage, gridX, outXY);
+
+        if (rank >= maxItemsPerPage) {
+            return rank;
+        }
+
+        return outXY[0] + (gridX * outXY[1]);
+    }
+
+    public void getCellXYPositionForRank(int rank, int[] outXY) {
+        getCellXYPositionForRank(rank, mMaxItemsPerPage, mGridCountX, outXY);
+    }
+
+    /**
+     * Returns the cell XY position for a Folder item with the given rank.
+     */
+    public static void getCellXYPositionForRank(int rank, int maxItemsPerPage, int gridX,
+            int[] outXY) {
+        boolean onFirstPage = rank < maxItemsPerPage;
+
+        if (onFirstPage && gridX == 3) {
+            outXY[0] = FolderPermutation.THREE_COLS[rank][0];
+            outXY[1] = FolderPermutation.THREE_COLS[rank][1];
+        } else if (onFirstPage && gridX == 4) {
+            outXY[0] = FolderPermutation.FOUR_COLS[rank][0];
+            outXY[1] = FolderPermutation.FOUR_COLS[rank][1];
+        } else if (onFirstPage && gridX == 5) {
+            outXY[0] = FolderPermutation.FIVE_COLS[rank][0];
+            outXY[1] = FolderPermutation.FIVE_COLS[rank][1];
+        } else {
+            outXY[0] = (rank % maxItemsPerPage) % gridX;
+            outXY[1] = (rank % maxItemsPerPage) / gridX;
+        }
+    }
+
+    /**
+     * Provides the mapping between a folder item's rank and its cell location, based on the
+     * number of columns.
+     *
+     * We use this mapping, rather than the regular reading order, to preserve the items in the
+     * upper left quadrant of the Folder. This allows a smooth transition between the FolderIcon
+     * and the opened Folder.
+     *
+     * TODO: We will replace these hard coded tables with an algorithm b/62986680
+     */
+    private static class FolderPermutation {
+        /**
+         *  R0 R1 R4
+         *  R2 R3 R5
+         *  R6 R7 R8
+         */
+        static final int[][] THREE_COLS = new int[][] {
+                {0, 0}, {1, 0}, {0, 1}, {1, 1}, {2, 0}, {2, 1}, {0, 2}, {1, 2}, {2, 2}
+        };
+
+        /**
+         * R0  R1  R4  R6
+         * R2  R3  R5  R7
+         * R8  R9  R10 R11
+         * R12 R13 R14 R15
+         */
+        static final int[][] FOUR_COLS = new int[][] {
+                {0, 0}, {1, 0}, {0, 1}, {1, 1}, {2, 0}, {2, 1}, {3, 0}, {3, 1}, {0, 2}, {1, 2},
+                {2, 2}, {3, 2}, {0, 3}, {1, 3}, {2, 3}, {3, 3}
+        };
+
+        /**
+         * R0  R1  R4  R6  R12
+         * R2  R3  R5  R7  R13
+         * R8  R9  R10 R11 R14
+         * R15 R16 R17 R18 R19
+         * R20 R21 R22 R23 R24
+         */
+        static final int[][] FIVE_COLS = new int[][] {
+                {0, 0}, {1, 0}, {0, 1}, {1, 1}, {2, 0}, {2, 1}, {3, 0}, {3, 1}, {0, 2}, {1, 2},
+                {2, 2}, {3, 2}, {4, 0}, {4, 1}, {4, 2}, {0, 3}, {1, 3}, {2, 3}, {3, 3}, {4, 3},
+                {0, 4}, {1, 4}, {2, 4}, {3, 4}, {4, 4}
+        };
+    }
 }
diff --git a/src/com/android/launcher3/folder/PreviewBackground.java b/src/com/android/launcher3/folder/PreviewBackground.java
index 44ebbcd..eb6a6d5 100644
--- a/src/com/android/launcher3/folder/PreviewBackground.java
+++ b/src/com/android/launcher3/folder/PreviewBackground.java
@@ -88,7 +88,7 @@
     public boolean isClipping = true;
 
     // Drawing / animation configurations
-    private static final float ACCEPT_SCALE_FACTOR = 1.25f;
+    private static final float ACCEPT_SCALE_FACTOR = 1.20f;
     private static final float ACCEPT_COLOR_MULTIPLIER = 1.5f;
 
     // Expressed on a scale from 0 to 255.
diff --git a/src/com/android/launcher3/graphics/LauncherIcons.java b/src/com/android/launcher3/graphics/LauncherIcons.java
index 830ca82..739eb04 100644
--- a/src/com/android/launcher3/graphics/LauncherIcons.java
+++ b/src/com/android/launcher3/graphics/LauncherIcons.java
@@ -35,6 +35,7 @@
 import android.os.Build;
 import android.os.Process;
 import android.os.UserHandle;
+import android.support.annotation.Nullable;
 
 import com.android.launcher3.AppInfo;
 import com.android.launcher3.IconCache;
@@ -45,6 +46,7 @@
 import com.android.launcher3.model.PackageItemInfo;
 import com.android.launcher3.shortcuts.DeepShortcutManager;
 import com.android.launcher3.shortcuts.ShortcutInfoCompat;
+import com.android.launcher3.util.Provider;
 
 /**
  * Helper methods for generating various launcher icons
@@ -315,14 +317,28 @@
 
     public static Bitmap createShortcutIcon(ShortcutInfoCompat shortcutInfo, Context context,
             boolean badged) {
+        return createShortcutIcon(shortcutInfo, context, badged, null);
+    }
+
+    public static Bitmap createShortcutIcon(ShortcutInfoCompat shortcutInfo, Context context,
+            boolean badged, @Nullable Provider<Bitmap> fallbackIconProvider) {
         LauncherAppState app = LauncherAppState.getInstance(context);
         Drawable unbadgedDrawable = DeepShortcutManager.getInstance(context)
                 .getShortcutIconDrawable(shortcutInfo,
                         app.getInvariantDeviceProfile().fillResIconDpi);
         IconCache cache = app.getIconCache();
-        Bitmap unbadgedBitmap = unbadgedDrawable == null
-                ? cache.getDefaultIcon(Process.myUserHandle())
-                : LauncherIcons.createScaledBitmapWithoutShadow(unbadgedDrawable, context, 0);
+        Bitmap unbadgedBitmap = null;
+        if (unbadgedDrawable != null) {
+            unbadgedBitmap = LauncherIcons.createScaledBitmapWithoutShadow(
+                    unbadgedDrawable, context, 0);
+        } else {
+            if (fallbackIconProvider != null) {
+                unbadgedBitmap = fallbackIconProvider.get();
+            }
+            if (unbadgedBitmap == null) {
+                unbadgedBitmap = cache.getDefaultIcon(Process.myUserHandle());
+            }
+        }
 
         if (!badged) {
             return unbadgedBitmap;
diff --git a/src/com/android/launcher3/logging/LoggerUtils.java b/src/com/android/launcher3/logging/LoggerUtils.java
index 329b7d5..72a083b 100644
--- a/src/com/android/launcher3/logging/LoggerUtils.java
+++ b/src/com/android/launcher3/logging/LoggerUtils.java
@@ -66,8 +66,14 @@
     }
 
     public static String getActionStr(Action action) {
+        String str = "";
         switch (action.type) {
-            case Action.Type.TOUCH: return getFieldName(action.touch, Action.Touch.class);
+            case Action.Type.TOUCH:
+                str += getFieldName(action.touch, Action.Touch.class);
+                if (action.touch == Action.Touch.SWIPE) {
+                    str += " direction=" + getFieldName(action.dir, Action.Direction.class);
+                }
+                return str;
             case Action.Type.COMMAND: return getFieldName(action.command, Action.Command.class);
             default: return UNKNOWN;
         }
diff --git a/src/com/android/launcher3/model/LoaderCursor.java b/src/com/android/launcher3/model/LoaderCursor.java
index 1a2c04d..bc7da9b 100644
--- a/src/com/android/launcher3/model/LoaderCursor.java
+++ b/src/com/android/launcher3/model/LoaderCursor.java
@@ -184,9 +184,13 @@
                 icon = LauncherIcons.createIconBitmap(
                         BitmapFactory.decodeByteArray(data, 0, data.length), mContext);
             } catch (Exception e) {
+                Log.e(TAG, "Failed to load icon for info " + info, e);
                 return null;
             }
         }
+        if (icon == null) {
+            Log.e(TAG, "Failed to load icon for info " + info);
+        }
         return icon;
     }
 
diff --git a/src/com/android/launcher3/model/LoaderTask.java b/src/com/android/launcher3/model/LoaderTask.java
index bb2d0b6..5bad436 100644
--- a/src/com/android/launcher3/model/LoaderTask.java
+++ b/src/com/android/launcher3/model/LoaderTask.java
@@ -24,8 +24,8 @@
 import android.content.IntentFilter;
 import android.content.pm.LauncherActivityInfo;
 import android.content.pm.PackageInstaller;
+import android.graphics.Bitmap;
 import android.os.Handler;
-import android.os.Looper;
 import android.os.Process;
 import android.os.SystemClock;
 import android.os.Trace;
@@ -66,6 +66,7 @@
 import com.android.launcher3.util.ManagedProfileHeuristic;
 import com.android.launcher3.util.MultiHashMap;
 import com.android.launcher3.util.PackageManagerHelper;
+import com.android.launcher3.util.Provider;
 
 import java.util.ArrayList;
 import java.util.Collections;
@@ -459,8 +460,18 @@
                                         continue;
                                     }
                                     info = new ShortcutInfo(pinnedShortcut, context);
+                                    final ShortcutInfo finalInfo = info;
+                                    Provider<Bitmap> fallbackIconProvider = new Provider<Bitmap>() {
+                                        @Override
+                                        public Bitmap get() {
+                                            // If the pinned deep shortcut is no longer published,
+                                            // use the last saved icon instead of the default.
+                                            return c.loadIcon(finalInfo);
+                                        }
+                                    };
                                     info.iconBitmap = LauncherIcons
-                                            .createShortcutIcon(pinnedShortcut, context);
+                                            .createShortcutIcon(pinnedShortcut, context,
+                                                    true /* badged */, fallbackIconProvider);
                                     if (pmHelper.isAppSuspended(
                                             pinnedShortcut.getPackage(), info.user)) {
                                         info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SUSPENDED;
diff --git a/src/com/android/launcher3/notification/NotificationItemView.java b/src/com/android/launcher3/notification/NotificationItemView.java
index 0b08ef8..0cd5a4c 100644
--- a/src/com/android/launcher3/notification/NotificationItemView.java
+++ b/src/com/android/launcher3/notification/NotificationItemView.java
@@ -48,6 +48,7 @@
 
     private static final Rect sTempRect = new Rect();
 
+    private TextView mHeaderText;
     private TextView mHeaderCount;
     private NotificationMainView mMainView;
     private NotificationFooterLayout mFooter;
@@ -70,6 +71,7 @@
     @Override
     protected void onFinishInflate() {
         super.onFinishInflate();
+        mHeaderText = (TextView) findViewById(R.id.notification_text);
         mHeaderCount = (TextView) findViewById(R.id.notification_count);
         mMainView = (NotificationMainView) findViewById(R.id.main_view);
         mFooter = (NotificationFooterLayout) findViewById(R.id.footer);
@@ -106,6 +108,7 @@
                         IconPalette.resolveContrastColor(getContext(), palette.dominantColor,
                                 Themes.getAttrColor(getContext(), R.attr.popupColorPrimary));
             }
+            mHeaderText.setTextColor(mNotificationHeaderTextColor);
             mHeaderCount.setTextColor(mNotificationHeaderTextColor);
         }
     }
diff --git a/src/com/android/launcher3/notification/NotificationListener.java b/src/com/android/launcher3/notification/NotificationListener.java
index baaa66a..8121fd5 100644
--- a/src/com/android/launcher3/notification/NotificationListener.java
+++ b/src/com/android/launcher3/notification/NotificationListener.java
@@ -127,8 +127,9 @@
         }
         sNotificationsChangedListener = listener;
 
-        if (sNotificationListenerInstance != null) {
-            sNotificationListenerInstance.onNotificationFullRefresh();
+        NotificationListener notificationListener = getInstanceIfConnected();
+        if (notificationListener != null) {
+            notificationListener.onNotificationFullRefresh();
         }
     }
 
diff --git a/src/com/android/launcher3/popup/PopupContainerWithArrow.java b/src/com/android/launcher3/popup/PopupContainerWithArrow.java
index 77375fa..c6ae0d2 100644
--- a/src/com/android/launcher3/popup/PopupContainerWithArrow.java
+++ b/src/com/android/launcher3/popup/PopupContainerWithArrow.java
@@ -20,6 +20,7 @@
 import android.animation.AnimatorListenerAdapter;
 import android.animation.AnimatorSet;
 import android.animation.ObjectAnimator;
+import android.animation.TimeInterpolator;
 import android.animation.ValueAnimator;
 import android.annotation.TargetApi;
 import android.content.Context;
@@ -53,7 +54,6 @@
 import com.android.launcher3.Launcher;
 import com.android.launcher3.LauncherAnimUtils;
 import com.android.launcher3.LauncherModel;
-import com.android.launcher3.LauncherSettings;
 import com.android.launcher3.R;
 import com.android.launcher3.Utilities;
 import com.android.launcher3.accessibility.LauncherAccessibilityDelegate;
@@ -285,9 +285,11 @@
                 int roundedCorners = ROUNDED_TOP_CORNERS | ROUNDED_BOTTOM_CORNERS;
                 if (shouldUnroundTopCorners) {
                     roundedCorners &= ~ROUNDED_TOP_CORNERS;
+                    mNotificationItemView.findViewById(R.id.gutter_top).setVisibility(VISIBLE);
                 }
                 if (shouldUnroundBottomCorners) {
                     roundedCorners &= ~ROUNDED_BOTTOM_CORNERS;
+                    mNotificationItemView.findViewById(R.id.gutter_bottom).setVisibility(VISIBLE);
                 }
                 int backgroundColor = Themes.getAttrColor(mLauncher, R.attr.popupColorTertiary);
                 mNotificationItemView.setBackgroundWithCorners(backgroundColor, roundedCorners);
@@ -308,9 +310,15 @@
                 }
                 if (itemTypeToPopulate != PopupPopulator.Item.SYSTEM_SHORTCUT_ICON
                         && numNotifications > 0) {
+                    int prevHeight = item.getLayoutParams().height;
                     // Condense shortcuts height when there are notifications.
                     item.getLayoutParams().height = res.getDimensionPixelSize(
                             R.dimen.bg_popup_item_condensed_height);
+                    if (item instanceof DeepShortcutView) {
+                        float iconScale = (float) item.getLayoutParams().height / prevHeight;
+                        ((DeepShortcutView) item).getIconView().setScaleX(iconScale);
+                        ((DeepShortcutView) item).getIconView().setScaleY(iconScale);
+                    }
                 }
                 mShortcutsItemView.addShortcutView(item, itemTypeToPopulate);
                 if (shouldUnroundBottomCorners) {
@@ -320,8 +328,7 @@
                 addView(item);
             }
         }
-        int backgroundColor = Themes.getAttrColor(mLauncher, mNotificationItemView == null
-                ? R.attr.popupColorPrimary : R.attr.popupColorSecondary);
+        int backgroundColor = Themes.getAttrColor(mLauncher, R.attr.popupColorPrimary);
         mShortcutsItemView.setBackgroundWithCorners(backgroundColor, shortcutsItemRoundedCorners);
         if (numNotifications > 0) {
             mShortcutsItemView.hideShortcuts(mIsAboveIcon, MAX_SHORTCUTS_IF_NOTIFICATIONS);
@@ -347,6 +354,8 @@
 
         final AnimatorSet openAnim = LauncherAnimUtils.createAnimatorSet();
         final Resources res = getResources();
+        final long revealDuration = (long) res.getInteger(R.integer.config_popupOpenCloseDuration);
+        final TimeInterpolator revealInterpolator = new AccelerateDecelerateInterpolator();
 
         // Rectangular reveal.
         int itemsTotalHeight = 0;
@@ -360,8 +369,13 @@
         mEndRect.set(0, top, getMeasuredWidth(), top + itemsTotalHeight);
         final ValueAnimator revealAnim = new RoundedRectRevealOutlineProvider
                 (radius, radius, mStartRect, mEndRect).createRevealAnimator(this, false);
-        revealAnim.setDuration((long) res.getInteger(R.integer.config_popupOpenCloseDuration));
-        revealAnim.setInterpolator(new AccelerateDecelerateInterpolator());
+        revealAnim.setDuration(revealDuration);
+        revealAnim.setInterpolator(revealInterpolator);
+
+        Animator fadeIn = ObjectAnimator.ofFloat(this, ALPHA, 0, 1);
+        fadeIn.setDuration(revealDuration);
+        fadeIn.setInterpolator(revealInterpolator);
+        openAnim.play(fadeIn);
 
         // Animate the arrow.
         mArrow.setScaleX(0);
@@ -845,10 +859,8 @@
 
         final AnimatorSet closeAnim = LauncherAnimUtils.createAnimatorSet();
         final Resources res = getResources();
-
-        // Animate the arrow.
-        Animator arrowScale = createArrowScaleAnim(0).setDuration(res.getInteger(
-                R.integer.config_popupArrowOpenDuration));
+        final long revealDuration = (long) res.getInteger(R.integer.config_popupOpenCloseDuration);
+        final TimeInterpolator revealInterpolator = new AccelerateDecelerateInterpolator();
 
         // Rectangular reveal (reversed).
         int itemsTotalHeight = 0;
@@ -864,11 +876,19 @@
         }
         final ValueAnimator revealAnim = new RoundedRectRevealOutlineProvider(
                 radius, radius, mStartRect, mEndRect).createRevealAnimator(this, true);
-        revealAnim.setDuration((long) res.getInteger(R.integer.config_popupOpenCloseDuration));
-        revealAnim.setInterpolator(new AccelerateDecelerateInterpolator());
+        revealAnim.setDuration(revealDuration);
+        revealAnim.setInterpolator(revealInterpolator);
+        closeAnim.play(revealAnim);
+
+        Animator fadeOut = ObjectAnimator.ofFloat(this, ALPHA, 0);
+        fadeOut.setDuration(revealDuration);
+        fadeOut.setInterpolator(revealInterpolator);
+        closeAnim.play(fadeOut);
 
         // Animate original icon's text back in.
-        closeAnim.play(mOriginalIcon.createTextAlphaAnimator(true /* fadeIn */));
+        Animator fadeText = mOriginalIcon.createTextAlphaAnimator(true /* fadeIn */);
+        fadeText.setDuration(revealDuration);
+        closeAnim.play(fadeText);
 
         closeAnim.addListener(new AnimatorListenerAdapter() {
             @Override
@@ -882,7 +902,6 @@
             }
         });
         mOpenCloseAnimator = closeAnim;
-        closeAnim.playSequentially(arrowScale, revealAnim);
         closeAnim.start();
         mOriginalIcon.forceHideBadge(false);
     }
@@ -897,9 +916,7 @@
         }
         mIsOpen = false;
         mDeferContainerRemoval = false;
-        boolean isInHotseat = ((ItemInfo) mOriginalIcon.getTag()).container
-                == LauncherSettings.Favorites.CONTAINER_HOTSEAT;
-        mOriginalIcon.setTextVisibility(!isInHotseat);
+        mOriginalIcon.setTextVisibility(mOriginalIcon.shouldTextBeVisible());
         mOriginalIcon.forceHideBadge(false);
         mLauncher.getDragController().removeDragListener(this);
         mLauncher.getDragLayer().removeView(this);
diff --git a/src/com/android/launcher3/shortcuts/ShortcutsItemView.java b/src/com/android/launcher3/shortcuts/ShortcutsItemView.java
index 8785a56..f6fffe0 100644
--- a/src/com/android/launcher3/shortcuts/ShortcutsItemView.java
+++ b/src/com/android/launcher3/shortcuts/ShortcutsItemView.java
@@ -35,6 +35,7 @@
 import com.android.launcher3.Launcher;
 import com.android.launcher3.LauncherAnimUtils;
 import com.android.launcher3.R;
+import com.android.launcher3.anim.PropertyListBuilder;
 import com.android.launcher3.anim.RoundedRectRevealOutlineProvider;
 import com.android.launcher3.dragndrop.DragOptions;
 import com.android.launcher3.dragndrop.DragView;
@@ -280,6 +281,9 @@
             // Make sure the text and icon stay centered in the shortcut.
             animation.play(translateYFrom(shortcut.getBubbleText(), heightDiff / 2 * fromDir));
             animation.play(translateYFrom(shortcut.getIconView(), heightDiff / 2 * fromDir));
+            // Scale icons back up to full size.
+            animation.play(LauncherAnimUtils.ofPropertyValuesHolder(shortcut.getIconView(),
+                    new PropertyListBuilder().scale(1f).build()));
         }
         return animation;
     }
diff --git a/src/com/android/launcher3/widget/WidgetsBottomSheet.java b/src/com/android/launcher3/widget/WidgetsBottomSheet.java
index fff3472..a754375 100644
--- a/src/com/android/launcher3/widget/WidgetsBottomSheet.java
+++ b/src/com/android/launcher3/widget/WidgetsBottomSheet.java
@@ -44,10 +44,12 @@
 import com.android.launcher3.anim.PropertyListBuilder;
 import com.android.launcher3.dragndrop.DragController;
 import com.android.launcher3.dragndrop.DragOptions;
+import com.android.launcher3.graphics.GradientView;
 import com.android.launcher3.model.WidgetItem;
 import com.android.launcher3.userevent.nano.LauncherLogProto;
 import com.android.launcher3.util.PackageUserKey;
 import com.android.launcher3.util.SystemUiController;
+import com.android.launcher3.util.Themes;
 import com.android.launcher3.util.TouchController;
 
 import java.util.List;
@@ -70,6 +72,7 @@
     private VerticalPullDetector.ScrollInterpolator mScrollInterpolator;
     private Rect mInsets;
     private VerticalPullDetector mVerticalPullDetector;
+    private GradientView mGradientBackground;
 
     public WidgetsBottomSheet(Context context, AttributeSet attrs) {
         this(context, attrs, 0);
@@ -86,6 +89,7 @@
         mInsets = new Rect();
         mVerticalPullDetector = new VerticalPullDetector(context);
         mVerticalPullDetector.setListener(this);
+        mGradientBackground = (GradientView) mLauncher.findViewById(R.id.gradient_bg);
     }
 
     @Override
@@ -178,8 +182,10 @@
             return;
         }
         mIsOpen = true;
+        boolean isSheetDark = Themes.getAttrBoolean(mLauncher, R.attr.isMainColorDark);
         mLauncher.getSystemUiController().updateUiState(
-                SystemUiController.UI_STATE_WIDGET_BOTTOM_SHEET, SystemUiController.FLAG_LIGHT_NAV);
+                SystemUiController.UI_STATE_WIDGET_BOTTOM_SHEET,
+                isSheetDark ? SystemUiController.FLAG_DARK_NAV : SystemUiController.FLAG_LIGHT_NAV);
         if (animate) {
             mOpenCloseAnimator.setValues(new PropertyListBuilder()
                     .translationY(mTranslationYOpen).build());
@@ -267,6 +273,13 @@
     }
 
     @Override
+    public void setTranslationY(float translationY) {
+        super.setTranslationY(translationY);
+        if (mGradientBackground == null) return;
+        mGradientBackground.setProgress((mTranslationYClosed - translationY) / mTranslationYRange);
+    }
+
+    @Override
     public void onDragEnd(float velocity, boolean fling) {
         if ((fling && velocity > 0) || getTranslationY() > (mTranslationYRange) / 2) {
             mScrollInterpolator.setVelocityAtZero(velocity);