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