Merge "Updating widget tray theme" into ub-launcher3-master
diff --git a/protos/launcher_log.proto b/protos/launcher_log.proto
index 33041db..c42b142 100644
--- a/protos/launcher_log.proto
+++ b/protos/launcher_log.proto
@@ -64,6 +64,7 @@
   DEEPSHORTCUT = 5;
   SEARCHBOX = 6;
   EDITTEXT = 7;
+  NOTIFICATION = 8;
 }
 
 // Used to define what type of container a Target would represent.
diff --git a/res/values/dimens.xml b/res/values/dimens.xml
index 2cf17ea..f00a00d 100644
--- a/res/values/dimens.xml
+++ b/res/values/dimens.xml
@@ -172,6 +172,8 @@
 <!-- Icon badges (with notification counts) -->
     <dimen name="badge_size">24dp</dimen>
     <dimen name="badge_text_size">12dp</dimen>
+    <dimen name="badge_small_padding">1dp</dimen>
+    <dimen name="badge_large_padding">3dp</dimen>
     <dimen name="notification_icon_size">28dp</dimen>
     <dimen name="notification_footer_icon_size">24dp</dimen>
     <!-- (icon_size - secondary_icon_size) / 2 -->
diff --git a/src/com/android/launcher3/AbstractFloatingView.java b/src/com/android/launcher3/AbstractFloatingView.java
index c834c6b..52a83dc 100644
--- a/src/com/android/launcher3/AbstractFloatingView.java
+++ b/src/com/android/launcher3/AbstractFloatingView.java
@@ -121,4 +121,6 @@
     public static AbstractFloatingView getTopOpenView(Launcher launcher) {
         return getOpenView(launcher, TYPE_FOLDER | TYPE_POPUP_CONTAINER_WITH_ARROW);
     }
+
+    public abstract int getLogContainerType();
 }
diff --git a/src/com/android/launcher3/BubbleTextView.java b/src/com/android/launcher3/BubbleTextView.java
index 8043eac..bbf2cb8 100644
--- a/src/com/android/launcher3/BubbleTextView.java
+++ b/src/com/android/launcher3/BubbleTextView.java
@@ -167,7 +167,7 @@
             applyPromiseState(promiseStateChanged);
         }
 
-        applyBadgeState(info);
+        applyBadgeState(info, false /* animate */);
     }
 
     public void applyFromApplicationInfo(AppInfo info) {
@@ -179,7 +179,7 @@
         // Verify high res immediately
         verifyHighRes();
 
-        applyBadgeState(info);
+        applyBadgeState(info, false /* animate */);
     }
 
     public void applyFromPackageItemInfo(PackageItemInfo info) {
@@ -501,11 +501,11 @@
         }
     }
 
-    public void applyBadgeState(ItemInfo itemInfo) {
+    public void applyBadgeState(ItemInfo itemInfo, boolean animate) {
         if (mIcon instanceof FastBitmapDrawable) {
             BadgeInfo badgeInfo = mLauncher.getPopupDataProvider().getBadgeInfoForItem(itemInfo);
             BadgeRenderer badgeRenderer = mLauncher.getDeviceProfile().mBadgeRenderer;
-            ((FastBitmapDrawable) mIcon).applyIconBadge(badgeInfo, badgeRenderer);
+            ((FastBitmapDrawable) mIcon).applyIconBadge(badgeInfo, badgeRenderer, animate);
         }
     }
 
diff --git a/src/com/android/launcher3/DeviceProfile.java b/src/com/android/launcher3/DeviceProfile.java
index 34ce923..c9e3d4f 100644
--- a/src/com/android/launcher3/DeviceProfile.java
+++ b/src/com/android/launcher3/DeviceProfile.java
@@ -196,9 +196,7 @@
         hotseatBarBottomPaddingPx = 0;
         hotseatLandGutterPx = res.getDimensionPixelSize(R.dimen.dynamic_grid_hotseat_gutter_width);
 
-        int badgeSize = res.getDimensionPixelSize(R.dimen.badge_size);
-        int badgeTextSize = res.getDimensionPixelSize(R.dimen.badge_text_size);
-        mBadgeRenderer = new BadgeRenderer(badgeSize, badgeTextSize);
+        mBadgeRenderer = new BadgeRenderer(context);
 
         // Determine sizes.
         widthPx = width;
diff --git a/src/com/android/launcher3/FastBitmapDrawable.java b/src/com/android/launcher3/FastBitmapDrawable.java
index 95d2daf..1f74c88 100644
--- a/src/com/android/launcher3/FastBitmapDrawable.java
+++ b/src/com/android/launcher3/FastBitmapDrawable.java
@@ -30,7 +30,7 @@
 import android.graphics.PorterDuff;
 import android.graphics.PorterDuffColorFilter;
 import android.graphics.drawable.Drawable;
-import android.util.Log;
+import android.util.Property;
 import android.util.SparseArray;
 import android.view.animation.DecelerateInterpolator;
 
@@ -107,6 +107,21 @@
     private BadgeInfo mBadgeInfo;
     private BadgeRenderer mBadgeRenderer;
     private IconPalette mIconPalette;
+    private float mBadgeScale;
+
+    private static final Property<FastBitmapDrawable, Float> BADGE_SCALE_PROPERTY
+            = new Property<FastBitmapDrawable, Float>(Float.TYPE, "badgeScale") {
+        @Override
+        public Float get(FastBitmapDrawable fastBitmapDrawable) {
+            return fastBitmapDrawable.mBadgeScale;
+        }
+
+        @Override
+        public void set(FastBitmapDrawable fastBitmapDrawable, Float value) {
+            fastBitmapDrawable.mBadgeScale = value;
+            fastBitmapDrawable.invalidateSelf();
+        }
+    };
 
     // The saturation and brightness are values that are mapped to REDUCED_FILTER_VALUE_SPACE and
     // as a result, can be used to compose the key for the cached ColorMatrixColorFilters
@@ -123,14 +138,22 @@
         setFilterBitmap(true);
     }
 
-    public void applyIconBadge(BadgeInfo badgeInfo, BadgeRenderer badgeRenderer) {
+    public void applyIconBadge(final BadgeInfo badgeInfo, BadgeRenderer badgeRenderer,
+            boolean animate) {
         boolean wasBadged = mBadgeInfo != null;
         boolean isBadged = badgeInfo != null;
+        float newBadgeScale = isBadged ? 1f : 0;
         mBadgeInfo = badgeInfo;
         mBadgeRenderer = badgeRenderer;
         if (wasBadged || isBadged) {
             mIconPalette = getIconPalette();
-            invalidateSelf();
+            // Animate when a badge is first added or when it is removed.
+            if (animate && (wasBadged ^ isBadged) && isVisible()) {
+                ObjectAnimator.ofFloat(this, BADGE_SCALE_PROPERTY, newBadgeScale).start();
+            } else {
+                mBadgeScale = newBadgeScale;
+                invalidateSelf();
+            }
         }
     }
 
@@ -154,7 +177,7 @@
 
     protected void drawBadgeIfNecessary(Canvas canvas) {
         if (hasBadge()) {
-            mBadgeRenderer.draw(canvas, mIconPalette, mBadgeInfo, getBounds());
+            mBadgeRenderer.draw(canvas, mIconPalette, mBadgeInfo, getBounds(), mBadgeScale);
         }
     }
 
@@ -167,7 +190,7 @@
     }
 
     private boolean hasBadge() {
-        return mBadgeInfo != null && mBadgeInfo.getNotificationCount() != 0;
+        return (mBadgeInfo != null && mBadgeInfo.getNotificationCount() > 0) || mBadgeScale > 0;
     }
 
     @Override
diff --git a/src/com/android/launcher3/Launcher.java b/src/com/android/launcher3/Launcher.java
index d963f43..826f686 100644
--- a/src/com/android/launcher3/Launcher.java
+++ b/src/com/android/launcher3/Launcher.java
@@ -111,6 +111,7 @@
 import com.android.launcher3.popup.PopupContainerWithArrow;
 import com.android.launcher3.shortcuts.DeepShortcutManager;
 import com.android.launcher3.shortcuts.ShortcutKey;
