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