Merge "Transition from back to showing widget tray if shortcut/Widget configure activity was cancelled." into ub-launcher3-burnaby
diff --git a/res/layout/user_folder.xml b/res/layout/user_folder.xml
index d75d6cd..67b69ca 100644
--- a/res/layout/user_folder.xml
+++ b/res/layout/user_folder.xml
@@ -38,6 +38,9 @@
             android:id="@+id/folder_content"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
+            android:paddingLeft="4dp"
+            android:paddingRight="4dp"
+            android:paddingTop="4dp"
             launcher:pageIndicator="@+id/folder_page_indicator" />
     </FrameLayout>
 
diff --git a/res/layout/widget_cell.xml b/res/layout/widget_cell.xml
index a85f0aa..500cf10 100644
--- a/res/layout/widget_cell.xml
+++ b/res/layout/widget_cell.xml
@@ -44,7 +44,7 @@
             android:ellipsize="end"
             android:fadingEdge="horizontal"
             android:textColor="@color/widgets_view_item_text_color"
-            android:textSize="16sp"
+            android:textSize="14sp"
             android:textAlignment="viewStart"
             android:fontFamily="sans-serif-condensed"
             android:shadowRadius="2.0"
@@ -61,7 +61,7 @@
             android:layout_weight="0"
             android:gravity="start"
             android:textColor="@color/widgets_view_item_text_color"
-            android:textSize="16sp"
+            android:textSize="14sp"
             android:textAlignment="viewStart"
             android:fontFamily="sans-serif-condensed"
             android:shadowRadius="2.0"
diff --git a/res/layout/widgets_list_row_view.xml b/res/layout/widgets_list_row_view.xml
index be62ee9..dc1bcce 100644
--- a/res/layout/widgets_list_row_view.xml
+++ b/res/layout/widgets_list_row_view.xml
@@ -41,7 +41,7 @@
         android:paddingTop="@dimen/widget_section_vertical_padding"
         android:singleLine="true"
         android:textColor="@color/widgets_view_section_text_color"
-        android:textSize="20sp"
+        android:textSize="16sp"
         launcher:customShadows="false"
         launcher:deferShadowGeneration="true"
         launcher:iconDisplay="widget_section"
diff --git a/res/values/dimens.xml b/res/values/dimens.xml
index 5e1f3de..d2f6237 100644
--- a/res/values/dimens.xml
+++ b/res/values/dimens.xml
@@ -119,4 +119,11 @@
     <dimen name="profile_badge_size">24dp</dimen>
     <dimen name="profile_badge_margin">4dp</dimen>
     <dimen name="profile_badge_minimum_top">2dp</dimen>
+
+<!-- Shadows and outlines -->
+    <dimen name="blur_size_thin_outline">1dp</dimen>
+    <dimen name="blur_size_medium_outline">2dp</dimen>
+    <dimen name="blur_size_click_shadow">4dp</dimen>
+    <dimen name="click_shadow_high_shift">2dp</dimen>
+
 </resources>
diff --git a/src/com/android/launcher3/AppsContainerView.java b/src/com/android/launcher3/AppsContainerView.java
index 7c1aee2..8709101 100644
--- a/src/com/android/launcher3/AppsContainerView.java
+++ b/src/com/android/launcher3/AppsContainerView.java
@@ -396,6 +396,7 @@
                 inset, 0, inset, 0);
         mContentView.setBackground(background);
         mAppsRecyclerView.updateBackgroundPadding(background);
+        mAdapter.updateBackgroundPadding(background);
         getRevealView().setBackground(background.getConstantState().newDrawable());
     }
 
@@ -658,12 +659,14 @@
                 // We workaround the fact that the recycler view needs the touches for the scroll
                 // and we want to intercept it for clicks in the prediction bar by handling clicks
                 // and long clicks in the prediction bar ourselves.
