Merge "Mark off-screen pages as unimportant for accessibility" into ub-launcher3-dorval-polish
diff --git a/res/drawable/ic_warning.xml b/res/drawable/ic_warning.xml
new file mode 100644
index 0000000..a14b9f6
--- /dev/null
+++ b/res/drawable/ic_warning.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+        http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+        android:width="24dp"
+        android:height="24dp"
+        android:viewportWidth="24.0"
+        android:viewportHeight="24.0"
+        android:tint="?android:attr/textColorPrimary" >
+    <path
+        android:fillColor="#FFFFFFFF"
+        android:pathData="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/>
+</vector>
diff --git a/res/layout/notification_pref_warning.xml b/res/layout/notification_pref_warning.xml
new file mode 100644
index 0000000..795699e
--- /dev/null
+++ b/res/layout/notification_pref_warning.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+        http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<ImageView
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="48dp"
+    android:layout_height="match_parent"
+    android:background="?android:attr/selectableItemBackgroundBorderless"
+    android:contentDescription="@string/title_missing_notification_access"
+    android:scaleType="center"
+    android:src="@drawable/ic_warning"
+    android:tint="?android:attr/textColorSecondary" />
diff --git a/res/values/strings.xml b/res/values/strings.xml
index da6da04..9929671 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -178,6 +178,12 @@
     <string name="icon_badging_desc_on">On</string>
     <!-- Text to indicate that the system icon badging setting is off [CHAR LIMIT=100] -->
     <string name="icon_badging_desc_off">Off</string>
+    <!-- Title for the dialog shown when the app does not has notification access, explaining the requirement for notification access [CHAR LIMIT=50] -->
+    <string name="title_missing_notification_access">Notification access needed</string>
+    <!-- Message explaining to the user that the notification access is required by the app for showing 'Notification dots' [CHAR LIMIT=NONE] -->
+    <string name="msg_missing_notification_access">To show Notification Dots, turn on app notifications for <xliff:g id="name" example="My App">%1$s</xliff:g></string>
+    <!-- Button text in the confirmation dialog which would take the user to the system settings [CHAR LIMIT=50] -->
+    <string name="title_change_settings">Change settings</string>
 
     <!-- Label for the setting that allows the automatic placement of launcher shortcuts for applications and games installed on the device [CHAR LIMIT=40] -->
     <string name="auto_add_shortcuts_label">Add icon to Home screen</string>
diff --git a/res/xml/launcher_preferences.xml b/res/xml/launcher_preferences.xml
index c76f118..28a35b8 100644
--- a/res/xml/launcher_preferences.xml
+++ b/res/xml/launcher_preferences.xml
@@ -16,17 +16,18 @@
 
 <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
 
-    <Preference
+    <com.android.launcher3.views.ButtonPreference
         android:key="pref_icon_badging"
         android:title="@string/icon_badging_title"
-        android:persistent="false">
+        android:persistent="false"
+        android:widgetLayout="@layout/notification_pref_warning" >
         <intent android:action="android.settings.NOTIFICATION_SETTINGS">
             <!-- This extra highlights the "Allow icon badges" field in Notification settings -->
             <extra
                 android:name=":settings:fragment_args_key"
                 android:value="notification_badging" />
         </intent>
-    </Preference>
+    </com.android.launcher3.views.ButtonPreference>
 
     <SwitchPreference
         android:key="pref_add_icon_to_home"
diff --git a/src/com/android/launcher3/IconCache.java b/src/com/android/launcher3/IconCache.java
index 4b71ba0..3bcd7af 100644
--- a/src/com/android/launcher3/IconCache.java
+++ b/src/com/android/launcher3/IconCache.java
@@ -68,7 +68,7 @@
     private static final int INITIAL_ICON_CACHE_CAPACITY = 50;
 
     // Empty class name is used for storing package default entry.
-    private static final String EMPTY_CLASS_NAME = ".";
+    public static final String EMPTY_CLASS_NAME = ".";
 
     private static final boolean DEBUG = false;
     private static final boolean DEBUG_IGNORE_CACHE = false;
diff --git a/src/com/android/launcher3/ItemInfo.java b/src/com/android/launcher3/ItemInfo.java
index 11c5309..c5be096 100644
--- a/src/com/android/launcher3/ItemInfo.java
+++ b/src/com/android/launcher3/ItemInfo.java
@@ -137,7 +137,18 @@
     }
 
     public ComponentName getTargetComponent() {
-        return getIntent() == null ? null : getIntent().getComponent();
+        Intent intent = getIntent();
+        if (intent == null) {
+            return null;
+        }
+        ComponentName cn = intent.getComponent();
+        if (itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT && cn == null) {
+            // Legacy shortcuts may not have a componentName but just a packageName. In that case
+            // create a dummy componentName instead of adding additional check everywhere.
+            String pkg = intent.getPackage();
+            return pkg == null ? null : new ComponentName(pkg, IconCache.EMPTY_CLASS_NAME);
+        }
+        return cn;
     }
 
     public void writeToValues(ContentWriter writer) {
diff --git a/src/com/android/launcher3/SettingsActivity.java b/src/com/android/launcher3/SettingsActivity.java
index a34e469..d5d5eab 100644
--- a/src/com/android/launcher3/SettingsActivity.java
+++ b/src/com/android/launcher3/SettingsActivity.java
@@ -17,7 +17,15 @@
 package com.android.launcher3;
 
 import android.app.Activity;
+import android.app.AlertDialog;
+import android.app.Dialog;
+import android.app.DialogFragment;
+import android.app.FragmentManager;
+import android.content.ComponentName;
 import android.content.ContentResolver;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.Intent;
 import android.database.ContentObserver;
 import android.os.Bundle;
 import android.os.Handler;
@@ -26,8 +34,11 @@
 import android.preference.PreferenceFragment;
 import android.provider.Settings;
 import android.provider.Settings.System;
+import android.view.View;
 
 import com.android.launcher3.graphics.IconShapeOverride;
+import com.android.launcher3.notification.NotificationListener;
+import com.android.launcher3.views.ButtonPreference;
 
 /**
  * Settings activity for Launcher. Currently implements the following setting: Allow rotation
@@ -37,6 +48,8 @@
     private static final String ICON_BADGING_PREFERENCE_KEY = "pref_icon_badging";
     // TODO: use Settings.Secure.NOTIFICATION_BADGING
     private static final String NOTIFICATION_BADGING = "notification_badging";
+    /** Hidden field Settings.Secure.ENABLED_NOTIFICATION_LISTENERS */
+    private static final String NOTIFICATION_ENABLED_LISTENERS = "enabled_notification_listeners";
 
     @Override
     protected void onCreate(Bundle savedInstanceState) {
@@ -85,17 +98,22 @@
                 rotationPref.setDefaultValue(Utilities.getAllowRotationDefaultValue(getActivity()));
             }
 
-            Preference iconBadgingPref = findPreference(ICON_BADGING_PREFERENCE_KEY);
+            ButtonPreference iconBadgingPref =
+                    (ButtonPreference) findPreference(ICON_BADGING_PREFERENCE_KEY);
             if (!Utilities.isAtLeastO()) {
                 getPreferenceScreen().removePreference(
                         findPreference(SessionCommitReceiver.ADD_ICON_PREFERENCE_KEY));
                 getPreferenceScreen().removePreference(iconBadgingPref);
             } else {
                 // Listen to system notification badge settings while this UI is active.
-                mIconBadgingObserver = new IconBadgingObserver(iconBadgingPref, resolver);
+                mIconBadgingObserver = new IconBadgingObserver(
+                        iconBadgingPref, resolver, getFragmentManager());
                 resolver.registerContentObserver(
                         Settings.Secure.getUriFor(NOTIFICATION_BADGING),
                         false, mIconBadgingObserver);
+                resolver.registerContentObserver(
+                        Settings.Secure.getUriFor(NOTIFICATION_ENABLED_LISTENERS),
+                        false, mIconBadgingObserver);
                 mIconBadgingObserver.onChange(true);
             }
 
@@ -153,24 +171,74 @@
      * Content observer which listens for system badging setting changes,
      * and updates the launcher badging setting subtext accordingly.
      */
-    private static class IconBadgingObserver extends ContentObserver {
+    private static class IconBadgingObserver extends ContentObserver
+            implements View.OnClickListener {
 
-        private final Preference mBadgingPref;
+        private final ButtonPreference mBadgingPref;
         private final ContentResolver mResolver;
+        private final FragmentManager mFragmentManager;
 
-        public IconBadgingObserver(Preference badgingPref, ContentResolver resolver) {
+        public IconBadgingObserver(ButtonPreference badgingPref, ContentResolver resolver,
+                FragmentManager fragmentManager) {
             super(new Handler());
             mBadgingPref = badgingPref;
             mResolver = resolver;
+            mFragmentManager = fragmentManager;
         }
 
         @Override
         public void onChange(boolean selfChange) {
             boolean enabled = Settings.Secure.getInt(mResolver, NOTIFICATION_BADGING, 1) == 1;
-            mBadgingPref.setSummary(enabled
-                    ? R.string.icon_badging_desc_on
-                    : R.string.icon_badging_desc_off);
+            int summary = enabled ? R.string.icon_badging_desc_on : R.string.icon_badging_desc_off;
+
+            boolean serviceEnabled = true;
+            if (enabled) {
+                // Check if the listener is enabled or not.
+                String enabledListeners =
+                        Settings.Secure.getString(mResolver, NOTIFICATION_ENABLED_LISTENERS);
+                ComponentName myListener =
+                        new ComponentName(mBadgingPref.getContext(), NotificationListener.class);
+                serviceEnabled = enabledListeners != null &&
+                        (enabledListeners.contains(myListener.flattenToString()) ||
+                                enabledListeners.contains(myListener.flattenToShortString()));
+                if (!serviceEnabled) {
+                    summary = R.string.title_missing_notification_access;
+                }
+            }
+            mBadgingPref.setButtonOnClickListener(serviceEnabled ? null : this);
+            mBadgingPref.setSummary(summary);
+
+        }
+
+        @Override
+        public void onClick(View view) {
+            new NotificationAccessConfirmation().show(mFragmentManager, "notification_access");
         }
     }
 
+    public static class NotificationAccessConfirmation
+            extends DialogFragment implements DialogInterface.OnClickListener {
+
+        @Override
+        public Dialog onCreateDialog(Bundle savedInstanceState) {
+            final Context context = getActivity();
+            String msg = context.getString(R.string.msg_missing_notification_access,
+                    context.getString(R.string.derived_app_name));
+            return new AlertDialog.Builder(context)
+                    .setTitle(R.string.title_missing_notification_access)
+                    .setMessage(msg)
+                    .setNegativeButton(android.R.string.cancel, null)
+                    .setPositiveButton(R.string.title_change_settings, this)
+                    .create();
+        }
+
+        @Override
+        public void onClick(DialogInterface dialogInterface, int i) {
+            ComponentName cn = new ComponentName(getActivity(), NotificationListener.class);
+            Intent intent = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)
+                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+                    .putExtra(":settings:fragment_args_key", cn.flattenToString());
+            getActivity().startActivity(intent);
+        }
+    }
 }
diff --git a/src/com/android/launcher3/Workspace.java b/src/com/android/launcher3/Workspace.java
index 7f10191..3b11619 100644
--- a/src/com/android/launcher3/Workspace.java
+++ b/src/com/android/launcher3/Workspace.java
@@ -2375,7 +2375,7 @@
                 fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale,
                         postAnimationRunnable);
             } else {
-                fi.prepareCreate(v);
+                fi.prepareCreateAnimation(v);
                 fi.addItem(destInfo);
                 fi.addItem(sourceInfo);
             }