+import com.android.launcher3.userevent.nano.LauncherLogProto;
 import com.android.launcher3.userevent.nano.LauncherLogProto.Action;
 import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
 import com.android.launcher3.userevent.nano.LauncherLogProto.ControlType;
@@ -2272,7 +2273,11 @@
 
         if (v instanceof CellLayout) {
             if (mWorkspace.isInOverviewMode()) {
-                mWorkspace.snapToPageFromOverView(mWorkspace.indexOfChild(v));
+                int page = mWorkspace.indexOfChild(v);
+                getUserEventDispatcher().logActionOnContainer(LauncherLogProto.Action.Type.TOUCH,
+                        LauncherLogProto.Action.Direction.NONE,
+                        LauncherLogProto.ContainerType.OVERVIEW, page);
+                mWorkspace.snapToPageFromOverView(page);
                 showWorkspace(true);
             }
             return;
diff --git a/src/com/android/launcher3/Workspace.java b/src/com/android/launcher3/Workspace.java
index c80d4a8..3aa8825 100644
--- a/src/com/android/launcher3/Workspace.java
+++ b/src/com/android/launcher3/Workspace.java
@@ -61,6 +61,7 @@
 import com.android.launcher3.accessibility.OverviewScreenAccessibilityDelegate;
 import com.android.launcher3.accessibility.WorkspaceAccessibilityHelper;
 import com.android.launcher3.anim.AnimationLayerSet;
+import com.android.launcher3.badge.FolderBadgeInfo;
 import com.android.launcher3.compat.AppWidgetManagerCompat;
 import com.android.launcher3.config.FeatureFlags;
 import com.android.launcher3.config.ProviderConfig;
@@ -3985,19 +3986,39 @@
 
     public void updateIconBadges(final Set<PackageUserKey> updatedBadges) {
         final PackageUserKey packageUserKey = new PackageUserKey(null, null);
+        final HashSet<Long> folderIds = new HashSet<>();
         mapOverItems(MAP_RECURSE, new ItemOperator() {
             @Override
             public boolean evaluate(ItemInfo info, View v) {
                 if (info instanceof ShortcutInfo && v instanceof BubbleTextView
                         && packageUserKey.updateFromItemInfo(info)) {
                     if (updatedBadges.contains(packageUserKey)) {
-                        ((BubbleTextView) v).applyBadgeState(info);
+                        ((BubbleTextView) v).applyBadgeState(info, true /* animate */);
+                        folderIds.add(info.container);
                     }
                 }
                 // process all the shortcuts
                 return false;
             }
         });
+
+        // Update folder icons
+        mapOverItems(MAP_NO_RECURSE, new ItemOperator() {
+            @Override
+            public boolean evaluate(ItemInfo info, View v) {
+                if (info instanceof FolderInfo && folderIds.contains(info.id)
+                        && v instanceof FolderIcon) {
+                    FolderBadgeInfo folderBadgeInfo = new FolderBadgeInfo();
+                    for (ShortcutInfo si : ((FolderInfo) info).contents) {
+                        folderBadgeInfo.addBadgeInfo(mLauncher.getPopupDataProvider()
+                                .getBadgeInfoForItem(si));
+                    }
+                    ((FolderIcon) v).setBadgeInfo(folderBadgeInfo);
+                }
+                // process all the shortcuts
+                return false;
+            }
+        });
     }
 
     public void removeAbandonedPromise(String packageName, UserHandle user) {
diff --git a/src/com/android/launcher3/badge/BadgeInfo.java b/src/com/android/launcher3/badge/BadgeInfo.java
index 77355c7..532396c 100644
--- a/src/com/android/launcher3/badge/BadgeInfo.java
+++ b/src/com/android/launcher3/badge/BadgeInfo.java
@@ -16,6 +16,14 @@
 
 package com.android.launcher3.badge;
 
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.graphics.BitmapShader;
+import android.graphics.Canvas;
+import android.graphics.Shader;
+import android.graphics.drawable.Drawable;
+import android.support.annotation.Nullable;
+
 import com.android.launcher3.notification.NotificationInfo;
 import com.android.launcher3.util.PackageUserKey;
 
@@ -29,12 +37,22 @@
 
     /** Used to link this BadgeInfo to icons on the workspace and all apps */
     private PackageUserKey mPackageUserKey;
+
     /**
      * The keys of the notifications that this badge represents. These keys can later be
      * used to retrieve {@link NotificationInfo}'s.
      */
     private List<String> mNotificationKeys;
 
+    /** This will only be initialized if the badge should display the notification icon. */
+    private NotificationInfo mNotificationInfo;
+
+    /**
+     * When retrieving the notification icon, we draw it into this shader, which can be clipped
+     * as necessary when drawn in a badge.
+     */
+    private Shader mNotificationIcon;
+
     public BadgeInfo(PackageUserKey packageUserKey) {
         mPackageUserKey = packageUserKey;
         mNotificationKeys = new ArrayList<>();
@@ -65,15 +83,55 @@
         return mNotificationKeys.size();
     }
 
+    public void setNotificationToShow(@Nullable NotificationInfo notificationInfo) {
+        mNotificationInfo = notificationInfo;
+        mNotificationIcon = null;
+    }
+
+    public boolean hasNotificationToShow() {
+        return mNotificationInfo != null;
+    }
+
+    /**
+     * Returns a shader to set on a Paint that will draw the notification icon in a badge.
+     *
+     * The shader is cached until {@link #setNotificationToShow(NotificationInfo)} is called.
+     */
+    public @Nullable Shader getNotificationIconForBadge(Context context, int badgeColor,
+            int badgeSize, int badgePadding) {
+        if (mNotificationInfo == null) {
+            return null;
+        }
+        if (mNotificationIcon == null) {
+            Drawable icon = mNotificationInfo.getIconForBackground(context, badgeColor)
+                    .getConstantState().newDrawable();
+            int iconSize = badgeSize - badgePadding * 2;
+            icon.setBounds(0, 0, iconSize, iconSize);
+            Bitmap iconBitmap = Bitmap.createBitmap(badgeSize, badgeSize, Bitmap.Config.ARGB_8888);
+            Canvas canvas = new Canvas(iconBitmap);
+            canvas.translate(badgePadding, badgePadding);
+            icon.draw(canvas);
+            mNotificationIcon = new BitmapShader(iconBitmap, Shader.TileMode.CLAMP,
+                    Shader.TileMode.CLAMP);
+        }
+        return mNotificationIcon;
+    }
+
+    public boolean isIconLarge() {
+        return mNotificationInfo != null && mNotificationInfo.isIconLarge();
+    }
+
     /**
      * Whether newBadge represents the same PackageUserKey as this badge, and icons with
      * this badge should be invalidated. So, for instance, if a badge has 3 notifications
      * and one of those notifications is updated, this method should return false because
      * the badge still says "3" and the contents of those notifications are only retrieved
-     * upon long-click. This method always returns true when adding or removing notifications.
+     * upon long-click. This method always returns true when adding or removing notifications,
+     * or if the badge has a notification icon to show.
      */
     public boolean shouldBeInvalidated(BadgeInfo newBadge) {
         return mPackageUserKey.equals(newBadge.mPackageUserKey)
-                && getNotificationCount() != newBadge.getNotificationCount();
+                && (getNotificationCount() != newBadge.getNotificationCount()
+                    || hasNotificationToShow());
     }
 }
diff --git a/src/com/android/launcher3/badge/BadgeRenderer.java b/src/com/android/launcher3/badge/BadgeRenderer.java
index 787ee72..8bbc2af 100644
--- a/src/com/android/launcher3/badge/BadgeRenderer.java
+++ b/src/com/android/launcher3/badge/BadgeRenderer.java
@@ -16,11 +16,17 @@
 
 package com.android.launcher3.badge;
 
+import android.content.Context;
+import android.content.res.Resources;
+import android.graphics.Bitmap;
 import android.graphics.Canvas;
 import android.graphics.Paint;
 import android.graphics.Rect;
 import android.graphics.RectF;
+import android.graphics.Shader;
+import android.support.annotation.Nullable;
 
+import com.android.launcher3.R;
 import com.android.launcher3.graphics.IconPalette;
 
 /**
@@ -29,42 +35,81 @@
  */
 public class BadgeRenderer {
 
-    public int size;
-    public int textSize;
-
-    private final RectF mBackgroundRect = new RectF();
+    private final Context mContext;
+    private final int mSize;
+    private final int mTextHeight;
+    private final IconDrawer mLargeIconDrawer;
+    private final IconDrawer mSmallIconDrawer;
     private final Paint mBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
     private final Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
-    private final int mTextHeight;
 
-    public BadgeRenderer(int size, int textSize) {
-        this.size = size;
-        this.textSize = textSize;
+    public BadgeRenderer(Context context) {
+        mContext = context;
+        Resources res = context.getResources();
+        mSize = res.getDimensionPixelSize(R.dimen.badge_size);
+        mLargeIconDrawer = new IconDrawer(res.getDimensionPixelSize(R.dimen.badge_small_padding));
+        mSmallIconDrawer = new IconDrawer(res.getDimensionPixelSize(R.dimen.badge_large_padding));
         mTextPaint.setTextAlign(Paint.Align.CENTER);
-        mTextPaint.setTextSize(textSize);
+        mTextPaint.setTextSize(res.getDimensionPixelSize(R.dimen.badge_text_size));
         // Measure the text height.
-        Rect temp = new Rect();
-        mTextPaint.getTextBounds("0", 0, 1, temp);
-        mTextHeight = temp.height();
+        Rect tempTextHeight = new Rect();
+        mTextPaint.getTextBounds("0", 0, 1, tempTextHeight);
+        mTextHeight = tempTextHeight.height();
     }
 
     /**
      * Draw a circle in the top right corner of the given bounds, and draw
      * {@link BadgeInfo#getNotificationCount()} on top of the circle.
      * @param palette The colors (based on the icon) to use for the badge.
-     * @param badgeInfo Contains data to draw on the badge.
+     * @param badgeInfo Contains data to draw on the badge. Could be null if we are animating out.
      * @param iconBounds The bounds of the icon being badged.
+     * @param badgeScale The progress of the animation, from 0 to 1.
      */
-    public void draw(Canvas canvas, IconPalette palette, BadgeInfo badgeInfo, Rect iconBounds) {
+    public void draw(Canvas canvas, IconPalette palette, @Nullable BadgeInfo badgeInfo,
+            Rect iconBounds, float badgeScale) {
         mBackgroundPaint.setColor(palette.backgroundColor);
         mTextPaint.setColor(palette.textColor);
-        mBackgroundRect.set(iconBounds.right - size, iconBounds.top, iconBounds.right,
-                iconBounds.top + size);
-        canvas.drawOval(mBackgroundRect, mBackgroundPaint);
-        String notificationCount = String.valueOf(badgeInfo.getNotificationCount());
-        canvas.drawText(notificationCount,
-                mBackgroundRect.centerX(),
-                mBackgroundRect.centerY() + mTextHeight / 2,
-                mTextPaint);
+        canvas.save(Canvas.MATRIX_SAVE_FLAG);
+        // We draw the badge relative to its center.
+        canvas.translate(iconBounds.right - mSize / 2, iconBounds.top + mSize / 2);
+        canvas.scale(badgeScale, badgeScale);
+        canvas.drawCircle(0, 0, mSize / 2, mBackgroundPaint);
+        IconDrawer iconDrawer = badgeInfo != null && badgeInfo.isIconLarge()
+                ? mLargeIconDrawer : mSmallIconDrawer;
+        Shader icon = badgeInfo == null ? null : badgeInfo.getNotificationIconForBadge(
+                mContext, palette.backgroundColor, mSize, iconDrawer.mPadding);
+        if (icon != null) {
+            // Draw the notification icon with padding.
+            iconDrawer.drawIcon(icon, canvas);
+        } else {
+            // Draw the notification count.
+            String notificationCount = badgeInfo == null ? "0"
+                    : String.valueOf(badgeInfo.getNotificationCount());
+            canvas.drawText(notificationCount, 0, mTextHeight / 2, mTextPaint);
+        }
+        canvas.restore();
+    }
+
+    /** Draws the notification icon with padding of a given size. */
+    private class IconDrawer {
+
+        private final int mPadding;
+        private final Bitmap mCircleClipBitmap;
+        private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG |
+                Paint.FILTER_BITMAP_FLAG);
+
+        public IconDrawer(int padding) {
+            mPadding = padding;
+            mCircleClipBitmap = Bitmap.createBitmap(mSize, mSize, Bitmap.Config.ALPHA_8);
+            Canvas canvas = new Canvas();
+            canvas.setBitmap(mCircleClipBitmap);
+            canvas.drawCircle(mSize / 2, mSize / 2, mSize / 2 - padding, mPaint);
+        }
+
+        public void drawIcon(Shader icon, Canvas canvas) {
+            mPaint.setShader(icon);
+            canvas.drawBitmap(mCircleClipBitmap, -mSize / 2, -mSize / 2, mPaint);
+            mPaint.setShader(null);
+        }
     }
 }
diff --git a/src/com/android/launcher3/badge/FolderBadgeInfo.java b/src/com/android/launcher3/badge/FolderBadgeInfo.java
new file mode 100644
index 0000000..4d1e5c2
--- /dev/null
+++ b/src/com/android/launcher3/badge/FolderBadgeInfo.java
@@ -0,0 +1,60 @@
+/*
+ * 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.badge;
+
+import com.android.launcher3.Utilities;
+
+import static com.android.launcher3.Utilities.boundToRange;
+
+/**
+ * Subclass of BadgeInfo that only contains the badge count,
+ * which is the sum of all the Folder's items' counts.
+ */
+public class FolderBadgeInfo extends BadgeInfo {
+
+    private static final int MIN_COUNT = 0;
+    private static final int MAX_COUNT = 999;
+
+    private int mTotalNotificationCount;
+
+    public FolderBadgeInfo() {
+        super(null);
+    }
+
+    public void addBadgeInfo(BadgeInfo badgeToAdd) {
+        if (badgeToAdd == null) {
+            return;
+        }
+        mTotalNotificationCount += badgeToAdd.getNotificationCount();
+        mTotalNotificationCount = Utilities.boundToRange(
+                mTotalNotificationCount, MIN_COUNT, MAX_COUNT);
+    }
+
+    public void subtractBadgeInfo(BadgeInfo badgeToSubtract) {
+        if (badgeToSubtract == null) {
+            return;
+        }
+        mTotalNotificationCount -= badgeToSubtract.getNotificationCount();
+        mTotalNotificationCount = Utilities.boundToRange(
+                mTotalNotificationCount, MIN_COUNT, MAX_COUNT);
+    }
+
+    @Override
+    public int getNotificationCount() {
+        return mTotalNotificationCount;
+    }
+}
diff --git a/src/com/android/launcher3/dragndrop/DragController.java b/src/com/android/launcher3/dragndrop/DragController.java
index e31c8ff..7410ae6 100644
--- a/src/com/android/launcher3/dragndrop/DragController.java
+++ b/src/com/android/launcher3/dragndrop/DragController.java
@@ -582,8 +582,8 @@
             }
         }
         final View dropTargetAsView = dropTarget instanceof View ? (View) dropTarget : null;