-                mPredictionIconTouchDownPos.set(x, y);
-                mPredictionIconUnderTouch = findPredictedAppAtCoordinate(x, y);
-                if (mPredictionIconUnderTouch != null) {
-                    mPredictionIconCheckForLongPress =
-                            new CheckLongPressHelper(mPredictionIconUnderTouch, this);
-                    mPredictionIconCheckForLongPress.postCheckForLongPress();
+                if (mPredictionBarView != null && mPredictionBarView.getVisibility() == View.VISIBLE) {
+                    mPredictionIconTouchDownPos.set(x, y);
+                    mPredictionIconUnderTouch = findPredictedAppAtCoordinate(x, y);
+                    if (mPredictionIconUnderTouch != null) {
+                        mPredictionIconCheckForLongPress =
+                                new CheckLongPressHelper(mPredictionIconUnderTouch, this);
+                        mPredictionIconCheckForLongPress.postCheckForLongPress();
+                    }
                 }
 
                 if (!mFixedBounds.isEmpty()) {
@@ -730,6 +733,9 @@
         Utilities.mapCoordInSelfToDescendent(mPredictionBarView, this, coord);
         for (int i = 0; i < mPredictionBarView.getChildCount(); i++) {
             View child = mPredictionBarView.getChildAt(i);
+            if (child.getVisibility() != View.VISIBLE) {
+                continue;
+            }
             child.getHitRect(hitRect);
             if (hitRect.contains(coord[0], coord[1])) {
                 return child;
diff --git a/src/com/android/launcher3/AppsGridAdapter.java b/src/com/android/launcher3/AppsGridAdapter.java
index dfbfa01..d5a411e 100644
--- a/src/com/android/launcher3/AppsGridAdapter.java
+++ b/src/com/android/launcher3/AppsGridAdapter.java
@@ -6,6 +6,7 @@
 import android.graphics.Paint;
 import android.graphics.PointF;
 import android.graphics.Rect;
+import android.graphics.drawable.Drawable;
 import android.os.Handler;
 import android.support.v7.widget.GridLayoutManager;
 import android.support.v7.widget.RecyclerView;
@@ -112,9 +113,9 @@
 
                 if (shouldDrawItemDivider(holder, items) && !hasDrawnPredictedAppsDivider) {
                     // Draw the divider under the predicted apps
-                    parent.getBackground().getPadding(mTmpBounds);
                     int top = child.getTop() + child.getHeight();
-                    c.drawLine(mTmpBounds.left, top, parent.getWidth() - mTmpBounds.right, top,
+                    c.drawLine(mBackgroundPadding.left, top,
+                            parent.getWidth() - mBackgroundPadding.right, top,
                             mPredictedAppsDividerPaint);
                     hasDrawnPredictedAppsDivider = true;
 
@@ -265,6 +266,7 @@
     private View.OnTouchListener mTouchListener;
     private View.OnClickListener mIconClickListener;
     private View.OnLongClickListener mIconLongClickListener;
+    @Thunk final Rect mBackgroundPadding = new Rect();
     @Thunk int mPredictionBarHeight;
     @Thunk int mAppsPerRow;
     @Thunk boolean mIsRtl;
@@ -341,6 +343,14 @@
     }
 
     /**
+     * Notifies the adapter of the background padding so that it can draw things correctly in the
+     * item decorator.
+     */
+    public void updateBackgroundPadding(Drawable background) {
+        background.getPadding(mBackgroundPadding);
+    }
+
+    /**
      * Returns the grid layout manager.
      */
     public GridLayoutManager getLayoutManager() {
diff --git a/src/com/android/launcher3/BubbleTextView.java b/src/com/android/launcher3/BubbleTextView.java
index bbcd893..5dc3b12 100644
--- a/src/com/android/launcher3/BubbleTextView.java
+++ b/src/com/android/launcher3/BubbleTextView.java
@@ -276,7 +276,7 @@
         // Only show the shadow effect when persistent pressed state is set.
         if (getParent() instanceof ShortcutAndWidgetContainer) {
             CellLayout layout = (CellLayout) getParent().getParent();
-            layout.setPressedIcon(this, mPressedBackground, mOutlineHelper.shadowBitmapPadding);
+            layout.setPressedIcon(this, mPressedBackground);
         }
 
         updateIconState();
diff --git a/src/com/android/launcher3/CellLayout.java b/src/com/android/launcher3/CellLayout.java
index 72eabf1..a348008 100644
--- a/src/com/android/launcher3/CellLayout.java
+++ b/src/com/android/launcher3/CellLayout.java
@@ -132,7 +132,7 @@
     private int mDragOutlineCurrent = 0;
     private final Paint mDragOutlinePaint = new Paint();
 
-    private final FastBitmapView mTouchFeedbackView;
+    private final ClickShadowView mTouchFeedbackView;
 
     @Thunk HashMap<CellLayout.LayoutParams, Animator> mReorderAnimators = new
             HashMap<CellLayout.LayoutParams, Animator>();
@@ -301,9 +301,8 @@
         mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap,
                 mCountX, mCountY);
 
-        mTouchFeedbackView = new FastBitmapView(context);
-        // Make the feedback view large enough to hold the blur bitmap.
-        addView(mTouchFeedbackView, (int) (grid.cellWidthPx * 1.5), (int) (grid.cellHeightPx * 1.5));
+        mTouchFeedbackView = new ClickShadowView(context);
+        addView(mTouchFeedbackView);
         addView(mShortcutsAndWidgets);
     }
 
@@ -410,22 +409,14 @@
         invalidate();
     }
 
-    void setPressedIcon(BubbleTextView icon, Bitmap background, int padding) {
+    void setPressedIcon(BubbleTextView icon, Bitmap background) {
         if (icon == null || background == null) {
             mTouchFeedbackView.setBitmap(null);
             mTouchFeedbackView.animate().cancel();
         } else {
-            int offset = getMeasuredWidth() - getPaddingLeft() - getPaddingRight()
-                    - (mCountX * mCellWidth);
-            mTouchFeedbackView.setTranslationX(icon.getLeft() + (int) Math.ceil(offset / 2f)
-                    - padding);
-            mTouchFeedbackView.setTranslationY(icon.getTop() - padding);
             if (mTouchFeedbackView.setBitmap(background)) {
-                mTouchFeedbackView.setAlpha(0);
-                mTouchFeedbackView.animate().alpha(1)
-                    .setDuration(FastBitmapDrawable.CLICK_FEEDBACK_DURATION)
-                    .setInterpolator(FastBitmapDrawable.CLICK_FEEDBACK_INTERPOLATOR)
-                    .start();
+                mTouchFeedbackView.alignWithIconView(icon, mShortcutsAndWidgets);
+                mTouchFeedbackView.animateShadow();
             }
         }
     }
@@ -895,19 +886,20 @@
             mWidthGap = mOriginalWidthGap;
             mHeightGap = mOriginalHeightGap;
         }
-        int count = getChildCount();
-        int maxWidth = 0;
-        int maxHeight = 0;
-        for (int i = 0; i < count; i++) {
-            View child = getChildAt(i);
-            int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(newWidth,
-                    MeasureSpec.EXACTLY);
-            int childheightMeasureSpec = MeasureSpec.makeMeasureSpec(newHeight,
-                    MeasureSpec.EXACTLY);
-            child.measure(childWidthMeasureSpec, childheightMeasureSpec);
-            maxWidth = Math.max(maxWidth, child.getMeasuredWidth());
-            maxHeight = Math.max(maxHeight, child.getMeasuredHeight());
-        }
+
+        // Make the feedback view large enough to hold the blur bitmap.
+        mTouchFeedbackView.measure(
+                MeasureSpec.makeMeasureSpec(mCellWidth + mTouchFeedbackView.getExtraSize(),
+                        MeasureSpec.EXACTLY),
+                MeasureSpec.makeMeasureSpec(mCellHeight + mTouchFeedbackView.getExtraSize(),
+                        MeasureSpec.EXACTLY));
+
+        mShortcutsAndWidgets.measure(
+                MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY),
+                MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY));
+
+        int maxWidth = mShortcutsAndWidgets.getMeasuredWidth();
+        int maxHeight = mShortcutsAndWidgets.getMeasuredHeight();
         if (mFixedWidth > 0 && mFixedHeight > 0) {
             setMeasuredDimension(maxWidth, maxHeight);
         } else {
@@ -921,13 +913,13 @@
                 (mCountX * mCellWidth);
         int left = getPaddingLeft() + (int) Math.ceil(offset / 2f);
         int top = getPaddingTop();
-        int count = getChildCount();
-        for (int i = 0; i < count; i++) {
-            View child = getChildAt(i);
-            child.layout(left, top,
-                    left + r - l,
-                    top + b - t);
-        }
+
+        mTouchFeedbackView.layout(left, top,
+                left + mTouchFeedbackView.getMeasuredWidth(),
+                top + mTouchFeedbackView.getMeasuredHeight());
+        mShortcutsAndWidgets.layout(left, top,
+                left + r - l,
+                top + b - t);
     }
 
     @Override
diff --git a/src/com/android/launcher3/ClickShadowView.java b/src/com/android/launcher3/ClickShadowView.java
new file mode 100644
index 0000000..42fafe2
--- /dev/null
+++ b/src/com/android/launcher3/ClickShadowView.java
@@ -0,0 +1,110 @@
+/*
+ * Copyright (C) 2014 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;
+
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.Paint;
+import android.view.View;
+import android.view.ViewGroup;
+
+public class ClickShadowView extends View {
+
+    private static final int SHADOW_SIZE_FACTOR = 3;
+    private static final int SHADOW_LOW_ALPHA = 30;
+    private static final int SHADOW_HIGH_ALPHA = 60;
+
+    private final Paint mPaint;
+
+    private final float mShadowOffset;
+    private final float mShadowPadding;
+
+    private Bitmap mBitmap;
+
+    public ClickShadowView(Context context) {
+        super(context);
+        mPaint = new Paint(Paint.FILTER_BITMAP_FLAG);
+        mPaint.setColor(Color.BLACK);
+
+        mShadowPadding = getResources().getDimension(R.dimen.blur_size_click_shadow);
+        mShadowOffset = getResources().getDimension(R.dimen.click_shadow_high_shift);
+    }
+
+    /**
+     * @return extra space required by the view to show the shadow.
+     */
+    public int getExtraSize() {
+        return (int) (SHADOW_SIZE_FACTOR * mShadowPadding);
+    }
+
+    /**
+     * Applies the new bitmap.
+     * @return true if the view was invalidated.
+     */
+    public boolean setBitmap(Bitmap b) {
+        if (b != mBitmap){
+            mBitmap = b;
+            invalidate();
+            return true;
+        }
+        return false;
+    }
+
+    @Override
+    protected void onDraw(Canvas canvas) {
+        if (mBitmap != null) {
+            mPaint.setAlpha(SHADOW_LOW_ALPHA);
+            canvas.drawBitmap(mBitmap, 0, 0, mPaint);
+            mPaint.setAlpha(SHADOW_HIGH_ALPHA);
+            canvas.drawBitmap(mBitmap, 0, mShadowOffset, mPaint);
+        }
+    }
+
+    public void animateShadow() {
+        setAlpha(0);
+        animate().alpha(1)
+            .setDuration(FastBitmapDrawable.CLICK_FEEDBACK_DURATION)
+            .setInterpolator(FastBitmapDrawable.CLICK_FEEDBACK_INTERPOLATOR)
+            .start();
+    }
+
+    /**
+     * Aligns the shadow with {@param view}
+     * @param viewParent immediate parent of {@param view}. It must be a sibling of this view.
+     */
+    public void alignWithIconView(BubbleTextView view, ViewGroup viewParent) {
+        float leftShift = view.getLeft() + viewParent.getLeft() - getLeft();
+        float topShift = view.getTop() + viewParent.getTop() - getTop();
+        int iconWidth = view.getRight() - view.getLeft();
+        int iconHSpace = iconWidth - view.getCompoundPaddingRight() - view.getCompoundPaddingLeft();
+        float drawableWidth = view.getIcon().getBounds().width();
+
+        setTranslationX(leftShift
+                + view.getCompoundPaddingLeft() * view.getScaleX()
+                + (iconHSpace - drawableWidth) * view.getScaleX() / 2  /* drawable gap */
+                + iconWidth * (1 - view.getScaleX()) / 2  /* gap due to scale */
+                - mShadowPadding  /* extra shadow size */
+                );
+        setTranslationY(topShift
+                + view.getPaddingTop() * view.getScaleY()  /* drawable gap */
+                + view.getHeight() * (1 - view.getScaleY()) / 2  /* gap due to scale */
+                - mShadowPadding  /* extra shadow size */
+                );
+    }
+}
diff --git a/src/com/android/launcher3/FastBitmapView.java b/src/com/android/launcher3/FastBitmapView.java
deleted file mode 100644
index 0937eb7..0000000
--- a/src/com/android/launcher3/FastBitmapView.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2014 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;
-
-import android.content.Context;
-import android.graphics.Bitmap;
-import android.graphics.Canvas;
-import android.graphics.Paint;
-import android.view.View;
-
-public class FastBitmapView extends View {
-
-    private final Paint mPaint = new Paint(Paint.FILTER_BITMAP_FLAG);
-    private Bitmap mBitmap;
-
-    public FastBitmapView(Context context) {
-        super(context);
-    }
-
-    /**
-     * Applies the new bitmap.
-     * @return true if the view was invalidated.
-     */
-    public boolean setBitmap(Bitmap b) {
-        if (b != mBitmap){
-            if (mBitmap != null) {
-                invalidate(0, 0, mBitmap.getWidth(), mBitmap.getHeight());
-            }
-            mBitmap = b;
-            if (mBitmap != null) {
-                invalidate(0, 0, mBitmap.getWidth(), mBitmap.getHeight());
-            }
-            return true;
-        }
-        return false;
-    }
-
-    @Override
-    protected void onDraw(Canvas canvas) {
-        if (mBitmap != null) {
-            canvas.drawBitmap(mBitmap, 0, 0, mPaint);
-        }
-    }
-}
diff --git a/src/com/android/launcher3/Folder.java b/src/com/android/launcher3/Folder.java
index 131633c..69b1837 100644
--- a/src/com/android/launcher3/Folder.java
+++ b/src/com/android/launcher3/Folder.java
@@ -406,9 +406,9 @@
      *
      * @return A new UserFolder.
      */
