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