Merge "Enable to recreate icon with shadow without resizing it." 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/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 5065a09..063a9a2 100644
--- a/src/com/android/launcher3/Workspace.java
+++ b/src/com/android/launcher3/Workspace.java
@@ -3979,8 +3979,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 {
@@ -3993,10 +3994,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 afbf9f2..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) {
@@ -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 7fdacc0..ae6a0e8 100644
--- a/src/com/android/launcher3/folder/FolderIcon.java
+++ b/src/com/android/launcher3/folder/FolderIcon.java
@@ -471,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) {
@@ -639,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/PreviewItemManager.java b/src/com/android/launcher3/folder/PreviewItemManager.java
index 2524a6d..74c2102 100644
--- a/src/com/android/launcher3/folder/PreviewItemManager.java
+++ b/src/com/android/launcher3/folder/PreviewItemManager.java
@@ -16,6 +16,9 @@
 
 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;
@@ -48,10 +51,19 @@
 
     // 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;
     }
@@ -116,15 +128,30 @@
         return params;
     }
 
-    public void draw(Canvas canvas) {
-        computePreviewDrawingParams(mReferenceDrawable);
+    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 = mFirstPageParams.size() - 1; i >= 0; i--) {
-            PreviewItemDrawingParams p = mFirstPageParams.get(i);
+        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() {
@@ -156,21 +183,21 @@
         }
     }
 
-    void updateItemDrawingParams(boolean animate) {
-        List<BubbleTextView> items = mIcon.getItemsToDisplay();
-        int numItemsInPreview = items.size();
-        int prevNumItems = mFirstPageParams.size();
+    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 (numItemsInPreview < mFirstPageParams.size()) {
-            mFirstPageParams.remove(mFirstPageParams.size() - 1);
+        // 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 (numItemsInPreview > mFirstPageParams.size()) {
-            mFirstPageParams.add(new PreviewItemDrawingParams(0, 0, 0, 0));
+        while (items.size() > params.size()) {
+            params.add(new PreviewItemDrawingParams(0, 0, 0, 0));
         }
 
-        for (int i = 0; i < mFirstPageParams.size(); i++) {
-            PreviewItemDrawingParams p = mFirstPageParams.get(i);
+        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()) {
@@ -180,13 +207,13 @@
             }
 
             if (!animate || FeatureFlags.LAUNCHER3_LEGACY_FOLDER_ICON) {
-                computePreviewItemDrawingParams(i, numItemsInPreview, p);
+                computePreviewItemDrawingParams(i, numItemsInFirstPagePreview, p);
                 if (mReferenceDrawable == null) {
                     mReferenceDrawable = p.drawable;
                 }
             } else {
                 FolderPreviewItemAnim anim = new FolderPreviewItemAnim(this, p, i, prevNumItems, i,
-                        numItemsInPreview, DROP_IN_ANIMATION_DURATION, null);
+                        numItemsInFirstPagePreview, DROP_IN_ANIMATION_DURATION, null);
 
                 if (p.anim != null) {
                     if (p.anim.hasEqualFinalState(anim)) {
@@ -201,6 +228,39 @@
         }
     }
 
+    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) {
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);
+        }
+    }
+}