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