Workspace.java revision 0f76b56865bd7b63bd21d53aaac47300396aa38f
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.launcher3;
18
19import android.animation.Animator;
20import android.animation.AnimatorListenerAdapter;
21import android.animation.AnimatorSet;
22import android.animation.LayoutTransition;
23import android.animation.ObjectAnimator;
24import android.animation.PropertyValuesHolder;
25import android.animation.ValueAnimator;
26import android.animation.ValueAnimator.AnimatorUpdateListener;
27import android.annotation.SuppressLint;
28import android.app.WallpaperManager;
29import android.appwidget.AppWidgetHostView;
30import android.appwidget.AppWidgetProviderInfo;
31import android.content.Context;
32import android.content.res.Resources;
33import android.graphics.Bitmap;
34import android.graphics.Canvas;
35import android.graphics.Point;
36import android.graphics.Rect;
37import android.graphics.drawable.Drawable;
38import android.os.Handler;
39import android.os.IBinder;
40import android.os.Parcelable;
41import android.util.AttributeSet;
42import android.util.Log;
43import android.util.Property;
44import android.util.SparseArray;
45import android.view.MotionEvent;
46import android.view.View;
47import android.view.ViewDebug;
48import android.view.ViewGroup;
49import android.view.accessibility.AccessibilityManager;
50import android.view.animation.DecelerateInterpolator;
51import android.view.animation.Interpolator;
52import android.widget.TextView;
53import android.widget.Toast;
54
55import com.android.launcher3.Launcher.CustomContentCallbacks;
56import com.android.launcher3.Launcher.LauncherOverlay;
57import com.android.launcher3.UninstallDropTarget.DropTargetSource;
58import com.android.launcher3.accessibility.AccessibleDragListenerAdapter;
59import com.android.launcher3.accessibility.OverviewAccessibilityDelegate;
60import com.android.launcher3.accessibility.OverviewScreenAccessibilityDelegate;
61import com.android.launcher3.accessibility.WorkspaceAccessibilityHelper;
62import com.android.launcher3.anim.AnimationLayerSet;
63import com.android.launcher3.compat.AppWidgetManagerCompat;
64import com.android.launcher3.compat.UserHandleCompat;
65import com.android.launcher3.config.FeatureFlags;
66import com.android.launcher3.config.ProviderConfig;
67import com.android.launcher3.dragndrop.DragController;
68import com.android.launcher3.dragndrop.DragLayer;
69import com.android.launcher3.dragndrop.DragOptions;
70import com.android.launcher3.dragndrop.DragScroller;
71import com.android.launcher3.dragndrop.DragView;
72import com.android.launcher3.dragndrop.SpringLoadedDragController;
73import com.android.launcher3.folder.Folder;
74import com.android.launcher3.folder.FolderIcon;
75import com.android.launcher3.graphics.DragPreviewProvider;
76import com.android.launcher3.shortcuts.DeepShortcutsContainer;
77import com.android.launcher3.userevent.nano.LauncherLogProto;
78import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
79import com.android.launcher3.util.ItemInfoMatcher;
80import com.android.launcher3.util.LongArrayMap;
81import com.android.launcher3.util.MultiStateAlphaController;
82import com.android.launcher3.util.Thunk;
83import com.android.launcher3.util.VerticalFlingDetector;
84import com.android.launcher3.util.WallpaperOffsetInterpolator;
85import com.android.launcher3.widget.PendingAddShortcutInfo;
86import com.android.launcher3.widget.PendingAddWidgetInfo;
87
88import java.util.ArrayList;
89import java.util.HashSet;
90
91/**
92 * The workspace is a wide area with a wallpaper and a finite number of pages.
93 * Each page contains a number of icons, folders or widgets the user can
94 * interact with. A workspace is meant to be used with a fixed width only.
95 */
96public class Workspace extends PagedView
97        implements DropTarget, DragSource, DragScroller, View.OnTouchListener,
98        DragController.DragListener, ViewGroup.OnHierarchyChangeListener,
99        Insettable, DropTargetSource {
100    private static final String TAG = "Launcher.Workspace";
101
102    /** The value that {@link #mTransitionProgress} must be greater than for
103     * {@link #transitionStateShouldAllowDrop()} to return true. */
104    private static final float ALLOW_DROP_TRANSITION_PROGRESS = 0.25f;
105
106    /** The value that {@link #mTransitionProgress} must be greater than for
107     * {@link #isFinishedSwitchingState()} ()} to return true. */
108    private static final float FINISHED_SWITCHING_STATE_TRANSITION_PROGRESS = 0.5f;
109
110    private static boolean ENFORCE_DRAG_EVENT_ORDER = false;
111
112    private static final int SNAP_OFF_EMPTY_SCREEN_DURATION = 400;
113    private static final int FADE_EMPTY_SCREEN_DURATION = 150;
114
115    private static final int ADJACENT_SCREEN_DROP_DURATION = 300;
116
117    private static final boolean MAP_NO_RECURSE = false;
118    private static final boolean MAP_RECURSE = true;
119
120    // The screen id used for the empty screen always present to the right.
121    public static final long EXTRA_EMPTY_SCREEN_ID = -201;
122    // The is the first screen. It is always present, even if its empty.
123    public static final long FIRST_SCREEN_ID = 0;
124
125    private final static long CUSTOM_CONTENT_SCREEN_ID = -301;
126
127    private static final long CUSTOM_CONTENT_GESTURE_DELAY = 200;
128    private long mTouchDownTime = -1;
129    private long mCustomContentShowTime = -1;
130
131    private LayoutTransition mLayoutTransition;
132    @Thunk final WallpaperManager mWallpaperManager;
133
134    private ShortcutAndWidgetContainer mDragSourceInternal;
135
136    @Thunk LongArrayMap<CellLayout> mWorkspaceScreens = new LongArrayMap<>();
137    @Thunk ArrayList<Long> mScreenOrder = new ArrayList<Long>();
138
139    @Thunk Runnable mRemoveEmptyScreenRunnable;
140    @Thunk boolean mDeferRemoveExtraEmptyScreen = false;
141
142    /**
143     * CellInfo for the cell that is currently being dragged
144     */
145    private CellLayout.CellInfo mDragInfo;
146
147    /**
148     * Target drop area calculated during last acceptDrop call.
149     */
150    @Thunk int[] mTargetCell = new int[2];
151    private int mDragOverX = -1;
152    private int mDragOverY = -1;
153
154    CustomContentCallbacks mCustomContentCallbacks;
155    boolean mCustomContentShowing;
156    private float mLastCustomContentScrollProgress = -1f;
157    private String mCustomContentDescription = "";
158
159    /**
160     * The CellLayout that is currently being dragged over
161     */
162    @Thunk CellLayout mDragTargetLayout = null;
163    /**
164     * The CellLayout that we will show as highlighted
165     */
166    private CellLayout mDragOverlappingLayout = null;
167
168    /**
169     * The CellLayout which will be dropped to
170     */
171    private CellLayout mDropToLayout = null;
172
173    @Thunk Launcher mLauncher;
174    @Thunk IconCache mIconCache;
175    @Thunk DragController mDragController;
176
177    // These are temporary variables to prevent having to allocate a new object just to
178    // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
179    private static final Rect sTempRect = new Rect();
180
181    private final int[] mTempXY = new int[2];
182    @Thunk float[] mDragViewVisualCenter = new float[2];
183    private float[] mTempCellLayoutCenterCoordinates = new float[2];
184
185    private SpringLoadedDragController mSpringLoadedDragController;
186    private float mOverviewModeShrinkFactor;
187
188    // State variable that indicates whether the pages are small (ie when you're
189    // in all apps or customize mode)
190
191    public enum State {
192        NORMAL          (false, false, LauncherLogProto.WORKSPACE),
193        NORMAL_HIDDEN   (false, false, LauncherLogProto.ALLAPPS),
194        SPRING_LOADED   (false, true, LauncherLogProto.WORKSPACE),
195        OVERVIEW        (true, true, LauncherLogProto.OVERVIEW),
196        OVERVIEW_HIDDEN (true, false, LauncherLogProto.WIDGETS);
197
198        public final boolean shouldUpdateWidget;
199        public final boolean hasMultipleVisiblePages;
200        public final int containerType;
201
202        State(boolean shouldUpdateWidget, boolean hasMultipleVisiblePages, int containerType) {
203            this.shouldUpdateWidget = shouldUpdateWidget;
204            this.hasMultipleVisiblePages = hasMultipleVisiblePages;
205            this.containerType = containerType;
206        }
207    }
208
209    // Direction used for moving the workspace and hotseat UI
210    public enum Direction {
211        X  (TRANSLATION_X),
212        Y  (TRANSLATION_Y);
213
214        private final Property<View, Float> viewProperty;
215
216        Direction(Property<View, Float> viewProperty) {
217            this.viewProperty = viewProperty;
218        }
219    }
220
221    private static final int HOTSEAT_STATE_ALPHA_INDEX = 2;
222
223    /**
224     * These values correspond to {@link Direction#X} & {@link Direction#Y}
225     */
226    private float[] mPageAlpha = new float[] {1, 1};
227    /**
228     * Hotseat alpha can be changed when moving horizontally, vertically, changing states.
229     * The values correspond to {@link Direction#X}, {@link Direction#Y} &
230     * {@link #HOTSEAT_STATE_ALPHA_INDEX} respectively.
231     */
232    private float[] mHotseatAlpha = new float[] {1, 1, 1};
233
234    public static final int QSB_ALPHA_INDEX_STATE_CHANGE = 0;
235    public static final int QSB_ALPHA_INDEX_Y_TRANSLATION = 1;
236    public static final int QSB_ALPHA_INDEX_PAGE_SCROLL = 2;
237    public static final int QSB_ALPHA_INDEX_OVERLAY_SCROLL = 3;
238
239
240    MultiStateAlphaController mQsbAlphaController;
241
242    @ViewDebug.ExportedProperty(category = "launcher")
243    private State mState = State.NORMAL;
244    private boolean mIsSwitchingState = false;
245
246    boolean mAnimatingViewIntoPlace = false;
247    boolean mChildrenLayersEnabled = true;
248
249    private boolean mStripScreensOnPageStopMoving = false;
250
251    /** Is the user is dragging an item near the edge of a page? */
252    private boolean mInScrollArea = false;
253
254    private DragPreviewProvider mOutlineProvider = null;
255    public static final int DRAG_BITMAP_PADDING = DragPreviewProvider.DRAG_BITMAP_PADDING;
256    private boolean mWorkspaceFadeInAdjacentScreens;
257
258    final WallpaperOffsetInterpolator mWallpaperOffset;
259    private boolean mUnlockWallpaperFromDefaultPageOnLayout;
260
261    @Thunk Runnable mDelayedResizeRunnable;
262    private Runnable mDelayedSnapToPageRunnable;
263
264    // Variables relating to the creation of user folders by hovering shortcuts over shortcuts
265    private static final int FOLDER_CREATION_TIMEOUT = 0;
266    public static final int REORDER_TIMEOUT = 350;
267    private final Alarm mFolderCreationAlarm = new Alarm();
268    private final Alarm mReorderAlarm = new Alarm();
269    private FolderIcon.PreviewBackground mFolderCreateBg;
270    private FolderIcon mDragOverFolderIcon = null;
271    private boolean mCreateUserFolderOnDrop = false;
272    private boolean mAddToExistingFolderOnDrop = false;
273    private float mMaxDistanceForFolderCreation;
274
275    private final Canvas mCanvas = new Canvas();
276
277    // Variables relating to touch disambiguation (scrolling workspace vs. scrolling a widget)
278    private float mXDown;
279    private float mYDown;
280    final static float START_DAMPING_TOUCH_SLOP_ANGLE = (float) Math.PI / 6;
281    final static float MAX_SWIPE_ANGLE = (float) Math.PI / 3;
282    final static float TOUCH_SLOP_DAMPING_FACTOR = 4;
283
284    // Relating to the animation of items being dropped externally
285    public static final int ANIMATE_INTO_POSITION_AND_DISAPPEAR = 0;
286    public static final int ANIMATE_INTO_POSITION_AND_REMAIN = 1;
287    public static final int ANIMATE_INTO_POSITION_AND_RESIZE = 2;
288    public static final int COMPLETE_TWO_STAGE_WIDGET_DROP_ANIMATION = 3;
289    public static final int CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION = 4;
290
291    // Related to dragging, folder creation and reordering
292    private static final int DRAG_MODE_NONE = 0;
293    private static final int DRAG_MODE_CREATE_FOLDER = 1;
294    private static final int DRAG_MODE_ADD_TO_FOLDER = 2;
295    private static final int DRAG_MODE_REORDER = 3;
296    private int mDragMode = DRAG_MODE_NONE;
297    @Thunk int mLastReorderX = -1;
298    @Thunk int mLastReorderY = -1;
299
300    private SparseArray<Parcelable> mSavedStates;
301    private final ArrayList<Integer> mRestoredPages = new ArrayList<Integer>();
302
303    private float mCurrentScale;
304    private float mTransitionProgress;
305
306    @Thunk Runnable mDeferredAction;
307    private boolean mDeferDropAfterUninstall;
308    private boolean mUninstallSuccessful;
309
310    // State related to Launcher Overlay
311    LauncherOverlay mLauncherOverlay;
312    boolean mScrollInteractionBegan;
313    boolean mStartedSendingScrollEvents;
314    float mLastOverlayScroll = 0;
315    // Total over scrollX in the overlay direction.
316    private int mUnboundedScrollX;
317    private boolean mForceDrawAdjacentPages = false;
318    // Total over scrollX in the overlay direction.
319    private float mOverlayTranslation;
320    private int mFirstPageScrollX;
321    private boolean mIgnoreQsbScroll;
322
323    // Handles workspace state transitions
324    private WorkspaceStateTransitionAnimation mStateTransitionAnimation;
325
326    private AccessibilityDelegate mPagesAccessibilityDelegate;
327    private OnStateChangeListener mOnStateChangeListener;
328
329    /**
330     * Used to inflate the Workspace from XML.
331     *
332     * @param context The application's context.
333     * @param attrs The attributes set containing the Workspace's customization values.
334     */
335    public Workspace(Context context, AttributeSet attrs) {
336        this(context, attrs, 0);
337    }
338
339    /**
340     * Used to inflate the Workspace from XML.
341     *
342     * @param context The application's context.
343     * @param attrs The attributes set containing the Workspace's customization values.
344     * @param defStyle Unused.
345     */
346    public Workspace(Context context, AttributeSet attrs, int defStyle) {
347        super(context, attrs, defStyle);
348
349        mLauncher = Launcher.getLauncher(context);
350        mStateTransitionAnimation = new WorkspaceStateTransitionAnimation(mLauncher, this);
351        final Resources res = getResources();
352        DeviceProfile grid = mLauncher.getDeviceProfile();
353        mWorkspaceFadeInAdjacentScreens = grid.shouldFadeAdjacentWorkspaceScreens();
354        mWallpaperManager = WallpaperManager.getInstance(context);
355
356        mWallpaperOffset = new WallpaperOffsetInterpolator(this);
357        mOverviewModeShrinkFactor =
358                res.getInteger(R.integer.config_workspaceOverviewShrinkPercentage) / 100f;
359
360        setOnHierarchyChangeListener(this);
361        setHapticFeedbackEnabled(false);
362
363        initWorkspace();
364
365        // Disable multitouch across the workspace/all apps/customize tray
366        setMotionEventSplittingEnabled(true);
367    }
368
369    @Override
370    public void setInsets(Rect insets) {
371        mInsets.set(insets);
372
373        CellLayout customScreen = getScreenWithId(CUSTOM_CONTENT_SCREEN_ID);
374        if (customScreen != null) {
375            View customContent = customScreen.getShortcutsAndWidgets().getChildAt(0);
376            if (customContent instanceof Insettable) {
377                ((Insettable) customContent).setInsets(mInsets);
378            }
379        }
380    }
381
382    public void setOnStateChangeListener(OnStateChangeListener listener) {
383        mOnStateChangeListener = listener;
384    }
385
386    // estimate the size of a widget with spans hSpan, vSpan. return MAX_VALUE for each
387    // dimension if unsuccessful
388    public int[] estimateItemSize(ItemInfo itemInfo, boolean springLoaded) {
389        float shrinkFactor = mLauncher.getDeviceProfile().workspaceSpringLoadShrinkFactor;
390        int[] size = new int[2];
391        if (getChildCount() > 0) {
392            // Use the first non-custom page to estimate the child position
393            CellLayout cl = (CellLayout) getChildAt(numCustomPages());
394            Rect r = estimateItemPosition(cl, 0, 0, itemInfo.spanX, itemInfo.spanY);
395            size[0] = r.width();
396            size[1] = r.height();
397            if (springLoaded) {
398                size[0] *= shrinkFactor;
399                size[1] *= shrinkFactor;
400            }
401            return size;
402        } else {
403            size[0] = Integer.MAX_VALUE;
404            size[1] = Integer.MAX_VALUE;
405            return size;
406        }
407    }
408
409    public Rect estimateItemPosition(CellLayout cl, int hCell, int vCell, int hSpan, int vSpan) {
410        Rect r = new Rect();
411        cl.cellToRect(hCell, vCell, hSpan, vSpan, r);
412        return r;
413    }
414
415    @Override
416    public void onDragStart(DropTarget.DragObject dragObject, DragOptions options) {
417        if (ENFORCE_DRAG_EVENT_ORDER) {
418            enforceDragParity("onDragStart", 0, 0);
419        }
420
421        if (mDragInfo != null && mDragInfo.cell != null) {
422            CellLayout layout = (CellLayout) mDragInfo.cell.getParent().getParent();
423            layout.markCellsAsUnoccupiedForView(mDragInfo.cell);
424        }
425
426        if (mOutlineProvider != null) {
427            // The outline is used to visualize where the item will land if dropped
428            mOutlineProvider.generateDragOutline(mCanvas);
429        }
430
431        updateChildrenLayersEnabled(false);
432        mLauncher.onDragStarted();
433        mLauncher.lockScreenOrientation();
434        mLauncher.onInteractionBegin();
435        // Prevent any Un/InstallShortcutReceivers from updating the db while we are dragging
436        InstallShortcutReceiver.enableInstallQueue();
437
438        // Do not add a new page if it is a accessible drag which was not started by the workspace.
439        // We do not support accessibility drag from other sources and instead provide a direct
440        // action for move/add to homescreen.
441        // When a accessible drag is started by the folder, we only allow rearranging withing the
442        // folder.
443        boolean addNewPage = !(options.isAccessibleDrag && dragObject.dragSource != this);
444
445        if (addNewPage) {
446            mDeferRemoveExtraEmptyScreen = false;
447            addExtraEmptyScreenOnDrag();
448
449            if (dragObject.dragInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET
450                    && dragObject.dragSource != this) {
451                // When dragging a widget from different source, move to a page which has
452                // enough space to place this widget (after rearranging/resizing). We special case
453                // widgets as they cannot be placed inside a folder.
454                // Start at the current page and search right (on LTR) until finding a page with
455                // enough space. Since an empty screen is the furthest right, a page must be found.
456                int currentPage = getPageNearestToCenterOfScreen();
457                for (int pageIndex = currentPage; pageIndex < getPageCount(); pageIndex++) {
458                    CellLayout page = (CellLayout) getPageAt(pageIndex);
459                    if (page.hasReorderSolution(dragObject.dragInfo)) {
460                        setCurrentPage(pageIndex);
461                        break;
462                    }
463                }
464            }
465        }
466
467        if (!FeatureFlags.LAUNCHER3_LEGACY_WORKSPACE_DND) {
468            // Always enter the spring loaded mode
469            mLauncher.enterSpringLoadedDragMode();
470        }
471    }
472
473    public void deferRemoveExtraEmptyScreen() {
474        mDeferRemoveExtraEmptyScreen = true;
475    }
476
477    @Override
478    public void onDragEnd() {
479        if (ENFORCE_DRAG_EVENT_ORDER) {
480            enforceDragParity("onDragEnd", 0, 0);
481        }
482
483        if (!mDeferRemoveExtraEmptyScreen) {
484            removeExtraEmptyScreen(true, mDragSourceInternal != null);
485        }
486
487        updateChildrenLayersEnabled(false);
488        mLauncher.unlockScreenOrientation(false);
489
490        // Re-enable any Un/InstallShortcutReceiver and now process any queued items
491        InstallShortcutReceiver.disableAndFlushInstallQueue(getContext());
492
493        mOutlineProvider = null;
494        mDragInfo = null;
495        mDragSourceInternal = null;
496        mLauncher.onInteractionEnd();
497    }
498
499    /**
500     * Initializes various states for this workspace.
501     */
502    protected void initWorkspace() {
503        mCurrentPage = getDefaultPage();
504        LauncherAppState app = LauncherAppState.getInstance();
505        DeviceProfile grid = mLauncher.getDeviceProfile();
506        mIconCache = app.getIconCache();
507        setWillNotDraw(false);
508        setClipChildren(false);
509        setClipToPadding(false);
510
511        setMinScale(mOverviewModeShrinkFactor);
512        setupLayoutTransition();
513
514        mMaxDistanceForFolderCreation = (0.55f * grid.iconSizePx);
515
516        // Set the wallpaper dimensions when Launcher starts up
517        setWallpaperDimension();
518
519        setEdgeGlowColor(getResources().getColor(R.color.workspace_edge_effect_color));
520    }
521
522    @Override
523    public void initParentViews(View parent) {
524        super.initParentViews(parent);
525        mPageIndicator.setAccessibilityDelegate(new OverviewAccessibilityDelegate());
526        mQsbAlphaController = new MultiStateAlphaController(mLauncher.getQsbContainer(), 4);
527    }
528
529    private int getDefaultPage() {
530        return numCustomPages();
531    }
532
533    private void setupLayoutTransition() {
534        // We want to show layout transitions when pages are deleted, to close the gap.
535        mLayoutTransition = new LayoutTransition();
536        mLayoutTransition.enableTransitionType(LayoutTransition.DISAPPEARING);
537        mLayoutTransition.enableTransitionType(LayoutTransition.CHANGE_DISAPPEARING);
538        mLayoutTransition.disableTransitionType(LayoutTransition.APPEARING);
539        mLayoutTransition.disableTransitionType(LayoutTransition.CHANGE_APPEARING);
540        setLayoutTransition(mLayoutTransition);
541    }
542
543    void enableLayoutTransitions() {
544        setLayoutTransition(mLayoutTransition);
545    }
546    void disableLayoutTransitions() {
547        setLayoutTransition(null);
548    }
549
550    @Override
551    public void onChildViewAdded(View parent, View child) {
552        if (!(child instanceof CellLayout)) {
553            throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
554        }
555        CellLayout cl = ((CellLayout) child);
556        cl.setOnInterceptTouchListener(this);
557        cl.setClickable(true);
558        cl.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
559        super.onChildViewAdded(parent, child);
560    }
561
562    boolean isTouchActive() {
563        return mTouchState != TOUCH_STATE_REST;
564    }
565
566    private int getEmbeddedQsbId() {
567        return mLauncher.getDeviceProfile().isVerticalBarLayout()
568                ? R.id.qsb_container : R.id.workspace_blocked_row;
569    }
570
571    /**
572     * Initializes and binds the first page
573     * @param qsb an existing qsb to recycle or null.
574     */
575    public void bindAndInitFirstWorkspaceScreen(View qsb) {
576        if (!FeatureFlags.QSB_ON_FIRST_SCREEN) {
577            return;
578        }
579        // Add the first page
580        CellLayout firstPage = insertNewWorkspaceScreen(Workspace.FIRST_SCREEN_ID, 0);
581        if (FeatureFlags.PULLDOWN_SEARCH) {
582            firstPage.setOnTouchListener(new VerticalFlingDetector(mLauncher) {
583                // detect fling when touch started from empty space
584                @Override
585                public boolean onTouch(View v, MotionEvent ev) {
586                    if (workspaceInModalState()) return false;
587                    if (shouldConsumeTouch(v)) return true;
588                    if (super.onTouch(v, ev)) {
589                        mLauncher.startSearch("", false, null, false);
590                        return true;
591                    }
592                    return false;
593                }
594            });
595            firstPage.setOnInterceptTouchListener(new VerticalFlingDetector(mLauncher) {
596                // detect fling when touch started from on top of the icons
597                @Override
598                public boolean onTouch(View v, MotionEvent ev) {
599                    if (shouldConsumeTouch(v)) return true;
600                    if (super.onTouch(v, ev)) {
601                        mLauncher.startSearch("", false, null, false);
602                        return true;
603                    }
604                    return false;
605                }
606            });
607        }
608        // Always add a QSB on the first screen.
609        if (qsb == null) {
610            // In transposed layout, we add the QSB in the Grid. As workspace does not touch the
611            // edges, we do not need a full width QSB.
612            qsb = mLauncher.getLayoutInflater().inflate(
613                    mLauncher.getDeviceProfile().isVerticalBarLayout()
614                            ? R.layout.qsb_container : R.layout.qsb_blocker_view,
615                    firstPage, false);
616        }
617
618        CellLayout.LayoutParams lp = new CellLayout.LayoutParams(0, 0, firstPage.getCountX(), 1);
619        lp.canReorder = false;
620        if (!firstPage.addViewToCellLayout(qsb, 0, getEmbeddedQsbId(), lp, true)) {
621            Log.e(TAG, "Failed to add to item at (0, 0) to CellLayout");
622        }
623    }
624
625    @Override
626    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
627        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
628
629        // Update the QSB to match the cell height. This is treating the QSB essentially as a child
630        // of workspace despite that it's not a true child.
631        // Note that it relies on the strict ordering of measuring the workspace before the QSB
632        // at the dragLayer level.
633        if (getChildCount() > 0) {
634            CellLayout firstPage = (CellLayout) getChildAt(0);
635            int cellHeight = firstPage.getCellHeight();
636
637            View qsbContainer = mLauncher.getQsbContainer();
638            ViewGroup.LayoutParams lp = qsbContainer.getLayoutParams();
639            if (cellHeight > 0 && lp.height != cellHeight) {
640                lp.height = cellHeight;
641                qsbContainer.setLayoutParams(lp);
642            }
643        }
644    }
645
646    public void removeAllWorkspaceScreens() {
647        // Disable all layout transitions before removing all pages to ensure that we don't get the
648        // transition animations competing with us changing the scroll when we add pages or the
649        // custom content screen
650        disableLayoutTransitions();
651
652        // Since we increment the current page when we call addCustomContentPage via bindScreens
653        // (and other places), we need to adjust the current page back when we clear the pages
654        if (hasCustomContent()) {
655            removeCustomContentPage();
656        }
657
658        // Recycle the QSB widget
659        View qsb = findViewById(getEmbeddedQsbId());
660        if (qsb != null) {
661            ((ViewGroup) qsb.getParent()).removeView(qsb);
662        }
663
664        // Remove the pages and clear the screen models
665        removeAllViews();
666        mScreenOrder.clear();
667        mWorkspaceScreens.clear();
668
669        // Ensure that the first page is always present
670        bindAndInitFirstWorkspaceScreen(qsb);
671
672        // Re-enable the layout transitions
673        enableLayoutTransitions();
674    }
675
676    public void insertNewWorkspaceScreenBeforeEmptyScreen(long screenId) {
677        // Find the index to insert this view into.  If the empty screen exists, then
678        // insert it before that.
679        int insertIndex = mScreenOrder.indexOf(EXTRA_EMPTY_SCREEN_ID);
680        if (insertIndex < 0) {
681            insertIndex = mScreenOrder.size();
682        }
683        insertNewWorkspaceScreen(screenId, insertIndex);
684    }
685
686    public void insertNewWorkspaceScreen(long screenId) {
687        insertNewWorkspaceScreen(screenId, getChildCount());
688    }
689
690    public CellLayout insertNewWorkspaceScreen(long screenId, int insertIndex) {
691        if (mWorkspaceScreens.containsKey(screenId)) {
692            throw new RuntimeException("Screen id " + screenId + " already exists!");
693        }
694
695        // Inflate the cell layout, but do not add it automatically so that we can get the newly
696        // created CellLayout.
697        CellLayout newScreen = (CellLayout) mLauncher.getLayoutInflater().inflate(
698                        R.layout.workspace_screen, this, false /* attachToRoot */);
699        newScreen.setOnLongClickListener(mLongClickListener);
700        newScreen.setOnClickListener(mLauncher);
701        newScreen.setSoundEffectsEnabled(false);
702        mWorkspaceScreens.put(screenId, newScreen);
703        mScreenOrder.add(insertIndex, screenId);
704        addView(newScreen, insertIndex);
705
706        if (mLauncher.getAccessibilityDelegate().isInAccessibleDrag()) {
707            newScreen.enableAccessibleDrag(true, CellLayout.WORKSPACE_ACCESSIBILITY_DRAG);
708        }
709
710        return newScreen;
711    }
712
713    public void createCustomContentContainer() {
714        CellLayout customScreen = (CellLayout)
715                mLauncher.getLayoutInflater().inflate(R.layout.workspace_screen, this, false);
716        customScreen.disableDragTarget();
717        customScreen.disableJailContent();
718
719        mWorkspaceScreens.put(CUSTOM_CONTENT_SCREEN_ID, customScreen);
720        mScreenOrder.add(0, CUSTOM_CONTENT_SCREEN_ID);
721
722        // We want no padding on the custom content
723        customScreen.setPadding(0, 0, 0, 0);
724
725        addFullScreenPage(customScreen);
726
727        // Update the custom content hint
728        setCurrentPage(getCurrentPage() + 1);
729    }
730
731    public void removeCustomContentPage() {
732        CellLayout customScreen = getScreenWithId(CUSTOM_CONTENT_SCREEN_ID);
733        if (customScreen == null) {
734            throw new RuntimeException("Expected custom content screen to exist");
735        }
736
737        mWorkspaceScreens.remove(CUSTOM_CONTENT_SCREEN_ID);
738        mScreenOrder.remove(CUSTOM_CONTENT_SCREEN_ID);
739        removeView(customScreen);
740
741        if (mCustomContentCallbacks != null) {
742            mCustomContentCallbacks.onScrollProgressChanged(0);
743            mCustomContentCallbacks.onHide();
744        }
745
746        mCustomContentCallbacks = null;
747
748        // Update the custom content hint
749        setCurrentPage(getCurrentPage() - 1);
750    }
751
752    public void addToCustomContentPage(View customContent, CustomContentCallbacks callbacks,
753            String description) {
754        if (getPageIndexForScreenId(CUSTOM_CONTENT_SCREEN_ID) < 0) {
755            throw new RuntimeException("Expected custom content screen to exist");
756        }
757
758        // Add the custom content to the full screen custom page
759        CellLayout customScreen = getScreenWithId(CUSTOM_CONTENT_SCREEN_ID);
760        int spanX = customScreen.getCountX();
761        int spanY = customScreen.getCountY();
762        CellLayout.LayoutParams lp = new CellLayout.LayoutParams(0, 0, spanX, spanY);
763        lp.canReorder  = false;
764        lp.isFullscreen = true;
765        if (customContent instanceof Insettable) {
766            ((Insettable)customContent).setInsets(mInsets);
767        }
768
769        // Verify that the child is removed from any existing parent.
770        if (customContent.getParent() instanceof ViewGroup) {
771            ViewGroup parent = (ViewGroup) customContent.getParent();
772            parent.removeView(customContent);
773        }
774        customScreen.removeAllViews();
775        customContent.setFocusable(true);
776        customContent.setOnKeyListener(new FullscreenKeyEventListener());
777        customContent.setOnFocusChangeListener(mLauncher.mFocusHandler
778                .getHideIndicatorOnFocusListener());
779        customScreen.addViewToCellLayout(customContent, 0, 0, lp, true);
780        mCustomContentDescription = description;
781
782        mCustomContentCallbacks = callbacks;
783    }
784
785    public void addExtraEmptyScreenOnDrag() {
786        boolean lastChildOnScreen = false;
787        boolean childOnFinalScreen = false;
788
789        // Cancel any pending removal of empty screen
790        mRemoveEmptyScreenRunnable = null;
791
792        if (mDragSourceInternal != null) {
793            if (mDragSourceInternal.getChildCount() == 1) {
794                lastChildOnScreen = true;
795            }
796            CellLayout cl = (CellLayout) mDragSourceInternal.getParent();
797            if (indexOfChild(cl) == getChildCount() - 1) {
798                childOnFinalScreen = true;
799            }
800        }
801
802        // If this is the last item on the final screen
803        if (lastChildOnScreen && childOnFinalScreen) {
804            return;
805        }
806        if (!mWorkspaceScreens.containsKey(EXTRA_EMPTY_SCREEN_ID)) {
807            insertNewWorkspaceScreen(EXTRA_EMPTY_SCREEN_ID);
808        }
809    }
810
811    public boolean addExtraEmptyScreen() {
812        if (!mWorkspaceScreens.containsKey(EXTRA_EMPTY_SCREEN_ID)) {
813            insertNewWorkspaceScreen(EXTRA_EMPTY_SCREEN_ID);
814            return true;
815        }
816        return false;
817    }
818
819    private void convertFinalScreenToEmptyScreenIfNecessary() {
820        if (mLauncher.isWorkspaceLoading()) {
821            // Invalid and dangerous operation if workspace is loading
822            return;
823        }
824
825        if (hasExtraEmptyScreen() || mScreenOrder.size() == 0) return;
826        long finalScreenId = mScreenOrder.get(mScreenOrder.size() - 1);
827
828        if (finalScreenId == CUSTOM_CONTENT_SCREEN_ID) return;
829        CellLayout finalScreen = mWorkspaceScreens.get(finalScreenId);
830
831        // If the final screen is empty, convert it to the extra empty screen
832        if (finalScreen.getShortcutsAndWidgets().getChildCount() == 0 &&
833                !finalScreen.isDropPending()) {
834            mWorkspaceScreens.remove(finalScreenId);
835            mScreenOrder.remove(finalScreenId);
836
837            // if this is the last non-custom content screen, convert it to the empty screen
838            mWorkspaceScreens.put(EXTRA_EMPTY_SCREEN_ID, finalScreen);
839            mScreenOrder.add(EXTRA_EMPTY_SCREEN_ID);
840
841            // Update the model if we have changed any screens
842            mLauncher.getModel().updateWorkspaceScreenOrder(mLauncher, mScreenOrder);
843        }
844    }
845
846    public void removeExtraEmptyScreen(final boolean animate, boolean stripEmptyScreens) {
847        removeExtraEmptyScreenDelayed(animate, null, 0, stripEmptyScreens);
848    }
849
850    public void removeExtraEmptyScreenDelayed(final boolean animate, final Runnable onComplete,
851            final int delay, final boolean stripEmptyScreens) {
852        if (mLauncher.isWorkspaceLoading()) {
853            // Don't strip empty screens if the workspace is still loading
854            return;
855        }
856
857        if (delay > 0) {
858            postDelayed(new Runnable() {
859                @Override
860                public void run() {
861                    removeExtraEmptyScreenDelayed(animate, onComplete, 0, stripEmptyScreens);
862                }
863            }, delay);
864            return;
865        }
866
867        convertFinalScreenToEmptyScreenIfNecessary();
868        if (hasExtraEmptyScreen()) {
869            int emptyIndex = mScreenOrder.indexOf(EXTRA_EMPTY_SCREEN_ID);
870            if (getNextPage() == emptyIndex) {
871                snapToPage(getNextPage() - 1, SNAP_OFF_EMPTY_SCREEN_DURATION);
872                fadeAndRemoveEmptyScreen(SNAP_OFF_EMPTY_SCREEN_DURATION, FADE_EMPTY_SCREEN_DURATION,
873                        onComplete, stripEmptyScreens);
874            } else {
875                snapToPage(getNextPage(), 0);
876                fadeAndRemoveEmptyScreen(0, FADE_EMPTY_SCREEN_DURATION,
877                        onComplete, stripEmptyScreens);
878            }
879            return;
880        } else if (stripEmptyScreens) {
881            // If we're not going to strip the empty screens after removing
882            // the extra empty screen, do it right away.
883            stripEmptyScreens();
884        }
885
886        if (onComplete != null) {
887            onComplete.run();
888        }
889    }
890
891    private void fadeAndRemoveEmptyScreen(int delay, int duration, final Runnable onComplete,
892            final boolean stripEmptyScreens) {
893        // XXX: Do we need to update LM workspace screens below?
894        PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0f);
895        PropertyValuesHolder bgAlpha = PropertyValuesHolder.ofFloat("backgroundAlpha", 0f);
896
897        final CellLayout cl = mWorkspaceScreens.get(EXTRA_EMPTY_SCREEN_ID);
898
899        mRemoveEmptyScreenRunnable = new Runnable() {
900            @Override
901            public void run() {
902                if (hasExtraEmptyScreen()) {
903                    mWorkspaceScreens.remove(EXTRA_EMPTY_SCREEN_ID);
904                    mScreenOrder.remove(EXTRA_EMPTY_SCREEN_ID);
905                    removeView(cl);
906                    if (stripEmptyScreens) {
907                        stripEmptyScreens();
908                    }
909                    // Update the page indicator to reflect the removed page.
910                    showPageIndicatorAtCurrentScroll();
911                }
912            }
913        };
914
915        ObjectAnimator oa = ObjectAnimator.ofPropertyValuesHolder(cl, alpha, bgAlpha);
916        oa.setDuration(duration);
917        oa.setStartDelay(delay);
918        oa.addListener(new AnimatorListenerAdapter() {
919            @Override
920            public void onAnimationEnd(Animator animation) {
921                if (mRemoveEmptyScreenRunnable != null) {
922                    mRemoveEmptyScreenRunnable.run();
923                }
924                if (onComplete != null) {
925                    onComplete.run();
926                }
927            }
928        });
929        oa.start();
930    }
931
932    public boolean hasExtraEmptyScreen() {
933        int nScreens = getChildCount();
934        nScreens = nScreens - numCustomPages();
935        return mWorkspaceScreens.containsKey(EXTRA_EMPTY_SCREEN_ID) && nScreens > 1;
936    }
937
938    public long commitExtraEmptyScreen() {
939        if (mLauncher.isWorkspaceLoading()) {
940            // Invalid and dangerous operation if workspace is loading
941            return -1;
942        }
943
944        int index = getPageIndexForScreenId(EXTRA_EMPTY_SCREEN_ID);
945        CellLayout cl = mWorkspaceScreens.get(EXTRA_EMPTY_SCREEN_ID);
946        mWorkspaceScreens.remove(EXTRA_EMPTY_SCREEN_ID);
947        mScreenOrder.remove(EXTRA_EMPTY_SCREEN_ID);
948
949        long newId = LauncherSettings.Settings.call(getContext().getContentResolver(),
950                LauncherSettings.Settings.METHOD_NEW_SCREEN_ID)
951                .getLong(LauncherSettings.Settings.EXTRA_VALUE);
952        mWorkspaceScreens.put(newId, cl);
953        mScreenOrder.add(newId);
954
955        // Update the model for the new screen
956        mLauncher.getModel().updateWorkspaceScreenOrder(mLauncher, mScreenOrder);
957
958        return newId;
959    }
960
961    public CellLayout getScreenWithId(long screenId) {
962        return mWorkspaceScreens.get(screenId);
963    }
964
965    public long getIdForScreen(CellLayout layout) {
966        int index = mWorkspaceScreens.indexOfValue(layout);
967        if (index != -1) {
968            return mWorkspaceScreens.keyAt(index);
969        }
970        return -1;
971    }
972
973    public int getPageIndexForScreenId(long screenId) {
974        return indexOfChild(mWorkspaceScreens.get(screenId));
975    }
976
977    public long getScreenIdForPageIndex(int index) {
978        if (0 <= index && index < mScreenOrder.size()) {
979            return mScreenOrder.get(index);
980        }
981        return -1;
982    }
983
984    public ArrayList<Long> getScreenOrder() {
985        return mScreenOrder;
986    }
987
988    public void stripEmptyScreens() {
989        if (mLauncher.isWorkspaceLoading()) {
990            // Don't strip empty screens if the workspace is still loading.
991            // This is dangerous and can result in data loss.
992            return;
993        }
994
995        if (isPageInTransition()) {
996            mStripScreensOnPageStopMoving = true;
997            return;
998        }
999
1000        int currentPage = getNextPage();
1001        ArrayList<Long> removeScreens = new ArrayList<Long>();
1002        int total = mWorkspaceScreens.size();
1003        for (int i = 0; i < total; i++) {
1004            long id = mWorkspaceScreens.keyAt(i);
1005            CellLayout cl = mWorkspaceScreens.valueAt(i);
1006            // FIRST_SCREEN_ID can never be removed.
1007            if ((!FeatureFlags.QSB_ON_FIRST_SCREEN || id > FIRST_SCREEN_ID)
1008                    && cl.getShortcutsAndWidgets().getChildCount() == 0) {
1009                removeScreens.add(id);
1010            }
1011        }
1012
1013        boolean isInAccessibleDrag = mLauncher.getAccessibilityDelegate().isInAccessibleDrag();
1014
1015        // We enforce at least one page to add new items to. In the case that we remove the last
1016        // such screen, we convert the last screen to the empty screen
1017        int minScreens = 1 + numCustomPages();
1018
1019        int pageShift = 0;
1020        for (Long id: removeScreens) {
1021            CellLayout cl = mWorkspaceScreens.get(id);
1022            mWorkspaceScreens.remove(id);
1023            mScreenOrder.remove(id);
1024
1025            if (getChildCount() > minScreens) {
1026                if (indexOfChild(cl) < currentPage) {
1027                    pageShift++;
1028                }
1029
1030                if (isInAccessibleDrag) {
1031                    cl.enableAccessibleDrag(false, CellLayout.WORKSPACE_ACCESSIBILITY_DRAG);
1032                }
1033
1034                removeView(cl);
1035            } else {
1036                // if this is the last non-custom content screen, convert it to the empty screen
1037                mRemoveEmptyScreenRunnable = null;
1038                mWorkspaceScreens.put(EXTRA_EMPTY_SCREEN_ID, cl);
1039                mScreenOrder.add(EXTRA_EMPTY_SCREEN_ID);
1040            }
1041        }
1042
1043        if (!removeScreens.isEmpty()) {
1044            // Update the model if we have changed any screens
1045            mLauncher.getModel().updateWorkspaceScreenOrder(mLauncher, mScreenOrder);
1046        }
1047
1048        if (pageShift >= 0) {
1049            setCurrentPage(currentPage - pageShift);
1050        }
1051    }
1052
1053    /**
1054     * At bind time, we use the rank (screenId) to compute x and y for hotseat items.
1055     * See {@link #addInScreen}.
1056     */
1057    public void addInScreenFromBind(View child, ItemInfo info) {
1058        int x = info.cellX;
1059        int y = info.cellY;
1060        if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1061            int screenId = (int) info.screenId;
1062            x = mLauncher.getHotseat().getCellXFromOrder(screenId);
1063            y = mLauncher.getHotseat().getCellYFromOrder(screenId);
1064        }
1065        addInScreen(child, info.container, info.screenId, x, y, info.spanX, info.spanY);
1066    }
1067
1068    /**
1069     * Adds the specified child in the specified screen based on the {@param info}
1070     * See {@link #addInScreen}.
1071     */
1072    public void addInScreen(View child, ItemInfo info) {
1073        addInScreen(child, info.container, info.screenId, info.cellX, info.cellY,
1074                info.spanX, info.spanY);
1075    }
1076
1077    /**
1078     * Adds the specified child in the specified screen. The position and dimension of
1079     * the child are defined by x, y, spanX and spanY.
1080     *
1081     * @param child The child to add in one of the workspace's screens.
1082     * @param screenId The screen in which to add the child.
1083     * @param x The X position of the child in the screen's grid.
1084     * @param y The Y position of the child in the screen's grid.
1085     * @param spanX The number of cells spanned horizontally by the child.
1086     * @param spanY The number of cells spanned vertically by the child.
1087     */
1088    private void addInScreen(View child, long container, long screenId, int x, int y,
1089            int spanX, int spanY) {
1090        if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1091            if (getScreenWithId(screenId) == null) {
1092                Log.e(TAG, "Skipping child, screenId " + screenId + " not found");
1093                // DEBUGGING - Print out the stack trace to see where we are adding from
1094                new Throwable().printStackTrace();
1095                return;
1096            }
1097        }
1098        if (screenId == EXTRA_EMPTY_SCREEN_ID) {
1099            // This should never happen
1100            throw new RuntimeException("Screen id should not be EXTRA_EMPTY_SCREEN_ID");
1101        }
1102
1103        final CellLayout layout;
1104        if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1105            layout = mLauncher.getHotseat().getLayout();
1106            child.setOnKeyListener(new HotseatIconKeyEventListener());
1107
1108            // Hide folder title in the hotseat
1109            if (child instanceof FolderIcon) {
1110                ((FolderIcon) child).setTextVisible(false);
1111            }
1112        } else {
1113            // Show folder title if not in the hotseat
1114            if (child instanceof FolderIcon) {
1115                ((FolderIcon) child).setTextVisible(true);
1116            }
1117            layout = getScreenWithId(screenId);
1118            child.setOnKeyListener(new IconKeyEventListener());
1119        }
1120
1121        ViewGroup.LayoutParams genericLp = child.getLayoutParams();
1122        CellLayout.LayoutParams lp;
1123        if (genericLp == null || !(genericLp instanceof CellLayout.LayoutParams)) {
1124            lp = new CellLayout.LayoutParams(x, y, spanX, spanY);
1125        } else {
1126            lp = (CellLayout.LayoutParams) genericLp;
1127            lp.cellX = x;
1128            lp.cellY = y;
1129            lp.cellHSpan = spanX;
1130            lp.cellVSpan = spanY;
1131        }
1132
1133        if (spanX < 0 && spanY < 0) {
1134            lp.isLockedToGrid = false;
1135        }
1136
1137        // Get the canonical child id to uniquely represent this view in this screen
1138        ItemInfo info = (ItemInfo) child.getTag();
1139        int childId = mLauncher.getViewIdForItem(info);
1140
1141        boolean markCellsAsOccupied = !(child instanceof Folder);
1142        if (!layout.addViewToCellLayout(child, -1, childId, lp, markCellsAsOccupied)) {
1143            // TODO: This branch occurs when the workspace is adding views
1144            // outside of the defined grid
1145            // maybe we should be deleting these items from the LauncherModel?
1146            Log.e(TAG, "Failed to add to item at (" + lp.cellX + "," + lp.cellY + ") to CellLayout");
1147        }
1148
1149        if (!(child instanceof Folder)) {
1150            child.setHapticFeedbackEnabled(false);
1151            child.setOnLongClickListener(mLongClickListener);
1152        }
1153        if (child instanceof DropTarget) {
1154            mDragController.addDropTarget((DropTarget) child);
1155        }
1156    }
1157
1158    /**
1159     * Called directly from a CellLayout (not by the framework), after we've been added as a
1160     * listener via setOnInterceptTouchEventListener(). This allows us to tell the CellLayout
1161     * that it should intercept touch events, which is not something that is normally supported.
1162     */
1163    @SuppressLint("ClickableViewAccessibility")
1164    @Override
1165    public boolean onTouch(View v, MotionEvent event) {
1166        return shouldConsumeTouch(v);
1167    }
1168
1169    private boolean shouldConsumeTouch(View v) {
1170        return !workspaceIconsCanBeDragged()
1171                || (!workspaceInModalState() && indexOfChild(v) != mCurrentPage);
1172    }
1173
1174    public boolean isSwitchingState() {
1175        return mIsSwitchingState;
1176    }
1177
1178    /** This differs from isSwitchingState in that we take into account how far the transition
1179     *  has completed. */
1180    public boolean isFinishedSwitchingState() {
1181        return !mIsSwitchingState
1182                || (mTransitionProgress > FINISHED_SWITCHING_STATE_TRANSITION_PROGRESS);
1183    }
1184
1185    protected void onWindowVisibilityChanged (int visibility) {
1186        mLauncher.onWindowVisibilityChanged(visibility);
1187    }
1188
1189    @Override
1190    public boolean dispatchUnhandledMove(View focused, int direction) {
1191        if (workspaceInModalState() || !isFinishedSwitchingState()) {
1192            // when the home screens are shrunken, shouldn't allow side-scrolling
1193            return false;
1194        }
1195        return super.dispatchUnhandledMove(focused, direction);
1196    }
1197
1198    @Override
1199    public boolean onInterceptTouchEvent(MotionEvent ev) {
1200        switch (ev.getAction() & MotionEvent.ACTION_MASK) {
1201        case MotionEvent.ACTION_DOWN:
1202            mXDown = ev.getX();
1203            mYDown = ev.getY();
1204            mTouchDownTime = System.currentTimeMillis();
1205            break;
1206        case MotionEvent.ACTION_POINTER_UP:
1207        case MotionEvent.ACTION_UP:
1208            if (mTouchState == TOUCH_STATE_REST) {
1209                final CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage);
1210                if (currentPage != null) {
1211                    onWallpaperTap(ev);
1212                }
1213            }
1214        }
1215        return super.onInterceptTouchEvent(ev);
1216    }
1217
1218    @Override
1219    public boolean onGenericMotionEvent(MotionEvent event) {
1220        // Ignore pointer scroll events if the custom content doesn't allow scrolling.
1221        if ((getScreenIdForPageIndex(getCurrentPage()) == CUSTOM_CONTENT_SCREEN_ID)
1222                && (mCustomContentCallbacks != null)
1223                && !mCustomContentCallbacks.isScrollingAllowed()) {
1224            return false;
1225        }
1226        return super.onGenericMotionEvent(event);
1227    }
1228
1229    protected void reinflateWidgetsIfNecessary() {
1230        final int clCount = getChildCount();
1231        for (int i = 0; i < clCount; i++) {
1232            CellLayout cl = (CellLayout) getChildAt(i);
1233            ShortcutAndWidgetContainer swc = cl.getShortcutsAndWidgets();
1234            final int itemCount = swc.getChildCount();
1235            for (int j = 0; j < itemCount; j++) {
1236                View v = swc.getChildAt(j);
1237
1238                if (v instanceof LauncherAppWidgetHostView
1239                        && v.getTag() instanceof LauncherAppWidgetInfo) {
1240                    LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) v.getTag();
1241                    LauncherAppWidgetHostView lahv = (LauncherAppWidgetHostView) v;
1242                    if (lahv.isReinflateRequired()) {
1243                        // Remove and rebind the current widget (which was inflated in the wrong
1244                        // orientation), but don't delete it from the database
1245                        mLauncher.removeItem(lahv, info, false  /* deleteFromDb */);
1246                        mLauncher.bindAppWidget(info);
1247                    }
1248                }
1249            }
1250        }
1251    }
1252
1253    @Override
1254    protected void determineScrollingStart(MotionEvent ev) {
1255        if (!isFinishedSwitchingState()) return;
1256
1257        float deltaX = ev.getX() - mXDown;
1258        float absDeltaX = Math.abs(deltaX);
1259        float absDeltaY = Math.abs(ev.getY() - mYDown);
1260
1261        if (Float.compare(absDeltaX, 0f) == 0) return;
1262
1263        float slope = absDeltaY / absDeltaX;
1264        float theta = (float) Math.atan(slope);
1265
1266        if (absDeltaX > mTouchSlop || absDeltaY > mTouchSlop) {
1267            cancelCurrentPageLongPress();
1268        }
1269
1270        boolean passRightSwipesToCustomContent =
1271                (mTouchDownTime - mCustomContentShowTime) > CUSTOM_CONTENT_GESTURE_DELAY;
1272
1273        boolean swipeInIgnoreDirection = mIsRtl ? deltaX < 0 : deltaX > 0;
1274        boolean onCustomContentScreen =
1275                getScreenIdForPageIndex(getCurrentPage()) == CUSTOM_CONTENT_SCREEN_ID;
1276        if (swipeInIgnoreDirection && onCustomContentScreen && passRightSwipesToCustomContent) {
1277            // Pass swipes to the right to the custom content page.
1278            return;
1279        }
1280
1281        if (onCustomContentScreen && (mCustomContentCallbacks != null)
1282                && !mCustomContentCallbacks.isScrollingAllowed()) {
1283            // Don't allow workspace scrolling if the current custom content screen doesn't allow
1284            // scrolling.
1285            return;
1286        }
1287
1288        if (theta > MAX_SWIPE_ANGLE) {
1289            // Above MAX_SWIPE_ANGLE, we don't want to ever start scrolling the workspace
1290            return;
1291        } else if (theta > START_DAMPING_TOUCH_SLOP_ANGLE) {
1292            // Above START_DAMPING_TOUCH_SLOP_ANGLE and below MAX_SWIPE_ANGLE, we want to
1293            // increase the touch slop to make it harder to begin scrolling the workspace. This
1294            // results in vertically scrolling widgets to more easily. The higher the angle, the
1295            // more we increase touch slop.
1296            theta -= START_DAMPING_TOUCH_SLOP_ANGLE;
1297            float extraRatio = (float)
1298                    Math.sqrt((theta / (MAX_SWIPE_ANGLE - START_DAMPING_TOUCH_SLOP_ANGLE)));
1299            super.determineScrollingStart(ev, 1 + TOUCH_SLOP_DAMPING_FACTOR * extraRatio);
1300        } else {
1301            // Below START_DAMPING_TOUCH_SLOP_ANGLE, we don't do anything special
1302            super.determineScrollingStart(ev);
1303        }
1304    }
1305
1306    protected void onPageBeginTransition() {
1307        super.onPageBeginTransition();
1308        updateChildrenLayersEnabled(false);
1309    }
1310
1311    protected void onPageEndTransition() {
1312        super.onPageEndTransition();
1313        updateChildrenLayersEnabled(false);
1314
1315        if (mDragController.isDragging()) {
1316            if (workspaceInModalState()) {
1317                // If we are in springloaded mode, then force an event to check if the current touch
1318                // is under a new page (to scroll to)
1319                mDragController.forceTouchMove();
1320            }
1321        }
1322
1323        if (mDelayedResizeRunnable != null && !mIsSwitchingState) {
1324            mDelayedResizeRunnable.run();
1325            mDelayedResizeRunnable = null;
1326        }
1327
1328        if (mDelayedSnapToPageRunnable != null) {
1329            mDelayedSnapToPageRunnable.run();
1330            mDelayedSnapToPageRunnable = null;
1331        }
1332        if (mStripScreensOnPageStopMoving) {
1333            stripEmptyScreens();
1334            mStripScreensOnPageStopMoving = false;
1335        }
1336    }
1337
1338    protected void onScrollInteractionBegin() {
1339        super.onScrollInteractionEnd();
1340        mScrollInteractionBegan = true;
1341    }
1342
1343    protected void onScrollInteractionEnd() {
1344        super.onScrollInteractionEnd();
1345        mScrollInteractionBegan = false;
1346        if (mStartedSendingScrollEvents) {
1347            mStartedSendingScrollEvents = false;
1348            mLauncherOverlay.onScrollInteractionEnd();
1349        }
1350    }
1351
1352    public void setLauncherOverlay(LauncherOverlay overlay) {
1353        mLauncherOverlay = overlay;
1354        // A new overlay has been set. Reset event tracking
1355        mStartedSendingScrollEvents = false;
1356        onOverlayScrollChanged(0);
1357    }
1358
1359    @Override
1360    protected int getUnboundedScrollX() {
1361        if (isScrollingOverlay()) {
1362            return mUnboundedScrollX;
1363        }
1364
1365        return super.getUnboundedScrollX();
1366    }
1367
1368    private boolean isScrollingOverlay() {
1369        return mLauncherOverlay != null &&
1370                ((mIsRtl && mUnboundedScrollX > mMaxScrollX) || (!mIsRtl && mUnboundedScrollX < 0));
1371    }
1372
1373    @Override
1374    protected void snapToDestination() {
1375        // If we're overscrolling the overlay, we make sure to immediately reset the PagedView
1376        // to it's baseline position instead of letting the overscroll settle. The overlay handles
1377        // it's own settling, and every gesture to the overlay should be self-contained and start
1378        // from 0, so we zero it out here.
1379        if (isScrollingOverlay()) {
1380            int finalScroll = mIsRtl ? mMaxScrollX : 0;
1381
1382            // We reset mWasInOverscroll so that PagedView doesn't zero out the overscroll
1383            // interaction when we call scrollTo.
1384            mWasInOverscroll = false;
1385            scrollTo(finalScroll, getScrollY());
1386        } else {
1387            super.snapToDestination();
1388        }
1389    }
1390
1391    @Override
1392    public void scrollTo(int x, int y) {
1393        mUnboundedScrollX = x;
1394        super.scrollTo(x, y);
1395    }
1396
1397    private void onWorkspaceOverallScrollChanged() {
1398        if (!mIgnoreQsbScroll) {
1399            mLauncher.getQsbContainer().setTranslationX(
1400                    mOverlayTranslation + mFirstPageScrollX - getScrollX());
1401        }
1402    }
1403
1404    @Override
1405    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
1406        super.onScrollChanged(l, t, oldl, oldt);
1407        onWorkspaceOverallScrollChanged();
1408
1409        // Update the page indicator progress.
1410        boolean isTransitioning = mIsSwitchingState
1411                || (getLayoutTransition() != null && getLayoutTransition().isRunning());
1412        if (!isTransitioning) {
1413            showPageIndicatorAtCurrentScroll();
1414        }
1415
1416        updatePageAlphaValues();
1417        updateStateForCustomContent();
1418        enableHwLayersOnVisiblePages();
1419    }
1420
1421    private void showPageIndicatorAtCurrentScroll() {
1422        if (mPageIndicator != null) {
1423            mPageIndicator.setScroll(getScrollX(), computeMaxScrollX());
1424        }
1425    }
1426
1427    @Override
1428    protected void overScroll(float amount) {
1429        boolean shouldOverScroll = (amount <= 0 && (!hasCustomContent() || mIsRtl)) ||
1430                (amount >= 0 && (!hasCustomContent() || !mIsRtl));
1431
1432        boolean shouldScrollOverlay = mLauncherOverlay != null &&
1433                ((amount <= 0 && !mIsRtl) || (amount >= 0 && mIsRtl));
1434
1435        boolean shouldZeroOverlay = mLauncherOverlay != null && mLastOverlayScroll != 0 &&
1436                ((amount >= 0 && !mIsRtl) || (amount <= 0 && mIsRtl));
1437
1438        if (shouldScrollOverlay) {
1439            if (!mStartedSendingScrollEvents && mScrollInteractionBegan) {
1440                mStartedSendingScrollEvents = true;
1441                mLauncherOverlay.onScrollInteractionBegin();
1442            }
1443
1444            mLastOverlayScroll = Math.abs(amount / getViewportWidth());
1445            mLauncherOverlay.onScrollChange(mLastOverlayScroll, mIsRtl);
1446        } else if (shouldOverScroll) {
1447            dampedOverScroll(amount);
1448        }
1449
1450        if (shouldZeroOverlay) {
1451            mLauncherOverlay.onScrollChange(0, mIsRtl);
1452        }
1453    }
1454
1455    private final Interpolator mAlphaInterpolator = new DecelerateInterpolator(3f);
1456
1457    /**
1458     * The overlay scroll is being controlled locally, just update our overlay effect
1459     */
1460    public void onOverlayScrollChanged(float scroll) {
1461        float offset = 0f;
1462        float slip = 0f;
1463
1464        scroll = Math.max(scroll - offset, 0);
1465        scroll = Math.min(1, scroll / (1 - offset));
1466
1467        float alpha = 1 - mAlphaInterpolator.getInterpolation(scroll);
1468        float transX = mLauncher.getDragLayer().getMeasuredWidth() * scroll;
1469        transX *= 1 - slip;
1470
1471        if (mIsRtl) {
1472            transX = -transX;
1473        }
1474        mOverlayTranslation = transX;
1475
1476        // TODO(adamcohen): figure out a final effect here. We may need to recommend
1477        // different effects based on device performance. On at least one relatively high-end
1478        // device I've tried, translating the launcher causes things to get quite laggy.
1479        setWorkspaceTranslationAndAlpha(Direction.X, transX, alpha);
1480        setHotseatTranslationAndAlpha(Direction.X, transX, alpha);
1481        onWorkspaceOverallScrollChanged();
1482
1483        mQsbAlphaController.setAlphaAtIndex(alpha, QSB_ALPHA_INDEX_OVERLAY_SCROLL);
1484    }
1485
1486    /**
1487     * Moves the workspace UI in the Y direction.
1488     * @param translation the amount of shift.
1489     * @param alpha the alpha for the workspace page
1490     */
1491    public void setWorkspaceYTranslationAndAlpha(float translation, float alpha) {
1492        setWorkspaceTranslationAndAlpha(Direction.Y, translation, alpha);
1493
1494        mLauncher.getQsbContainer().setTranslationY(translation);
1495        mQsbAlphaController.setAlphaAtIndex(alpha, QSB_ALPHA_INDEX_Y_TRANSLATION);
1496    }
1497
1498    /**
1499     * Moves the workspace UI in the provided direction.
1500     * @param direction the direction to move the workspace
1501     * @param translation the amount of shift.
1502     * @param alpha the alpha for the workspace page
1503     */
1504    private void setWorkspaceTranslationAndAlpha(Direction direction, float translation, float alpha) {
1505        Property<View, Float> property = direction.viewProperty;
1506        mPageAlpha[direction.ordinal()] = alpha;
1507        float finalAlpha = mPageAlpha[0] * mPageAlpha[1];
1508
1509        View currentChild = getChildAt(getCurrentPage());
1510        if (currentChild != null) {
1511            property.set(currentChild, translation);
1512            currentChild.setAlpha(finalAlpha);
1513        }
1514
1515        // When the animation finishes, reset all pages, just in case we missed a page.
1516        if (Float.compare(translation, 0) == 0) {
1517            for (int i = getChildCount() - 1; i >= 0; i--) {
1518                View child = getChildAt(i);
1519                property.set(child, translation);
1520                child.setAlpha(finalAlpha);
1521            }
1522        }
1523    }
1524
1525    /**
1526     * Moves the Hotseat UI in the provided direction.
1527     * @param direction the direction to move the workspace
1528     * @param translation the amount of shift.
1529     * @param alpha the alpha for the hotseat page
1530     */
1531    public void setHotseatTranslationAndAlpha(Direction direction, float translation, float alpha) {
1532        Property<View, Float> property = direction.viewProperty;
1533        // Skip the page indicator movement in the vertical bar layout
1534        if (direction != Direction.Y || !mLauncher.getDeviceProfile().isVerticalBarLayout()) {
1535            property.set(mPageIndicator, translation);
1536        }
1537        property.set(mLauncher.getHotseat(), translation);
1538        setHotseatAlphaAtIndex(alpha, direction.ordinal());
1539    }
1540
1541    private void setHotseatAlphaAtIndex(float alpha, int index) {
1542        mHotseatAlpha[index] = alpha;
1543        final float hotseatAlpha = mHotseatAlpha[0] * mHotseatAlpha[1] * mHotseatAlpha[2];
1544        final float pageIndicatorAlpha = mHotseatAlpha[0] * mHotseatAlpha[2];
1545
1546        mLauncher.getHotseat().setAlpha(hotseatAlpha);
1547        mPageIndicator.setAlpha(pageIndicatorAlpha);
1548    }
1549
1550    public ValueAnimator createHotseatAlphaAnimator(float finalValue) {
1551        if (Float.compare(finalValue, mHotseatAlpha[HOTSEAT_STATE_ALPHA_INDEX]) == 0) {
1552            // Return a dummy animator to avoid null checks.
1553            return ValueAnimator.ofFloat(0, 0);
1554        } else {
1555            ValueAnimator animator = ValueAnimator
1556                    .ofFloat(mHotseatAlpha[HOTSEAT_STATE_ALPHA_INDEX], finalValue);
1557            animator.addUpdateListener(new AnimatorUpdateListener() {
1558                @Override
1559                public void onAnimationUpdate(ValueAnimator valueAnimator) {
1560                    float value = (Float) valueAnimator.getAnimatedValue();
1561                    setHotseatAlphaAtIndex(value, HOTSEAT_STATE_ALPHA_INDEX);
1562                }
1563            });
1564
1565            AccessibilityManager am = (AccessibilityManager)
1566                    mLauncher.getSystemService(Context.ACCESSIBILITY_SERVICE);
1567            final boolean accessibilityEnabled = am.isEnabled();
1568            animator.addUpdateListener(
1569                    new AlphaUpdateListener(mLauncher.getHotseat(), accessibilityEnabled));
1570            animator.addUpdateListener(
1571                    new AlphaUpdateListener(mPageIndicator, accessibilityEnabled));
1572            return animator;
1573        }
1574    }
1575
1576    @Override
1577    protected void getEdgeVerticalPosition(int[] pos) {
1578        View child = getChildAt(getPageCount() - 1);
1579        pos[0] = child.getTop();
1580        pos[1] = child.getBottom();
1581    }
1582
1583    @Override
1584    protected void notifyPageSwitchListener() {
1585        super.notifyPageSwitchListener();
1586
1587        if (hasCustomContent() && getNextPage() == 0 && !mCustomContentShowing) {
1588            mCustomContentShowing = true;
1589            if (mCustomContentCallbacks != null) {
1590                mCustomContentCallbacks.onShow(false);
1591                mCustomContentShowTime = System.currentTimeMillis();
1592            }
1593        } else if (hasCustomContent() && getNextPage() != 0 && mCustomContentShowing) {
1594            mCustomContentShowing = false;
1595            if (mCustomContentCallbacks != null) {
1596                mCustomContentCallbacks.onHide();
1597            }
1598        }
1599    }
1600
1601    protected CustomContentCallbacks getCustomContentCallbacks() {
1602        return mCustomContentCallbacks;
1603    }
1604
1605    protected void setWallpaperDimension() {
1606        Utilities.THREAD_POOL_EXECUTOR.execute(new Runnable() {
1607            @Override
1608            public void run() {
1609                final Point size = LauncherAppState.getInstance()
1610                        .getInvariantDeviceProfile().defaultWallpaperSize;
1611                if (size.x != mWallpaperManager.getDesiredMinimumWidth()
1612                        || size.y != mWallpaperManager.getDesiredMinimumHeight()) {
1613                    mWallpaperManager.suggestDesiredDimensions(size.x, size.y);
1614                }
1615            }
1616        });
1617    }
1618
1619    public void lockWallpaperToDefaultPage() {
1620        mWallpaperOffset.setLockToDefaultPage(true);
1621    }
1622
1623    public void unlockWallpaperFromDefaultPageOnNextLayout() {
1624        if (mWallpaperOffset.isLockedToDefaultPage()) {
1625            mUnlockWallpaperFromDefaultPageOnLayout = true;
1626            requestLayout();
1627        }
1628    }
1629
1630    protected void snapToPage(int whichPage, Runnable r) {
1631        snapToPage(whichPage, SLOW_PAGE_SNAP_ANIMATION_DURATION, r);
1632    }
1633
1634    protected void snapToPage(int whichPage, int duration, Runnable r) {
1635        if (mDelayedSnapToPageRunnable != null) {
1636            mDelayedSnapToPageRunnable.run();
1637        }
1638        mDelayedSnapToPageRunnable = r;
1639        snapToPage(whichPage, duration);
1640    }
1641
1642    public void snapToScreenId(long screenId) {
1643        snapToScreenId(screenId, null);
1644    }
1645
1646    protected void snapToScreenId(long screenId, Runnable r) {
1647        snapToPage(getPageIndexForScreenId(screenId), r);
1648    }
1649
1650    @Override
1651    public void computeScroll() {
1652        super.computeScroll();
1653        mWallpaperOffset.syncWithScroll();
1654    }
1655
1656    public void computeScrollWithoutInvalidation() {
1657        computeScrollHelper(false);
1658    }
1659
1660    @Override
1661    protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
1662        if (!isSwitchingState()) {
1663            super.determineScrollingStart(ev, touchSlopScale);
1664        }
1665    }
1666
1667    @Override
1668    public void announceForAccessibility(CharSequence text) {
1669        // Don't announce if apps is on top of us.
1670        if (!mLauncher.isAppsViewVisible()) {
1671            super.announceForAccessibility(text);
1672        }
1673    }
1674
1675    public void showOutlinesTemporarily() {
1676        if (!mIsPageInTransition && !isTouchActive()) {
1677            snapToPage(mCurrentPage);
1678        }
1679    }
1680
1681    private void updatePageAlphaValues() {
1682        if (mWorkspaceFadeInAdjacentScreens &&
1683                !workspaceInModalState() &&
1684                !mIsSwitchingState) {
1685            int screenCenter = getScrollX() + getViewportWidth() / 2;
1686            for (int i = numCustomPages(); i < getChildCount(); i++) {
1687                CellLayout child = (CellLayout) getChildAt(i);
1688                if (child != null) {
1689                    float scrollProgress = getScrollProgress(screenCenter, child, i);
1690                    float alpha = 1 - Math.abs(scrollProgress);
1691                    child.getShortcutsAndWidgets().setAlpha(alpha);
1692
1693                    if (isQsbContainerPage(i)) {
1694                        mQsbAlphaController.setAlphaAtIndex(alpha, QSB_ALPHA_INDEX_PAGE_SCROLL);
1695                    }
1696                }
1697            }
1698        }
1699    }
1700
1701    public boolean hasCustomContent() {
1702        return (mScreenOrder.size() > 0 && mScreenOrder.get(0) == CUSTOM_CONTENT_SCREEN_ID);
1703    }
1704
1705    public int numCustomPages() {
1706        return hasCustomContent() ? 1 : 0;
1707    }
1708
1709    public boolean isOnOrMovingToCustomContent() {
1710        return hasCustomContent() && getNextPage() == 0;
1711    }
1712
1713    private void updateStateForCustomContent() {
1714        float translationX = 0;
1715        float progress = 0;
1716        if (hasCustomContent()) {
1717            int index = mScreenOrder.indexOf(CUSTOM_CONTENT_SCREEN_ID);
1718
1719            int scrollDelta = getScrollX() - getScrollForPage(index) -
1720                    getLayoutTransitionOffsetForPage(index);
1721            float scrollRange = getScrollForPage(index + 1) - getScrollForPage(index);
1722            translationX = scrollRange - scrollDelta;
1723            progress = (scrollRange - scrollDelta) / scrollRange;
1724
1725            if (mIsRtl) {
1726                translationX = Math.min(0, translationX);
1727            } else {
1728                translationX = Math.max(0, translationX);
1729            }
1730            progress = Math.max(0, progress);
1731        }
1732
1733        if (Float.compare(progress, mLastCustomContentScrollProgress) == 0) return;
1734
1735        CellLayout cc = mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID);
1736        if (progress > 0 && cc.getVisibility() != VISIBLE && !workspaceInModalState()) {
1737            cc.setVisibility(VISIBLE);
1738        }
1739
1740        mLastCustomContentScrollProgress = progress;
1741
1742        // We should only update the drag layer background alpha if we are not in all apps or the
1743        // widgets tray
1744        if (mState == State.NORMAL) {
1745            mLauncher.getDragLayer().setBackgroundAlpha(progress == 1 ? 0 : progress * 0.8f);
1746        }
1747
1748        if (mLauncher.getHotseat() != null) {
1749            mLauncher.getHotseat().setTranslationX(translationX);
1750        }
1751
1752        if (mPageIndicator != null) {
1753            mPageIndicator.setTranslationX(translationX);
1754        }
1755
1756        if (mCustomContentCallbacks != null) {
1757            mCustomContentCallbacks.onScrollProgressChanged(progress);
1758        }
1759    }
1760
1761    protected void onAttachedToWindow() {
1762        super.onAttachedToWindow();
1763        IBinder windowToken = getWindowToken();
1764        mWallpaperOffset.setWindowToken(windowToken);
1765        computeScroll();
1766        mDragController.setWindowToken(windowToken);
1767    }
1768
1769    protected void onDetachedFromWindow() {
1770        super.onDetachedFromWindow();
1771        mWallpaperOffset.setWindowToken(null);
1772    }
1773
1774    protected void onResume() {
1775        // Update wallpaper dimensions if they were changed since last onResume
1776        // (we also always set the wallpaper dimensions in the constructor)
1777        if (LauncherAppState.getInstance().hasWallpaperChangedSinceLastCheck()) {
1778            setWallpaperDimension();
1779        }
1780        mWallpaperOffset.onResume();
1781    }
1782
1783    @Override
1784    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
1785        if (mUnlockWallpaperFromDefaultPageOnLayout) {
1786            mWallpaperOffset.setLockToDefaultPage(false);
1787            mUnlockWallpaperFromDefaultPageOnLayout = false;
1788        }
1789        if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
1790            mWallpaperOffset.syncWithScroll();
1791            mWallpaperOffset.jumpToFinal();
1792        }
1793        super.onLayout(changed, left, top, right, bottom);
1794        mFirstPageScrollX = getScrollForPage(0);
1795        onWorkspaceOverallScrollChanged();
1796
1797        final LayoutTransition transition = getLayoutTransition();
1798        // If the transition is running defer updating max scroll, as some empty pages could
1799        // still be present, and a max scroll change could cause sudden jumps in scroll.
1800        if (transition != null && transition.isRunning()) {
1801            transition.addTransitionListener(new LayoutTransition.TransitionListener() {
1802
1803                @Override
1804                public void startTransition(LayoutTransition transition, ViewGroup container,
1805                                            View view, int transitionType) {
1806                    mIgnoreQsbScroll = true;
1807                }
1808
1809                @Override
1810                public void endTransition(LayoutTransition transition, ViewGroup container,
1811                                          View view, int transitionType) {
1812                    // Wait until all transitions are complete.
1813                    if (!transition.isRunning()) {
1814                        mIgnoreQsbScroll = false;
1815                        transition.removeTransitionListener(this);
1816                        mFirstPageScrollX = getScrollForPage(0);
1817                        onWorkspaceOverallScrollChanged();
1818                    }
1819                }
1820            });
1821        }
1822        updatePageAlphaValues();
1823    }
1824
1825    @Override
1826    public int getDescendantFocusability() {
1827        if (workspaceInModalState()) {
1828            return ViewGroup.FOCUS_BLOCK_DESCENDANTS;
1829        }
1830        return super.getDescendantFocusability();
1831    }
1832
1833    public boolean workspaceInModalState() {
1834        return mState != State.NORMAL;
1835    }
1836
1837    /** Returns whether a drag should be allowed to be started from the current workspace state. */
1838    public boolean workspaceIconsCanBeDragged() {
1839        return mState == State.NORMAL || mState == State.SPRING_LOADED;
1840    }
1841
1842    @Thunk void updateChildrenLayersEnabled(boolean force) {
1843        boolean small = mState == State.OVERVIEW || mIsSwitchingState;
1844        boolean enableChildrenLayers = force || small || mAnimatingViewIntoPlace || isPageInTransition();
1845
1846        if (enableChildrenLayers != mChildrenLayersEnabled) {
1847            mChildrenLayersEnabled = enableChildrenLayers;
1848            if (mChildrenLayersEnabled) {
1849                enableHwLayersOnVisiblePages();
1850            } else {
1851                for (int i = 0; i < getPageCount(); i++) {
1852                    final CellLayout cl = (CellLayout) getChildAt(i);
1853                    cl.enableHardwareLayer(false);
1854                }
1855            }
1856        }
1857    }
1858
1859    private void enableHwLayersOnVisiblePages() {
1860        if (mChildrenLayersEnabled) {
1861            final int screenCount = getChildCount();
1862
1863            float visibleLeft = getViewportOffsetX();
1864            float visibleRight = visibleLeft + getViewportWidth();
1865            float scaleX = getScaleX();
1866            if (scaleX < 1 && scaleX > 0) {
1867                float mid = getMeasuredWidth() / 2;
1868                visibleLeft = mid - ((mid - visibleLeft) / scaleX);
1869                visibleRight = mid + ((visibleRight - mid) / scaleX);
1870            }
1871
1872            int leftScreen = -1;
1873            int rightScreen = -1;
1874            for (int i = numCustomPages(); i < screenCount; i++) {
1875                final View child = getPageAt(i);
1876
1877                float left = child.getLeft() + child.getTranslationX() - getScrollX();
1878                if (left <= visibleRight && (left + child.getMeasuredWidth()) >= visibleLeft) {
1879                    if (leftScreen == -1) {
1880                        leftScreen = i;
1881                    }
1882                    rightScreen = i;
1883                }
1884            }
1885            if (mForceDrawAdjacentPages) {
1886                // In overview mode, make sure that the two side pages are visible.
1887                leftScreen = Utilities.boundToRange(getCurrentPage() - 1,
1888                    numCustomPages(), rightScreen);
1889                rightScreen = Utilities.boundToRange(getCurrentPage() + 1,
1890                    leftScreen, getPageCount() - 1);
1891            }
1892
1893            if (leftScreen == rightScreen) {
1894                // make sure we're caching at least two pages always
1895                if (rightScreen < screenCount - 1) {
1896                    rightScreen++;
1897                } else if (leftScreen > 0) {
1898                    leftScreen--;
1899                }
1900            }
1901
1902            for (int i = numCustomPages(); i < screenCount; i++) {
1903                final CellLayout layout = (CellLayout) getPageAt(i);
1904                // enable layers between left and right screen inclusive.
1905                boolean enableLayer = leftScreen <= i && i <= rightScreen;
1906                layout.enableHardwareLayer(enableLayer);
1907            }
1908        }
1909    }
1910
1911    public void buildPageHardwareLayers() {
1912        // force layers to be enabled just for the call to buildLayer
1913        updateChildrenLayersEnabled(true);
1914        if (getWindowToken() != null) {
1915            final int childCount = getChildCount();
1916            for (int i = 0; i < childCount; i++) {
1917                CellLayout cl = (CellLayout) getChildAt(i);
1918                cl.buildHardwareLayer();
1919            }
1920        }
1921        updateChildrenLayersEnabled(false);
1922    }
1923
1924    protected void onWallpaperTap(MotionEvent ev) {
1925        final int[] position = mTempXY;
1926        getLocationOnScreen(position);
1927
1928        int pointerIndex = ev.getActionIndex();
1929        position[0] += (int) ev.getX(pointerIndex);
1930        position[1] += (int) ev.getY(pointerIndex);
1931
1932        mWallpaperManager.sendWallpaperCommand(getWindowToken(),
1933                ev.getAction() == MotionEvent.ACTION_UP
1934                        ? WallpaperManager.COMMAND_TAP : WallpaperManager.COMMAND_SECONDARY_TAP,
1935                position[0], position[1], 0, null);
1936    }
1937
1938    public void prepareDragWithProvider(DragPreviewProvider outlineProvider) {
1939        mOutlineProvider = outlineProvider;
1940    }
1941
1942    public void exitWidgetResizeMode() {
1943        DragLayer dragLayer = mLauncher.getDragLayer();
1944        dragLayer.clearResizeFrame();
1945    }
1946
1947    @Override
1948    protected void getFreeScrollPageRange(int[] range) {
1949        getOverviewModePages(range);
1950    }
1951
1952    private void getOverviewModePages(int[] range) {
1953        int start = numCustomPages();
1954        int end = getChildCount() - 1;
1955
1956        range[0] = Math.max(0, Math.min(start, getChildCount() - 1));
1957        range[1] = Math.max(0, end);
1958    }
1959
1960    public void onStartReordering() {
1961        super.onStartReordering();
1962        // Reordering handles its own animations, disable the automatic ones.
1963        disableLayoutTransitions();
1964    }
1965
1966    public void onEndReordering() {
1967        super.onEndReordering();
1968
1969        if (mLauncher.isWorkspaceLoading()) {
1970            // Invalid and dangerous operation if workspace is loading
1971            return;
1972        }
1973
1974        mScreenOrder.clear();
1975        int count = getChildCount();
1976        for (int i = 0; i < count; i++) {
1977            CellLayout cl = ((CellLayout) getChildAt(i));
1978            mScreenOrder.add(getIdForScreen(cl));
1979        }
1980        mLauncher.getUserEventDispatcher().logOverviewReorder();
1981        mLauncher.getModel().updateWorkspaceScreenOrder(mLauncher, mScreenOrder);
1982
1983        // Re-enable auto layout transitions for page deletion.
1984        enableLayoutTransitions();
1985    }
1986
1987    public boolean isInOverviewMode() {
1988        return mState == State.OVERVIEW;
1989    }
1990
1991    public void snapToPageFromOverView(int whichPage) {
1992        mStateTransitionAnimation.snapToPageFromOverView(whichPage);
1993    }
1994
1995    int getOverviewModeTranslationY() {
1996        DeviceProfile grid = mLauncher.getDeviceProfile();
1997        int overviewButtonBarHeight = grid.getOverviewModeButtonBarHeight();
1998
1999        int scaledHeight = (int) (mOverviewModeShrinkFactor * getNormalChildHeight());
2000        Rect workspacePadding = grid.getWorkspacePadding(sTempRect);
2001        int workspaceTop = mInsets.top + workspacePadding.top;
2002        int workspaceBottom = getViewportHeight() - mInsets.bottom - workspacePadding.bottom;
2003        int overviewTop = mInsets.top;
2004        int overviewBottom = getViewportHeight() - mInsets.bottom - overviewButtonBarHeight;
2005        int workspaceOffsetTopEdge = workspaceTop + ((workspaceBottom - workspaceTop) - scaledHeight) / 2;
2006        int overviewOffsetTopEdge = overviewTop + (overviewBottom - overviewTop - scaledHeight) / 2;
2007        return -workspaceOffsetTopEdge + overviewOffsetTopEdge;
2008    }
2009
2010    float getSpringLoadedTranslationY() {
2011        DeviceProfile grid = mLauncher.getDeviceProfile();
2012        if (grid.isVerticalBarLayout() || getChildCount() == 0) {
2013            return 0;
2014        }
2015
2016        float scaledHeight = grid.workspaceSpringLoadShrinkFactor * getNormalChildHeight();
2017        float shrunkTop = mInsets.top + grid.dropTargetBarSizePx;
2018        float shrunkBottom = getViewportHeight() - mInsets.bottom
2019                - grid.getWorkspacePadding(sTempRect).bottom
2020                - grid.workspaceSpringLoadedBottomSpace;
2021        float totalShrunkSpace = shrunkBottom - shrunkTop;
2022
2023        float desiredCellTop = shrunkTop + (totalShrunkSpace - scaledHeight) / 2;
2024
2025        float halfHeight = getHeight() / 2;
2026        float myCenter = getTop() + halfHeight;
2027        float cellTopFromCenter = halfHeight - getChildAt(0).getTop();
2028        float actualCellTop = myCenter - cellTopFromCenter * grid.workspaceSpringLoadShrinkFactor;
2029        return (desiredCellTop - actualCellTop) / grid.workspaceSpringLoadShrinkFactor;
2030    }
2031
2032    float getOverviewModeShrinkFactor() {
2033        return mOverviewModeShrinkFactor;
2034    }
2035
2036    /**
2037     * Sets the current workspace {@link State}, returning an animation transitioning the workspace
2038     * to that new state.
2039     */
2040    public Animator setStateWithAnimation(State toState, boolean animated,
2041            AnimationLayerSet layerViews) {
2042        // Create the animation to the new state
2043        AnimatorSet workspaceAnim =  mStateTransitionAnimation.getAnimationToState(mState,
2044                toState, animated, layerViews);
2045
2046        boolean shouldNotifyWidgetChange = !mState.shouldUpdateWidget
2047                && toState.shouldUpdateWidget;
2048        // Update the current state
2049        mState = toState;
2050        updateAccessibilityFlags();
2051
2052        if (shouldNotifyWidgetChange) {
2053            mLauncher.notifyWidgetProvidersChanged();
2054        }
2055
2056        if (mOnStateChangeListener != null) {
2057            mOnStateChangeListener.prepareStateChange(toState, animated ? workspaceAnim : null);
2058        }
2059
2060        onPrepareStateTransition(mState.hasMultipleVisiblePages);
2061
2062        StateTransitionListener listener = new StateTransitionListener();
2063        if (animated) {
2064            ValueAnimator stepAnimator = ValueAnimator.ofFloat(0, 1);
2065            stepAnimator.addUpdateListener(listener);
2066
2067            workspaceAnim.play(stepAnimator);
2068            workspaceAnim.addListener(listener);
2069        } else {
2070            listener.onAnimationStart(null);
2071            listener.onAnimationEnd(null);
2072        }
2073
2074        return workspaceAnim;
2075    }
2076
2077    public State getState() {
2078        return mState;
2079    }
2080
2081    public void updateAccessibilityFlags() {
2082        // TODO: Update the accessibility flags appropriately when dragging.
2083        if (!mLauncher.getAccessibilityDelegate().isInAccessibleDrag()) {
2084            if (Utilities.ATLEAST_LOLLIPOP) {
2085                int total = getPageCount();
2086                for (int i = numCustomPages(); i < total; i++) {
2087                    updateAccessibilityFlags((CellLayout) getPageAt(i), i);
2088                }
2089                setImportantForAccessibility((mState == State.NORMAL || mState == State.OVERVIEW)
2090                        ? IMPORTANT_FOR_ACCESSIBILITY_AUTO
2091                        : IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
2092            } else {
2093                int accessible = mState == State.NORMAL ?
2094                        IMPORTANT_FOR_ACCESSIBILITY_AUTO :
2095                        IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
2096                setImportantForAccessibility(accessible);
2097            }
2098        }
2099    }
2100
2101    private void updateAccessibilityFlags(CellLayout page, int pageNo) {
2102        if (mState == State.OVERVIEW) {
2103            page.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
2104            page.getShortcutsAndWidgets().setImportantForAccessibility(
2105                    IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
2106            page.setContentDescription(getPageDescription(pageNo));
2107
2108            // No custom action for the first page.
2109            if (!FeatureFlags.QSB_ON_FIRST_SCREEN || pageNo > 0) {
2110                if (mPagesAccessibilityDelegate == null) {
2111                    mPagesAccessibilityDelegate = new OverviewScreenAccessibilityDelegate(this);
2112                }
2113                page.setAccessibilityDelegate(mPagesAccessibilityDelegate);
2114            }
2115        } else {
2116            int accessible = mState == State.NORMAL ?
2117                    IMPORTANT_FOR_ACCESSIBILITY_AUTO :
2118                        IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
2119            page.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
2120            page.getShortcutsAndWidgets().setImportantForAccessibility(accessible);
2121            page.setContentDescription(null);
2122            page.setAccessibilityDelegate(null);
2123        }
2124    }
2125
2126    public void onPrepareStateTransition(boolean multiplePagesVisible) {
2127        mIsSwitchingState = true;
2128        mTransitionProgress = 0;
2129
2130        if (multiplePagesVisible) {
2131            mForceDrawAdjacentPages = true;
2132        }
2133        invalidate(); // This will call dispatchDraw(), which calls getVisiblePages().
2134
2135        updateChildrenLayersEnabled(false);
2136        hideCustomContentIfNecessary();
2137    }
2138
2139    public void onEndStateTransition() {
2140        mIsSwitchingState = false;
2141        updateChildrenLayersEnabled(false);
2142        showCustomContentIfNecessary();
2143        mForceDrawAdjacentPages = false;
2144        mTransitionProgress = 1;
2145    }
2146
2147    void updateCustomContentVisibility() {
2148        int visibility = mState == Workspace.State.NORMAL ? VISIBLE : INVISIBLE;
2149        setCustomContentVisibility(visibility);
2150    }
2151
2152    void setCustomContentVisibility(int visibility) {
2153        if (hasCustomContent()) {
2154            mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID).setVisibility(visibility);
2155        }
2156    }
2157
2158    void showCustomContentIfNecessary() {
2159        boolean show  = mState == Workspace.State.NORMAL;
2160        if (show && hasCustomContent()) {
2161            mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID).setVisibility(VISIBLE);
2162        }
2163    }
2164
2165    void hideCustomContentIfNecessary() {
2166        boolean hide  = mState != Workspace.State.NORMAL;
2167        if (hide && hasCustomContent()) {
2168            disableLayoutTransitions();
2169            mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID).setVisibility(INVISIBLE);
2170            enableLayoutTransitions();
2171        }
2172    }
2173
2174    /**
2175     * Returns the drawable for the given text view.
2176     */
2177    public static Drawable getTextViewIcon(TextView tv) {
2178        final Drawable[] drawables = tv.getCompoundDrawables();
2179        for (int i = 0; i < drawables.length; i++) {
2180            if (drawables[i] != null) {
2181                return drawables[i];
2182            }
2183        }
2184        return null;
2185    }
2186
2187    public void startDrag(CellLayout.CellInfo cellInfo, DragOptions options) {
2188        View child = cellInfo.cell;
2189
2190        // Make sure the drag was started by a long press as opposed to a long click.
2191        if (!child.isInTouchMode()) {
2192            return;
2193        }
2194
2195        mDragInfo = cellInfo;
2196        child.setVisibility(INVISIBLE);
2197
2198        if (options.isAccessibleDrag) {
2199            mDragController.addDragListener(new AccessibleDragListenerAdapter(
2200                    this, CellLayout.WORKSPACE_ACCESSIBILITY_DRAG) {
2201                @Override
2202                protected void enableAccessibleDrag(boolean enable) {
2203                    super.enableAccessibleDrag(enable);
2204                    setEnableForLayout(mLauncher.getHotseat().getLayout(),enable);
2205
2206                    // We need to allow our individual children to become click handlers in this
2207                    // case, so temporarily unset the click handlers.
2208                    setOnClickListener(enable ? null : mLauncher);
2209                }
2210            });
2211        }
2212
2213        beginDragShared(child, this, options);
2214    }
2215
2216    public void beginDragShared(View child, DragSource source, DragOptions options) {
2217        Object dragObject = child.getTag();
2218        if (!(dragObject instanceof ItemInfo)) {
2219            String msg = "Drag started with a view that has no tag set. This "
2220                    + "will cause a crash (issue 11627249) down the line. "
2221                    + "View: " + child + "  tag: " + child.getTag();
2222            throw new IllegalStateException(msg);
2223        }
2224        beginDragShared(child, source, (ItemInfo) dragObject,
2225                new DragPreviewProvider(child), options);
2226    }
2227
2228
2229    public DragView beginDragShared(View child, DragSource source, ItemInfo dragObject,
2230            DragPreviewProvider previewProvider, DragOptions dragOptions) {
2231        child.clearFocus();
2232        child.setPressed(false);
2233        mOutlineProvider = previewProvider;
2234
2235        // The drag bitmap follows the touch point around on the screen
2236        final Bitmap b = previewProvider.createDragBitmap(mCanvas);
2237        int halfPadding = previewProvider.previewPadding / 2;
2238
2239        float scale = previewProvider.getScaleAndPosition(b, mTempXY);
2240        int dragLayerX = mTempXY[0];
2241        int dragLayerY = mTempXY[1];
2242
2243        DeviceProfile grid = mLauncher.getDeviceProfile();
2244        Point dragVisualizeOffset = null;
2245        Rect dragRect = null;
2246        if (child instanceof BubbleTextView) {
2247            int iconSize = grid.iconSizePx;
2248            int top = child.getPaddingTop();
2249            int left = (b.getWidth() - iconSize) / 2;
2250            int right = left + iconSize;
2251            int bottom = top + iconSize;
2252            dragLayerY += top;
2253            // Note: The drag region is used to calculate drag layer offsets, but the
2254            // dragVisualizeOffset in addition to the dragRect (the size) to position the outline.
2255            dragVisualizeOffset = new Point(- halfPadding, halfPadding);
2256            dragRect = new Rect(left, top, right, bottom);
2257        } else if (child instanceof FolderIcon) {
2258            int previewSize = grid.folderIconSizePx;
2259            dragVisualizeOffset = new Point(- halfPadding, halfPadding - child.getPaddingTop());
2260            dragRect = new Rect(0, child.getPaddingTop(), child.getWidth(), previewSize);
2261        }
2262
2263        // Clear the pressed state if necessary
2264        if (child instanceof BubbleTextView) {
2265            BubbleTextView icon = (BubbleTextView) child;
2266            icon.clearPressedBackground();
2267        }
2268
2269        if (child.getParent() instanceof ShortcutAndWidgetContainer) {
2270            mDragSourceInternal = (ShortcutAndWidgetContainer) child.getParent();
2271        }
2272
2273        if (child instanceof BubbleTextView) {
2274            DeepShortcutsContainer dsc = DeepShortcutsContainer.showForIcon((BubbleTextView) child);
2275            if (dsc != null) {
2276                dragOptions.preDragCondition = dsc.createPreDragCondition();
2277
2278                mLauncher.getUserEventDispatcher().resetElapsedContainerMillis();
2279            }
2280        }
2281
2282        DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source,
2283                dragObject, dragVisualizeOffset, dragRect, scale, dragOptions);
2284        dv.setIntrinsicIconScaleFactor(source.getIntrinsicIconScaleFactor());
2285        b.recycle();
2286        return dv;
2287    }
2288
2289    private boolean transitionStateShouldAllowDrop() {
2290        return ((!isSwitchingState() || mTransitionProgress > ALLOW_DROP_TRANSITION_PROGRESS) &&
2291                (mState == State.NORMAL || mState == State.SPRING_LOADED));
2292    }
2293
2294    /**
2295     * {@inheritDoc}
2296     */
2297    public boolean acceptDrop(DragObject d) {
2298        // If it's an external drop (e.g. from All Apps), check if it should be accepted
2299        CellLayout dropTargetLayout = mDropToLayout;
2300        if (d.dragSource != this) {
2301            // Don't accept the drop if we're not over a screen at time of drop
2302            if (dropTargetLayout == null) {
2303                return false;
2304            }
2305            if (!transitionStateShouldAllowDrop()) return false;
2306
2307            mDragViewVisualCenter = d.getVisualCenter(mDragViewVisualCenter);
2308
2309            // We want the point to be mapped to the dragTarget.
2310            if (mLauncher.isHotseatLayout(dropTargetLayout)) {
2311                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
2312            } else {
2313                mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter);
2314            }
2315
2316            int spanX = 1;
2317            int spanY = 1;
2318            if (mDragInfo != null) {
2319                final CellLayout.CellInfo dragCellInfo = mDragInfo;
2320                spanX = dragCellInfo.spanX;
2321                spanY = dragCellInfo.spanY;
2322            } else {
2323                spanX = d.dragInfo.spanX;
2324                spanY = d.dragInfo.spanY;
2325            }
2326
2327            int minSpanX = spanX;
2328            int minSpanY = spanY;
2329            if (d.dragInfo instanceof PendingAddWidgetInfo) {
2330                minSpanX = ((PendingAddWidgetInfo) d.dragInfo).minSpanX;
2331                minSpanY = ((PendingAddWidgetInfo) d.dragInfo).minSpanY;
2332            }
2333
2334            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2335                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, dropTargetLayout,
2336                    mTargetCell);
2337            float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0],
2338                    mDragViewVisualCenter[1], mTargetCell);
2339            if (mCreateUserFolderOnDrop && willCreateUserFolder(d.dragInfo,
2340                    dropTargetLayout, mTargetCell, distance, true)) {
2341                return true;
2342            }
2343
2344            if (mAddToExistingFolderOnDrop && willAddToExistingUserFolder(d.dragInfo,
2345                    dropTargetLayout, mTargetCell, distance)) {
2346                return true;
2347            }
2348
2349            int[] resultSpan = new int[2];
2350            mTargetCell = dropTargetLayout.performReorder((int) mDragViewVisualCenter[0],
2351                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY,
2352                    null, mTargetCell, resultSpan, CellLayout.MODE_ACCEPT_DROP);
2353            boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0;
2354
2355            // Don't accept the drop if there's no room for the item
2356            if (!foundCell) {
2357                onNoCellFound(dropTargetLayout);
2358                return false;
2359            }
2360        }
2361
2362        long screenId = getIdForScreen(dropTargetLayout);
2363        if (screenId == EXTRA_EMPTY_SCREEN_ID) {
2364            commitExtraEmptyScreen();
2365        }
2366
2367        return true;
2368    }
2369
2370    boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell,
2371            float distance, boolean considerTimeout) {
2372        if (distance > mMaxDistanceForFolderCreation) return false;
2373        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2374        return willCreateUserFolder(info, dropOverView, considerTimeout);
2375    }
2376
2377    boolean willCreateUserFolder(ItemInfo info, View dropOverView, boolean considerTimeout) {
2378        if (dropOverView != null) {
2379            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams();
2380            if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.cellY)) {
2381                return false;
2382            }
2383        }
2384
2385        boolean hasntMoved = false;
2386        if (mDragInfo != null) {
2387            hasntMoved = dropOverView == mDragInfo.cell;
2388        }
2389
2390        if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) {
2391            return false;
2392        }
2393
2394        boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo);
2395        boolean willBecomeShortcut =
2396                (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
2397                        info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT ||
2398                        info.itemType == LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT);
2399
2400        return (aboveShortcut && willBecomeShortcut);
2401    }
2402
2403    boolean willAddToExistingUserFolder(ItemInfo dragInfo, CellLayout target, int[] targetCell,
2404            float distance) {
2405        if (distance > mMaxDistanceForFolderCreation) return false;
2406        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2407        return willAddToExistingUserFolder(dragInfo, dropOverView);
2408
2409    }
2410    boolean willAddToExistingUserFolder(ItemInfo dragInfo, View dropOverView) {
2411        if (dropOverView != null) {
2412            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams();
2413            if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.cellY)) {
2414                return false;
2415            }
2416        }
2417
2418        if (dropOverView instanceof FolderIcon) {
2419            FolderIcon fi = (FolderIcon) dropOverView;
2420            if (fi.acceptDrop(dragInfo)) {
2421                return true;
2422            }
2423        }
2424        return false;
2425    }
2426
2427    boolean createUserFolderIfNecessary(View newView, long container, CellLayout target,
2428            int[] targetCell, float distance, boolean external, DragView dragView,
2429            Runnable postAnimationRunnable) {
2430        if (distance > mMaxDistanceForFolderCreation) return false;
2431        View v = target.getChildAt(targetCell[0], targetCell[1]);
2432
2433        boolean hasntMoved = false;
2434        if (mDragInfo != null) {
2435            CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell);
2436            hasntMoved = (mDragInfo.cellX == targetCell[0] &&
2437                    mDragInfo.cellY == targetCell[1]) && (cellParent == target);
2438        }
2439
2440        if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false;
2441        mCreateUserFolderOnDrop = false;
2442        final long screenId = getIdForScreen(target);
2443
2444        boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo);
2445        boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo);
2446
2447        if (aboveShortcut && willBecomeShortcut) {
2448            ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag();
2449            ShortcutInfo destInfo = (ShortcutInfo) v.getTag();
2450            // if the drag started here, we need to remove it from the workspace
2451            if (!external) {
2452                getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2453            }
2454
2455            Rect folderLocation = new Rect();
2456            float scale = mLauncher.getDragLayer().getDescendantRectRelativeToSelf(v, folderLocation);
2457            target.removeView(v);
2458
2459            FolderIcon fi =
2460                mLauncher.addFolder(target, container, screenId, targetCell[0], targetCell[1]);
2461            destInfo.cellX = -1;
2462            destInfo.cellY = -1;
2463            sourceInfo.cellX = -1;
2464            sourceInfo.cellY = -1;
2465
2466            // If the dragView is null, we can't animate
2467            boolean animate = dragView != null;
2468            if (animate) {
2469                // In order to keep everything continuous, we hand off the currently rendered
2470                // folder background to the newly created icon. This preserves animation state.
2471                fi.setFolderBackground(mFolderCreateBg);
2472                mFolderCreateBg = new FolderIcon.PreviewBackground();
2473                fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale,
2474                        postAnimationRunnable);
2475            } else {
2476                fi.prepareCreate(v);
2477                fi.addItem(destInfo);
2478                fi.addItem(sourceInfo);
2479            }
2480            return true;
2481        }
2482        return false;
2483    }
2484
2485    boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell,
2486            float distance, DragObject d, boolean external) {
2487        if (distance > mMaxDistanceForFolderCreation) return false;
2488
2489        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2490        if (!mAddToExistingFolderOnDrop) return false;
2491        mAddToExistingFolderOnDrop = false;
2492
2493        if (dropOverView instanceof FolderIcon) {
2494            FolderIcon fi = (FolderIcon) dropOverView;
2495            if (fi.acceptDrop(d.dragInfo)) {
2496                fi.onDrop(d);
2497
2498                // if the drag started here, we need to remove it from the workspace
2499                if (!external) {
2500                    getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2501                }
2502                return true;
2503            }
2504        }
2505        return false;
2506    }
2507
2508    @Override
2509    public void prepareAccessibilityDrop() { }
2510
2511    public void onDrop(final DragObject d) {
2512        mDragViewVisualCenter = d.getVisualCenter(mDragViewVisualCenter);
2513        CellLayout dropTargetLayout = mDropToLayout;
2514
2515        // We want the point to be mapped to the dragTarget.
2516        if (dropTargetLayout != null) {
2517            if (mLauncher.isHotseatLayout(dropTargetLayout)) {
2518                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
2519            } else {
2520                mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter);
2521            }
2522        }
2523
2524        int snapScreen = -1;
2525        boolean resizeOnDrop = false;
2526        if (d.dragSource != this) {
2527            final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0],
2528                    (int) mDragViewVisualCenter[1] };
2529            onDropExternal(touchXY, d.dragInfo, dropTargetLayout, d);
2530        } else if (mDragInfo != null) {
2531            final View cell = mDragInfo.cell;
2532            boolean droppedOnOriginalCellDuringTransition = false;
2533
2534            if (dropTargetLayout != null && !d.cancelled) {
2535                // Move internally
2536                boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout);
2537                boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout);
2538                long container = hasMovedIntoHotseat ?
2539                        LauncherSettings.Favorites.CONTAINER_HOTSEAT :
2540                        LauncherSettings.Favorites.CONTAINER_DESKTOP;
2541                long screenId = (mTargetCell[0] < 0) ?
2542                        mDragInfo.screenId : getIdForScreen(dropTargetLayout);
2543                int spanX = mDragInfo != null ? mDragInfo.spanX : 1;
2544                int spanY = mDragInfo != null ? mDragInfo.spanY : 1;
2545                // First we find the cell nearest to point at which the item is
2546                // dropped, without any consideration to whether there is an item there.
2547
2548                mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int)
2549                        mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell);
2550                float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0],
2551                        mDragViewVisualCenter[1], mTargetCell);
2552
2553                // If the item being dropped is a shortcut and the nearest drop
2554                // cell also contains a shortcut, then create a folder with the two shortcuts.
2555                if (!mInScrollArea && createUserFolderIfNecessary(cell, container,
2556                        dropTargetLayout, mTargetCell, distance, false, d.dragView, null)) {
2557                    return;
2558                }
2559
2560                if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell,
2561                        distance, d, false)) {
2562                    return;
2563                }
2564
2565                // Aside from the special case where we're dropping a shortcut onto a shortcut,
2566                // we need to find the nearest cell location that is vacant
2567                ItemInfo item = d.dragInfo;
2568                int minSpanX = item.spanX;
2569                int minSpanY = item.spanY;
2570                if (item.minSpanX > 0 && item.minSpanY > 0) {
2571                    minSpanX = item.minSpanX;
2572                    minSpanY = item.minSpanY;
2573                }
2574
2575                droppedOnOriginalCellDuringTransition = mIsSwitchingState
2576                        && item.screenId == screenId && item.container == container
2577                        && item.cellX == mTargetCell[0] && item.cellY == mTargetCell[1];
2578
2579                // When quickly moving an item, a user may accidentally rearrange their
2580                // workspace. So instead we move the icon back safely to its original position.
2581                boolean returnToOriginalCellToPreventShuffling = !isFinishedSwitchingState()
2582                        && !droppedOnOriginalCellDuringTransition && !dropTargetLayout
2583                        .isRegionVacant(mTargetCell[0], mTargetCell[1], spanX, spanY);
2584                int[] resultSpan = new int[2];
2585                if (returnToOriginalCellToPreventShuffling) {
2586                    mTargetCell[0] = mTargetCell[1] = -1;
2587                } else {
2588                    mTargetCell = dropTargetLayout.performReorder((int) mDragViewVisualCenter[0],
2589                            (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, cell,
2590                            mTargetCell, resultSpan, CellLayout.MODE_ON_DROP);
2591                }
2592
2593                boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0;
2594
2595                // if the widget resizes on drop
2596                if (foundCell && (cell instanceof AppWidgetHostView) &&
2597                        (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY)) {
2598                    resizeOnDrop = true;
2599                    item.spanX = resultSpan[0];
2600                    item.spanY = resultSpan[1];
2601                    AppWidgetHostView awhv = (AppWidgetHostView) cell;
2602                    AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, resultSpan[0],
2603                            resultSpan[1]);
2604                }
2605
2606                if (foundCell) {
2607                    if (getScreenIdForPageIndex(mCurrentPage) != screenId && !hasMovedIntoHotseat) {
2608                        snapScreen = getPageIndexForScreenId(screenId);
2609                        snapToPage(snapScreen);
2610                    }
2611
2612                    final ItemInfo info = (ItemInfo) cell.getTag();
2613                    if (hasMovedLayouts) {
2614                        // Reparent the view
2615                        CellLayout parentCell = getParentCellLayoutForView(cell);
2616                        if (parentCell != null) {
2617                            parentCell.removeView(cell);
2618                        } else if (ProviderConfig.IS_DOGFOOD_BUILD) {
2619                            throw new NullPointerException("mDragInfo.cell has null parent");
2620                        }
2621                        addInScreen(cell, container, screenId, mTargetCell[0], mTargetCell[1],
2622                                info.spanX, info.spanY);
2623                    }
2624
2625                    // update the item's position after drop
2626                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
2627                    lp.cellX = lp.tmpCellX = mTargetCell[0];
2628                    lp.cellY = lp.tmpCellY = mTargetCell[1];
2629                    lp.cellHSpan = item.spanX;
2630                    lp.cellVSpan = item.spanY;
2631                    lp.isLockedToGrid = true;
2632
2633                    if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
2634                            cell instanceof LauncherAppWidgetHostView) {
2635                        final CellLayout cellLayout = dropTargetLayout;
2636                        // We post this call so that the widget has a chance to be placed
2637                        // in its final location
2638
2639                        final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell;
2640                        AppWidgetProviderInfo pInfo = hostView.getAppWidgetInfo();
2641                        if (pInfo != null && pInfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE
2642                                && !d.accessibleDrag) {
2643                            mDelayedResizeRunnable = new Runnable() {
2644                                public void run() {
2645                                    if (!isPageInTransition()) {
2646                                        DragLayer dragLayer = mLauncher.getDragLayer();
2647                                        dragLayer.addResizeFrame(hostView, cellLayout);
2648                                    }
2649                                }
2650                            };
2651                        }
2652                    }
2653
2654                    LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId, lp.cellX,
2655                            lp.cellY, item.spanX, item.spanY);
2656                } else {
2657                    if (!returnToOriginalCellToPreventShuffling) {
2658                        onNoCellFound(dropTargetLayout);
2659                    }
2660
2661                    // If we can't find a drop location, we return the item to its original position
2662                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
2663                    mTargetCell[0] = lp.cellX;
2664                    mTargetCell[1] = lp.cellY;
2665                    CellLayout layout = (CellLayout) cell.getParent().getParent();
2666                    layout.markCellsAsOccupiedForView(cell);
2667                }
2668            }
2669
2670            final CellLayout parent = (CellLayout) cell.getParent().getParent();
2671            // Prepare it to be animated into its new position
2672            // This must be called after the view has been re-parented
2673            final Runnable onCompleteRunnable = new Runnable() {
2674                @Override
2675                public void run() {
2676                    mAnimatingViewIntoPlace = false;
2677                    updateChildrenLayersEnabled(false);
2678                }
2679            };
2680            mAnimatingViewIntoPlace = true;
2681            if (d.dragView.hasDrawn()) {
2682                if (droppedOnOriginalCellDuringTransition) {
2683                    // Animate the item to its original position, while simultaneously exiting
2684                    // spring-loaded mode so the page meets the icon where it was picked up.
2685                    mLauncher.getDragController().animateDragViewToOriginalPosition(
2686                            mDelayedResizeRunnable, cell,
2687                            mStateTransitionAnimation.mSpringLoadedTransitionTime);
2688                    mLauncher.exitSpringLoadedDragMode();
2689                    mLauncher.getDropTargetBar().onDragEnd();
2690                    parent.onDropChild(cell);
2691                    return;
2692                }
2693                final ItemInfo info = (ItemInfo) cell.getTag();
2694                boolean isWidget = info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET
2695                        || info.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
2696                if (isWidget) {
2697                    int animationType = resizeOnDrop ? ANIMATE_INTO_POSITION_AND_RESIZE :
2698                            ANIMATE_INTO_POSITION_AND_DISAPPEAR;
2699                    animateWidgetDrop(info, parent, d.dragView,
2700                            onCompleteRunnable, animationType, cell, false);
2701                } else {
2702                    int duration = snapScreen < 0 ? -1 : ADJACENT_SCREEN_DROP_DURATION;
2703                    mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration,
2704                            onCompleteRunnable, this);
2705                }
2706            } else {
2707                d.deferDragViewCleanupPostAnimation = false;
2708                cell.setVisibility(VISIBLE);
2709            }
2710            parent.onDropChild(cell);
2711        }
2712        if (d.stateAnnouncer != null) {
2713            d.stateAnnouncer.completeAction(R.string.item_moved);
2714        }
2715    }
2716
2717    public void onNoCellFound(View dropTargetLayout) {
2718        if (mLauncher.isHotseatLayout(dropTargetLayout)) {
2719            Hotseat hotseat = mLauncher.getHotseat();
2720            boolean droppedOnAllAppsIcon = !FeatureFlags.NO_ALL_APPS_ICON
2721                    && mTargetCell != null && !mLauncher.getDeviceProfile().inv.isAllAppsButtonRank(
2722                    hotseat.getOrderInHotseat(mTargetCell[0], mTargetCell[1]));
2723            if (!droppedOnAllAppsIcon) {
2724                // Only show message when hotseat is full and drop target was not AllApps button
2725                showOutOfSpaceMessage(true);
2726            }
2727        } else {
2728            showOutOfSpaceMessage(false);
2729        }
2730    }
2731
2732    private void showOutOfSpaceMessage(boolean isHotseatLayout) {
2733        int strId = (isHotseatLayout ? R.string.hotseat_out_of_space : R.string.out_of_space);
2734        Toast.makeText(mLauncher, mLauncher.getString(strId), Toast.LENGTH_SHORT).show();
2735    }
2736
2737    /**
2738     * Computes the area relative to dragLayer which is used to display a page.
2739     */
2740    public void getPageAreaRelativeToDragLayer(Rect outArea) {
2741        CellLayout child = (CellLayout) getChildAt(getNextPage());
2742        if (child == null) {
2743            return;
2744        }
2745        ShortcutAndWidgetContainer boundingLayout = child.getShortcutsAndWidgets();
2746
2747        // Use the absolute left instead of the child left, as we want the visible area
2748        // irrespective of the visible child. Since the view can only scroll horizontally, the
2749        // top position is not affected.
2750        mTempXY[0] = getViewportOffsetX() + getPaddingLeft() + boundingLayout.getLeft();
2751        mTempXY[1] = child.getTop() + boundingLayout.getTop();
2752
2753        float scale = mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempXY);
2754        outArea.set(mTempXY[0], mTempXY[1],
2755                (int) (mTempXY[0] + scale * boundingLayout.getMeasuredWidth()),
2756                (int) (mTempXY[1] + scale * boundingLayout.getMeasuredHeight()));
2757    }
2758
2759    @Override
2760    public void onDragEnter(DragObject d) {
2761        if (ENFORCE_DRAG_EVENT_ORDER) {
2762            enforceDragParity("onDragEnter", 1, 1);
2763        }
2764
2765        mCreateUserFolderOnDrop = false;
2766        mAddToExistingFolderOnDrop = false;
2767
2768        mDropToLayout = null;
2769        setDropLayoutForDragObject(d);
2770
2771        if (!workspaceInModalState() && FeatureFlags.LAUNCHER3_LEGACY_WORKSPACE_DND) {
2772            mLauncher.getDragLayer().showPageHints();
2773        }
2774    }
2775
2776    @Override
2777    public void onDragExit(DragObject d) {
2778        if (ENFORCE_DRAG_EVENT_ORDER) {
2779            enforceDragParity("onDragExit", -1, 0);
2780        }
2781
2782        // Here we store the final page that will be dropped to, if the workspace in fact
2783        // receives the drop
2784        if (mInScrollArea) {
2785            if (isPageInTransition()) {
2786                // If the user drops while the page is scrolling, we should use that page as the
2787                // destination instead of the page that is being hovered over.
2788                mDropToLayout = (CellLayout) getPageAt(getNextPage());
2789            } else {
2790                mDropToLayout = mDragOverlappingLayout;
2791            }
2792        } else {
2793            mDropToLayout = mDragTargetLayout;
2794        }
2795
2796        if (mDragMode == DRAG_MODE_CREATE_FOLDER) {
2797            mCreateUserFolderOnDrop = true;
2798        } else if (mDragMode == DRAG_MODE_ADD_TO_FOLDER) {
2799            mAddToExistingFolderOnDrop = true;
2800        }
2801
2802        // Reset the scroll area and previous drag target
2803        onResetScrollArea();
2804        setCurrentDropLayout(null);
2805        setCurrentDragOverlappingLayout(null);
2806
2807        mSpringLoadedDragController.cancel();
2808
2809        mLauncher.getDragLayer().hidePageHints();
2810    }
2811
2812    private void enforceDragParity(String event, int update, int expectedValue) {
2813        enforceDragParity(this, event, update, expectedValue);
2814        for (int i = 0; i < getChildCount(); i++) {
2815            enforceDragParity(getChildAt(i), event, update, expectedValue);
2816        }
2817    }
2818
2819    private void enforceDragParity(View v, String event, int update, int expectedValue) {
2820        Object tag = v.getTag(R.id.drag_event_parity);
2821        int value = tag == null ? 0 : (Integer) tag;
2822        value += update;
2823        v.setTag(R.id.drag_event_parity, value);
2824
2825        if (value != expectedValue) {
2826            Log.e(TAG, event + ": Drag contract violated: " + value);
2827        }
2828    }
2829
2830    void setCurrentDropLayout(CellLayout layout) {
2831        if (mDragTargetLayout != null) {
2832            mDragTargetLayout.revertTempState();
2833            mDragTargetLayout.onDragExit();
2834        }
2835        mDragTargetLayout = layout;
2836        if (mDragTargetLayout != null) {
2837            mDragTargetLayout.onDragEnter();
2838        }
2839        cleanupReorder(true);
2840        cleanupFolderCreation();
2841        setCurrentDropOverCell(-1, -1);
2842    }
2843
2844    void setCurrentDragOverlappingLayout(CellLayout layout) {
2845        if (mDragOverlappingLayout != null) {
2846            mDragOverlappingLayout.setIsDragOverlapping(false);
2847        }
2848        mDragOverlappingLayout = layout;
2849        if (mDragOverlappingLayout != null) {
2850            mDragOverlappingLayout.setIsDragOverlapping(true);
2851        }
2852        // Invalidating the scrim will also force this CellLayout
2853        // to be invalidated so that it is highlighted if necessary.
2854        mLauncher.getDragLayer().invalidateScrim();
2855    }
2856
2857    public CellLayout getCurrentDragOverlappingLayout() {
2858        return mDragOverlappingLayout;
2859    }
2860
2861    void setCurrentDropOverCell(int x, int y) {
2862        if (x != mDragOverX || y != mDragOverY) {
2863            mDragOverX = x;
2864            mDragOverY = y;
2865            setDragMode(DRAG_MODE_NONE);
2866        }
2867    }
2868
2869    void setDragMode(int dragMode) {
2870        if (dragMode != mDragMode) {
2871            if (dragMode == DRAG_MODE_NONE) {
2872                cleanupAddToFolder();
2873                // We don't want to cancel the re-order alarm every time the target cell changes
2874                // as this feels to slow / unresponsive.
2875                cleanupReorder(false);
2876                cleanupFolderCreation();
2877            } else if (dragMode == DRAG_MODE_ADD_TO_FOLDER) {
2878                cleanupReorder(true);
2879                cleanupFolderCreation();
2880            } else if (dragMode == DRAG_MODE_CREATE_FOLDER) {
2881                cleanupAddToFolder();
2882                cleanupReorder(true);
2883            } else if (dragMode == DRAG_MODE_REORDER) {
2884                cleanupAddToFolder();
2885                cleanupFolderCreation();
2886            }
2887            mDragMode = dragMode;
2888        }
2889    }
2890
2891    private void cleanupFolderCreation() {
2892        if (mFolderCreateBg != null) {
2893            mFolderCreateBg.animateToRest();
2894        }
2895        mFolderCreationAlarm.setOnAlarmListener(null);
2896        mFolderCreationAlarm.cancelAlarm();
2897    }
2898
2899    private void cleanupAddToFolder() {
2900        if (mDragOverFolderIcon != null) {
2901            mDragOverFolderIcon.onDragExit();
2902            mDragOverFolderIcon = null;
2903        }
2904    }
2905
2906    private void cleanupReorder(boolean cancelAlarm) {
2907        // Any pending reorders are canceled
2908        if (cancelAlarm) {
2909            mReorderAlarm.cancelAlarm();
2910        }
2911        mLastReorderX = -1;
2912        mLastReorderY = -1;
2913    }
2914
2915   /*
2916    *
2917    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2918    * coordinate space. The argument xy is modified with the return result.
2919    */
2920   void mapPointFromSelfToChild(View v, float[] xy) {
2921       xy[0] = xy[0] - v.getLeft();
2922       xy[1] = xy[1] - v.getTop();
2923   }
2924
2925   boolean isPointInSelfOverHotseat(int x, int y) {
2926       mTempXY[0] = x;
2927       mTempXY[1] = y;
2928       mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempXY, true);
2929       View hotseat = mLauncher.getHotseat();
2930       return mTempXY[0] >= hotseat.getLeft() &&
2931               mTempXY[0] <= hotseat.getRight() &&
2932               mTempXY[1] >= hotseat.getTop() &&
2933               mTempXY[1] <= hotseat.getBottom();
2934   }
2935
2936   void mapPointFromSelfToHotseatLayout(Hotseat hotseat, float[] xy) {
2937       mTempXY[0] = (int) xy[0];
2938       mTempXY[1] = (int) xy[1];
2939       mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempXY, true);
2940       mLauncher.getDragLayer().mapCoordInSelfToDescendant(hotseat.getLayout(), mTempXY);
2941
2942       xy[0] = mTempXY[0];
2943       xy[1] = mTempXY[1];
2944   }
2945
2946   /*
2947    *
2948    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
2949    * the parent View's coordinate space. The argument xy is modified with the return result.
2950    *
2951    */
2952   void mapPointFromChildToSelf(View v, float[] xy) {
2953       xy[0] += v.getLeft();
2954       xy[1] += v.getTop();
2955   }
2956
2957   static private float squaredDistance(float[] point1, float[] point2) {
2958        float distanceX = point1[0] - point2[0];
2959        float distanceY = point2[1] - point2[1];
2960        return distanceX * distanceX + distanceY * distanceY;
2961   }
2962
2963    /*
2964     *
2965     * This method returns the CellLayout that is currently being dragged to. In order to drag
2966     * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
2967     * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
2968     *
2969     * Return null if no CellLayout is currently being dragged over
2970     *
2971     */
2972    private CellLayout findMatchingPageForDragOver(
2973            DragView dragView, float originX, float originY, boolean exact) {
2974        // We loop through all the screens (ie CellLayouts) and see which ones overlap
2975        // with the item being dragged and then choose the one that's closest to the touch point
2976        final int screenCount = getChildCount();
2977        CellLayout bestMatchingScreen = null;
2978        float smallestDistSoFar = Float.MAX_VALUE;
2979
2980        for (int i = 0; i < screenCount; i++) {
2981            // The custom content screen is not a valid drag over option
2982            if (mScreenOrder.get(i) == CUSTOM_CONTENT_SCREEN_ID) {
2983                continue;
2984            }
2985
2986            CellLayout cl = (CellLayout) getChildAt(i);
2987
2988            final float[] touchXy = {originX, originY};
2989            mapPointFromSelfToChild(cl, touchXy);
2990
2991            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
2992                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
2993                return cl;
2994            }
2995
2996            if (!exact) {
2997                // Get the center of the cell layout in screen coordinates
2998                final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
2999                cellLayoutCenter[0] = cl.getWidth()/2;
3000                cellLayoutCenter[1] = cl.getHeight()/2;
3001                mapPointFromChildToSelf(cl, cellLayoutCenter);
3002
3003                touchXy[0] = originX;
3004                touchXy[1] = originY;
3005
3006                // Calculate the distance between the center of the CellLayout
3007                // and the touch point
3008                float dist = squaredDistance(touchXy, cellLayoutCenter);
3009
3010                if (dist < smallestDistSoFar) {
3011                    smallestDistSoFar = dist;
3012                    bestMatchingScreen = cl;
3013                }
3014            }
3015        }
3016        return bestMatchingScreen;
3017    }
3018
3019    private boolean isDragWidget(DragObject d) {
3020        return (d.dragInfo instanceof LauncherAppWidgetInfo ||
3021                d.dragInfo instanceof PendingAddWidgetInfo);
3022    }
3023
3024    public void onDragOver(DragObject d) {
3025        // Skip drag over events while we are dragging over side pages
3026        if (mInScrollArea || !transitionStateShouldAllowDrop()) return;
3027
3028        ItemInfo item = d.dragInfo;
3029        if (item == null) {
3030            if (ProviderConfig.IS_DOGFOOD_BUILD) {
3031                throw new NullPointerException("DragObject has null info");
3032            }
3033            return;
3034        }
3035
3036        // Ensure that we have proper spans for the item that we are dropping
3037        if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found");
3038        mDragViewVisualCenter = d.getVisualCenter(mDragViewVisualCenter);
3039
3040        final View child = (mDragInfo == null) ? null : mDragInfo.cell;
3041        if (setDropLayoutForDragObject(d)) {
3042            boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED);
3043            if (isInSpringLoadedMode) {
3044                if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
3045                    mSpringLoadedDragController.cancel();
3046                } else {
3047                    mSpringLoadedDragController.setAlarm(mDragTargetLayout);
3048                }
3049            }
3050        }
3051
3052        // Handle the drag over
3053        if (mDragTargetLayout != null) {
3054            // We want the point to be mapped to the dragTarget.
3055            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
3056                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
3057            } else {
3058                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter);
3059            }
3060
3061            int minSpanX = item.spanX;
3062            int minSpanY = item.spanY;
3063            if (item.minSpanX > 0 && item.minSpanY > 0) {
3064                minSpanX = item.minSpanX;
3065                minSpanY = item.minSpanY;
3066            }
3067
3068            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
3069                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY,
3070                    mDragTargetLayout, mTargetCell);
3071            int reorderX = mTargetCell[0];
3072            int reorderY = mTargetCell[1];
3073
3074            setCurrentDropOverCell(mTargetCell[0], mTargetCell[1]);
3075
3076            float targetCellDistance = mDragTargetLayout.getDistanceFromCell(
3077                    mDragViewVisualCenter[0], mDragViewVisualCenter[1], mTargetCell);
3078
3079            manageFolderFeedback(mDragTargetLayout, mTargetCell, targetCellDistance, d);
3080
3081            boolean nearestDropOccupied = mDragTargetLayout.isNearestDropLocationOccupied((int)
3082                    mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], item.spanX,
3083                    item.spanY, child, mTargetCell);
3084
3085            if (!nearestDropOccupied) {
3086                mDragTargetLayout.visualizeDropLocation(child, mOutlineProvider,
3087                        mTargetCell[0], mTargetCell[1], item.spanX, item.spanY, false, d);
3088            } else if ((mDragMode == DRAG_MODE_NONE || mDragMode == DRAG_MODE_REORDER)
3089                    && !mReorderAlarm.alarmPending() && (mLastReorderX != reorderX ||
3090                    mLastReorderY != reorderY)) {
3091
3092                int[] resultSpan = new int[2];
3093                mDragTargetLayout.performReorder((int) mDragViewVisualCenter[0],
3094                        (int) mDragViewVisualCenter[1], minSpanX, minSpanY, item.spanX, item.spanY,
3095                        child, mTargetCell, resultSpan, CellLayout.MODE_SHOW_REORDER_HINT);
3096
3097                // Otherwise, if we aren't adding to or creating a folder and there's no pending
3098                // reorder, then we schedule a reorder
3099                ReorderAlarmListener listener = new ReorderAlarmListener(mDragViewVisualCenter,
3100                        minSpanX, minSpanY, item.spanX, item.spanY, d, child);
3101                mReorderAlarm.setOnAlarmListener(listener);
3102                mReorderAlarm.setAlarm(REORDER_TIMEOUT);
3103            }
3104
3105            if (mDragMode == DRAG_MODE_CREATE_FOLDER || mDragMode == DRAG_MODE_ADD_TO_FOLDER ||
3106                    !nearestDropOccupied) {
3107                if (mDragTargetLayout != null) {
3108                    mDragTargetLayout.revertTempState();
3109                }
3110            }
3111        }
3112    }
3113
3114    /**
3115     * Updates {@link #mDragTargetLayout} and {@link #mDragOverlappingLayout}
3116     * based on the DragObject's position.
3117     *
3118     * The layout will be:
3119     * - The Hotseat if the drag object is over it
3120     * - A side page if we are in spring-loaded mode and the drag object is over it
3121     * - The current page otherwise
3122     *
3123     * @return whether the layout is different from the current {@link #mDragTargetLayout}.
3124     */
3125    private boolean setDropLayoutForDragObject(DragObject d) {
3126        CellLayout layout = null;
3127        // Test to see if we are over the hotseat first
3128        if (mLauncher.getHotseat() != null && !isDragWidget(d)) {
3129            if (isPointInSelfOverHotseat(d.x, d.y)) {
3130                layout = mLauncher.getHotseat().getLayout();
3131            }
3132        }
3133        if (layout == null) {
3134            // Identify whether we have dragged over a side page,
3135            // otherwise just use the current page
3136            layout = workspaceInModalState() ?
3137                    findMatchingPageForDragOver(d.dragView, d.x, d.y, false)
3138                    : getCurrentDropLayout();
3139        }
3140        if (layout != mDragTargetLayout) {
3141            setCurrentDropLayout(layout);
3142            setCurrentDragOverlappingLayout(layout);
3143            return true;
3144        }
3145        return false;
3146    }
3147
3148    private void manageFolderFeedback(CellLayout targetLayout,
3149            int[] targetCell, float distance, DragObject dragObject) {
3150        if (distance > mMaxDistanceForFolderCreation) return;
3151
3152        final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0], mTargetCell[1]);
3153        ItemInfo info = dragObject.dragInfo;
3154        boolean userFolderPending = willCreateUserFolder(info, dragOverView, false);
3155        if (mDragMode == DRAG_MODE_NONE && userFolderPending &&
3156                !mFolderCreationAlarm.alarmPending()) {
3157
3158            FolderCreationAlarmListener listener = new
3159                    FolderCreationAlarmListener(targetLayout, targetCell[0], targetCell[1]);
3160
3161            if (!dragObject.accessibleDrag) {
3162                mFolderCreationAlarm.setOnAlarmListener(listener);
3163                mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT);
3164            } else {
3165                listener.onAlarm(mFolderCreationAlarm);
3166            }
3167
3168            if (dragObject.stateAnnouncer != null) {
3169                dragObject.stateAnnouncer.announce(WorkspaceAccessibilityHelper
3170                        .getDescriptionForDropOver(dragOverView, getContext()));
3171            }
3172            return;
3173        }
3174
3175        boolean willAddToFolder = willAddToExistingUserFolder(info, dragOverView);
3176        if (willAddToFolder && mDragMode == DRAG_MODE_NONE) {
3177            mDragOverFolderIcon = ((FolderIcon) dragOverView);
3178            mDragOverFolderIcon.onDragEnter(info);
3179            if (targetLayout != null) {
3180                targetLayout.clearDragOutlines();
3181            }
3182            setDragMode(DRAG_MODE_ADD_TO_FOLDER);
3183
3184            if (dragObject.stateAnnouncer != null) {
3185                dragObject.stateAnnouncer.announce(WorkspaceAccessibilityHelper
3186                        .getDescriptionForDropOver(dragOverView, getContext()));
3187            }
3188            return;
3189        }
3190
3191        if (mDragMode == DRAG_MODE_ADD_TO_FOLDER && !willAddToFolder) {
3192            setDragMode(DRAG_MODE_NONE);
3193        }
3194        if (mDragMode == DRAG_MODE_CREATE_FOLDER && !userFolderPending) {
3195            setDragMode(DRAG_MODE_NONE);
3196        }
3197    }
3198
3199    class FolderCreationAlarmListener implements OnAlarmListener {
3200        CellLayout layout;
3201        int cellX;
3202        int cellY;
3203
3204        FolderIcon.PreviewBackground bg = new FolderIcon.PreviewBackground();
3205
3206        public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) {
3207            this.layout = layout;
3208            this.cellX = cellX;
3209            this.cellY = cellY;
3210
3211            DeviceProfile grid = mLauncher.getDeviceProfile();
3212            BubbleTextView cell = (BubbleTextView) layout.getChildAt(cellX, cellY);
3213
3214            bg.setup(getResources().getDisplayMetrics(), grid, null,
3215                    cell.getMeasuredWidth(), cell.getPaddingTop());
3216
3217            // The full preview background should appear behind the icon
3218            bg.isClipping = false;
3219        }
3220
3221        public void onAlarm(Alarm alarm) {
3222            mFolderCreateBg = bg;
3223            mFolderCreateBg.animateToAccept(layout, cellX, cellY);
3224            layout.clearDragOutlines();
3225            setDragMode(DRAG_MODE_CREATE_FOLDER);
3226        }
3227    }
3228
3229    class ReorderAlarmListener implements OnAlarmListener {
3230        float[] dragViewCenter;
3231        int minSpanX, minSpanY, spanX, spanY;
3232        DragObject dragObject;
3233        View child;
3234
3235        public ReorderAlarmListener(float[] dragViewCenter, int minSpanX, int minSpanY, int spanX,
3236                int spanY, DragObject dragObject, View child) {
3237            this.dragViewCenter = dragViewCenter;
3238            this.minSpanX = minSpanX;
3239            this.minSpanY = minSpanY;
3240            this.spanX = spanX;
3241            this.spanY = spanY;
3242            this.child = child;
3243            this.dragObject = dragObject;
3244        }
3245
3246        public void onAlarm(Alarm alarm) {
3247            int[] resultSpan = new int[2];
3248            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
3249                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, mDragTargetLayout,
3250                    mTargetCell);
3251            mLastReorderX = mTargetCell[0];
3252            mLastReorderY = mTargetCell[1];
3253
3254            mTargetCell = mDragTargetLayout.performReorder((int) mDragViewVisualCenter[0],
3255                (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY,
3256                child, mTargetCell, resultSpan, CellLayout.MODE_DRAG_OVER);
3257
3258            if (mTargetCell[0] < 0 || mTargetCell[1] < 0) {
3259                mDragTargetLayout.revertTempState();
3260            } else {
3261                setDragMode(DRAG_MODE_REORDER);
3262            }
3263
3264            boolean resize = resultSpan[0] != spanX || resultSpan[1] != spanY;
3265            mDragTargetLayout.visualizeDropLocation(child, mOutlineProvider,
3266                mTargetCell[0], mTargetCell[1], resultSpan[0], resultSpan[1], resize, dragObject);
3267        }
3268    }
3269
3270    @Override
3271    public void getHitRectRelativeToDragLayer(Rect outRect) {
3272        // We want the workspace to have the whole area of the display (it will find the correct
3273        // cell layout to drop to in the existing drag/drop logic.
3274        mLauncher.getDragLayer().getDescendantRectRelativeToSelf(this, outRect);
3275    }
3276
3277    /**
3278     * Drop an item that didn't originate on one of the workspace screens.
3279     * It may have come from Launcher (e.g. from all apps or customize), or it may have
3280     * come from another app altogether.
3281     *
3282     * NOTE: This can also be called when we are outside of a drag event, when we want
3283     * to add an item to one of the workspace screens.
3284     */
3285    private void onDropExternal(final int[] touchXY, final ItemInfo dragInfo,
3286            final CellLayout cellLayout, DragObject d) {
3287        final Runnable exitSpringLoadedRunnable = new Runnable() {
3288            @Override
3289            public void run() {
3290                mLauncher.exitSpringLoadedDragModeDelayed(true,
3291                        Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, null);
3292            }
3293        };
3294
3295        ItemInfo info = dragInfo;
3296        int spanX = info.spanX;
3297        int spanY = info.spanY;
3298        if (mDragInfo != null) {
3299            spanX = mDragInfo.spanX;
3300            spanY = mDragInfo.spanY;
3301        }
3302
3303        final long container = mLauncher.isHotseatLayout(cellLayout) ?
3304                LauncherSettings.Favorites.CONTAINER_HOTSEAT :
3305                    LauncherSettings.Favorites.CONTAINER_DESKTOP;
3306        final long screenId = getIdForScreen(cellLayout);
3307        if (!mLauncher.isHotseatLayout(cellLayout)
3308                && screenId != getScreenIdForPageIndex(mCurrentPage)
3309                && mState != State.SPRING_LOADED) {
3310            snapToScreenId(screenId, null);
3311        }
3312
3313        if (info instanceof PendingAddItemInfo) {
3314            final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo;
3315
3316            boolean findNearestVacantCell = true;
3317            if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
3318                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
3319                        cellLayout, mTargetCell);
3320                float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0],
3321                        mDragViewVisualCenter[1], mTargetCell);
3322                if (willCreateUserFolder(d.dragInfo, cellLayout, mTargetCell, distance, true)
3323                        || willAddToExistingUserFolder(
3324                                d.dragInfo, cellLayout, mTargetCell, distance)) {
3325                    findNearestVacantCell = false;
3326                }
3327            }
3328
3329            final ItemInfo item = d.dragInfo;
3330            boolean updateWidgetSize = false;
3331            if (findNearestVacantCell) {
3332                int minSpanX = item.spanX;
3333                int minSpanY = item.spanY;
3334                if (item.minSpanX > 0 && item.minSpanY > 0) {
3335                    minSpanX = item.minSpanX;
3336                    minSpanY = item.minSpanY;
3337                }
3338                int[] resultSpan = new int[2];
3339                mTargetCell = cellLayout.performReorder((int) mDragViewVisualCenter[0],
3340                        (int) mDragViewVisualCenter[1], minSpanX, minSpanY, info.spanX, info.spanY,
3341                        null, mTargetCell, resultSpan, CellLayout.MODE_ON_DROP_EXTERNAL);
3342
3343                if (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY) {
3344                    updateWidgetSize = true;
3345                }
3346                item.spanX = resultSpan[0];
3347                item.spanY = resultSpan[1];
3348            }
3349
3350            Runnable onAnimationCompleteRunnable = new Runnable() {
3351                @Override
3352                public void run() {
3353                    // Normally removeExtraEmptyScreen is called in Workspace#onDragEnd, but when
3354                    // adding an item that may not be dropped right away (due to a config activity)
3355                    // we defer the removal until the activity returns.
3356                    deferRemoveExtraEmptyScreen();
3357
3358                    // When dragging and dropping from customization tray, we deal with creating
3359                    // widgets/shortcuts/folders in a slightly different way
3360                    mLauncher.addPendingItem(pendingInfo, container, screenId, mTargetCell,
3361                            item.spanX, item.spanY);
3362                }
3363            };
3364            boolean isWidget = pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET
3365                    || pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
3366
3367            AppWidgetHostView finalView = isWidget ?
3368                    ((PendingAddWidgetInfo) pendingInfo).boundWidget : null;
3369
3370            if (finalView != null && updateWidgetSize) {
3371                AppWidgetResizeFrame.updateWidgetSizeRanges(finalView, mLauncher, item.spanX,
3372                        item.spanY);
3373            }
3374
3375            int animationStyle = ANIMATE_INTO_POSITION_AND_DISAPPEAR;
3376            if (isWidget && ((PendingAddWidgetInfo) pendingInfo).info != null &&
3377                    ((PendingAddWidgetInfo) pendingInfo).info.configure != null) {
3378                animationStyle = ANIMATE_INTO_POSITION_AND_REMAIN;
3379            }
3380            animateWidgetDrop(info, cellLayout, d.dragView, onAnimationCompleteRunnable,
3381                    animationStyle, finalView, true);
3382        } else {
3383            // This is for other drag/drop cases, like dragging from All Apps
3384            View view = null;
3385
3386            switch (info.itemType) {
3387            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
3388            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3389            case LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT:
3390                if (info.container == NO_ID && info instanceof AppInfo) {
3391                    // Came from all apps -- make a copy
3392                    info = ((AppInfo) info).makeShortcut();
3393                    d.dragInfo = info;
3394                }
3395                view = mLauncher.createShortcut(cellLayout, (ShortcutInfo) info);
3396                break;
3397            case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
3398                view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout,
3399                        (FolderInfo) info, mIconCache);
3400                break;
3401            default:
3402                throw new IllegalStateException("Unknown item type: " + info.itemType);
3403            }
3404
3405            // First we find the cell nearest to point at which the item is
3406            // dropped, without any consideration to whether there is an item there.
3407            if (touchXY != null) {
3408                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
3409                        cellLayout, mTargetCell);
3410                float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0],
3411                        mDragViewVisualCenter[1], mTargetCell);
3412                d.postAnimationRunnable = exitSpringLoadedRunnable;
3413                if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, distance,
3414                        true, d.dragView, d.postAnimationRunnable)) {
3415                    return;
3416                }
3417                if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, distance, d,
3418                        true)) {
3419                    return;
3420                }
3421            }
3422
3423            if (touchXY != null) {
3424                // when dragging and dropping, just find the closest free spot
3425                mTargetCell = cellLayout.performReorder((int) mDragViewVisualCenter[0],
3426                        (int) mDragViewVisualCenter[1], 1, 1, 1, 1,
3427                        null, mTargetCell, null, CellLayout.MODE_ON_DROP_EXTERNAL);
3428            } else {
3429                cellLayout.findCellForSpan(mTargetCell, 1, 1);
3430            }
3431            // Add the item to DB before adding to screen ensures that the container and other
3432            // values of the info is properly updated.
3433            LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screenId,
3434                    mTargetCell[0], mTargetCell[1]);
3435
3436            addInScreen(view, container, screenId, mTargetCell[0], mTargetCell[1],
3437                    info.spanX, info.spanY);
3438            cellLayout.onDropChild(view);
3439            cellLayout.getShortcutsAndWidgets().measureChild(view);
3440
3441            if (d.dragView != null) {
3442                // We wrap the animation call in the temporary set and reset of the current
3443                // cellLayout to its final transform -- this means we animate the drag view to
3444                // the correct final location.
3445                setFinalTransitionTransform(cellLayout);
3446                mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view,
3447                        exitSpringLoadedRunnable, this);
3448                resetTransitionTransform(cellLayout);
3449            }
3450        }
3451    }
3452
3453    public Bitmap createWidgetBitmap(ItemInfo widgetInfo, View layout) {
3454        int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(widgetInfo, false);
3455        int visibility = layout.getVisibility();
3456        layout.setVisibility(VISIBLE);
3457
3458        int width = MeasureSpec.makeMeasureSpec(unScaledSize[0], MeasureSpec.EXACTLY);
3459        int height = MeasureSpec.makeMeasureSpec(unScaledSize[1], MeasureSpec.EXACTLY);
3460        Bitmap b = Bitmap.createBitmap(unScaledSize[0], unScaledSize[1],
3461                Bitmap.Config.ARGB_8888);
3462        mCanvas.setBitmap(b);
3463
3464        layout.measure(width, height);
3465        layout.layout(0, 0, unScaledSize[0], unScaledSize[1]);
3466        layout.draw(mCanvas);
3467        mCanvas.setBitmap(null);
3468        layout.setVisibility(visibility);
3469        return b;
3470    }
3471
3472    private void getFinalPositionForDropAnimation(int[] loc, float[] scaleXY,
3473            DragView dragView, CellLayout layout, ItemInfo info, int[] targetCell, boolean scale) {
3474        // Now we animate the dragView, (ie. the widget or shortcut preview) into its final
3475        // location and size on the home screen.
3476        int spanX = info.spanX;
3477        int spanY = info.spanY;
3478
3479        Rect r = estimateItemPosition(layout, targetCell[0], targetCell[1], spanX, spanY);
3480        loc[0] = r.left;
3481        loc[1] = r.top;
3482
3483        setFinalTransitionTransform(layout);
3484        float cellLayoutScale =
3485                mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(layout, loc, true);
3486        resetTransitionTransform(layout);
3487
3488        float dragViewScaleX = 1f;
3489        float dragViewScaleY = 1f;
3490        if (scale) {
3491            float width = info.spanX * layout.mCellWidth;
3492            float height = info.spanY * layout.mCellHeight;
3493
3494            dragViewScaleX = r.width() / width;
3495            dragViewScaleY = r.height() / height;
3496        }
3497
3498        // The animation will scale the dragView about its center, so we need to center about
3499        // the final location.
3500        loc[0] -= (dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2
3501                - Math.ceil(layout.getUnusedHorizontalSpace() / 2f);
3502        loc[1] -= (dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2;
3503
3504        scaleXY[0] = dragViewScaleX * cellLayoutScale;
3505        scaleXY[1] = dragViewScaleY * cellLayoutScale;
3506    }
3507
3508    public void animateWidgetDrop(ItemInfo info, CellLayout cellLayout, final DragView dragView,
3509            final Runnable onCompleteRunnable, int animationType, final View finalView,
3510            boolean external) {
3511        Rect from = new Rect();
3512        mLauncher.getDragLayer().getViewRectRelativeToSelf(dragView, from);
3513
3514        int[] finalPos = new int[2];
3515        float scaleXY[] = new float[2];
3516        boolean scalePreview = !(info instanceof PendingAddShortcutInfo);
3517        getFinalPositionForDropAnimation(finalPos, scaleXY, dragView, cellLayout, info, mTargetCell,
3518                scalePreview);
3519
3520        Resources res = mLauncher.getResources();
3521        final int duration = res.getInteger(R.integer.config_dropAnimMaxDuration) - 200;
3522
3523        boolean isWidget = info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET ||
3524                info.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
3525        if ((animationType == ANIMATE_INTO_POSITION_AND_RESIZE || external) && finalView != null) {
3526            Bitmap crossFadeBitmap = createWidgetBitmap(info, finalView);
3527            dragView.setCrossFadeBitmap(crossFadeBitmap);
3528            dragView.crossFade((int) (duration * 0.8f));
3529        } else if (isWidget && external) {
3530            scaleXY[0] = scaleXY[1] = Math.min(scaleXY[0],  scaleXY[1]);
3531        }
3532
3533        DragLayer dragLayer = mLauncher.getDragLayer();
3534        if (animationType == CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION) {
3535            mLauncher.getDragLayer().animateViewIntoPosition(dragView, finalPos, 0f, 0.1f, 0.1f,
3536                    DragLayer.ANIMATION_END_DISAPPEAR, onCompleteRunnable, duration);
3537        } else {
3538            int endStyle;
3539            if (animationType == ANIMATE_INTO_POSITION_AND_REMAIN) {
3540                endStyle = DragLayer.ANIMATION_END_REMAIN_VISIBLE;
3541            } else {
3542                endStyle = DragLayer.ANIMATION_END_DISAPPEAR;
3543            }
3544
3545            Runnable onComplete = new Runnable() {
3546                @Override
3547                public void run() {
3548                    if (finalView != null) {
3549                        finalView.setVisibility(VISIBLE);
3550                    }
3551                    if (onCompleteRunnable != null) {
3552                        onCompleteRunnable.run();
3553                    }
3554                }
3555            };
3556            dragLayer.animateViewIntoPosition(dragView, from.left, from.top, finalPos[0],
3557                    finalPos[1], 1, 1, 1, scaleXY[0], scaleXY[1], onComplete, endStyle,
3558                    duration, this);
3559        }
3560    }
3561
3562    public void setFinalTransitionTransform(CellLayout layout) {
3563        if (isSwitchingState()) {
3564            mCurrentScale = getScaleX();
3565            setScaleX(mStateTransitionAnimation.getFinalScale());
3566            setScaleY(mStateTransitionAnimation.getFinalScale());
3567        }
3568    }
3569    public void resetTransitionTransform(CellLayout layout) {
3570        if (isSwitchingState()) {
3571            setScaleX(mCurrentScale);
3572            setScaleY(mCurrentScale);
3573        }
3574    }
3575
3576    public WorkspaceStateTransitionAnimation getStateTransitionAnimation() {
3577        return mStateTransitionAnimation;
3578    }
3579
3580    /**
3581     * Return the current {@link CellLayout}, correctly picking the destination
3582     * screen while a scroll is in progress.
3583     */
3584    public CellLayout getCurrentDropLayout() {
3585        return (CellLayout) getChildAt(getNextPage());
3586    }
3587
3588    /**
3589     * Return the current CellInfo describing our current drag; this method exists
3590     * so that Launcher can sync this object with the correct info when the activity is created/
3591     * destroyed
3592     *
3593     */
3594    public CellLayout.CellInfo getDragInfo() {
3595        return mDragInfo;
3596    }
3597
3598    public int getCurrentPageOffsetFromCustomContent() {
3599        return getNextPage() - numCustomPages();
3600    }
3601
3602    /**
3603     * Calculate the nearest cell where the given object would be dropped.
3604     *
3605     * pixelX and pixelY should be in the coordinate system of layout
3606     */
3607    @Thunk int[] findNearestArea(int pixelX, int pixelY,
3608            int spanX, int spanY, CellLayout layout, int[] recycle) {
3609        return layout.findNearestArea(
3610                pixelX, pixelY, spanX, spanY, recycle);
3611    }
3612
3613    void setup(DragController dragController) {
3614        mSpringLoadedDragController = new SpringLoadedDragController(mLauncher);
3615        mDragController = dragController;
3616
3617        // hardware layers on children are enabled on startup, but should be disabled until
3618        // needed
3619        updateChildrenLayersEnabled(false);
3620    }
3621
3622    /**
3623     * Called at the end of a drag which originated on the workspace.
3624     */
3625    public void onDropCompleted(final View target, final DragObject d,
3626            final boolean isFlingToDelete, final boolean success) {
3627        if (mDeferDropAfterUninstall) {
3628            final CellLayout.CellInfo dragInfo = mDragInfo;
3629            mDeferredAction = new Runnable() {
3630                public void run() {
3631                    mDragInfo = dragInfo; // Restore the drag info that was cleared in onDragEnd()
3632                    onDropCompleted(target, d, isFlingToDelete, success);
3633                    mDeferredAction = null;
3634                }
3635            };
3636            return;
3637        }
3638
3639        boolean beingCalledAfterUninstall = mDeferredAction != null;
3640
3641        if (success && !(beingCalledAfterUninstall && !mUninstallSuccessful)) {
3642            if (target != this && mDragInfo != null) {
3643                removeWorkspaceItem(mDragInfo.cell);
3644            }
3645        } else if (mDragInfo != null) {
3646            final CellLayout cellLayout = mLauncher.getCellLayout(
3647                    mDragInfo.container, mDragInfo.screenId);
3648            if (cellLayout != null) {
3649                cellLayout.onDropChild(mDragInfo.cell);
3650            } else if (ProviderConfig.IS_DOGFOOD_BUILD) {
3651                throw new RuntimeException("Invalid state: cellLayout == null in "
3652                        + "Workspace#onDropCompleted. Please file a bug. ");
3653            };
3654        }
3655        if ((d.cancelled || (beingCalledAfterUninstall && !mUninstallSuccessful))
3656                && mDragInfo.cell != null) {
3657            mDragInfo.cell.setVisibility(VISIBLE);
3658        }
3659        mDragInfo = null;
3660
3661        if (!isFlingToDelete) {
3662            // Fling to delete already exits spring loaded mode after the animation finishes.
3663            mLauncher.exitSpringLoadedDragModeDelayed(success,
3664                    Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, mDelayedResizeRunnable);
3665            mDelayedResizeRunnable = null;
3666        }
3667    }
3668
3669    /**
3670     * For opposite operation. See {@link #addInScreen}.
3671     */
3672    public void removeWorkspaceItem(View v) {
3673        CellLayout parentCell = getParentCellLayoutForView(v);
3674        if (parentCell != null) {
3675            parentCell.removeView(v);
3676        } else if (ProviderConfig.IS_DOGFOOD_BUILD) {
3677            // When an app is uninstalled using the drop target, we wait until resume to remove
3678            // the icon. We also remove all the corresponding items from the workspace at
3679            // {@link Launcher#bindComponentsRemoved}. That call can come before or after
3680            // {@link Launcher#mOnResumeCallbacks} depending on how busy the worker thread is.
3681            Log.e(TAG, "mDragInfo.cell has null parent");
3682        }
3683        if (v instanceof DropTarget) {
3684            mDragController.removeDropTarget((DropTarget) v);
3685        }
3686    }
3687
3688    /**
3689     * Removes all folder listeners
3690     */
3691    public void removeFolderListeners() {
3692        mapOverItems(false, new ItemOperator() {
3693            @Override
3694            public boolean evaluate(ItemInfo info, View view) {
3695                if (view instanceof FolderIcon) {
3696                    ((FolderIcon) view).removeListeners();
3697                }
3698                return false;
3699            }
3700        });
3701    }
3702
3703    @Override
3704    public void deferCompleteDropAfterUninstallActivity() {
3705        mDeferDropAfterUninstall = true;
3706    }
3707
3708    /// maybe move this into a smaller part
3709    @Override
3710    public void onDragObjectRemoved(boolean success) {
3711        mDeferDropAfterUninstall = false;
3712        mUninstallSuccessful = success;
3713        if (mDeferredAction != null) {
3714            mDeferredAction.run();
3715        }
3716    }
3717
3718    @Override
3719    public float getIntrinsicIconScaleFactor() {
3720        return 1f;
3721    }
3722
3723    @Override
3724    public boolean supportsAppInfoDropTarget() {
3725        return !FeatureFlags.LAUNCHER3_LEGACY_WORKSPACE_DND;
3726    }
3727
3728    @Override
3729    public boolean supportsDeleteDropTarget() {
3730        return true;
3731    }
3732
3733    public boolean isDropEnabled() {
3734        return true;
3735    }
3736
3737    @Override
3738    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
3739        // We don't dispatch restoreInstanceState to our children using this code path.
3740        // Some pages will be restored immediately as their items are bound immediately, and
3741        // others we will need to wait until after their items are bound.
3742        mSavedStates = container;
3743    }
3744
3745    public void restoreInstanceStateForChild(int child) {
3746        if (mSavedStates != null) {
3747            mRestoredPages.add(child);
3748            CellLayout cl = (CellLayout) getChildAt(child);
3749            if (cl != null) {
3750                cl.restoreInstanceState(mSavedStates);
3751            }
3752        }
3753    }
3754
3755    public void restoreInstanceStateForRemainingPages() {
3756        int count = getChildCount();
3757        for (int i = 0; i < count; i++) {
3758            if (!mRestoredPages.contains(i)) {
3759                restoreInstanceStateForChild(i);
3760            }
3761        }
3762        mRestoredPages.clear();
3763        mSavedStates = null;
3764    }
3765
3766    @Override
3767    public void scrollLeft() {
3768        if (!workspaceInModalState() && !mIsSwitchingState) {
3769            super.scrollLeft();
3770        }
3771        Folder openFolder = Folder.getOpen(mLauncher);
3772        if (openFolder != null) {
3773            openFolder.completeDragExit();
3774        }
3775    }
3776
3777    @Override
3778    public void scrollRight() {
3779        if (!workspaceInModalState() && !mIsSwitchingState) {
3780            super.scrollRight();
3781        }
3782        Folder openFolder = Folder.getOpen(mLauncher);
3783        if (openFolder != null) {
3784            openFolder.completeDragExit();
3785        }
3786    }
3787
3788    @Override
3789    public boolean onEnterScrollArea(int x, int y, int direction) {
3790        // Ignore the scroll area if we are dragging over the hot seat
3791        boolean isPortrait = !mLauncher.getDeviceProfile().isLandscape;
3792        if (mLauncher.getHotseat() != null && isPortrait) {
3793            Rect r = new Rect();
3794            mLauncher.getHotseat().getHitRect(r);
3795            if (r.contains(x, y)) {
3796                return false;
3797            }
3798        }
3799
3800        boolean result = false;
3801        if (!workspaceInModalState() && !mIsSwitchingState && Folder.getOpen(mLauncher) == null) {
3802            mInScrollArea = true;
3803
3804            final int page = getNextPage() +
3805                       (direction == DragController.SCROLL_LEFT ? -1 : 1);
3806            // We always want to exit the current layout to ensure parity of enter / exit
3807            setCurrentDropLayout(null);
3808
3809            if (0 <= page && page < getChildCount()) {
3810                // Ensure that we are not dragging over to the custom content screen
3811                if (getScreenIdForPageIndex(page) == CUSTOM_CONTENT_SCREEN_ID) {
3812                    return false;
3813                }
3814
3815                CellLayout layout = (CellLayout) getChildAt(page);
3816                setCurrentDragOverlappingLayout(layout);
3817
3818                // Workspace is responsible for drawing the edge glow on adjacent pages,
3819                // so we need to redraw the workspace when this may have changed.
3820                invalidate();
3821                result = true;
3822            }
3823        }
3824        return result;
3825    }
3826
3827    @Override
3828    public boolean onExitScrollArea() {
3829        boolean result = false;
3830        if (mInScrollArea) {
3831            invalidate();
3832            CellLayout layout = getCurrentDropLayout();
3833            setCurrentDropLayout(layout);
3834            setCurrentDragOverlappingLayout(layout);
3835
3836            result = true;
3837            mInScrollArea = false;
3838        }
3839        return result;
3840    }
3841
3842    private void onResetScrollArea() {
3843        setCurrentDragOverlappingLayout(null);
3844        mInScrollArea = false;
3845    }
3846
3847    /**
3848     * Returns a specific CellLayout
3849     */
3850    CellLayout getParentCellLayoutForView(View v) {
3851        ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts();
3852        for (CellLayout layout : layouts) {
3853            if (layout.getShortcutsAndWidgets().indexOfChild(v) > -1) {
3854                return layout;
3855            }
3856        }
3857        return null;
3858    }
3859
3860    /**
3861     * Returns a list of all the CellLayouts in the workspace.
3862     */
3863    ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() {
3864        ArrayList<CellLayout> layouts = new ArrayList<CellLayout>();
3865        int screenCount = getChildCount();
3866        for (int screen = 0; screen < screenCount; screen++) {
3867            layouts.add(((CellLayout) getChildAt(screen)));
3868        }
3869        if (mLauncher.getHotseat() != null) {
3870            layouts.add(mLauncher.getHotseat().getLayout());
3871        }
3872        return layouts;
3873    }
3874
3875    /**
3876     * We should only use this to search for specific children.  Do not use this method to modify
3877     * ShortcutsAndWidgetsContainer directly. Includes ShortcutAndWidgetContainers from
3878     * the hotseat and workspace pages
3879     */
3880    ArrayList<ShortcutAndWidgetContainer> getAllShortcutAndWidgetContainers() {
3881        ArrayList<ShortcutAndWidgetContainer> childrenLayouts = new ArrayList<>();
3882        int screenCount = getChildCount();
3883        for (int screen = 0; screen < screenCount; screen++) {
3884            childrenLayouts.add(((CellLayout) getChildAt(screen)).getShortcutsAndWidgets());
3885        }
3886        if (mLauncher.getHotseat() != null) {
3887            childrenLayouts.add(mLauncher.getHotseat().getLayout().getShortcutsAndWidgets());
3888        }
3889        return childrenLayouts;
3890    }
3891
3892    public View getHomescreenIconByItemId(final long id) {
3893        return getFirstMatch(new ItemOperator() {
3894
3895            @Override
3896            public boolean evaluate(ItemInfo info, View v) {
3897                return info != null && info.id == id;
3898            }
3899        });
3900    }
3901
3902    public View getViewForTag(final Object tag) {
3903        return getFirstMatch(new ItemOperator() {
3904
3905            @Override
3906            public boolean evaluate(ItemInfo info, View v) {
3907                return info == tag;
3908            }
3909        });
3910    }
3911
3912    public LauncherAppWidgetHostView getWidgetForAppWidgetId(final int appWidgetId) {
3913        return (LauncherAppWidgetHostView) getFirstMatch(new ItemOperator() {
3914
3915            @Override
3916            public boolean evaluate(ItemInfo info, View v) {
3917                return (info instanceof LauncherAppWidgetInfo) &&
3918                        ((LauncherAppWidgetInfo) info).appWidgetId == appWidgetId;
3919            }
3920        });
3921    }
3922
3923    public View getFirstMatch(final ItemOperator operator) {
3924        final View[] value = new View[1];
3925        mapOverItems(MAP_NO_RECURSE, new ItemOperator() {
3926            @Override
3927            public boolean evaluate(ItemInfo info, View v) {
3928                if (operator.evaluate(info, v)) {
3929                    value[0] = v;
3930                    return true;
3931                }
3932                return false;
3933            }
3934        });
3935        return value[0];
3936    }
3937
3938    void clearDropTargets() {
3939        mapOverItems(MAP_NO_RECURSE, new ItemOperator() {
3940            @Override
3941            public boolean evaluate(ItemInfo info, View v) {
3942                if (v instanceof DropTarget) {
3943                    mDragController.removeDropTarget((DropTarget) v);
3944                }
3945                // not done, process all the shortcuts
3946                return false;
3947            }
3948        });
3949    }
3950
3951    /**
3952     * Removes items that match the {@param matcher}. When applications are removed
3953     * as a part of an update, this is called to ensure that other widgets and application
3954     * shortcuts are not removed.
3955     */
3956    public void removeItemsByMatcher(final ItemInfoMatcher matcher) {
3957        ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
3958        for (final CellLayout layoutParent: cellLayouts) {
3959            final ViewGroup layout = layoutParent.getShortcutsAndWidgets();
3960
3961            LongArrayMap<View> idToViewMap = new LongArrayMap<>();
3962            ArrayList<ItemInfo> items = new ArrayList<>();
3963            for (int j = 0; j < layout.getChildCount(); j++) {
3964                final View view = layout.getChildAt(j);
3965                if (view.getTag() instanceof ItemInfo) {
3966                    ItemInfo item = (ItemInfo) view.getTag();
3967                    items.add(item);
3968                    idToViewMap.put(item.id, view);
3969                }
3970            }
3971
3972            for (ItemInfo itemToRemove : matcher.filterItemInfos(items)) {
3973                View child = idToViewMap.get(itemToRemove.id);
3974
3975                if (child != null) {
3976                    // Note: We can not remove the view directly from CellLayoutChildren as this
3977                    // does not re-mark the spaces as unoccupied.
3978                    layoutParent.removeViewInLayout(child);
3979                    if (child instanceof DropTarget) {
3980                        mDragController.removeDropTarget((DropTarget) child);
3981                    }
3982                } else if (itemToRemove.container >= 0) {
3983                    // The item may belong to a folder.
3984                    View parent = idToViewMap.get(itemToRemove.container);
3985                    if (parent != null) {
3986                        ((FolderInfo) parent.getTag()).remove((ShortcutInfo) itemToRemove, false);
3987                    }
3988                }
3989            }
3990        }
3991
3992        // Strip all the empty screens
3993        stripEmptyScreens();
3994    }
3995
3996    public interface ItemOperator {
3997        /**
3998         * Process the next itemInfo, possibly with side-effect on the next item.
3999         *
4000         * @param info info for the shortcut
4001         * @param view view for the shortcut
4002         * @return true if done, false to continue the map
4003         */
4004        public boolean evaluate(ItemInfo info, View view);
4005    }
4006
4007    /**
4008     * Map the operator over the shortcuts and widgets, return the first-non-null value.
4009     *
4010     * @param recurse true: iterate over folder children. false: op get the folders themselves.
4011     * @param op the operator to map over the shortcuts
4012     */
4013    void mapOverItems(boolean recurse, ItemOperator op) {
4014        ArrayList<ShortcutAndWidgetContainer> containers = getAllShortcutAndWidgetContainers();
4015        final int containerCount = containers.size();
4016        for (int containerIdx = 0; containerIdx < containerCount; containerIdx++) {
4017            ShortcutAndWidgetContainer container = containers.get(containerIdx);
4018            // map over all the shortcuts on the workspace
4019            final int itemCount = container.getChildCount();
4020            for (int itemIdx = 0; itemIdx < itemCount; itemIdx++) {
4021                View item = container.getChildAt(itemIdx);
4022                ItemInfo info = (ItemInfo) item.getTag();
4023                if (recurse && info instanceof FolderInfo && item instanceof FolderIcon) {
4024                    FolderIcon folder = (FolderIcon) item;
4025                    ArrayList<View> folderChildren = folder.getFolder().getItemsInReadingOrder();
4026                    // map over all the children in the folder
4027                    final int childCount = folderChildren.size();
4028                    for (int childIdx = 0; childIdx < childCount; childIdx++) {
4029                        View child = folderChildren.get(childIdx);
4030                        info = (ItemInfo) child.getTag();
4031                        if (op.evaluate(info, child)) {
4032                            return;
4033                        }
4034                    }
4035                } else {
4036                    if (op.evaluate(info, item)) {
4037                        return;
4038                    }
4039                }
4040            }
4041        }
4042    }
4043
4044    void updateShortcuts(ArrayList<ShortcutInfo> shortcuts) {
4045        int total  = shortcuts.size();
4046        final HashSet<ShortcutInfo> updates = new HashSet<ShortcutInfo>(total);
4047        final HashSet<Long> folderIds = new HashSet<>();
4048
4049        for (int i = 0; i < total; i++) {
4050            ShortcutInfo s = shortcuts.get(i);
4051            updates.add(s);
4052            folderIds.add(s.container);
4053        }
4054
4055        mapOverItems(MAP_RECURSE, new ItemOperator() {
4056            @Override
4057            public boolean evaluate(ItemInfo info, View v) {
4058                if (info instanceof ShortcutInfo && v instanceof BubbleTextView &&
4059                        updates.contains(info)) {
4060                    ShortcutInfo si = (ShortcutInfo) info;
4061                    BubbleTextView shortcut = (BubbleTextView) v;
4062                    Drawable oldIcon = getTextViewIcon(shortcut);
4063                    boolean oldPromiseState = (oldIcon instanceof PreloadIconDrawable)
4064                            && ((PreloadIconDrawable) oldIcon).hasNotCompleted();
4065                    shortcut.applyFromShortcutInfo(si, mIconCache,
4066                            si.isPromise() != oldPromiseState);
4067                }
4068                // process all the shortcuts
4069                return false;
4070            }
4071        });
4072
4073        // Update folder icons
4074        mapOverItems(MAP_NO_RECURSE, new ItemOperator() {
4075            @Override
4076            public boolean evaluate(ItemInfo info, View v) {
4077                if (info instanceof FolderInfo && folderIds.contains(info.id)) {
4078                    ((FolderInfo) info).itemsChanged(false);
4079                }
4080                // process all the shortcuts
4081                return false;
4082            }
4083        });
4084    }
4085
4086    public void removeAbandonedPromise(String packageName, UserHandleCompat user) {
4087        HashSet<String> packages = new HashSet<>(1);
4088        packages.add(packageName);
4089        ItemInfoMatcher matcher = ItemInfoMatcher.ofPackages(packages, user);
4090        LauncherModel.deleteItemsFromDatabase(mLauncher, matcher);
4091        removeItemsByMatcher(matcher);
4092    }
4093
4094    public void updateRestoreItems(final HashSet<ItemInfo> updates) {
4095        mapOverItems(MAP_RECURSE, new ItemOperator() {
4096            @Override
4097            public boolean evaluate(ItemInfo info, View v) {
4098                if (info instanceof ShortcutInfo && v instanceof BubbleTextView
4099                        && updates.contains(info)) {
4100                    ((BubbleTextView) v).applyState(false);
4101                } else if (v instanceof PendingAppWidgetHostView
4102                        && info instanceof LauncherAppWidgetInfo
4103                        && updates.contains(info)) {
4104                    ((PendingAppWidgetHostView) v).applyState();
4105                }
4106                // process all the shortcuts
4107                return false;
4108            }
4109        });
4110    }
4111
4112    public void widgetsRestored(final ArrayList<LauncherAppWidgetInfo> changedInfo) {
4113        if (!changedInfo.isEmpty()) {
4114            DeferredWidgetRefresh widgetRefresh = new DeferredWidgetRefresh(changedInfo,
4115                    mLauncher.getAppWidgetHost());
4116
4117            LauncherAppWidgetInfo item = changedInfo.get(0);
4118            final AppWidgetProviderInfo widgetInfo;
4119            if (item.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_ID_NOT_VALID)) {
4120                widgetInfo = AppWidgetManagerCompat
4121                        .getInstance(mLauncher).findProvider(item.providerName, item.user);
4122            } else {
4123                widgetInfo = AppWidgetManagerCompat.getInstance(mLauncher)
4124                        .getAppWidgetInfo(item.appWidgetId);
4125            }
4126
4127            if (widgetInfo != null) {
4128                // Re-inflate the widgets which have changed status
4129                widgetRefresh.run();
4130            } else {
4131                // widgetRefresh will automatically run when the packages are updated.
4132                // For now just update the progress bars
4133                mapOverItems(MAP_NO_RECURSE, new ItemOperator() {
4134                    @Override
4135                    public boolean evaluate(ItemInfo info, View view) {
4136                        if (view instanceof PendingAppWidgetHostView
4137                                && changedInfo.contains(info)) {
4138                            ((LauncherAppWidgetInfo) info).installProgress = 100;
4139                            ((PendingAppWidgetHostView) view).applyState();
4140                        }
4141                        // process all the shortcuts
4142                        return false;
4143                    }
4144                });
4145            }
4146        }
4147    }
4148
4149    private void moveToScreen(int page, boolean animate) {
4150        if (!workspaceInModalState()) {
4151            if (animate) {
4152                snapToPage(page);
4153            } else {
4154                setCurrentPage(page);
4155            }
4156        }
4157        View child = getChildAt(page);
4158        if (child != null) {
4159            child.requestFocus();
4160        }
4161    }
4162
4163    void moveToDefaultScreen(boolean animate) {
4164        moveToScreen(getDefaultPage(), animate);
4165    }
4166
4167    void moveToCustomContentScreen(boolean animate) {
4168        if (hasCustomContent()) {
4169            int ccIndex = getPageIndexForScreenId(CUSTOM_CONTENT_SCREEN_ID);
4170            if (animate) {
4171                snapToPage(ccIndex);
4172            } else {
4173                setCurrentPage(ccIndex);
4174            }
4175            View child = getChildAt(ccIndex);
4176            if (child != null) {
4177                child.requestFocus();
4178            }
4179         }
4180        exitWidgetResizeMode();
4181    }
4182
4183    @Override
4184    protected String getPageIndicatorDescription() {
4185        return getResources().getString(R.string.all_apps_button_label);
4186    }
4187
4188    @Override
4189    protected String getCurrentPageDescription() {
4190        if (hasCustomContent() && getNextPage() == 0) {
4191            return mCustomContentDescription;
4192        }
4193        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
4194        return getPageDescription(page);
4195    }
4196
4197    private String getPageDescription(int page) {
4198        int delta = numCustomPages();
4199        int nScreens = getChildCount() - delta;
4200        int extraScreenId = mScreenOrder.indexOf(EXTRA_EMPTY_SCREEN_ID);
4201        if (extraScreenId >= 0 && nScreens > 1) {
4202            if (page == extraScreenId) {
4203                return getContext().getString(R.string.workspace_new_page);
4204            }
4205            nScreens--;
4206        }
4207        if (nScreens == 0) {
4208            // When the workspace is not loaded, we do not know how many screen will be bound.
4209            return getContext().getString(R.string.all_apps_home_button_label);
4210        }
4211        return getContext().getString(R.string.workspace_scroll_format,
4212                page + 1 - delta, nScreens);
4213    }
4214
4215    @Override
4216    public void fillInLogContainerData(View v, ItemInfo info, Target target, Target targetParent) {
4217        target.gridX = info.cellX;
4218        target.gridY = info.cellY;
4219        target.pageIndex = getCurrentPage();
4220        targetParent.containerType = LauncherLogProto.WORKSPACE;
4221        if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
4222            target.rank = info.rank;
4223            targetParent.containerType = LauncherLogProto.HOTSEAT;
4224        } else if (info.container >= 0) {
4225            targetParent.containerType = LauncherLogProto.FOLDER;
4226        }
4227    }
4228
4229    /**
4230     * Used as a workaround to ensure that the AppWidgetService receives the
4231     * PACKAGE_ADDED broadcast before updating widgets.
4232     */
4233    private class DeferredWidgetRefresh implements Runnable {
4234        private final ArrayList<LauncherAppWidgetInfo> mInfos;
4235        private final LauncherAppWidgetHost mHost;
4236        private final Handler mHandler;
4237
4238        private boolean mRefreshPending;
4239
4240        public DeferredWidgetRefresh(ArrayList<LauncherAppWidgetInfo> infos,
4241                LauncherAppWidgetHost host) {
4242            mInfos = infos;
4243            mHost = host;
4244            mHandler = new Handler();
4245            mRefreshPending = true;
4246
4247            mHost.addProviderChangeListener(this);
4248            // Force refresh after 10 seconds, if we don't get the provider changed event.
4249            // This could happen when the provider is no longer available in the app.
4250            mHandler.postDelayed(this, 10000);
4251        }
4252
4253        @Override
4254        public void run() {
4255            mHost.removeProviderChangeListener(this);
4256            mHandler.removeCallbacks(this);
4257
4258            if (!mRefreshPending) {
4259                return;
4260            }
4261
4262            mRefreshPending = false;
4263
4264            mapOverItems(MAP_NO_RECURSE, new ItemOperator() {
4265                @Override
4266                public boolean evaluate(ItemInfo info, View view) {
4267                    if (view instanceof PendingAppWidgetHostView && mInfos.contains(info)) {
4268                        mLauncher.removeItem(view, info, false /* deleteFromDb */);
4269                        mLauncher.bindAppWidget((LauncherAppWidgetInfo) info);
4270                    }
4271                    // process all the shortcuts
4272                    return false;
4273                }
4274            });
4275        }
4276    }
4277
4278    public interface OnStateChangeListener {
4279
4280        /**
4281         * Called when the workspace state is changing.
4282         * @param toState final state
4283         * @param targetAnim animation which will be played during the transition or null.
4284         */
4285        void prepareStateChange(State toState, AnimatorSet targetAnim);
4286    }
4287
4288    public static final boolean isQsbContainerPage(int pageNo) {
4289        return pageNo == 0;
4290    }
4291
4292    private class StateTransitionListener extends AnimatorListenerAdapter
4293            implements AnimatorUpdateListener {
4294        @Override
4295        public void onAnimationUpdate(ValueAnimator anim) {
4296            mTransitionProgress = anim.getAnimatedFraction();
4297        }
4298
4299        @Override
4300        public void onAnimationStart(Animator animation) {
4301            if (mState == State.SPRING_LOADED) {
4302                // Show the page indicator at the same time as the rest of the transition.
4303                showPageIndicatorAtCurrentScroll();
4304            }
4305            mTransitionProgress = 0;
4306        }
4307
4308        @Override
4309        public void onAnimationEnd(Animator animation) {
4310            onEndStateTransition();
4311        }
4312    }
4313}
4314