-        mLauncher.getUserEventDispatcher().logDragNDrop(mDragObject, dropTargetAsView);
         if (!mIsInPreDrag) {
+            mLauncher.getUserEventDispatcher().logDragNDrop(mDragObject, dropTargetAsView);
             mDragObject.dragSource.onDropCompleted(
                     dropTargetAsView, mDragObject, flingAnimation != null, accepted);
         }
diff --git a/src/com/android/launcher3/dragndrop/DragLayer.java b/src/com/android/launcher3/dragndrop/DragLayer.java
index 1be40f7..23a2577 100644
--- a/src/com/android/launcher3/dragndrop/DragLayer.java
+++ b/src/com/android/launcher3/dragndrop/DragLayer.java
@@ -57,6 +57,8 @@
 import com.android.launcher3.folder.Folder;
 import com.android.launcher3.folder.FolderIcon;
 import com.android.launcher3.keyboard.ViewGroupFocusHelper;
+import com.android.launcher3.logging.LoggerUtils;
+import com.android.launcher3.userevent.nano.LauncherLogProto;
 import com.android.launcher3.util.Thunk;
 import com.android.launcher3.util.TouchController;
 
@@ -192,6 +194,8 @@
                         return true;
                     }
                 } else {
+                    mLauncher.getUserEventDispatcher().logActionTapOutside(
+                            LoggerUtils.newContainerTarget(topView.getLogContainerType()));
                     topView.close(true);
 
                     // We let touches on the original icon go through so that users can launch
diff --git a/src/com/android/launcher3/folder/ClippedFolderIconLayoutRule.java b/src/com/android/launcher3/folder/ClippedFolderIconLayoutRule.java
index 6ee02f9..840fcf5 100644
--- a/src/com/android/launcher3/folder/ClippedFolderIconLayoutRule.java
+++ b/src/com/android/launcher3/folder/ClippedFolderIconLayoutRule.java
@@ -1,16 +1,17 @@
 package com.android.launcher3.folder;
 
-import android.graphics.Path;
-import android.graphics.Point;
+import android.view.View;
 
-import com.android.launcher3.DeviceProfile;
-import com.android.launcher3.LauncherAppState;
-import com.android.launcher3.Utilities;
+import com.android.launcher3.config.FeatureFlags;
+
+import java.util.ArrayList;
+import java.util.List;
 
 public class ClippedFolderIconLayoutRule implements FolderIcon.PreviewLayoutRule {
 
     static final int MAX_NUM_ITEMS_IN_PREVIEW = 4;
     private static final int MIN_NUM_ITEMS_IN_PREVIEW = 2;
+    private static final int MAX_NUM_ITEMS_PER_ROW = 2;
 
     final float MIN_SCALE = 0.48f;
     final float MAX_SCALE = 0.58f;
@@ -38,7 +39,7 @@
     public FolderIcon.PreviewItemDrawingParams computePreviewItemDrawingParams(int index,
             int curNumItems, FolderIcon.PreviewItemDrawingParams params) {
 
-        float totalScale = scaleForNumItems(curNumItems);
+        float totalScale = scaleForItem(index, curNumItems);
         float transX;
         float transY;
         float overlayAlpha = 0;
@@ -94,7 +95,7 @@
                 MIN_NUM_ITEMS_IN_PREVIEW) / (MAX_NUM_ITEMS_IN_PREVIEW - MIN_NUM_ITEMS_IN_PREVIEW));
         double theta = theta0 + index * (2 * Math.PI / curNumItems) * direction;
 
-        float halfIconSize = (mIconSize * scaleForNumItems(curNumItems)) / 2;
+        float halfIconSize = (mIconSize * scaleForItem(index, curNumItems)) / 2;
 
         // Map the location along the circle, and offset the coordinates to represent the center
         // of the icon, and to be based from the top / left of the preview area. The y component
@@ -104,7 +105,9 @@
 
     }
 
