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