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