-    private float scaleForNumItems(int numItems) {
+    @Override
+    public float scaleForItem(int index, int numItems) {
+        // Scale is determined by the number of items in the preview.
         float scale = 1f;
         if (numItems <= 2) {
             scale = MAX_SCALE;
@@ -118,7 +121,7 @@
     }
 
     @Override
-    public int numItems() {
+    public int maxNumItems() {
         return MAX_NUM_ITEMS_IN_PREVIEW;
     }
 
@@ -127,4 +130,23 @@
         return true;
     }
 
+    @Override
+    public List<View> getItemsToDisplay(Folder folder) {
+        List<View> items = new ArrayList<>(folder.getItemsInReadingOrder());
+        int numItems = items.size();
+        if (FeatureFlags.LAUNCHER3_NEW_FOLDER_ANIMATION && numItems > MAX_NUM_ITEMS_IN_PREVIEW) {
+            // We match the icons in the preview with the layout of the opened folder (b/27944225),
+            // but we still need to figure out how we want to handle updating the preview when the
+            // upper left quadrant changes.
+            int appsPerRow = folder.mContent.getPageAt(0).getCountX();
+            int appsToDelete = appsPerRow - MAX_NUM_ITEMS_PER_ROW;
+
+            // We only display the upper left quadrant.
+            while (appsToDelete > 0) {
+                items.remove(MAX_NUM_ITEMS_PER_ROW);
+                appsToDelete--;
+            }
+        }
+        return items.subList(0, Math.min(numItems, MAX_NUM_ITEMS_IN_PREVIEW));
+    }
 }
diff --git a/src/com/android/launcher3/folder/Folder.java b/src/com/android/launcher3/folder/Folder.java
index 876c3c4..eacea4a 100644
--- a/src/com/android/launcher3/folder/Folder.java
+++ b/src/com/android/launcher3/folder/Folder.java
@@ -74,6 +74,7 @@
 import com.android.launcher3.dragndrop.DragLayer;
 import com.android.launcher3.dragndrop.DragOptions;
 import com.android.launcher3.pageindicators.PageIndicatorDots;
+import com.android.launcher3.userevent.nano.LauncherLogProto;
 import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
 import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
 import com.android.launcher3.util.CircleRevealOutlineProvider;
@@ -1532,4 +1533,9 @@
     public static Folder getOpen(Launcher launcher) {
         return getOpenView(launcher, TYPE_FOLDER);
     }
+
+    @Override
+    public int getLogContainerType() {
+        return ContainerType.FOLDER;
+    }
 }
diff --git a/src/com/android/launcher3/folder/FolderIcon.java b/src/com/android/launcher3/folder/FolderIcon.java
index 7f5569c..96d5675 100644
--- a/src/com/android/launcher3/folder/FolderIcon.java
+++ b/src/com/android/launcher3/folder/FolderIcon.java
@@ -33,6 +33,7 @@
 import android.os.Parcelable;
 import android.util.AttributeSet;
 import android.util.DisplayMetrics;
+import android.util.Property;
 import android.view.LayoutInflater;
 import android.view.MotionEvent;
 import android.view.View;
@@ -64,12 +65,16 @@
 import com.android.launcher3.StylusEventHelper;
 import com.android.launcher3.Utilities;
 import com.android.launcher3.Workspace;
+import com.android.launcher3.badge.BadgeRenderer;
+import com.android.launcher3.badge.FolderBadgeInfo;
 import com.android.launcher3.config.FeatureFlags;
 import com.android.launcher3.dragndrop.DragLayer;
 import com.android.launcher3.dragndrop.DragView;
+import com.android.launcher3.graphics.IconPalette;
 import com.android.launcher3.util.Thunk;
 
 import java.util.ArrayList;
