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