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