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