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