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