+    @SuppressLint("InflateParams")
     static Folder fromXml(Launcher launcher) {
-        return (Folder) LayoutInflater.from(launcher).inflate(R.layout.user_folder,
-                launcher.getDragLayer(), false);
+        return (Folder) launcher.getLayoutInflater().inflate(R.layout.user_folder, null);
     }
 
     /**
diff --git a/src/com/android/launcher3/FolderPagedView.java b/src/com/android/launcher3/FolderPagedView.java
index 94c016d..de30b60 100644
--- a/src/com/android/launcher3/FolderPagedView.java
+++ b/src/com/android/launcher3/FolderPagedView.java
@@ -237,13 +237,13 @@
         page.setInvertIfRtl(true);
         page.setGridSize(mGridCountX, mGridCountY);
 
-        LayoutParams lp = generateDefaultLayoutParams();
-        lp.isFullScreenPage = true;
-        addView(page, -1, lp);
+        addView(page, -1, generateDefaultLayoutParams());
         return page;
     }
 
     public void setFixedSize(int width, int height) {
+        width -= (getPaddingLeft() + getPaddingRight());
+        height -= (getPaddingTop() + getPaddingBottom());
         for (int i = getChildCount() - 1; i >= 0; i --) {
             ((CellLayout) getChildAt(i)).setFixedSize(width, height);
         }
@@ -339,11 +339,13 @@
     }
 
     public int getDesiredWidth() {
-        return getPageCount() > 0 ? getPageAt(0).getDesiredWidth() : 0;
+        return getPageCount() > 0 ?
+                (getPageAt(0).getDesiredWidth() + getPaddingLeft() + getPaddingRight()) : 0;
     }
 
     public int getDesiredHeight()  {
-        return  getPageCount() > 0 ? getPageAt(0).getDesiredHeight() : 0;
+        return  getPageCount() > 0 ?
+                (getPageAt(0).getDesiredHeight() + getPaddingTop() + getPaddingBottom()) : 0;
     }
 
     public int getItemCount() {
diff --git a/src/com/android/launcher3/HolographicOutlineHelper.java b/src/com/android/launcher3/HolographicOutlineHelper.java
index b1e0e68..4a04d03 100644
--- a/src/com/android/launcher3/HolographicOutlineHelper.java
+++ b/src/com/android/launcher3/HolographicOutlineHelper.java
@@ -17,6 +17,7 @@
 package com.android.launcher3;
 
 import android.content.Context;
+import android.content.res.Resources;
 import android.graphics.Bitmap;
 import android.graphics.BlurMaskFilter;
 import android.graphics.Canvas;
@@ -25,11 +26,16 @@
 import android.graphics.PorterDuff;
 import android.graphics.PorterDuffXfermode;
 import android.graphics.Rect;
-import android.graphics.Region.Op;
+import android.graphics.drawable.Drawable;
+import android.util.SparseArray;
 
+/**
+ * Utility class to generate shadow and outline effect, which are used for click feedback
+ * and drag-n-drop respectively.
+ */
 public class HolographicOutlineHelper {
 
-    private static final Rect sTempRect = new Rect();
+    private static HolographicOutlineHelper sInstance;
 
     private final Canvas mCanvas = new Canvas();
     private final Paint mDrawPaint = new Paint();
@@ -40,26 +46,23 @@
     private final BlurMaskFilter mThinOuterBlurMaskFilter;
     private final BlurMaskFilter mMediumInnerBlurMaskFilter;
 
-    private final BlurMaskFilter mShaowBlurMaskFilter;
-    private final int mShadowOffset;
+    private final BlurMaskFilter mShadowBlurMaskFilter;
 
-    /**
-     * Padding used when creating shadow bitmap;
-     */
-    final int shadowBitmapPadding;
-
-    static HolographicOutlineHelper INSTANCE;
+    // We have 4 different icon sizes: homescreen, hotseat, folder & all-apps
+    private final SparseArray<Bitmap> mBitmapCache = new SparseArray<>(4);
 
     private HolographicOutlineHelper(Context context) {
-        final float scale = LauncherAppState.getInstance().getScreenDensity();
+        Resources res = context.getResources();
 
-        mMediumOuterBlurMaskFilter = new BlurMaskFilter(scale * 2.0f, BlurMaskFilter.Blur.OUTER);
-        mThinOuterBlurMaskFilter = new BlurMaskFilter(scale * 1.0f, BlurMaskFilter.Blur.OUTER);
-        mMediumInnerBlurMaskFilter = new BlurMaskFilter(scale * 2.0f, BlurMaskFilter.Blur.NORMAL);
+        float mediumBlur = res.getDimension(R.dimen.blur_size_medium_outline);
+        mMediumOuterBlurMaskFilter = new BlurMaskFilter(mediumBlur, BlurMaskFilter.Blur.OUTER);
+        mMediumInnerBlurMaskFilter = new BlurMaskFilter(mediumBlur, BlurMaskFilter.Blur.NORMAL);
 
-        mShaowBlurMaskFilter = new BlurMaskFilter(scale * 4.0f, BlurMaskFilter.Blur.NORMAL);
-        mShadowOffset = (int) (scale * 2.0f);
-        shadowBitmapPadding = (int) (scale * 4.0f);
+        mThinOuterBlurMaskFilter = new BlurMaskFilter(
+                res.getDimension(R.dimen.blur_size_thin_outline), BlurMaskFilter.Blur.OUTER);
+
+        mShadowBlurMaskFilter = new BlurMaskFilter(
+                res.getDimension(R.dimen.blur_size_click_shadow), BlurMaskFilter.Blur.NORMAL);
 
         mDrawPaint.setFilterBitmap(true);
         mDrawPaint.setAntiAlias(true);
@@ -71,10 +74,10 @@
     }
 
     public static HolographicOutlineHelper obtain(Context context) {
-        if (INSTANCE == null) {
-            INSTANCE = new HolographicOutlineHelper(context);
+        if (sInstance == null) {
+            sInstance = new HolographicOutlineHelper(context);
         }
-        return INSTANCE;
+        return sInstance;
     }
 
     /**
@@ -153,51 +156,31 @@
     }
 
     Bitmap createMediumDropShadow(BubbleTextView view) {
-        final Bitmap result = Bitmap.createBitmap(
-                view.getWidth() + shadowBitmapPadding + shadowBitmapPadding,
-                view.getHeight() + shadowBitmapPadding + shadowBitmapPadding + mShadowOffset,
-                Bitmap.Config.ARGB_8888);
+        Drawable icon = view.getIcon();
+        Rect rect = icon.getBounds();
 
-        mCanvas.setBitmap(result);
+        int bitmapWidth = (int) (rect.width() * view.getScaleX());
+        int bitmapHeight = (int) (rect.height() * view.getScaleY());
 
-        final Rect clipRect = sTempRect;
-        view.getDrawingRect(sTempRect);
-        // adjust the clip rect so that we don't include the text label
-        clipRect.bottom = view.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V
-                + view.getLayout().getLineTop(0);
+        int key = (bitmapWidth << 16) | bitmapHeight;
+        Bitmap cache = mBitmapCache.get(key);
+        if (cache == null) {
+            cache = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
+            mCanvas.setBitmap(cache);
+            mBitmapCache.put(key, cache);
+        } else {
+            mCanvas.setBitmap(cache);
+            mCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
+        }
 
-        // Draw the View into the bitmap.
-        // The translate of scrollX and scrollY is necessary when drawing TextViews, because
-        // they set scrollX and scrollY to large values to achieve centered text
-        mCanvas.save();
-        mCanvas.scale(view.getScaleX(), view.getScaleY(),
-                view.getWidth() / 2 + shadowBitmapPadding,
-                view.getHeight() / 2 + shadowBitmapPadding);
-        mCanvas.translate(-view.getScrollX() + shadowBitmapPadding,
-                -view.getScrollY() + shadowBitmapPadding);
-        mCanvas.clipRect(clipRect, Op.REPLACE);
-        view.draw(mCanvas);
+        mCanvas.save(Canvas.MATRIX_SAVE_FLAG);
+        mCanvas.scale(view.getScaleX(), view.getScaleY());
+        mCanvas.translate(-rect.left, -rect.top);
+        icon.draw(mCanvas);
         mCanvas.restore();
-
-        int[] blurOffst = new int[2];
-        mBlurPaint.setMaskFilter(mShaowBlurMaskFilter);
-        Bitmap blurBitmap = result.extractAlpha(mBlurPaint, blurOffst);
-
-        mCanvas.save();
-        mCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
-        mCanvas.translate(blurOffst[0], blurOffst[1]);
-
-        mDrawPaint.setColor(Color.BLACK);
-        mDrawPaint.setAlpha(30);
-        mCanvas.drawBitmap(blurBitmap, 0, 0, mDrawPaint);
-
-        mDrawPaint.setAlpha(60);
-        mCanvas.drawBitmap(blurBitmap, 0, mShadowOffset, mDrawPaint);
-        mCanvas.restore();
-
         mCanvas.setBitmap(null);
-        blurBitmap.recycle();
 
-        return result;
+        mBlurPaint.setMaskFilter(mShadowBlurMaskFilter);
+        return cache.extractAlpha(mBlurPaint, null);
     }
 }
diff --git a/src/com/android/launcher3/LauncherModel.java b/src/com/android/launcher3/LauncherModel.java
index 658a3e2..c56022e 100644
--- a/src/com/android/launcher3/LauncherModel.java
+++ b/src/com/android/launcher3/LauncherModel.java
@@ -514,7 +514,7 @@
      * Adds the provided items to the workspace.
      */
     public void addAndBindAddedWorkspaceItems(final Context context,
-            final ArrayList<ItemInfo> workspaceApps) {
+            final ArrayList<? extends ItemInfo> workspaceApps) {
         final Callbacks callbacks = getCallback();
         if (workspaceApps.isEmpty()) {
             return;
diff --git a/src/com/android/launcher3/PagedView.java b/src/com/android/launcher3/PagedView.java
index 2ed490b..554a975 100644
--- a/src/com/android/launcher3/PagedView.java
+++ b/src/com/android/launcher3/PagedView.java
@@ -912,7 +912,8 @@
                     pageGap = getPaddingRight();
                 }
 
-                childLeft += childWidth + pageGap;
+                childLeft += childWidth + pageGap
+                        + (lp.isFullScreenPage ? 0 : (getPaddingLeft() + getPaddingRight()));
             }
         }
 
diff --git a/src/com/android/launcher3/ShortcutInfo.java b/src/com/android/launcher3/ShortcutInfo.java
index 8be4872..a9a8216 100644
--- a/src/com/android/launcher3/ShortcutInfo.java
+++ b/src/com/android/launcher3/ShortcutInfo.java
@@ -127,7 +127,7 @@
     /**
      * Refer {@link AppInfo#firstInstallTime}.
      */
-    long firstInstallTime;
+    public long firstInstallTime;
 
     /**
      * TODO move this to {@link status}
diff --git a/src/com/android/launcher3/Utilities.java b/src/com/android/launcher3/Utilities.java
index f3435fc..6734fdc 100644
--- a/src/com/android/launcher3/Utilities.java
+++ b/src/com/android/launcher3/Utilities.java
@@ -627,6 +627,10 @@
      * Non-breaking whitespaces are also removed.
      */
     public static String trim(CharSequence s) {
+        if (s == null) {
+            return null;
+        }
+
         // Just strip any sequence of whitespace or java space characters from the beginning and end
         Matcher m = sTrimPattern.matcher(s);
         return m.replaceAll("$1");
diff --git a/src/com/android/launcher3/WidgetPreviewLoader.java b/src/com/android/launcher3/WidgetPreviewLoader.java
index fe09fb6..8459673 100644
--- a/src/com/android/launcher3/WidgetPreviewLoader.java
+++ b/src/com/android/launcher3/WidgetPreviewLoader.java
@@ -88,7 +88,7 @@
      * @return a request id which can be used to cancel the request.
      */
     public PreviewLoadRequest getPreview(final Object o, int previewWidth, int previewHeight,
-            WidgetCell caller, Bitmap[] immediateResult) {
+            WidgetCell caller) {
         String size = previewWidth + "x" + previewHeight;
         WidgetCacheKey key = getObjectKey(o, size);
 
diff --git a/src/com/android/launcher3/util/ManagedProfileHeuristic.java b/src/com/android/launcher3/util/ManagedProfileHeuristic.java
index ae67ba0..94dc47f 100644
--- a/src/com/android/launcher3/util/ManagedProfileHeuristic.java
+++ b/src/com/android/launcher3/util/ManagedProfileHeuristic.java
@@ -23,8 +23,10 @@
 
 import java.util.ArrayList;
 import java.util.Collections;
+import java.util.Comparator;
 import java.util.HashSet;
 import java.util.List;
+import java.util.Set;
 
 /**
  * Handles addition of app shortcuts for managed profiles.
@@ -62,8 +64,8 @@
     private final long mUserCreationTime;
     private final String mPackageSetKey;
 
-    private ArrayList<ItemInfo> mHomescreenApps;
-    private ArrayList<ItemInfo> mWorkFolderApps;
+    private ArrayList<ShortcutInfo> mHomescreenApps;
+    private ArrayList<ShortcutInfo> mWorkFolderApps;
 
     private ManagedProfileHeuristic(Context context, UserHandleCompat user) {
         mContext = context;
@@ -84,9 +86,12 @@
      * workfolder.
      */
     public void processUserApps(List<LauncherActivityInfoCompat> apps) {
-        mHomescreenApps = new ArrayList<ItemInfo>();
-        mWorkFolderApps = new ArrayList<ItemInfo>();
-        HashSet<String> packageSet = getPackageSet();
+        mHomescreenApps = new ArrayList<>();
+        mWorkFolderApps = new ArrayList<>();
+
+        HashSet<String> packageSet = new HashSet<>();
+        final boolean userAppsExisted = getUserApps(packageSet);
+
         boolean newPackageAdded = false;
 
         for (LauncherActivityInfoCompat info : apps) {
@@ -107,12 +112,15 @@
 
         if (newPackageAdded) {
             mPrefs.edit().putStringSet(mPackageSetKey, packageSet).apply();
-            finalizeAdditions();
+            // Do not add shortcuts on the homescreen for the first time. This prevents the launcher
+            // getting filled with the managed user apps, when it start with a fresh DB (or after
+            // a very long time).
+            finalizeAdditions(userAppsExisted);
         }
     }
 
     private void markForAddition(LauncherActivityInfoCompat info, long installTime) {
-        ArrayList<ItemInfo> targetList =
+        ArrayList<ShortcutInfo> targetList =
                 (installTime <= mUserCreationTime + AUTO_ADD_TO_FOLDER_DURATION) ?
                         mWorkFolderApps : mHomescreenApps;
         targetList.add(ShortcutInfo.fromActivityInfo(info, mContext));
@@ -125,6 +133,13 @@
         if (mWorkFolderApps.isEmpty()) {
             return;
         }
+        Collections.sort(mWorkFolderApps, new Comparator<ShortcutInfo>() {
+
+            @Override
+            public int compare(ShortcutInfo lhs, ShortcutInfo rhs) {
+                return Long.compare(lhs.firstInstallTime, rhs.firstInstallTime);
+            }
+        });
 
         // Try to get a work folder.
         String folderIdKey = USER_FOLDER_ID_PREFIX + mUserSerial;
@@ -139,14 +154,14 @@
             }
             saveWorkFolderShortcuts(folderId, workFolder.contents.size());
 
-            final ArrayList<ItemInfo> shortcuts = mWorkFolderApps;
+            final ArrayList<ShortcutInfo> shortcuts = mWorkFolderApps;
             // FolderInfo could already be bound. We need to add shortcuts on the UI thread.
             new MainThreadExecutor().execute(new Runnable() {
 
                 @Override
                 public void run() {
-                    for (ItemInfo info : shortcuts) {
-                        workFolder.add((ShortcutInfo) info);
+                    for (ShortcutInfo info : shortcuts) {
+                        workFolder.add(info);
                     }
                 }
             });
@@ -157,8 +172,8 @@
             workFolder.setOption(FolderInfo.FLAG_WORK_FOLDER, true, null);
 
             // Add all shortcuts before adding it to the UI, as an empty folder might get deleted.
-            for (ItemInfo info : mWorkFolderApps) {
-                workFolder.add((ShortcutInfo) info);
+            for (ShortcutInfo info : mWorkFolderApps) {
+                workFolder.add(info);
             }
 
             // Add the item to home screen and DB. This also generates an item id synchronously.
@@ -184,10 +199,10 @@
     /**
      * Adds and binds all shortcuts marked for addition.
      */
-    private void finalizeAdditions() {
+    private void finalizeAdditions(boolean addHomeScreenShortcuts) {
         finalizeWorkFolder();
 
-        if (!mHomescreenApps.isEmpty()) {
+        if (addHomeScreenShortcuts && !mHomescreenApps.isEmpty()) {
             mModel.addAndBindAddedWorkspaceItems(mContext, mHomescreenApps);
         }
     }
@@ -196,9 +211,12 @@
      * Updates the list of installed apps and adds any new icons on homescreen or work folder.
      */
     public void processPackageAdd(String[] packages) {
-        mHomescreenApps = new ArrayList<ItemInfo>();
-        mWorkFolderApps = new ArrayList<ItemInfo>();
-        HashSet<String> packageSet = getPackageSet();
+        mHomescreenApps = new ArrayList<>();
+        mWorkFolderApps = new ArrayList<>();
+
+        HashSet<String> packageSet = new HashSet<>();
+        final boolean userAppsExisted = getUserApps(packageSet);
+
         boolean newPackageAdded = false;
         long installTime = System.currentTimeMillis();
         LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(mContext);
@@ -218,7 +236,7 @@
 
         if (newPackageAdded) {
             mPrefs.edit().putStringSet(mPackageSetKey, packageSet).apply();
-            finalizeAdditions();
+            finalizeAdditions(userAppsExisted);
         }
     }
 
@@ -226,7 +244,8 @@
      * Updates the list of installed packages for the user.
      */
     public void processPackageRemoved(String[] packages) {
-        HashSet<String> packageSet = getPackageSet();
+        HashSet<String> packageSet = new HashSet<String>();
+        getUserApps(packageSet);
         boolean packageRemoved = false;
 
         for (String packageName : packages) {
@@ -240,9 +259,18 @@
         }
     }
 
-    @SuppressWarnings("unchecked")
-    private HashSet<String> getPackageSet() {
-        return new HashSet<String>(mPrefs.getStringSet(mPackageSetKey, Collections.EMPTY_SET));
+    /**
+     * Reads the list of user apps which have already been processed.
+     * @return false if the list didn't exist, true otherwise
+     */
+    private boolean getUserApps(HashSet<String> outExistingApps) {
+        Set<String> userApps = mPrefs.getStringSet(mPackageSetKey, null);
+        if (userApps == null) {
+            return false;
+        } else {
+            outExistingApps.addAll(userApps);
+            return true;
+        }
     }
 
     /**
diff --git a/src/com/android/launcher3/widget/WidgetCell.java b/src/com/android/launcher3/widget/WidgetCell.java
index aade85f..a34e716 100644
--- a/src/com/android/launcher3/widget/WidgetCell.java
+++ b/src/com/android/launcher3/widget/WidgetCell.java
@@ -143,8 +143,8 @@
         }
         // TODO(hyunyoungs): setup a cache for these labels.
         mWidgetName.setText(AppWidgetManagerCompat.getInstance(getContext()).loadLabel(info));
-        int hSpan = Math.min(info.spanX, (int) grid.numColumns);
-        int vSpan = Math.min(info.spanY, (int) grid.numRows);
+        int hSpan = Math.min(info.spanX, grid.numColumns);
+        int vSpan = Math.min(info.spanY, grid.numRows);
         mWidgetDims.setText(String.format(mDimensionsFormatString, hSpan, vSpan));
         mWidgetPreviewLoader = loader;
     }
@@ -199,12 +199,7 @@
             Log.d(TAG, String.format("[tag=%s] ensurePreview (%d, %d):",
                     getTagToString(), size[0], size[1]));
         }
-        Bitmap[] immediateResult = new Bitmap[1];
-        mActiveRequest = mWidgetPreviewLoader.getPreview(mInfo, size[0], size[1], this,
-                immediateResult);
-        if (immediateResult[0] != null) {
-            applyPreview(immediateResult[0]);
-        }
+        mActiveRequest = mWidgetPreviewLoader.getPreview(mInfo, size[0], size[1], this);
     }
 
     @Override
diff --git a/src/com/android/launcher3/widget/WidgetsListAdapter.java b/src/com/android/launcher3/widget/WidgetsListAdapter.java
index 2dbe7a5..b8124d6 100644
--- a/src/com/android/launcher3/widget/WidgetsListAdapter.java
+++ b/src/com/android/launcher3/widget/WidgetsListAdapter.java
@@ -109,8 +109,7 @@
 
         if (diff > 0) {
             for (int i = 0; i < diff; i++) {
-                WidgetCell widget = new WidgetCell(mContext);
-                widget = (WidgetCell) mLayoutInflater.inflate(
+                WidgetCell widget = (WidgetCell) mLayoutInflater.inflate(
                         R.layout.widget_cell, row, false);
 
                 // set up touch.
@@ -135,11 +134,11 @@
         tv.applyFromPackageItemInfo(infoOut);
 
         // Bind the view in the widget horizontal tray region.
+        if (getWidgetPreviewLoader() == null) {
+            return;
+        }
         for (int i=0; i < infoList.size(); i++) {
             WidgetCell widget = (WidgetCell) row.getChildAt(i);
-            if (getWidgetPreviewLoader() == null) {
-                return;
-            }
             if (infoList.get(i) instanceof LauncherAppWidgetProviderInfo) {
                 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) infoList.get(i);
                 PendingAddWidgetInfo pawi = new PendingAddWidgetInfo(info, null);