@@ -3984,8 +3984,9 @@
         }
     }
 
-    private void moveToScreen(int page, boolean animate) {
-        if (!workspaceInModalState()) {
+    void moveToDefaultScreen(boolean animate) {
+        int page = getDefaultPage();
+        if (!workspaceInModalState() && getCurrentPage() != page) {
             if (animate) {
                 snapToPage(page);
             } else {
@@ -3998,10 +3999,6 @@
         }
     }
 
-    void moveToDefaultScreen(boolean animate) {
-        moveToScreen(getDefaultPage(), animate);
-    }
-
     void moveToCustomContentScreen(boolean animate) {
         if (hasCustomContent()) {
             int ccIndex = getPageIndexForScreenId(CUSTOM_CONTENT_SCREEN_ID);
diff --git a/src/com/android/launcher3/compat/WallpaperColorsCompat.java b/src/com/android/launcher3/compat/WallpaperColorsCompat.java
index 58d2a80..e25b9d9 100644
--- a/src/com/android/launcher3/compat/WallpaperColorsCompat.java
+++ b/src/com/android/launcher3/compat/WallpaperColorsCompat.java
@@ -21,6 +21,7 @@
 public class WallpaperColorsCompat {
 
     public static final int HINT_SUPPORTS_DARK_TEXT = 0x1;
+    public static final int HINT_SUPPORTS_DARK_THEME = 0x2;
 
     private final int mPrimaryColor;
     private final int mSecondaryColor;
diff --git a/src/com/android/launcher3/dynamicui/WallpaperColorInfo.java b/src/com/android/launcher3/dynamicui/WallpaperColorInfo.java
index 512e89a..80a89e3 100644
--- a/src/com/android/launcher3/dynamicui/WallpaperColorInfo.java
+++ b/src/com/android/launcher3/dynamicui/WallpaperColorInfo.java
@@ -81,9 +81,9 @@
         mSupportsDarkText = wallpaperColors != null
                 ? (wallpaperColors.getColorHints()
                     & WallpaperColorsCompat.HINT_SUPPORTS_DARK_TEXT) > 0 : false;
-        float[] hsl = new float[3];
-        ColorUtils.colorToHSL(mMainColor, hsl);
-        mIsDark = hsl[2] < 0.2f;
+        mIsDark = wallpaperColors != null
+                ? (wallpaperColors.getColorHints()
+                    & WallpaperColorsCompat.HINT_SUPPORTS_DARK_THEME) > 0 : false;
     }
 
     public void setOnThemeChangeListener(OnThemeChangeListener onThemeChangeListener) {
diff --git a/src/com/android/launcher3/folder/Folder.java b/src/com/android/launcher3/folder/Folder.java
index f68b394..3184d6d 100644
--- a/src/com/android/launcher3/folder/Folder.java
+++ b/src/com/android/launcher3/folder/Folder.java
@@ -791,12 +791,14 @@
         if (mFolderIcon != null) {
             mFolderIcon.setVisibility(View.VISIBLE);
             if (FeatureFlags.LAUNCHER3_NEW_FOLDER_ANIMATION) {
-                mFolderIcon.mFolderName.setTextVisibility(true);
                 mFolderIcon.setBackgroundVisible(true);
-                mFolderIcon.mBackground.fadeInBackgroundShadow();
             }
             if (wasAnimated) {
-                mFolderIcon.mBackground.animateBackgroundStroke();
+                if (FeatureFlags.LAUNCHER3_NEW_FOLDER_ANIMATION) {
+                    mFolderIcon.mBackground.fadeInBackgroundShadow();
+                    mFolderIcon.mBackground.animateBackgroundStroke();
+                    mFolderIcon.onFolderClose(mContent.getCurrentPage());
+                }
                 if (mFolderIcon.hasBadge()) {
                     mFolderIcon.createBadgeScaleAnimator(0f, 1f).start();
                 }
@@ -818,6 +820,7 @@
         mSuppressFolderDeletion = false;
         clearDragInfo();
         mState = STATE_SMALL;
+        mContent.setCurrentPage(0);
     }
 
     public boolean acceptDrop(DragObject d) {
@@ -1280,7 +1283,7 @@
         };
         View finalChild = mContent.getLastItem();
         if (finalChild != null) {
-            mFolderIcon.performDestroyAnimation(finalChild, onCompleteRunnable);
+            mFolderIcon.performDestroyAnimation(onCompleteRunnable);
         } else {
             onCompleteRunnable.run();
         }
@@ -1516,18 +1519,17 @@
         return itemsInReadingOrder;
     }
 
-    public List<BubbleTextView> getItemsOnCurrentPage() {
+    public List<BubbleTextView> getItemsOnPage(int page) {
         ArrayList<View> allItems = getItemsInRankOrder();
-        int currentPage = mContent.getCurrentPage();
         int lastPage = mContent.getPageCount() - 1;
         int totalItemsInFolder = allItems.size();
         int itemsPerPage = mContent.itemsPerPage();
-        int numItemsOnCurrentPage = currentPage == lastPage
-                ? totalItemsInFolder - (itemsPerPage * currentPage)
+        int numItemsOnCurrentPage = page == lastPage
+                ? totalItemsInFolder - (itemsPerPage * page)
                 : itemsPerPage;
 
-        int startIndex = currentPage * itemsPerPage;
-        int endIndex = startIndex + numItemsOnCurrentPage;
+        int startIndex = page * itemsPerPage;
+        int endIndex = Math.min(startIndex + numItemsOnCurrentPage, allItems.size());
 
         List<BubbleTextView> itemsOnCurrentPage = new ArrayList<>(numItemsOnCurrentPage);
         for (int i = startIndex; i < endIndex; ++i) {
diff --git a/src/com/android/launcher3/folder/FolderAnimationManager.java b/src/com/android/launcher3/folder/FolderAnimationManager.java
index 7e8d0c7..26a2c89 100644
--- a/src/com/android/launcher3/folder/FolderAnimationManager.java
+++ b/src/com/android/launcher3/folder/FolderAnimationManager.java
@@ -119,7 +119,7 @@
     public AnimatorSet getAnimator() {
         final DragLayer.LayoutParams lp = (DragLayer.LayoutParams) mFolder.getLayoutParams();
         FolderIcon.PreviewLayoutRule rule = mFolderIcon.getLayoutRule();
-        final List<BubbleTextView> itemsInPreview = mFolderIcon.getItemsToDisplay();
+        final List<BubbleTextView> itemsInPreview = mFolderIcon.getPreviewItems();
 
         // Match position of the FolderIcon
         final Rect folderIconPos = new Rect();
@@ -186,7 +186,7 @@
         PropertyResetListener colorResetListener = new PropertyResetListener<>(
                 BubbleTextView.TEXT_ALPHA_PROPERTY,
                 Color.alpha(Themes.getAttrColor(mContext, android.R.attr.textColorSecondary)));
-        for (BubbleTextView icon : mFolder.getItemsOnCurrentPage()) {
+        for (BubbleTextView icon : mFolder.getItemsOnPage(mFolder.mContent.getCurrentPage())) {
             if (mIsOpening) {
                 icon.setTextVisibility(false);
             }
@@ -237,13 +237,19 @@
     }
 
     /**
-     * Animate the items that are displayed in the preview.
+     * Animate the items on the current page.
      */
     private void addPreviewItemAnimators(AnimatorSet animatorSet, final float folderScale,
             int previewItemOffsetX) {
         FolderIcon.PreviewLayoutRule rule = mFolderIcon.getLayoutRule();
-        final List<BubbleTextView> itemsInPreview = mFolderIcon.getItemsToDisplay();
+        boolean isOnFirstPage = mFolder.mContent.getCurrentPage() == 0;
+        final List<BubbleTextView> itemsInPreview = isOnFirstPage
+                ? mFolderIcon.getPreviewItems()
+                : mFolderIcon.getPreviewItemsOnPage(mFolder.mContent.getCurrentPage());
         final int numItemsInPreview = itemsInPreview.size();
+        final int numItemsInFirstPagePreview = isOnFirstPage
+                ? numItemsInPreview
+                : FolderIcon.NUM_ITEMS_IN_PREVIEW;
 
         TimeInterpolator previewItemInterpolator = getPreviewItemInterpolator();
 
@@ -256,8 +262,8 @@
             btvLp.isLockedToGrid = true;
             cwc.setupLp(btv);
 
-            // Match scale of icons in the preview.
-            float previewScale = rule.scaleForItem(i, numItemsInPreview);
+            // Match scale of icons in the preview of the items on the first page.
+            float previewScale = rule.scaleForItem(i, numItemsInFirstPagePreview);
             float previewSize = rule.getIconSize() * previewScale;
             float iconScale = previewSize / itemsInPreview.get(i).getIconSize();
 
@@ -268,7 +274,7 @@
             btv.setScaleY(scale);
 
             // Match positions of the icons in the folder with their positions in the preview
-            rule.computePreviewItemDrawingParams(i, numItemsInPreview, mTmpParams);
+            rule.computePreviewItemDrawingParams(i, numItemsInFirstPagePreview, mTmpParams);
             // The PreviewLayoutRule assumes that the icon size takes up the entire width so we
             // offset by the actual size.
             int iconOffsetX = (int) ((btvLp.width - btv.getIconSize()) * iconScale) / 2;
diff --git a/src/com/android/launcher3/folder/FolderIcon.java b/src/com/android/launcher3/folder/FolderIcon.java
index 3a0e71f..ae6a0e8 100644
--- a/src/com/android/launcher3/folder/FolderIcon.java
+++ b/src/com/android/launcher3/folder/FolderIcon.java
@@ -37,7 +37,6 @@
 import android.view.animation.AccelerateInterpolator;
 import android.view.animation.DecelerateInterpolator;
 import android.widget.FrameLayout;
-import android.widget.TextView;
 
 import com.android.launcher3.Alarm;
 import com.android.launcher3.AppInfo;
@@ -71,6 +70,8 @@
 import java.util.ArrayList;
 import java.util.List;
 
+import static com.android.launcher3.folder.PreviewItemManager.INITIAL_ITEM_ANIMATION_DURATION;
+
 /**
  * An icon that can appear on in the workspace representing an {@link Folder}.
  */
@@ -87,9 +88,7 @@
     private CheckLongPressHelper mLongPressHelper;
     private StylusEventHelper mStylusEventHelper;
 
-    private static final int DROP_IN_ANIMATION_DURATION = 400;
-    private static final int INITIAL_ITEM_ANIMATION_DURATION = 350;
-    private static final int FINAL_ITEM_ANIMATION_DURATION = 200;
+    static final int DROP_IN_ANIMATION_DURATION = 400;
 
     // Flag whether the folder should open itself when an item is dragged over is enabled.
     public static final boolean SPRING_LOADING_ENABLED = true;
@@ -99,27 +98,19 @@
 
     @Thunk BubbleTextView mFolderName;
 
-    // These variables are all associated with the drawing of the preview; they are stored
-    // as member variables for shared usage and to avoid computation on each frame
-    private float mIntrinsicIconSize = -1;
-    private int mTotalWidth = -1;
-    private int mPrevTopPadding = -1;
-
     PreviewBackground mBackground = new PreviewBackground();
     private boolean mBackgroundIsVisible = true;
 
-    private PreviewLayoutRule mPreviewLayoutRule;
+    FolderIconPreviewVerifier mPreviewVerifier;
+    PreviewLayoutRule mPreviewLayoutRule;
+    private PreviewItemManager mPreviewItemManager;
+    private PreviewItemDrawingParams mTmpParams = new PreviewItemDrawingParams(0, 0, 0, 0);
 
     boolean mAnimating = false;
     private Rect mTempBounds = new Rect();
 
     private float mSlop;
 
-    FolderIconPreviewVerifier mPreviewVerifier;
-    private PreviewItemDrawingParams mTmpParams = new PreviewItemDrawingParams(0, 0, 0, 0);
-    private ArrayList<PreviewItemDrawingParams> mDrawingParams = new ArrayList<>();
-    private Drawable mReferenceDrawable = null;
-
     private Alarm mOpenAlarm = new Alarm();
 
     private FolderBadgeInfo mBadgeInfo = new FolderBadgeInfo();
@@ -158,6 +149,7 @@
                 new StackFolderIconLayoutRule() :
                 new ClippedFolderIconLayoutRule();
         mSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
+        mPreviewItemManager = new PreviewItemManager(this);
     }
 
     public static FolderIcon fromXml(int resId, Launcher launcher, ViewGroup group,
@@ -213,7 +205,7 @@
     private void setFolder(Folder folder) {
         mFolder = folder;
         mPreviewVerifier = new FolderIconPreviewVerifier(mLauncher.getDeviceProfile().inv);
-        updateItemDrawingParams(false);
+        mPreviewItemManager.updateItemDrawingParams(false);
     }
 
     private boolean willAcceptItem(ItemInfo item) {
@@ -254,40 +246,28 @@
         }
     };
 
-    public Drawable prepareCreate(final View destView) {
-        Drawable animateDrawable = ((TextView) destView).getCompoundDrawables()[1];
-        computePreviewDrawingParams(animateDrawable.getIntrinsicWidth(),
-                destView.getMeasuredWidth());
-        return animateDrawable;
+    public Drawable prepareCreateAnimation(final View destView) {
+        return mPreviewItemManager.prepareCreateAnimation(destView);
     }
 
     public void performCreateAnimation(final ShortcutInfo destInfo, final View destView,
             final ShortcutInfo srcInfo, final DragView srcView, Rect dstRect,
             float scaleRelativeToDragLayer, Runnable postAnimationRunnable) {
-
-        // These correspond two the drawable and view that the icon was dropped _onto_
-        Drawable animateDrawable = prepareCreate(destView);
-
-        mReferenceDrawable = animateDrawable;
-
+        prepareCreateAnimation(destView);
         addItem(destInfo);
         // This will animate the first item from it's position as an icon into its
         // position as the first item in the preview
-        animateFirstItem(animateDrawable, INITIAL_ITEM_ANIMATION_DURATION, false, null);
+        mPreviewItemManager.createFirstItemAnimation(false /* reverse */, null)
+                .start();
 
         // This will animate the dragView (srcView) into the new folder
         onDrop(srcInfo, srcView, dstRect, scaleRelativeToDragLayer, 1, postAnimationRunnable);
     }
 
-    public void performDestroyAnimation(final View finalView, Runnable onCompleteRunnable) {
-        Drawable animateDrawable = ((TextView) finalView).getCompoundDrawables()[1];
-        computePreviewDrawingParams(animateDrawable.getIntrinsicWidth(),
-                finalView.getMeasuredWidth());
-
-        // This will animate the first item from it's position as an icon into its
-        // position as the first item in the preview
-        animateFirstItem(animateDrawable, FINAL_ITEM_ANIMATION_DURATION, true,
-                onCompleteRunnable);
+    public void performDestroyAnimation(Runnable onCompleteRunnable) {
+        // This will animate the final item in the preview to be full size.
+        mPreviewItemManager.createFirstItemAnimation(true /* reverse */, onCompleteRunnable)
+                .start();
     }
 
     public void onDragExit() {
@@ -296,7 +276,7 @@
     }
 
     private void onDrop(final ShortcutInfo item, DragView animateView, Rect finalRect,
-            float scaleRelativeToDragLayer, int index, Runnable postAnimationRunnable) {
+            float scaleRelativeToDragLayer, final int index, Runnable postAnimationRunnable) {
         item.cellX = -1;
         item.cellY = -1;
 
@@ -342,12 +322,10 @@
             addItem(item);
             mFolder.hideItem(item);
 
-            final PreviewItemDrawingParams params = index < mDrawingParams.size() ?
-                    mDrawingParams.get(index) : null;
-            if (params != null) params.hidden = true;
+            mPreviewItemManager.hidePreviewItem(index, true);
             postDelayed(new Runnable() {
                 public void run() {
-                    if (params != null) params.hidden = false;
+                    mPreviewItemManager.hidePreviewItem(index, false);
                     mFolder.showItem(item);
                     invalidate();
                 }
@@ -369,25 +347,6 @@
         onDrop(item, d.dragView, null, 1.0f, mInfo.contents.size(), d.postAnimationRunnable);
     }
 
-    private void computePreviewDrawingParams(int drawableSize, int totalSize) {
-        if (mIntrinsicIconSize != drawableSize || mTotalWidth != totalSize ||
-                mPrevTopPadding != getPaddingTop()) {
-            mIntrinsicIconSize = drawableSize;
-            mTotalWidth = totalSize;
-            mPrevTopPadding = getPaddingTop();
-
-            mBackground.setup(mLauncher, this, mTotalWidth, getPaddingTop());
-            mPreviewLayoutRule.init(mBackground.previewSize, mIntrinsicIconSize,
-                    Utilities.isRtl(getResources()));
-
-            updateItemDrawingParams(false);
-        }
-    }
-
-    private void computePreviewDrawingParams(Drawable d) {
-        computePreviewDrawingParams(d.getIntrinsicWidth(), getMeasuredWidth());
-    }
-
     public void setBadgeInfo(FolderBadgeInfo badgeInfo) {
         updateBadgeScale(mBadgeInfo.hasBadge(), badgeInfo.hasBadge());
         mBadgeInfo = badgeInfo;
@@ -421,56 +380,21 @@
     }
 
     private float getLocalCenterForIndex(int index, int curNumItems, int[] center) {
-        mTmpParams = computePreviewItemDrawingParams(
+        mTmpParams = mPreviewItemManager.computePreviewItemDrawingParams(
                 Math.min(mPreviewLayoutRule.maxNumItems(), index), curNumItems, mTmpParams);
 
         mTmpParams.transX += mBackground.basePreviewOffsetX;
         mTmpParams.transY += mBackground.basePreviewOffsetY;
-        float offsetX = mTmpParams.transX + (mTmpParams.scale * mIntrinsicIconSize) / 2;
-        float offsetY = mTmpParams.transY + (mTmpParams.scale * mIntrinsicIconSize) / 2;
+
+        float intrinsicIconSize = mPreviewItemManager.getIntrinsicIconSize();
+        float offsetX = mTmpParams.transX + (mTmpParams.scale * intrinsicIconSize) / 2;
+        float offsetY = mTmpParams.transY + (mTmpParams.scale * intrinsicIconSize) / 2;
 
         center[0] = Math.round(offsetX);
         center[1] = Math.round(offsetY);
         return mTmpParams.scale;
     }
 
-    PreviewItemDrawingParams computePreviewItemDrawingParams(int index, int curNumItems,
-            PreviewItemDrawingParams params) {
-        // We use an index of -1 to represent an icon on the workspace for the destroy and
-        // create animations
-        if (index == -1) {
-            return getFinalIconParams(params);
-        }
-        return mPreviewLayoutRule.computePreviewItemDrawingParams(index, curNumItems, params);
-    }
-
-    private PreviewItemDrawingParams getFinalIconParams(PreviewItemDrawingParams params) {
-        float iconSize = mLauncher.getDeviceProfile().iconSizePx;
-
-        final float scale = iconSize / mReferenceDrawable.getIntrinsicWidth();
-        final float trans = (mBackground.previewSize - iconSize) / 2;
-
-        params.update(trans, trans, scale);
-        return params;
-    }
-
-    private void drawPreviewItem(Canvas canvas, PreviewItemDrawingParams params) {
-        canvas.save(Canvas.MATRIX_SAVE_FLAG);
-        canvas.translate(params.transX, params.transY);
-        canvas.scale(params.scale, params.scale);
-        Drawable d = params.drawable;
-
-        if (d != null) {
-            Rect bounds = d.getBounds();
-            canvas.save();
-            canvas.translate(-bounds.left, -bounds.top);
-            canvas.scale(mIntrinsicIconSize / bounds.width(), mIntrinsicIconSize / bounds.height());
-            d.draw(canvas);
-            canvas.restore();
-        }
-        canvas.restore();
-    }
-
     public void setFolderBackground(PreviewBackground bg) {
         mBackground = bg;
         mBackground.setInvalidateDelegate(this);
@@ -487,10 +411,6 @@
 
         if (!mBackgroundIsVisible) return;
 
-        if (mReferenceDrawable != null) {
-            computePreviewDrawingParams(mReferenceDrawable);
-        }
-
         if (!mBackground.drawingDelegated()) {
             mBackground.drawBackground(canvas);
         }
@@ -512,14 +432,7 @@
 
         // The items are drawn in coordinates relative to the preview offset
         canvas.translate(mBackground.basePreviewOffsetX, mBackground.basePreviewOffsetY);
-
-        // The first item should be drawn last (ie. on top of later items)
-        for (int i = mDrawingParams.size() - 1; i >= 0; i--) {
-            PreviewItemDrawingParams p = mDrawingParams.get(i);
-            if (!p.hidden) {
-                drawPreviewItem(canvas, p);
-            }
-        }
+        mPreviewItemManager.draw(canvas);
         canvas.translate(-mBackground.basePreviewOffsetX, -mBackground.basePreviewOffsetY);
 
         if (mPreviewLayoutRule.clipToBackground() && canvas.isHardwareAccelerated()) {
@@ -546,19 +459,6 @@
         }
     }
 
-    private void animateFirstItem(final Drawable d, int duration, final boolean reverse,
-            final Runnable onCompleteRunnable) {
-        FolderPreviewItemAnim anim;
-        if (!reverse) {
-            anim = new FolderPreviewItemAnim(this, mDrawingParams.get(0), -1, -1, 0, 2, duration,
-                    onCompleteRunnable);
-        } else {
-            anim = new FolderPreviewItemAnim(this, mDrawingParams.get(0), 0, 2, -1, -1, duration,
-                    onCompleteRunnable);
-        }
-        anim.start();
-    }
-
     public void setTextVisible(boolean visible) {
         if (visible) {
             mFolderName.setVisibility(VISIBLE);
@@ -571,15 +471,25 @@
         return mFolderName.getVisibility() == VISIBLE;
     }
 
-    public List<BubbleTextView> getItemsToDisplay() {
+    /**
+     * Returns the list of preview items displayed in the icon.
+     */
+    public List<BubbleTextView> getPreviewItems() {
+        return getPreviewItemsOnPage(0);
+    }
+
+    /**
+     * Returns the list of "preview items" on {@param page}.
+     */
+    public List<BubbleTextView> getPreviewItemsOnPage(int page) {
         mPreviewVerifier.setFolderInfo(mFolder.getInfo());
 
         List<BubbleTextView> itemsToDisplay = new ArrayList<>();
-        List<View> allItems = mFolder.getItemsInRankOrder();
-        int numItems = allItems.size();
+        List<BubbleTextView> itemsOnPage = mFolder.getItemsOnPage(page);
+        int numItems = itemsOnPage.size();
         for (int rank = 0; rank < numItems; ++rank) {
-            if (mPreviewVerifier.isItemInPreview(rank)) {
-                itemsToDisplay.add((BubbleTextView) allItems.get(rank));
+            if (mPreviewVerifier.isItemInPreview(page, rank)) {
+                itemsToDisplay.add(itemsOnPage.get(rank));
             }
 
             if (itemsToDisplay.size() == FolderIcon.NUM_ITEMS_IN_PREVIEW) {
@@ -591,63 +501,12 @@
 
     @Override
     protected boolean verifyDrawable(@NonNull Drawable who) {
-        for (int i = 0; i < mDrawingParams.size(); i++) {
-            if (mDrawingParams.get(i).drawable == who) {
-                return true;
-            }
-        }
-        return super.verifyDrawable(who);
-    }
-
-    private void updateItemDrawingParams(boolean animate) {
-        List<BubbleTextView> items = getItemsToDisplay();
-        int nItemsInPreview = items.size();
-
-        int prevNumItems = mDrawingParams.size();
-
-        // We adjust the size of the list to match the number of items in the preview
-        while (nItemsInPreview < mDrawingParams.size()) {
-            mDrawingParams.remove(mDrawingParams.size() - 1);
-        }
-        while (nItemsInPreview > mDrawingParams.size()) {
-            mDrawingParams.add(new PreviewItemDrawingParams(0, 0, 0, 0));
-        }
-
-        for (int i = 0; i < mDrawingParams.size(); i++) {
-            PreviewItemDrawingParams p = mDrawingParams.get(i);
-            p.drawable = items.get(i).getCompoundDrawables()[1];
-
-            if (p.drawable != null && !mFolder.isOpen()) {
-                // Set the callback to FolderIcon as it is responsible to drawing the icon. The
-                // callback will be release when the folder is opened.
-                p.drawable.setCallback(this);
-            }
-
-            if (!animate || FeatureFlags.LAUNCHER3_LEGACY_FOLDER_ICON) {
-                computePreviewItemDrawingParams(i, nItemsInPreview, p);
-                if (mReferenceDrawable == null) {
-                    mReferenceDrawable = p.drawable;
-                }
-            } else {
-                FolderPreviewItemAnim anim = new FolderPreviewItemAnim(this, p, i, prevNumItems, i,
-                        nItemsInPreview, DROP_IN_ANIMATION_DURATION, null);
-
-                if (p.anim != null) {
-                    if (p.anim.hasEqualFinalState(anim)) {
-                        // do nothing, let the current animation finish
-                        continue;
-                    }
-                    p.anim.cancel();
-                }
-                p.anim = anim;
-                p.anim.start();
-            }
-        }
+        return mPreviewItemManager.verifyDrawable(who) || super.verifyDrawable(who);
     }
 
     @Override
     public void onItemsChanged(boolean animate) {
-        updateItemDrawingParams(animate);
+        mPreviewItemManager.updateItemDrawingParams(animate);
         invalidate();
         requestLayout();
     }
@@ -790,6 +649,10 @@
         }
     }
 
+    public void onFolderClose(int currentPage) {
+        mPreviewItemManager.onFolderClose(currentPage);
+    }
+
     interface PreviewLayoutRule {
         PreviewItemDrawingParams computePreviewItemDrawingParams(int index, int curNumItems,
             PreviewItemDrawingParams params);
diff --git a/src/com/android/launcher3/folder/FolderIconPreviewVerifier.java b/src/com/android/launcher3/folder/FolderIconPreviewVerifier.java
index d0d8e79..eb415b9 100644
--- a/src/com/android/launcher3/folder/FolderIconPreviewVerifier.java
+++ b/src/com/android/launcher3/folder/FolderIconPreviewVerifier.java
@@ -25,15 +25,45 @@
  */
 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;
+
     public FolderIconPreviewVerifier(InvariantDeviceProfile profile) {
-        // b/37570804
+        mMaxGridCountX = profile.numFolderColumns;
+        mMaxGridCountY = profile.numFolderRows;
+        mMaxItemsPerPage = mMaxGridCountX * mMaxGridCountY;
     }
 
     public void setFolderInfo(FolderInfo info) {
-        // b/37570804
+        FolderPagedView.calculateGridSize(info.contents.size(), 0, 0, mMaxGridCountX,
+                mMaxGridCountY, mMaxItemsPerPage, mGridSize);
+        mGridCountX = mGridSize[0];
     }
 
+    /**
+     * Returns whether the item with {@param rank} is in the default Folder icon preview.
+     */
     public boolean isItemInPreview(int rank) {
+        return isItemInPreview(0, rank);
+    }
+
+    /**
+     * @param page The page the item is on.
+     * @param rank The rank of the item.
+     * @return True iff the icon is in the 2x2 upper left quadrant of the Folder.
+     */
+    public boolean isItemInPreview(int page, int rank) {
+        if (page > 0) {
+            // First page items are laid out such that the first 4 items are always in the upper
+            // left quadrant. For all other pages, we need to check the row and col.
+            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/FolderPreviewItemAnim.java b/src/com/android/launcher3/folder/FolderPreviewItemAnim.java
index 0da7c5c..be075bc 100644
--- a/src/com/android/launcher3/folder/FolderPreviewItemAnim.java
+++ b/src/com/android/launcher3/folder/FolderPreviewItemAnim.java
@@ -25,16 +25,16 @@
  * Animates a Folder preview item.
  */
 class FolderPreviewItemAnim {
+
+    private static PreviewItemDrawingParams sTmpParams = new PreviewItemDrawingParams(0, 0, 0, 0);
+
     private ValueAnimator mValueAnimator;
 
     float finalScale;
     float finalTransX;
     float finalTransY;
 
-    private PreviewItemDrawingParams mTmpParams = new PreviewItemDrawingParams(0, 0, 0, 0);
-
     /**
-     * @param folderIcon The FolderIcon this preview will be drawn in.
      * @param params layout params to animate
      * @param index0 original index of the item to be animated
      * @param items0 original number of items in the preview
@@ -43,20 +43,20 @@
      * @param duration duration in ms of the animation
      * @param onCompleteRunnable runnable to execute upon animation completion
      */
-    FolderPreviewItemAnim(final FolderIcon folderIcon, final PreviewItemDrawingParams params,
-            int index0, int items0, int index1, int items1, int duration,
-            final Runnable onCompleteRunnable) {
-        folderIcon.computePreviewItemDrawingParams(index1, items1, mTmpParams);
+    FolderPreviewItemAnim(final PreviewItemManager previewItemManager,
+            final PreviewItemDrawingParams params, int index0, int items0, int index1, int items1,
+            int duration, final Runnable onCompleteRunnable) {
+        previewItemManager.computePreviewItemDrawingParams(index1, items1, sTmpParams);
 
-        finalScale = mTmpParams.scale;
-        finalTransX = mTmpParams.transX;
-        finalTransY = mTmpParams.transY;
+        finalScale = sTmpParams.scale;
+        finalTransX = sTmpParams.transX;
+        finalTransY = sTmpParams.transY;
 
-        folderIcon.computePreviewItemDrawingParams(index0, items0, mTmpParams);
+        previewItemManager.computePreviewItemDrawingParams(index0, items0, sTmpParams);
 
-        final float scale0 = mTmpParams.scale;
-        final float transX0 = mTmpParams.transX;
-        final float transY0 = mTmpParams.transY;
+        final float scale0 = sTmpParams.scale;
+        final float transX0 = sTmpParams.transX;
+        final float transY0 = sTmpParams.transY;
 
         mValueAnimator = LauncherAnimUtils.ofFloat(0f, 1.0f);
         mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener(){
@@ -66,7 +66,7 @@
                 params.transX = transX0 + progress * (finalTransX - transX0);
                 params.transY = transY0 + progress * (finalTransY - transY0);
                 params.scale = scale0 + progress * (finalScale - scale0);
-                folderIcon.invalidate();
+                previewItemManager.onParamsChanged();
             }
         });
         mValueAnimator.addListener(new AnimatorListenerAdapter() {
diff --git a/src/com/android/launcher3/folder/PreviewItemManager.java b/src/com/android/launcher3/folder/PreviewItemManager.java
new file mode 100644
index 0000000..74c2102
--- /dev/null
+++ b/src/com/android/launcher3/folder/PreviewItemManager.java
@@ -0,0 +1,276 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.launcher3.folder;
+
+import android.animation.Animator;
+import android.animation.AnimatorListenerAdapter;
+import android.animation.ValueAnimator;
+import android.graphics.Canvas;
+import android.graphics.Rect;
+import android.graphics.drawable.Drawable;
+import android.support.annotation.NonNull;
+import android.view.View;
+import android.widget.TextView;
+
+import com.android.launcher3.BubbleTextView;
+import com.android.launcher3.Utilities;
+import com.android.launcher3.config.FeatureFlags;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static com.android.launcher3.folder.FolderIcon.DROP_IN_ANIMATION_DURATION;
+
+/**
+ * Manages the drawing and animations of {@link PreviewItemDrawingParams} for a {@link FolderIcon}.
+ */
+public class PreviewItemManager {
+
+    private FolderIcon mIcon;
+
+    // These variables are all associated with the drawing of the preview; they are stored
+    // as member variables for shared usage and to avoid computation on each frame
+    private float mIntrinsicIconSize = -1;
+    private int mTotalWidth = -1;
+    private int mPrevTopPadding = -1;
+    private Drawable mReferenceDrawable = null;
+
+    // These hold the first page preview items
+    private ArrayList<PreviewItemDrawingParams> mFirstPageParams = new ArrayList<>();
+    // These hold the current page preview items. It is empty if the current page is the first page.
+    private ArrayList<PreviewItemDrawingParams> mCurrentPageParams = new ArrayList<>();
+
+    private float mCurrentPageItemsTransX = 0;
+    private boolean mShouldSlideInFirstPage;
+
+    static final int INITIAL_ITEM_ANIMATION_DURATION = 350;
+    private static final int FINAL_ITEM_ANIMATION_DURATION = 200;
+
+    private static final int SLIDE_IN_FIRST_PAGE_ANIMATION_DURATION_DELAY = 200;
+    private static final int SLIDE_IN_FIRST_PAGE_ANIMATION_DURATION = 300;
+    private static final int ITEM_SLIDE_IN_OUT_DISTANCE_PX = 200;
+
+    public PreviewItemManager(FolderIcon icon) {
+        mIcon = icon;
+    }
+
+    /**
+     * @param reverse If true, animates the final item in the preview to be full size. If false,
+     *                animates the first item to its position in the preview.
+     */
+    public FolderPreviewItemAnim createFirstItemAnimation(final boolean reverse,
+            final Runnable onCompleteRunnable) {
+        return reverse
+                ? new FolderPreviewItemAnim(this, mFirstPageParams.get(0), 0, 2, -1, -1,
+                        FINAL_ITEM_ANIMATION_DURATION, onCompleteRunnable)
+                : new FolderPreviewItemAnim(this, mFirstPageParams.get(0), -1, -1, 0, 2,
+                        INITIAL_ITEM_ANIMATION_DURATION, onCompleteRunnable);
+    }
+
+    Drawable prepareCreateAnimation(final View destView) {
+        Drawable animateDrawable = ((TextView) destView).getCompoundDrawables()[1];
+        computePreviewDrawingParams(animateDrawable.getIntrinsicWidth(),
+                destView.getMeasuredWidth());
+        mReferenceDrawable = animateDrawable;
+        return animateDrawable;
+    }
+
+    private void computePreviewDrawingParams(Drawable d) {
+        computePreviewDrawingParams(d.getIntrinsicWidth(), mIcon.getMeasuredWidth());
+    }
+
+    private void computePreviewDrawingParams(int drawableSize, int totalSize) {
+        if (mIntrinsicIconSize != drawableSize || mTotalWidth != totalSize ||
+                mPrevTopPadding != mIcon.getPaddingTop()) {
+            mIntrinsicIconSize = drawableSize;
+            mTotalWidth = totalSize;
+            mPrevTopPadding = mIcon.getPaddingTop();
+
+            mIcon.mBackground.setup(mIcon.mLauncher, mIcon, mTotalWidth, mIcon.getPaddingTop());
+            mIcon.mPreviewLayoutRule.init(mIcon.mBackground.previewSize, mIntrinsicIconSize,
+                    Utilities.isRtl(mIcon.getResources()));
+
+            updateItemDrawingParams(false);
+        }
+    }
+
+    PreviewItemDrawingParams computePreviewItemDrawingParams(int index, int curNumItems,
+            PreviewItemDrawingParams params) {
+        // We use an index of -1 to represent an icon on the workspace for the destroy and
+        // create animations
+        if (index == -1) {
+            return getFinalIconParams(params);
+        }
+        return mIcon.mPreviewLayoutRule.computePreviewItemDrawingParams(index, curNumItems, params);
+    }
+
+    private PreviewItemDrawingParams getFinalIconParams(PreviewItemDrawingParams params) {
+        float iconSize = mIcon.mLauncher.getDeviceProfile().iconSizePx;
+
+        final float scale = iconSize / mReferenceDrawable.getIntrinsicWidth();
+        final float trans = (mIcon.mBackground.previewSize - iconSize) / 2;
+
+        params.update(trans, trans, scale);
+        return params;
+    }
+
+    public void drawParams(Canvas canvas, ArrayList<PreviewItemDrawingParams> params,
+            float transX) {
+        canvas.translate(transX, 0);
+        // The first item should be drawn last (ie. on top of later items)
+        for (int i = params.size() - 1; i >= 0; i--) {
+            PreviewItemDrawingParams p = params.get(i);
+            if (!p.hidden) {
+                drawPreviewItem(canvas, p);
+            }
+        }
+        canvas.translate(-transX, 0);
+    }
+
+    public void draw(Canvas canvas) {
+        computePreviewDrawingParams(mReferenceDrawable);
+
+        float firstPageItemsTransX = 0;
+        if (mShouldSlideInFirstPage) {
+            drawParams(canvas, mCurrentPageParams, mCurrentPageItemsTransX);
+
+            firstPageItemsTransX = -ITEM_SLIDE_IN_OUT_DISTANCE_PX + mCurrentPageItemsTransX;
+        }
+
+        drawParams(canvas, mFirstPageParams, firstPageItemsTransX);
+    }
+
+    public void onParamsChanged() {
+        mIcon.invalidate();
+    }
+
+    private void drawPreviewItem(Canvas canvas, PreviewItemDrawingParams params) {
+        canvas.save(Canvas.MATRIX_SAVE_FLAG);
+        canvas.translate(params.transX, params.transY);
+        canvas.scale(params.scale, params.scale);
+        Drawable d = params.drawable;
+
+        if (d != null) {
+            Rect bounds = d.getBounds();
+            canvas.save();
+            canvas.translate(-bounds.left, -bounds.top);
+            canvas.scale(mIntrinsicIconSize / bounds.width(), mIntrinsicIconSize / bounds.height());
+            d.draw(canvas);
+            canvas.restore();
+        }
+        canvas.restore();
+    }
+
+    public void hidePreviewItem(int index, boolean hidden) {
+        PreviewItemDrawingParams params = index < mFirstPageParams.size() ?
+                mFirstPageParams.get(index) : null;
+        if (params != null) {
+            params.hidden = hidden;
+        }
+    }
+
+    void buildParamsForPage(int page, ArrayList<PreviewItemDrawingParams> params, boolean animate) {
+        List<BubbleTextView> items = mIcon.getPreviewItemsOnPage(page);
+        int prevNumItems = params.size();
+
+        // We adjust the size of the list to match the number of items in the preview.
+        while (items.size() < params.size()) {
+            params.remove(params.size() - 1);
+        }
+        while (items.size() > params.size()) {
+            params.add(new PreviewItemDrawingParams(0, 0, 0, 0));
+        }
+
+        int numItemsInFirstPagePreview = page == 0 ? items.size() : FolderIcon.NUM_ITEMS_IN_PREVIEW;
+        for (int i = 0; i < params.size(); i++) {
+            PreviewItemDrawingParams p = params.get(i);
+            p.drawable = items.get(i).getCompoundDrawables()[1];
+
+            if (p.drawable != null && !mIcon.mFolder.isOpen()) {
+                // Set the callback to FolderIcon as it is responsible to drawing the icon. The
+                // callback will be released when the folder is opened.
+                p.drawable.setCallback(mIcon);
+            }
+
+            if (!animate || FeatureFlags.LAUNCHER3_LEGACY_FOLDER_ICON) {
+                computePreviewItemDrawingParams(i, numItemsInFirstPagePreview, p);
+                if (mReferenceDrawable == null) {
+                    mReferenceDrawable = p.drawable;
+                }
+            } else {
+                FolderPreviewItemAnim anim = new FolderPreviewItemAnim(this, p, i, prevNumItems, i,
+                        numItemsInFirstPagePreview, DROP_IN_ANIMATION_DURATION, null);
+
+                if (p.anim != null) {
+                    if (p.anim.hasEqualFinalState(anim)) {
+                        // do nothing, let the current animation finish
+                        continue;
+                    }
+                    p.anim.cancel();
+                }
+                p.anim = anim;
+                p.anim.start();
+            }
+        }
+    }
+
+    void onFolderClose(int currentPage) {
+        // If we are not closing on the first page, we animate the current page preview items
+        // out, and animate the first page preview items in.
+        mShouldSlideInFirstPage = currentPage != 0;
+        if (mShouldSlideInFirstPage) {
+            mCurrentPageItemsTransX = 0;
+            buildParamsForPage(currentPage, mCurrentPageParams, false);
+            onParamsChanged();
+
+            ValueAnimator slideAnimator = ValueAnimator.ofFloat(0, ITEM_SLIDE_IN_OUT_DISTANCE_PX);
+            slideAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
+                @Override
+                public void onAnimationUpdate(ValueAnimator valueAnimator) {
+                    mCurrentPageItemsTransX = (float) valueAnimator.getAnimatedValue();
+                    onParamsChanged();
+                }
+            });
+            slideAnimator.addListener(new AnimatorListenerAdapter() {
+                @Override
+                public void onAnimationEnd(Animator animation) {
+                    mCurrentPageParams.clear();
+                }
+            });
+            slideAnimator.setStartDelay(SLIDE_IN_FIRST_PAGE_ANIMATION_DURATION_DELAY);
+            slideAnimator.setDuration(SLIDE_IN_FIRST_PAGE_ANIMATION_DURATION);
+            slideAnimator.start();
+        }
+    }
+
+    void updateItemDrawingParams(boolean animate) {
+        buildParamsForPage(0, mFirstPageParams, animate);
+    }
+
+    boolean verifyDrawable(@NonNull Drawable who) {
+        for (int i = 0; i < mFirstPageParams.size(); i++) {
+            if (mFirstPageParams.get(i).drawable == who) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    float getIntrinsicIconSize() {
+        return mIntrinsicIconSize;
+    }
+}
diff --git a/src/com/android/launcher3/graphics/ShadowGenerator.java b/src/com/android/launcher3/graphics/ShadowGenerator.java
index fffea8e..3c71c3a 100644
--- a/src/com/android/launcher3/graphics/ShadowGenerator.java
+++ b/src/com/android/launcher3/graphics/ShadowGenerator.java
@@ -63,9 +63,15 @@
     }
 
     public synchronized Bitmap recreateIcon(Bitmap icon) {
+        return recreateIcon(icon, true);
+    }
+
+    public synchronized Bitmap recreateIcon(Bitmap icon, boolean resize) {
+        int width = resize ? mIconSize : icon.getWidth();
+        int height = resize ? mIconSize : icon.getHeight();
         int[] offset = new int[2];
         Bitmap shadow = icon.extractAlpha(mBlurPaint, offset);
-        Bitmap result = Bitmap.createBitmap(mIconSize, mIconSize, Config.ARGB_8888);
+        Bitmap result = Bitmap.createBitmap(width, height, Config.ARGB_8888);
         mCanvas.setBitmap(result);
 
         // Draw ambient shadow
diff --git a/src/com/android/launcher3/logging/UserEventDispatcher.java b/src/com/android/launcher3/logging/UserEventDispatcher.java
index edbb88c..e28a97a 100644
--- a/src/com/android/launcher3/logging/UserEventDispatcher.java
+++ b/src/com/android/launcher3/logging/UserEventDispatcher.java
@@ -20,6 +20,7 @@
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
+import android.content.SharedPreferences;
 import android.os.SystemClock;
 import android.support.annotation.Nullable;
 import android.util.Log;
@@ -40,6 +41,7 @@
 
 import java.util.List;
 import java.util.Locale;
+import java.util.UUID;
 
 import static com.android.launcher3.logging.LoggerUtils.newCommandAction;
 import static com.android.launcher3.logging.LoggerUtils.newContainerTarget;
@@ -62,13 +64,21 @@
     private static final String TAG = "UserEvent";
     private static final boolean IS_VERBOSE =
             FeatureFlags.IS_DOGFOOD_BUILD && Utilities.isPropertyEnabled(LogConfig.USEREVENT);
+    private static final String UUID_STORAGE = "uuid";
 
     public static UserEventDispatcher newInstance(Context context, boolean isInLandscapeMode,
             boolean isInMultiWindowMode) {
+        SharedPreferences sharedPrefs = Utilities.getDevicePrefs(context);
+        String uuidStr = sharedPrefs.getString(UUID_STORAGE, null);
+        if (uuidStr == null) {
+            uuidStr = UUID.randomUUID().toString();
+            sharedPrefs.edit().putString(UUID_STORAGE, uuidStr).apply();
+        }
         UserEventDispatcher ued = Utilities.getOverrideObject(UserEventDispatcher.class,
                 context.getApplicationContext(), R.string.user_event_dispatcher_class);
         ued.mIsInLandscapeMode = isInLandscapeMode;
         ued.mIsInMultiWindowMode = isInMultiWindowMode;
+        ued.mUuidStr = uuidStr;
         return ued;
     }
 
@@ -116,6 +126,7 @@
     private long mActionDurationMillis;
     private boolean mIsInMultiWindowMode;
     private boolean mIsInLandscapeMode;
+    private String mUuidStr;
 
     // Used for filling in predictedRank on {@link Target}s.
     private List<ComponentKey> mPredictedApps;
@@ -137,8 +148,8 @@
             ItemInfo itemInfo = (ItemInfo) v.getTag();
             event.srcTarget[idx].intentHash = intentHashCode;
             if (cn != null) {
-                event.srcTarget[idx].packageNameHash = cn.getPackageName().hashCode();
-                event.srcTarget[idx].componentHash = cn.hashCode();
+                event.srcTarget[idx].packageNameHash = (mUuidStr + cn.getPackageName()).hashCode();
+                event.srcTarget[idx].componentHash = (mUuidStr + cn.flattenToString()).hashCode();
                 if (mPredictedApps != null) {
                     event.srcTarget[idx].predictedRank = mPredictedApps.indexOf(
                             new ComponentKey(cn, itemInfo.user));
diff --git a/src/com/android/launcher3/notification/NotificationFooterLayout.java b/src/com/android/launcher3/notification/NotificationFooterLayout.java
index b83c9b9..2455eab 100644
--- a/src/com/android/launcher3/notification/NotificationFooterLayout.java
+++ b/src/com/android/launcher3/notification/NotificationFooterLayout.java
@@ -206,7 +206,10 @@
                     @Override
                     public void onAnimationEnd(Animator animation) {
                         ((ViewGroup) getParent()).findViewById(R.id.divider).setVisibility(GONE);
-                        ((ViewGroup) getParent()).removeView(NotificationFooterLayout.this);
+                        // Keep view around because gutter is aligned to it, but remove height to
+                        // both hide the view and keep calculations correct for last dismissal.
+                        getLayoutParams().height = 0;
+                        requestLayout();
                     }
                 });
                 collapseFooter.start();
diff --git a/src/com/android/launcher3/notification/NotificationItemView.java b/src/com/android/launcher3/notification/NotificationItemView.java
index 0cd5a4c..11f6aa0 100644
--- a/src/com/android/launcher3/notification/NotificationItemView.java
+++ b/src/com/android/launcher3/notification/NotificationItemView.java
@@ -17,6 +17,8 @@
 package com.android.launcher3.notification;
 
 import android.animation.Animator;
+import android.animation.AnimatorSet;
+import android.animation.ObjectAnimator;
 import android.app.Notification;
 import android.content.Context;
 import android.graphics.Rect;
@@ -28,7 +30,9 @@
 import android.widget.TextView;
 
 import com.android.launcher3.ItemInfo;
+import com.android.launcher3.LauncherAnimUtils;
 import com.android.launcher3.R;
+import com.android.launcher3.anim.PropertyResetListener;
 import com.android.launcher3.anim.RoundedRectRevealOutlineProvider;
 import com.android.launcher3.graphics.IconPalette;
 import com.android.launcher3.logging.UserEventDispatcher.LogContainerProvider;
@@ -89,6 +93,8 @@
     }
 
     public Animator animateHeightRemoval(int heightToRemove, boolean shouldRemoveFromTop) {
+        AnimatorSet anim = LauncherAnimUtils.createAnimatorSet();
+
         Rect startRect = new Rect(mPillRect);
         Rect endRect = new Rect(mPillRect);
         if (shouldRemoveFromTop) {
@@ -96,8 +102,18 @@
         } else {
             endRect.bottom -= heightToRemove;
         }
-        return new RoundedRectRevealOutlineProvider(getBackgroundRadius(), getBackgroundRadius(),
-                startRect, endRect, mRoundedCorners).createRevealAnimator(this, false);
+        anim.play(new RoundedRectRevealOutlineProvider(getBackgroundRadius(), getBackgroundRadius(),
+                startRect, endRect, mRoundedCorners).createRevealAnimator(this, false));
+
+        View bottomGutter = findViewById(R.id.gutter_bottom);
+        if (bottomGutter != null && bottomGutter.getVisibility() == VISIBLE) {
+            Animator translateGutter = ObjectAnimator.ofFloat(bottomGutter, TRANSLATION_Y,
+                    -heightToRemove);
+            translateGutter.addListener(new PropertyResetListener<>(TRANSLATION_Y, 0f));
+            anim.play(translateGutter);
+        }
+
+        return anim;
     }
 
     public void updateHeader(int notificationCount, @Nullable IconPalette palette) {
diff --git a/src/com/android/launcher3/views/ButtonPreference.java b/src/com/android/launcher3/views/ButtonPreference.java
new file mode 100644
index 0000000..4697e25
--- /dev/null
+++ b/src/com/android/launcher3/views/ButtonPreference.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.launcher3.views;
+
+import android.content.Context;
+import android.preference.Preference;
+import android.util.AttributeSet;
+import android.view.View;
+import android.view.ViewGroup;
+
+/**
+ * Extension of {@link Preference} which makes the widget layout clickable.
+ *
+ * @see #setWidgetLayoutResource(int)
+ */
+public class ButtonPreference extends Preference {
+
+    private View.OnClickListener mClickListener;
+
+    public ButtonPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
+        super(context, attrs, defStyleAttr, defStyleRes);
+    }
+
+    public ButtonPreference(Context context, AttributeSet attrs, int defStyleAttr) {
+        super(context, attrs, defStyleAttr);
+    }
+
+    public ButtonPreference(Context context, AttributeSet attrs) {
+        super(context, attrs);
+    }
+
+    public ButtonPreference(Context context) {
+        super(context);
+    }
+
+    public void setButtonOnClickListener(View.OnClickListener clickListener) {
+        if (mClickListener != clickListener) {
+            mClickListener = clickListener;
+            notifyChanged();
+        }
+    }
+
+    @Override
+    protected void onBindView(View view) {
+        super.onBindView(view);
+
+        ViewGroup widgetFrame = view.findViewById(android.R.id.widget_frame);
+        if (widgetFrame != null) {
+            View button = widgetFrame.getChildAt(0);
+            if (button != null) {
+                button.setOnClickListener(mClickListener);
+            }
+            widgetFrame.setVisibility(
+                    (mClickListener == null || button == null) ? View.GONE : View.VISIBLE);
+        }
+    }
+}
diff --git a/src/com/android/launcher3/views/DoubleShadowBubbleTextView.java b/src/com/android/launcher3/views/DoubleShadowBubbleTextView.java
index c0b5fe1..c8203f7 100644
--- a/src/com/android/launcher3/views/DoubleShadowBubbleTextView.java
+++ b/src/com/android/launcher3/views/DoubleShadowBubbleTextView.java
@@ -23,6 +23,7 @@
 import android.graphics.Region;
 import android.support.v4.graphics.ColorUtils;
 import android.util.AttributeSet;
+import android.widget.TextView;
 
 import com.android.launcher3.BubbleTextView;
 import com.android.launcher3.R;
@@ -50,13 +51,12 @@
 
     @Override
     public void onDraw(Canvas canvas) {
-        // If text is transparent, don't draw any shadow
-        int alpha = Color.alpha(getCurrentTextColor());
-        if (alpha == 0) {
-            getPaint().clearShadowLayer();
+        // If text is transparent or shadow alpha is 0, don't draw any shadow
+        if (mShadowInfo.skipDoubleShadow(this)) {
             super.onDraw(canvas);
             return;
         }
+        int alpha = Color.alpha(getCurrentTextColor());
 
         // We enhance the shadow by drawing the shadow twice
         getPaint().setShadowLayer(mShadowInfo.ambientShadowBlur, 0, 0,
@@ -97,5 +97,25 @@
             keyShadowColor = a.getColor(R.styleable.ShadowInfo_keyShadowColor, 0);
             a.recycle();
         }
+
+        public boolean skipDoubleShadow(TextView textView) {
+            int textAlpha = Color.alpha(textView.getCurrentTextColor());
+            int keyShadowAlpha = Color.alpha(keyShadowColor);
+            int ambientShadowAlpha = Color.alpha(ambientShadowColor);
+            if (textAlpha == 0 || (keyShadowAlpha == 0 && ambientShadowAlpha == 0)) {
+                textView.getPaint().clearShadowLayer();
+                return true;
+            } else if (ambientShadowAlpha > 0) {
+                textView.getPaint().setShadowLayer(ambientShadowBlur, 0, 0,
+                        ColorUtils.setAlphaComponent(ambientShadowColor, textAlpha));
+                return true;
+            } else if (keyShadowAlpha > 0) {
+                textView.getPaint().setShadowLayer(keyShadowBlur, 0.0f, keyShadowOffset,
+                        ColorUtils.setAlphaComponent(keyShadowColor, textAlpha));
+                return true;
+            } else {
+                return false;
+            }
+        }
     }
 }