+import java.util.List;
 
 /**
  * An icon that can appear on in the workspace representing an {@link Folder}.
@@ -124,6 +129,24 @@
 
     private Alarm mOpenAlarm = new Alarm();
 
+    private FolderBadgeInfo mBadgeInfo = new FolderBadgeInfo();
+    private BadgeRenderer mBadgeRenderer;
+    private float mBadgeScale;
+
+    private static final Property<FolderIcon, Float> BADGE_SCALE_PROPERTY
+            = new Property<FolderIcon, Float>(Float.TYPE, "badgeScale") {
+        @Override
+        public Float get(FolderIcon folderIcon) {
+            return folderIcon.mBadgeScale;
+        }
+
+        @Override
+        public void set(FolderIcon folderIcon, Float value) {
+            folderIcon.mBadgeScale = value;
+            folderIcon.invalidate();
+        }
+    };
+
     public FolderIcon(Context context, AttributeSet attrs) {
         super(context, attrs);
         init();
@@ -172,6 +195,7 @@
         icon.setOnClickListener(launcher);
         icon.mInfo = folderInfo;
         icon.mLauncher = launcher;
+        icon.mBadgeRenderer = launcher.getDeviceProfile().mBadgeRenderer;
         icon.setContentDescription(launcher.getString(R.string.folder_name_format, folderInfo.title));
         Folder folder = Folder.fromXml(launcher);
         folder.setDragController(launcher.getDragController());
@@ -320,7 +344,7 @@
             to.offset(center[0] - animateView.getMeasuredWidth() / 2,
                       center[1] - animateView.getMeasuredHeight() / 2);
 
-            float finalAlpha = index < mPreviewLayoutRule.numItems() ? 0.5f : 0f;
+            float finalAlpha = index < mPreviewLayoutRule.maxNumItems() ? 0.5f : 0f;
 
             float finalScale = scale * scaleRelativeToDragLayer;
             dragLayer.animateView(animateView, from, to, finalAlpha,
@@ -379,6 +403,28 @@
         computePreviewDrawingParams(d.getIntrinsicWidth(), getMeasuredWidth());
     }
 
+    public void setBadgeInfo(FolderBadgeInfo badgeInfo) {
+        updateBadgeScale(mBadgeInfo.getNotificationCount(), badgeInfo.getNotificationCount());
+        mBadgeInfo = badgeInfo;
+    }
+
+    /**
+     * Sets mBadgeScale to 1 or 0, animating if oldCount or newCount is 0
+     * (the badge is being added or removed).
+     */
+    private void updateBadgeScale(int oldCount, int newCount) {
+        boolean wasBadged = oldCount > 0;
+        boolean isBadged = newCount > 0;
+        float newBadgeScale = isBadged ? 1f : 0f;
+        // Animate when a badge is first added or when it is removed.
+        if ((wasBadged ^ isBadged) && isShown()) {
+            ObjectAnimator.ofFloat(this, BADGE_SCALE_PROPERTY, newBadgeScale).start();
+        } else {
+            mBadgeScale = newBadgeScale;
+            invalidate();
+        }
+    }
+
     static class PreviewItemDrawingParams {
         PreviewItemDrawingParams(float transX, float transY, float scale, float overlayAlpha) {
             this.transX = transX;
@@ -413,8 +459,8 @@
     }
 
     private float getLocalCenterForIndex(int index, int curNumItems, int[] center) {
-        mTmpParams = computePreviewItemDrawingParams(Math.min(mPreviewLayoutRule.numItems(), index),
-                curNumItems, mTmpParams);
+        mTmpParams = computePreviewItemDrawingParams(
+                Math.min(mPreviewLayoutRule.maxNumItems(), index), curNumItems, mTmpParams);
 
         mTmpParams.transX += mBackground.basePreviewOffsetX;
         mTmpParams.transY += mBackground.basePreviewOffsetY;
@@ -537,6 +583,14 @@
             return basePreviewOffsetY - (getScaledRadius() - getRadius());
         }
 
+        /**
+         * Returns the progress of the scale animation, where 0 means the scale is at 1f
+         * and 1 means the scale is at ACCEPT_SCALE_FACTOR.
+         */
+        float getScaleProgress() {
+            return (mScale - 1f) / (ACCEPT_SCALE_FACTOR - 1f);
+        }
+
         void invalidate() {
             int radius = getScaledRadius();
             mClipPath.reset();
@@ -767,6 +821,16 @@
         if (mPreviewLayoutRule.clipToBackground() && !mBackground.drawingDelegated()) {
             mBackground.drawBackgroundStroke(canvas, mBgPaint);
         }
+
+        int offsetX = mBackground.getOffsetX();
+        int offsetY = mBackground.getOffsetY();
+        int previewSize = (int) (mBackground.previewSize * mBackground.mScale);
+        Rect bounds = new Rect(offsetX, offsetY, offsetX + previewSize, offsetY + previewSize);
+        if ((mBadgeInfo != null && mBadgeInfo.getNotificationCount() > 0) || mBadgeScale > 0) {
+            // If we are animating to the accepting state, animate the badge out.
+            float badgeScale = Math.max(0, mBadgeScale - mBackground.getScaleProgress());
+            mBadgeRenderer.draw(canvas, IconPalette.FOLDER_ICON_PALETTE, mBadgeInfo, bounds, badgeScale);
+        }
     }
 
     class FolderPreviewItemAnim {
@@ -870,8 +934,8 @@
     }
 
     private void updateItemDrawingParams(boolean animate) {
-        ArrayList<View> items = mFolder.getItemsInReadingOrder();
-        int nItemsInPreview = Math.min(items.size(), mPreviewLayoutRule.numItems());
+        List<View> items = mPreviewLayoutRule.getItemsToDisplay(mFolder);
+        int nItemsInPreview = items.size();
 
         int prevNumItems = mDrawingParams.size();
 
@@ -916,16 +980,27 @@
         requestLayout();
     }
 
+    @Override
     public void onAdd(ShortcutInfo item) {
+        int oldCount = mBadgeInfo.getNotificationCount();
+        mBadgeInfo.addBadgeInfo(mLauncher.getPopupDataProvider().getBadgeInfoForItem(item));
+        int newCount = mBadgeInfo.getNotificationCount();
+        updateBadgeScale(oldCount, newCount);
         invalidate();
         requestLayout();
     }
 
+    @Override
     public void onRemove(ShortcutInfo item) {
+        int oldCount = mBadgeInfo.getNotificationCount();
+        mBadgeInfo.subtractBadgeInfo(mLauncher.getPopupDataProvider().getBadgeInfoForItem(item));
+        int newCount = mBadgeInfo.getNotificationCount();
+        updateBadgeScale(oldCount, newCount);
         invalidate();
         requestLayout();
     }
 
+    @Override
     public void onTitleChanged(CharSequence title) {
         mFolderName.setText(title);
         setContentDescription(getContext().getString(R.string.folder_name_format, title));
@@ -1037,10 +1112,10 @@
     public interface PreviewLayoutRule {
         PreviewItemDrawingParams computePreviewItemDrawingParams(int index, int curNumItems,
             PreviewItemDrawingParams params);
-
         void init(int availableSpace, int intrinsicIconSize, boolean rtl);
-
-        int numItems();
+        float scaleForItem(int index, int totalNumItems);
+        int maxNumItems();
         boolean clipToBackground();
+        List<View> getItemsToDisplay(Folder folder);
     }
 }
diff --git a/src/com/android/launcher3/folder/StackFolderIconLayoutRule.java b/src/com/android/launcher3/folder/StackFolderIconLayoutRule.java
index 7fb02e3..297203a 100644
--- a/src/com/android/launcher3/folder/StackFolderIconLayoutRule.java
+++ b/src/com/android/launcher3/folder/StackFolderIconLayoutRule.java
@@ -16,10 +16,12 @@
 
 package com.android.launcher3.folder;
 
-import android.graphics.Path;
+import android.view.View;
 
 import com.android.launcher3.folder.FolderIcon.PreviewItemDrawingParams;
 
+import java.util.List;
+
 public class StackFolderIconLayoutRule implements FolderIcon.PreviewLayoutRule {
 
     static final int MAX_NUM_ITEMS_IN_PREVIEW = 3;
@@ -54,10 +56,10 @@
     @Override
     public PreviewItemDrawingParams computePreviewItemDrawingParams(int index, int curNumItems,
             PreviewItemDrawingParams params) {
+        float scale = scaleForItem(index, curNumItems);
 
         index = MAX_NUM_ITEMS_IN_PREVIEW - index - 1;
         float r = (index * 1.0f) / (MAX_NUM_ITEMS_IN_PREVIEW - 1);
-        float scale = (1 - PERSPECTIVE_SCALE_FACTOR * (1 - r));
 
         float offset = (1 - r) * mMaxPerspectiveShift;
         float scaledSize = scale * mBaselineIconSize;
@@ -80,12 +82,26 @@
     }
 
     @Override
-    public int numItems() {
+    public int maxNumItems() {
         return MAX_NUM_ITEMS_IN_PREVIEW;
     }
 
     @Override
+    public float scaleForItem(int index, int numItems) {
+        // Scale is determined by the position of the icon in the preview.
+        index = MAX_NUM_ITEMS_IN_PREVIEW - index - 1;
+        float r = (index * 1.0f) / (MAX_NUM_ITEMS_IN_PREVIEW - 1);
+        return (1 - PERSPECTIVE_SCALE_FACTOR * (1 - r));
+    }
+
+    @Override
     public boolean clipToBackground() {
         return false;
     }
+
+    @Override
+    public List<View> getItemsToDisplay(Folder folder) {
+        List<View> items = folder.getItemsInReadingOrder();
+        return items.subList(0, Math.min(items.size(), MAX_NUM_ITEMS_IN_PREVIEW));
+    }
 }
diff --git a/src/com/android/launcher3/graphics/IconPalette.java b/src/com/android/launcher3/graphics/IconPalette.java
index 991038c..7cb69b3 100644
--- a/src/com/android/launcher3/graphics/IconPalette.java
+++ b/src/com/android/launcher3/graphics/IconPalette.java
@@ -32,6 +32,8 @@
     private static final boolean DEBUG = false;
     private static final String TAG = "IconPalette";
 
+    public static final IconPalette FOLDER_ICON_PALETTE = new IconPalette(Color.WHITE);
+
     private static final float MIN_PRELOAD_COLOR_SATURATION = 0.2f;
     private static final float MIN_PRELOAD_COLOR_LIGHTNESS = 0.6f;
     private static final int DEFAULT_PRELOAD_COLOR = 0xFF009688;
diff --git a/src/com/android/launcher3/logging/UserEventDispatcher.java b/src/com/android/launcher3/logging/UserEventDispatcher.java
index 8ab33dc..5f45c61 100644
--- a/src/com/android/launcher3/logging/UserEventDispatcher.java
+++ b/src/com/android/launcher3/logging/UserEventDispatcher.java
@@ -16,6 +16,7 @@
 
 package com.android.launcher3.logging;
 
+import android.app.PendingIntent;
 import android.content.ComponentName;
 import android.content.Intent;
 import android.os.SystemClock;
@@ -27,6 +28,7 @@
 import com.android.launcher3.ItemInfo;
 import com.android.launcher3.Utilities;
 import com.android.launcher3.config.ProviderConfig;
+import com.android.launcher3.userevent.nano.LauncherLogProto;
 import com.android.launcher3.userevent.nano.LauncherLogProto.Action;
 import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
 import com.android.launcher3.userevent.nano.LauncherLogProto.LauncherEvent;
@@ -112,7 +114,7 @@
     // intentHash                       required
     // --------------------------------------------------------------
 
-    protected LauncherEvent createLauncherEvent(View v, Intent intent) {
+    protected LauncherEvent createLauncherEvent(View v, int intentHashCode, ComponentName cn) {
         LauncherEvent event = newLauncherEvent(newTouchAction(Action.Touch.TAP),
                 newItemTarget(v), newTarget(Target.Type.CONTAINER));
 
@@ -120,8 +122,7 @@
         int idx = 0;
         if (fillInLogContainerData(event, v)) {
             ItemInfo itemInfo = (ItemInfo) v.getTag();
-            event.srcTarget[idx].intentHash = intent.hashCode();
-            ComponentName cn = intent.getComponent();
+            event.srcTarget[idx].intentHash = intentHashCode;
             if (cn != null) {
                 event.srcTarget[idx].packageNameHash = cn.getPackageName().hashCode();
                 event.srcTarget[idx].componentHash = cn.hashCode();
@@ -146,13 +147,22 @@
     }
 
     public void logAppLaunch(View v, Intent intent) {
-        LauncherEvent ev = createLauncherEvent(v, intent);
+        LauncherEvent ev = createLauncherEvent(v, intent.hashCode(), intent.getComponent());
         if (ev == null) {
             return;
         }
         dispatchUserEvent(ev, intent);
     }
 
+    public void logNotificationLaunch(View v, PendingIntent intent) {
+        ComponentName dummyComponent = new ComponentName(intent.getCreatorPackage(), "--dummy--");
+        LauncherEvent ev = createLauncherEvent(v, intent.hashCode(), dummyComponent);
+        if (ev == null) {
+            return;
+        }
+        dispatchUserEvent(ev, null);
+    }
+
     public void logActionCommand(int command, int containerType) {
         logActionCommand(command, containerType, 0);
     }
@@ -187,6 +197,13 @@
         dispatchUserEvent(event, null);
     }
 
+    public void logActionTapOutside(Target target) {
+        LauncherEvent event = newLauncherEvent(newTouchAction(Action.Type.TOUCH),
+                target);
+        event.action.isOutside = true;
+        dispatchUserEvent(event, null);
+    }
+
     public void logActionOnContainer(int action, int dir, int containerType) {
         logActionOnContainer(action, dir, containerType, 0);
     }
@@ -199,9 +216,17 @@
         dispatchUserEvent(event, null);
     }
 
+    public void logActionOnItem(int action, int dir, int itemType) {
+        Target itemTarget = newTarget(Target.Type.ITEM);
+        itemTarget.itemType = itemType;
+        LauncherEvent event = newLauncherEvent(newTouchAction(action), itemTarget);
+        event.action.dir = dir;
+        dispatchUserEvent(event, null);
+    }
+
     public void logDeepShortcutsOpen(View icon) {
         LogContainerProvider provider = getLaunchProviderRecursive(icon);
-        if (icon == null && !(icon.getTag() instanceof ItemInfo)) {
+        if (icon == null || !(icon.getTag() instanceof ItemInfo)) {
             return;
         }
         ItemInfo info = (ItemInfo) icon.getTag();
diff --git a/src/com/android/launcher3/notification/NotificationInfo.java b/src/com/android/launcher3/notification/NotificationInfo.java
index 6cc0e90..77a18c7 100644
--- a/src/com/android/launcher3/notification/NotificationInfo.java
+++ b/src/com/android/launcher3/notification/NotificationInfo.java
@@ -40,6 +40,11 @@
  */
 public class NotificationInfo implements View.OnClickListener {
 
+    // TODO: use Notification constants directly.
+    public static final int BADGE_ICON_NONE = 0;
+    public static final int BADGE_ICON_SMALL = 1;
+    public static final int BADGE_ICON_LARGE = 2;
+
     public final PackageUserKey packageUserKey;
     public final String notificationKey;
     public final CharSequence title;
@@ -48,9 +53,10 @@
     public final boolean autoCancel;
     public final boolean dismissable;
 
+    private final int mBadgeIcon;
     private final Drawable mIconDrawable;
-    private boolean mShouldTintIcon;
     private int mIconColor;
+    private boolean mIsIconLarge;
 
     /**
      * Extracts the data that we need from the StatusBarNotification.
@@ -61,17 +67,20 @@
         Notification notification = statusBarNotification.getNotification();
         title = notification.extras.getCharSequence(Notification.EXTRA_TITLE);
         text = notification.extras.getCharSequence(Notification.EXTRA_TEXT);
+        mBadgeIcon = BADGE_ICON_LARGE; // TODO: get from the Notification
         // Load the icon. Since it is backed by ashmem, we won't copy the entire bitmap
         // into our process as long as we don't touch it and it exists in systemui.
-        Icon icon = notification.getLargeIcon();
+        Icon icon = mBadgeIcon == BADGE_ICON_SMALL ? null : notification.getLargeIcon();
         if (icon == null) {
+            // Use the small icon.
             icon = notification.getSmallIcon();
             mIconDrawable = icon.loadDrawable(context);
             mIconColor = statusBarNotification.getNotification().color;
-            mShouldTintIcon = true;
+            mIsIconLarge = false;
         } else {
+            // Use the large icon.
             mIconDrawable = icon.loadDrawable(context);
-            mShouldTintIcon = false;
+            mIsIconLarge = true;
         }
         intent = notification.contentIntent;
         autoCancel = (notification.flags & Notification.FLAG_AUTO_CANCEL) != 0;
@@ -85,6 +94,7 @@
                 view, 0, 0, view.getWidth(), view.getHeight()).toBundle();
         try {
             intent.send(null, 0, null, null, null, null, activityOptions);
+            launcher.getUserEventDispatcher().logNotificationLaunch(view, intent);
         } catch (PendingIntent.CanceledException e) {
             e.printStackTrace();
         }
@@ -95,7 +105,8 @@
     }
 
     public Drawable getIconForBackground(Context context, int background) {
-        if (!mShouldTintIcon) {
+        if (mIsIconLarge) {
+            // Only small icons should be tinted.
             return mIconDrawable;
         }
         mIconColor = IconPalette.resolveContrastColor(context, mIconColor, background);
@@ -104,7 +115,17 @@
         // get it set and invalidated properly.
         icon.setTintList(null);
         icon.setTint(mIconColor);
-        mShouldTintIcon = false;
         return icon;
     }
+
+    public boolean isIconLarge() {
+        return mIsIconLarge;
+    }
+
+    public boolean shouldShowIconInBadge() {
+        // If the icon we're using for this notification matches what the Notification
+        // specified should show in the badge, then return true.
+        return mIsIconLarge && mBadgeIcon == BADGE_ICON_LARGE
+                || !mIsIconLarge && mBadgeIcon == BADGE_ICON_SMALL;
+    }
 }
diff --git a/src/com/android/launcher3/notification/NotificationItemView.java b/src/com/android/launcher3/notification/NotificationItemView.java
index 422722d..639447d 100644
--- a/src/com/android/launcher3/notification/NotificationItemView.java
+++ b/src/com/android/launcher3/notification/NotificationItemView.java
@@ -29,15 +29,16 @@
 import android.widget.FrameLayout;
 import android.widget.TextView;
 
+import com.android.launcher3.ItemInfo;
 import com.android.launcher3.LauncherAnimUtils;
 import com.android.launcher3.R;
 import com.android.launcher3.graphics.IconPalette;
+import com.android.launcher3.logging.UserEventDispatcher.LogContainerProvider;
 import com.android.launcher3.popup.PopupItemView;
+import com.android.launcher3.userevent.nano.LauncherLogProto;
 
 import java.util.ArrayList;
-import java.util.HashSet;
 import java.util.List;
-import java.util.Set;
 
 import static com.android.launcher3.LauncherAnimUtils.animateViewHeight;
 
@@ -47,7 +48,7 @@
  * The footer contains: A list of just the icons of all the notifications past the first one.
  * @see NotificationFooterLayout
  */
-public class NotificationItemView extends PopupItemView {
+public class NotificationItemView extends PopupItemView implements LogContainerProvider {
 
     private static final Rect sTempRect = new Rect();
 
@@ -57,7 +58,6 @@
     private NotificationFooterLayout mFooter;
     private SwipeHelper mSwipeHelper;
     private boolean mAnimatingNextIcon;
-    private IconPalette mIconPalette;
 
     public NotificationItemView(Context context) {
         this(context, null, 0);
@@ -114,7 +114,6 @@
     }
 
     public void applyColors(IconPalette iconPalette) {
-        mIconPalette = iconPalette;
         setBackgroundTintList(ColorStateList.valueOf(iconPalette.secondaryColor));
         mHeader.setBackgroundTintList(ColorStateList.valueOf(iconPalette.backgroundColor));
         mHeader.setTextColor(ColorStateList.valueOf(iconPalette.textColor));
@@ -174,4 +173,11 @@
         animation.playSequentially(removeMainView, removeRest);
         return animation;
     }
+
+    @Override
+    public void fillInLogContainerData(View v, ItemInfo info, LauncherLogProto.Target target,
+            LauncherLogProto.Target targetParent) {
+        target.itemType = LauncherLogProto.ItemType.NOTIFICATION;
+        targetParent.containerType = LauncherLogProto.ContainerType.DEEPSHORTCUTS;
+    }
 }
diff --git a/src/com/android/launcher3/notification/NotificationListener.java b/src/com/android/launcher3/notification/NotificationListener.java
index 3f9a584..206bb31 100644
--- a/src/com/android/launcher3/notification/NotificationListener.java
+++ b/src/com/android/launcher3/notification/NotificationListener.java
@@ -24,7 +24,6 @@
 import android.service.notification.StatusBarNotification;
 import android.support.annotation.Nullable;
 import android.support.v4.util.Pair;
-import android.util.Log;
 
 import com.android.launcher3.LauncherModel;
 import com.android.launcher3.config.FeatureFlags;
diff --git a/src/com/android/launcher3/notification/NotificationMainView.java b/src/com/android/launcher3/notification/NotificationMainView.java
index 76a84b7..6677c2f 100644
--- a/src/com/android/launcher3/notification/NotificationMainView.java
+++ b/src/com/android/launcher3/notification/NotificationMainView.java
@@ -20,18 +20,19 @@
 import android.animation.AnimatorSet;
 import android.animation.ValueAnimator;
 import android.content.Context;
-import android.support.annotation.Nullable;
 import android.util.AttributeSet;
 import android.view.MotionEvent;
 import android.view.View;
 import android.widget.LinearLayout;
 import android.widget.TextView;
 
+import com.android.launcher3.ItemInfo;
 import com.android.launcher3.Launcher;
 import com.android.launcher3.LauncherAnimUtils;
 import com.android.launcher3.LauncherViewPropertyAnimator;
 import com.android.launcher3.R;
 import com.android.launcher3.graphics.IconPalette;
+import com.android.launcher3.userevent.nano.LauncherLogProto;
 
 /**
  * A {@link LinearLayout} that contains a single notification, e.g. icon + title + text.
@@ -89,6 +90,9 @@
                 getContext(), mIconPalette.backgroundColor));
         setOnClickListener(mNotificationInfo);
         setTranslationX(0);
+        // Add a dummy ItemInfo so that logging populates the correct container and item types
+        // instead of DEFAULT_CONTAINERTYPE and DEFAULT_ITEMTYPE, respectively.
+        setTag(new ItemInfo());
         if (animate) {
             AnimatorSet animation = LauncherAnimUtils.createAnimatorSet();
             Animator textFade = new LauncherViewPropertyAnimator(mTextView).alpha(1);
@@ -135,8 +139,13 @@
 
     @Override
     public void onChildDismissed(View v) {
-        Launcher.getLauncher(getContext()).getPopupDataProvider().cancelNotification(
+        Launcher launcher = Launcher.getLauncher(getContext());
+        launcher.getPopupDataProvider().cancelNotification(
                 mNotificationInfo.notificationKey);
+        launcher.getUserEventDispatcher().logActionOnItem(
+                LauncherLogProto.Action.Touch.SWIPE,
+                LauncherLogProto.Action.Direction.RIGHT, // Assume all swipes are right for logging.
+                LauncherLogProto.ItemType.NOTIFICATION);
     }
 
     @Override
diff --git a/src/com/android/launcher3/popup/PopupContainerWithArrow.java b/src/com/android/launcher3/popup/PopupContainerWithArrow.java
index af1bd9b..7fda8b5 100644
--- a/src/com/android/launcher3/popup/PopupContainerWithArrow.java
+++ b/src/com/android/launcher3/popup/PopupContainerWithArrow.java
@@ -696,7 +696,7 @@
     @Override
     public void fillInLogContainerData(View v, ItemInfo info, Target target, Target targetParent) {
         target.itemType = ItemType.DEEPSHORTCUT;
-        // TODO: add target.rank
+        target.rank = info.rank;
         targetParent.containerType = ContainerType.DEEPSHORTCUTS;
     }
 
@@ -825,4 +825,9 @@
     public static PopupContainerWithArrow getOpen(Launcher launcher) {
         return getOpenView(launcher, TYPE_POPUP_CONTAINER_WITH_ARROW);
     }
+
+    @Override
+    public int getLogContainerType() {
+        return ContainerType.DEEPSHORTCUTS;
+    }
 }
diff --git a/src/com/android/launcher3/popup/PopupDataProvider.java b/src/com/android/launcher3/popup/PopupDataProvider.java
index bb9c520..4f3b8a6 100644
--- a/src/com/android/launcher3/popup/PopupDataProvider.java
+++ b/src/com/android/launcher3/popup/PopupDataProvider.java
@@ -23,6 +23,7 @@
 import com.android.launcher3.ItemInfo;
 import com.android.launcher3.Launcher;
 import com.android.launcher3.badge.BadgeInfo;
+import com.android.launcher3.notification.NotificationInfo;
 import com.android.launcher3.notification.NotificationListener;
 import com.android.launcher3.shortcuts.DeepShortcutManager;
 import com.android.launcher3.util.ComponentKey;
@@ -31,8 +32,10 @@
 
 import java.util.Collections;
 import java.util.HashMap;
+import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 
 /**
  * Provides data for the popup menu that appears after long-clicking on apps.
@@ -55,15 +58,17 @@
 
     @Override
     public void onNotificationPosted(PackageUserKey postedPackageUserKey, String notificationKey) {
-        BadgeInfo oldBadgeInfo = mPackageUserToBadgeInfos.get(postedPackageUserKey);
-        if (oldBadgeInfo == null) {
+        BadgeInfo badgeInfo = mPackageUserToBadgeInfos.get(postedPackageUserKey);
+        boolean notificationWasAdded; // As opposed to updated.
+        if (badgeInfo == null) {
             BadgeInfo newBadgeInfo = new BadgeInfo(postedPackageUserKey);
             newBadgeInfo.addNotificationKeyIfNotExists(notificationKey);
             mPackageUserToBadgeInfos.put(postedPackageUserKey, newBadgeInfo);
-            mLauncher.updateIconBadges(Collections.singleton(postedPackageUserKey));
-        } else if (oldBadgeInfo.addNotificationKeyIfNotExists(notificationKey)) {
-            mLauncher.updateIconBadges(Collections.singleton(postedPackageUserKey));
+            notificationWasAdded = true;
+        } else {
+            notificationWasAdded = badgeInfo.addNotificationKeyIfNotExists(notificationKey);
         }
+        updateLauncherIconBadges(Collections.singleton(postedPackageUserKey), notificationWasAdded);
     }
 
     @Override
@@ -73,7 +78,7 @@
             if (oldBadgeInfo.getNotificationCount() == 0) {
                 mPackageUserToBadgeInfos.remove(removedPackageUserKey);
             }
-            mLauncher.updateIconBadges(Collections.singleton(removedPackageUserKey));
+            updateLauncherIconBadges(Collections.singleton(removedPackageUserKey));
 
             PopupContainerWithArrow openContainer = PopupContainerWithArrow.getOpen(mLauncher);
             if (openContainer != null) {
@@ -112,7 +117,7 @@
         }
 
         if (!updatedBadges.isEmpty()) {
-            mLauncher.updateIconBadges(updatedBadges.keySet());
+            updateLauncherIconBadges(updatedBadges.keySet());
         }
 
         PopupContainerWithArrow openContainer = PopupContainerWithArrow.getOpen(mLauncher);
@@ -121,6 +126,58 @@
         }
     }
 
+    private void updateLauncherIconBadges(Set<PackageUserKey> updatedBadges) {
+        updateLauncherIconBadges(updatedBadges, true);
+    }
+
+    /**
+     * Updates the icons on launcher (workspace, folders, all apps) to refresh their badges.
+     * @param updatedBadges The packages whose badges should be refreshed (either a notification was
+     *                      added or removed, or the badge should show the notification icon).
+     * @param addedOrRemoved An optional parameter that will allow us to only refresh badges that
+     *                       updated (not added/removed) that have icons. If a badge updated
+     *                       but it doesn't have an icon, then the badge number doesn't change.
+     */
+    private void updateLauncherIconBadges(Set<PackageUserKey> updatedBadges,
+            boolean addedOrRemoved) {
+        Iterator<PackageUserKey> iterator = updatedBadges.iterator();
+        while (iterator.hasNext()) {
+            BadgeInfo badgeInfo = mPackageUserToBadgeInfos.get(iterator.next());
+            if (badgeInfo != null && !updateBadgeIcon(badgeInfo) && !addedOrRemoved) {
+                // The notification icon isn't used, and the badge wasn't added or removed
+                // so there is no update to be made.
+                iterator.remove();
+            }
+        }
+        if (!updatedBadges.isEmpty()) {
+            mLauncher.updateIconBadges(updatedBadges);
+        }
+    }
+
+    /**
+     * Determines whether the badge should show a notification icon rather than a number,
+     * and sets that icon on the BadgeInfo if so.
+     * @param badgeInfo The badge to update with an icon (null if it shouldn't show one).
+     * @return Whether the badge icon potentially changed (true unless it stayed null).
+     */
+    private boolean updateBadgeIcon(BadgeInfo badgeInfo) {
+        boolean hadNotificationToShow = badgeInfo.hasNotificationToShow();
+        NotificationInfo notificationInfo = null;
+        NotificationListener notificationListener = NotificationListener.getInstance();
+        if (notificationListener != null && badgeInfo.getNotificationKeys().size() == 1) {
+            StatusBarNotification[] activeNotifications = notificationListener
+                    .getActiveNotifications(new String[] {badgeInfo.getNotificationKeys().get(0)});
+            if (activeNotifications.length == 1) {
+                notificationInfo = new NotificationInfo(mLauncher, activeNotifications[0]);
+                if (!notificationInfo.shouldShowIconInBadge()) {
+                    notificationInfo = null;
+                }
+            }
+        }
+        badgeInfo.setNotificationToShow(notificationInfo);
+        return hadNotificationToShow || badgeInfo.hasNotificationToShow();
+    }
+
     public void setDeepShortcutMap(MultiHashMap<ComponentKey, String> deepShortcutMapCopy) {
         mDeepShortcutMap = deepShortcutMapCopy;
         if (LOGD) Log.d(TAG, "bindDeepShortcutMap: " + mDeepShortcutMap);
diff --git a/src/com/android/launcher3/popup/PopupPopulator.java b/src/com/android/launcher3/popup/PopupPopulator.java
index f990fa2..d2814ee 100644
--- a/src/com/android/launcher3/popup/PopupPopulator.java
+++ b/src/com/android/launcher3/popup/PopupPopulator.java
@@ -171,6 +171,7 @@
                     // Use unbadged icon for the menu.
                     si.iconBitmap = LauncherIcons.createShortcutIcon(
                             shortcut, launcher, false /* badged */);
+                    si.rank = i;
                     uiHandler.post(new UpdateShortcutChild(container, shortcutViews.get(i),
                             si, shortcut));
                 }
diff --git a/src_config/com/android/launcher3/config/FeatureFlags.java b/src_config/com/android/launcher3/config/FeatureFlags.java
index ffb86e4..5c29366 100644
--- a/src_config/com/android/launcher3/config/FeatureFlags.java
+++ b/src_config/com/android/launcher3/config/FeatureFlags.java
@@ -28,6 +28,7 @@
     public static boolean LAUNCHER3_USE_SYSTEM_DRAG_DRIVER = true;
     public static boolean LAUNCHER3_DISABLE_PINCH_TO_OVERVIEW = false;
     public static boolean LAUNCHER3_ALL_APPS_PULL_UP = true;
+    public static boolean LAUNCHER3_NEW_FOLDER_ANIMATION = false;
 
     // Feature flag to enable moving the QSB on the 0th screen of the workspace.
     public static final boolean QSB_ON_FIRST_SCREEN = true;