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