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