Workspace.java revision 1b36dc3f2bb643e3b9600755f1a98522e4efc2ed
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) return;
2670        if (mIsSwitchingState) return;
2671
2672        Rect r = new Rect();
2673        CellLayout layout = null;
2674        ItemInfo item = (ItemInfo) d.dragInfo;
2675
2676        // Ensure that we have proper spans for the item that we are dropping
2677        if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found");
2678        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
2679            d.dragView, mDragViewVisualCenter);
2680
2681        // Identify whether we have dragged over a side page
2682        if (isSmall()) {
2683            if (mLauncher.getHotseat() != null && !isExternalDragWidget(d)) {
2684                mLauncher.getHotseat().getHitRect(r);
2685                if (r.contains(d.x, d.y)) {
2686                    layout = mLauncher.getHotseat().getLayout();
2687                }
2688            }
2689            if (layout == null) {
2690                layout = findMatchingPageForDragOver(d.dragView, d.x, d.y, false);
2691            }
2692            if (layout != mDragTargetLayout) {
2693                // Cancel all intermediate folder states
2694                cleanupFolderCreation(d);
2695
2696                if (mDragTargetLayout != null) {
2697                    mDragTargetLayout.setIsDragOverlapping(false);
2698                    mDragTargetLayout.onDragExit();
2699                }
2700                mDragTargetLayout = layout;
2701                if (mDragTargetLayout != null) {
2702                    mDragTargetLayout.setIsDragOverlapping(true);
2703                    mDragTargetLayout.onDragEnter();
2704                } else {
2705                    mLastDragOverView = null;
2706                }
2707
2708                boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED);
2709                if (isInSpringLoadedMode) {
2710                    if (mLauncher.isHotseatLayout(layout)) {
2711                        mSpringLoadedDragController.cancel();
2712                    } else {
2713                        mSpringLoadedDragController.setAlarm(mDragTargetLayout);
2714                    }
2715                }
2716            }
2717        } else {
2718            // Test to see if we are over the hotseat otherwise just use the current page
2719            if (mLauncher.getHotseat() != null && !isDragWidget(d)) {
2720                mLauncher.getHotseat().getHitRect(r);
2721                if (r.contains(d.x, d.y)) {
2722                    layout = mLauncher.getHotseat().getLayout();
2723                }
2724            }
2725            if (layout == null) {
2726                layout = getCurrentDropLayout();
2727            }
2728            if (layout != mDragTargetLayout) {
2729                if (mDragTargetLayout != null) {
2730                    mDragTargetLayout.setIsDragOverlapping(false);
2731                    mDragTargetLayout.onDragExit();
2732                }
2733                mDragTargetLayout = layout;
2734                mDragTargetLayout.setIsDragOverlapping(true);
2735                mDragTargetLayout.onDragEnter();
2736            }
2737        }
2738
2739        // Handle the drag over
2740        if (mDragTargetLayout != null) {
2741            final View child = (mDragInfo == null) ? null : mDragInfo.cell;
2742
2743            // We want the point to be mapped to the dragTarget.
2744            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
2745                mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter);
2746            } else {
2747                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
2748            }
2749            ItemInfo info = (ItemInfo) d.dragInfo;
2750
2751            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2752                    (int) mDragViewVisualCenter[1], 1, 1, mDragTargetLayout, mTargetCell);
2753            final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0],
2754                    mTargetCell[1]);
2755
2756            boolean userFolderPending = willCreateUserFolder(info, mDragTargetLayout,
2757                    mTargetCell, false);
2758            boolean isOverFolder = dragOverView instanceof FolderIcon;
2759            if (dragOverView != mLastDragOverView) {
2760                cancelFolderCreation();
2761                if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) {
2762                    ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo);
2763                }
2764            }
2765
2766            if (userFolderPending && dragOverView != mLastDragOverView) {
2767                mFolderCreationAlarm.setOnAlarmListener(new
2768                        FolderCreationAlarmListener(mDragTargetLayout, mTargetCell[0], mTargetCell[1]));
2769                mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT);
2770            }
2771
2772            if (dragOverView != mLastDragOverView && isOverFolder) {
2773                ((FolderIcon) dragOverView).onDragEnter(d.dragInfo);
2774                if (mDragTargetLayout != null) {
2775                    mDragTargetLayout.clearDragOutlines();
2776                }
2777            }
2778            mLastDragOverView = dragOverView;
2779
2780            if (!mCreateUserFolderOnDrop && !isOverFolder) {
2781                mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
2782                        (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
2783                        item.spanX, item.spanY, d.dragView.getDragVisualizeOffset(),
2784                        d.dragView.getDragRegion());
2785            }
2786        }
2787    }
2788
2789    private void cleanupFolderCreation(DragObject d) {
2790        if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) {
2791            mDragFolderRingAnimator.animateToNaturalState();
2792        }
2793        if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) {
2794            if (d != null) {
2795                ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo);
2796            }
2797        }
2798        mFolderCreationAlarm.cancelAlarm();
2799    }
2800
2801    private void cancelFolderCreation() {
2802        if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) {
2803            mDragFolderRingAnimator.animateToNaturalState();
2804        }
2805        mCreateUserFolderOnDrop = false;
2806        mFolderCreationAlarm.cancelAlarm();
2807    }
2808
2809    class FolderCreationAlarmListener implements OnAlarmListener {
2810        CellLayout layout;
2811        int cellX;
2812        int cellY;
2813
2814        public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) {
2815            this.layout = layout;
2816            this.cellX = cellX;
2817            this.cellY = cellY;
2818        }
2819
2820        public void onAlarm(Alarm alarm) {
2821            if (mDragFolderRingAnimator == null) {
2822                mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null);
2823            }
2824            mDragFolderRingAnimator.setCell(cellX, cellY);
2825            mDragFolderRingAnimator.setCellLayout(layout);
2826            mDragFolderRingAnimator.animateToAcceptState();
2827            layout.showFolderAccept(mDragFolderRingAnimator);
2828            layout.clearDragOutlines();
2829            mCreateUserFolderOnDrop = true;
2830        }
2831    }
2832
2833    @Override
2834    public void getHitRect(Rect outRect) {
2835        // We want the workspace to have the whole area of the display (it will find the correct
2836        // cell layout to drop to in the existing drag/drop logic.
2837        outRect.set(0, 0, mDisplayWidth, mDisplayHeight);
2838    }
2839
2840    /**
2841     * Add the item specified by dragInfo to the given layout.
2842     * @return true if successful
2843     */
2844    public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) {
2845        if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) {
2846            onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false);
2847            return true;
2848        }
2849        mLauncher.showOutOfSpaceMessage();
2850        return false;
2851    }
2852
2853    private void onDropExternal(int[] touchXY, Object dragInfo,
2854            CellLayout cellLayout, boolean insertAtFirst) {
2855        onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null);
2856    }
2857
2858    /**
2859     * Drop an item that didn't originate on one of the workspace screens.
2860     * It may have come from Launcher (e.g. from all apps or customize), or it may have
2861     * come from another app altogether.
2862     *
2863     * NOTE: This can also be called when we are outside of a drag event, when we want
2864     * to add an item to one of the workspace screens.
2865     */
2866    private void onDropExternal(final int[] touchXY, final Object dragInfo,
2867            final CellLayout cellLayout, boolean insertAtFirst, DragObject d) {
2868        final Runnable exitSpringLoadedRunnable = new Runnable() {
2869            @Override
2870            public void run() {
2871                mLauncher.exitSpringLoadedDragModeDelayed(true, false, null);
2872            }
2873        };
2874
2875        ItemInfo info = (ItemInfo) dragInfo;
2876        int spanX = info.spanX;
2877        int spanY = info.spanY;
2878        if (mDragInfo != null) {
2879            spanX = mDragInfo.spanX;
2880            spanY = mDragInfo.spanY;
2881        }
2882
2883        final long container = mLauncher.isHotseatLayout(cellLayout) ?
2884                LauncherSettings.Favorites.CONTAINER_HOTSEAT :
2885                    LauncherSettings.Favorites.CONTAINER_DESKTOP;
2886        final int screen = indexOfChild(cellLayout);
2887        if (!mLauncher.isHotseatLayout(cellLayout) && screen != mCurrentPage
2888                && mState != State.SPRING_LOADED) {
2889            snapToPage(screen);
2890        }
2891
2892        if (info instanceof PendingAddItemInfo) {
2893            final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo;
2894
2895            boolean findNearestVacantCell = true;
2896            if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
2897                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
2898                        cellLayout, mTargetCell);
2899                if (willCreateUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, mTargetCell,
2900                        true) || willAddToExistingUserFolder((ItemInfo) d.dragInfo,
2901                                mDragTargetLayout, mTargetCell)) {
2902                    findNearestVacantCell = false;
2903                }
2904            }
2905            if (findNearestVacantCell) {
2906                    mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], spanX, spanY, null,
2907                        cellLayout, mTargetCell);
2908            }
2909
2910            Runnable onAnimationCompleteRunnable = new Runnable() {
2911                @Override
2912                public void run() {
2913                    // When dragging and dropping from customization tray, we deal with creating
2914                    // widgets/shortcuts/folders in a slightly different way
2915                    switch (pendingInfo.itemType) {
2916                    case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2917                        mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) pendingInfo,
2918                                container, screen, mTargetCell, null);
2919                        break;
2920                    case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2921                        mLauncher.processShortcutFromDrop(pendingInfo.componentName,
2922                                container, screen, mTargetCell, null);
2923                        break;
2924                    default:
2925                        throw new IllegalStateException("Unknown item type: " +
2926                                pendingInfo.itemType);
2927                    }
2928                    cellLayout.onDragExit();
2929                }
2930            };
2931
2932            animateExternalDrop((PendingAddItemInfo) info, cellLayout, d.dragView,
2933                    onAnimationCompleteRunnable, ANIMATE_INTO_POSITION);
2934        } else {
2935            // This is for other drag/drop cases, like dragging from All Apps
2936            View view = null;
2937
2938            switch (info.itemType) {
2939            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
2940            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2941                if (info.container == NO_ID && info instanceof ApplicationInfo) {
2942                    // Came from all apps -- make a copy
2943                    info = new ShortcutInfo((ApplicationInfo) info);
2944                }
2945                view = mLauncher.createShortcut(R.layout.application, cellLayout,
2946                        (ShortcutInfo) info);
2947                break;
2948            case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2949                view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout,
2950                        (FolderInfo) info, mIconCache);
2951                break;
2952            default:
2953                throw new IllegalStateException("Unknown item type: " + info.itemType);
2954            }
2955
2956            // First we find the cell nearest to point at which the item is
2957            // dropped, without any consideration to whether there is an item there.
2958            if (touchXY != null) {
2959                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
2960                        cellLayout, mTargetCell);
2961                d.postAnimationRunnable = exitSpringLoadedRunnable;
2962                if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, true,
2963                        d.dragView, d.postAnimationRunnable)) {
2964                    return;
2965                }
2966                if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, d, true)) {
2967                    return;
2968                }
2969            }
2970
2971            if (touchXY != null) {
2972                // when dragging and dropping, just find the closest free spot
2973                mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, null,
2974                        cellLayout, mTargetCell);
2975            } else {
2976                cellLayout.findCellForSpan(mTargetCell, 1, 1);
2977            }
2978            addInScreen(view, container, screen, mTargetCell[0], mTargetCell[1], info.spanX,
2979                    info.spanY, insertAtFirst);
2980            cellLayout.onDropChild(view);
2981            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
2982            cellLayout.getChildrenLayout().measureChild(view);
2983
2984            LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen,
2985                    lp.cellX, lp.cellY);
2986
2987            if (d.dragView != null) {
2988                // We wrap the animation call in the temporary set and reset of the current
2989                // cellLayout to its final transform -- this means we animate the drag view to
2990                // the correct final location.
2991                setFinalTransitionTransform(cellLayout);
2992                mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view,
2993                        exitSpringLoadedRunnable);
2994                resetTransitionTransform(cellLayout);
2995            }
2996        }
2997    }
2998
2999    // The following methods deal with animating an item from external drop
3000    void onPreDraw(View v) {
3001        if (v instanceof ViewGroup) {
3002            ViewGroup vg = (ViewGroup) v;
3003            for (int i = 0; i < vg.getChildCount(); i++) {
3004                View child = vg.getChildAt(i);
3005                onPreDraw(child);
3006            }
3007        } else if (v instanceof TextView) {
3008            ((TextView) v).onPreDraw();
3009        }
3010    }
3011
3012    public Bitmap createWidgetBitmap(PendingAddWidgetInfo widgetInfo) {
3013        int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(widgetInfo.spanX,
3014                widgetInfo.spanY, widgetInfo, false);
3015        View layout = widgetInfo.boundWidget;
3016        layout.setVisibility(VISIBLE);
3017
3018        int width = MeasureSpec.makeMeasureSpec(unScaledSize[0], MeasureSpec.EXACTLY);
3019        int height = MeasureSpec.makeMeasureSpec(unScaledSize[1], MeasureSpec.EXACTLY);
3020        Bitmap b = Bitmap.createBitmap(unScaledSize[0], unScaledSize[1],
3021                Bitmap.Config.ARGB_8888);
3022        Canvas c = new Canvas(b);
3023
3024        layout.measure(width, height);
3025        layout.layout(0, 0, unScaledSize[0], unScaledSize[1]);
3026        onPreDraw(layout);
3027        layout.draw(c);
3028        c.setBitmap(null);
3029        return b;
3030    }
3031
3032    public void animateExternalDrop(PendingAddItemInfo pendingInfo, CellLayout cellLayout,
3033            DragView dragView, Runnable onCompleteRunnable, int animationType) {
3034        // Now we animate the dragView, (ie. the widget or shortcut preview) into its final
3035        // location and size on the home screen.
3036        int spanX = pendingInfo.spanX;
3037        int spanY = pendingInfo.spanY;
3038        RectF r = estimateItemPosition(cellLayout, pendingInfo,
3039                mTargetCell[0], mTargetCell[1], spanX, spanY);
3040        int loc[] = new int[2];
3041        loc[0] = (int) r.left;
3042        loc[1] = (int) r.top;
3043        setFinalTransitionTransform(cellLayout);
3044        float cellLayoutScale =
3045                mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(cellLayout, loc);
3046        resetTransitionTransform(cellLayout);
3047
3048        float dragViewScaleX = r.width() / dragView.getMeasuredWidth();
3049        float dragViewScaleY = r.height() / dragView.getMeasuredHeight();
3050        // The animation will scale the dragView about its center, so we need to center about
3051        // the final location.
3052        loc[0] -= (dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2;
3053        loc[1] -= (dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2;
3054
3055        float scaleX = dragViewScaleX * cellLayoutScale;
3056        float scaleY = dragViewScaleY * cellLayoutScale;
3057
3058        Resources res = mLauncher.getResources();
3059        int duration = res.getInteger(R.integer.config_dropAnimMaxDuration) - 200;
3060
3061        int animationEnd = DragLayer.ANIMATION_END_REMAIN_VISIBLE;
3062        if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
3063                (((PendingAddWidgetInfo) pendingInfo).info.configure == null ||
3064                animationType == COMPLETE_TWO_STAGE_WIDGET_DROP_ANIMATION)) {
3065            Bitmap crossFadeBitmap = createWidgetBitmap((PendingAddWidgetInfo) pendingInfo);
3066            dragView.setCrossFadeBitmap(crossFadeBitmap);
3067            dragView.crossFade((int) (duration * 0.8f));
3068            animationEnd = DragLayer.ANIMATION_END_DISAPPEAR;
3069        } else {
3070            scaleX = scaleY = Math.min(scaleX,  scaleY);
3071        }
3072
3073        if (animationType == COMPLETE_TWO_STAGE_WIDGET_DROP_ANIMATION) {
3074            mLauncher.getDragLayer().scaleViewIntoPosition(dragView, loc, 1, scaleX, scaleY,
3075                    animationEnd, onCompleteRunnable, duration);
3076        } else if (animationType == CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION) {
3077            mLauncher.getDragLayer().scaleViewIntoPosition(dragView, loc, 0, 0.1f, 0.1f,
3078                    DragLayer.ANIMATION_END_DISAPPEAR, onCompleteRunnable, duration);
3079        } else {
3080            mLauncher.getDragLayer().animateViewIntoPosition(dragView, loc, scaleX, scaleY,
3081                animationEnd, onCompleteRunnable, duration);
3082        }
3083    }
3084
3085    public void setFinalTransitionTransform(CellLayout layout) {
3086        if (isSwitchingState()) {
3087            int index = indexOfChild(layout);
3088            mCurrentScaleX = layout.getScaleX();
3089            mCurrentScaleY = layout.getScaleY();
3090            mCurrentTranslationX = layout.getTranslationX();
3091            mCurrentTranslationY = layout.getTranslationY();
3092            mCurrentRotationY = layout.getRotationY();
3093            layout.setScaleX(mNewScaleXs[index]);
3094            layout.setScaleY(mNewScaleYs[index]);
3095            layout.setTranslationX(mNewTranslationXs[index]);
3096            layout.setTranslationY(mNewTranslationYs[index]);
3097            layout.setRotationY(mNewRotationYs[index]);
3098        }
3099    }
3100    public void resetTransitionTransform(CellLayout layout) {
3101        if (isSwitchingState()) {
3102            mCurrentScaleX = layout.getScaleX();
3103            mCurrentScaleY = layout.getScaleY();
3104            mCurrentTranslationX = layout.getTranslationX();
3105            mCurrentTranslationY = layout.getTranslationY();
3106            mCurrentRotationY = layout.getRotationY();
3107            layout.setScaleX(mCurrentScaleX);
3108            layout.setScaleY(mCurrentScaleY);
3109            layout.setTranslationX(mCurrentTranslationX);
3110            layout.setTranslationY(mCurrentTranslationY);
3111            layout.setRotationY(mCurrentRotationY);
3112        }
3113    }
3114
3115    /**
3116     * Return the current {@link CellLayout}, correctly picking the destination
3117     * screen while a scroll is in progress.
3118     */
3119    public CellLayout getCurrentDropLayout() {
3120        return (CellLayout) getChildAt(mNextPage == INVALID_PAGE ? mCurrentPage : mNextPage);
3121    }
3122
3123    /**
3124     * Return the current CellInfo describing our current drag; this method exists
3125     * so that Launcher can sync this object with the correct info when the activity is created/
3126     * destroyed
3127     *
3128     */
3129    public CellLayout.CellInfo getDragInfo() {
3130        return mDragInfo;
3131    }
3132
3133    /**
3134     * Calculate the nearest cell where the given object would be dropped.
3135     *
3136     * pixelX and pixelY should be in the coordinate system of layout
3137     */
3138    private int[] findNearestVacantArea(int pixelX, int pixelY,
3139            int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) {
3140        return layout.findNearestVacantArea(
3141                pixelX, pixelY, spanX, spanY, ignoreView, recycle);
3142    }
3143
3144    /**
3145     * Calculate the nearest cell where the given object would be dropped.
3146     *
3147     * pixelX and pixelY should be in the coordinate system of layout
3148     */
3149    private int[] findNearestArea(int pixelX, int pixelY,
3150            int spanX, int spanY, CellLayout layout, int[] recycle) {
3151        return layout.findNearestArea(
3152                pixelX, pixelY, spanX, spanY, recycle);
3153    }
3154
3155    void setup(DragController dragController) {
3156        mSpringLoadedDragController = new SpringLoadedDragController(mLauncher);
3157        mDragController = dragController;
3158
3159        // hardware layers on children are enabled on startup, but should be disabled until
3160        // needed
3161        updateChildrenLayersEnabled();
3162        setWallpaperDimension();
3163    }
3164
3165    /**
3166     * Called at the end of a drag which originated on the workspace.
3167     */
3168    public void onDropCompleted(View target, DragObject d, boolean success) {
3169        if (success) {
3170            if (target != this) {
3171                if (mDragInfo != null) {
3172                    getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
3173                    if (mDragInfo.cell instanceof DropTarget) {
3174                        mDragController.removeDropTarget((DropTarget) mDragInfo.cell);
3175                    }
3176                }
3177            }
3178        } else if (mDragInfo != null) {
3179            // NOTE: When 'success' is true, onDragExit is called by the DragController before
3180            // calling onDropCompleted(). We call it ourselves here, but maybe this should be
3181            // moved into DragController.cancelDrag().
3182            doDragExit(null);
3183            CellLayout cellLayout;
3184            if (mLauncher.isHotseatLayout(target)) {
3185                cellLayout = mLauncher.getHotseat().getLayout();
3186            } else {
3187                cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
3188            }
3189            cellLayout.onDropChild(mDragInfo.cell);
3190        }
3191        if (d.cancelled &&  mDragInfo.cell != null) {
3192                mDragInfo.cell.setVisibility(VISIBLE);
3193        }
3194        mDragOutline = null;
3195        mDragInfo = null;
3196
3197        // Hide the scrolling indicator after you pick up an item
3198        hideScrollingIndicator(false);
3199    }
3200
3201    public boolean isDropEnabled() {
3202        return true;
3203    }
3204
3205    @Override
3206    protected void onRestoreInstanceState(Parcelable state) {
3207        super.onRestoreInstanceState(state);
3208        Launcher.setScreen(mCurrentPage);
3209    }
3210
3211    @Override
3212    public void scrollLeft() {
3213        if (!isSmall() && !mIsSwitchingState) {
3214            super.scrollLeft();
3215        }
3216        Folder openFolder = getOpenFolder();
3217        if (openFolder != null) {
3218            openFolder.completeDragExit();
3219        }
3220    }
3221
3222    @Override
3223    public void scrollRight() {
3224        if (!isSmall() && !mIsSwitchingState) {
3225            super.scrollRight();
3226        }
3227        Folder openFolder = getOpenFolder();
3228        if (openFolder != null) {
3229            openFolder.completeDragExit();
3230        }
3231    }
3232
3233    @Override
3234    public boolean onEnterScrollArea(int x, int y, int direction) {
3235        // Ignore the scroll area if we are dragging over the hot seat
3236        if (mLauncher.getHotseat() != null) {
3237            Rect r = new Rect();
3238            mLauncher.getHotseat().getHitRect(r);
3239            if (r.contains(x, y)) {
3240                return false;
3241            }
3242        }
3243
3244        boolean result = false;
3245        if (!isSmall() && !mIsSwitchingState) {
3246            mInScrollArea = true;
3247
3248            final int page = (mNextPage != INVALID_PAGE ? mNextPage : mCurrentPage) +
3249                       (direction == DragController.SCROLL_LEFT ? -1 : 1);
3250            cancelFolderCreation();
3251
3252            if (0 <= page && page < getChildCount()) {
3253                CellLayout layout = (CellLayout) getChildAt(page);
3254                // Exit the current layout and mark the overlapping layout
3255                if (mDragTargetLayout != null) {
3256                    mDragTargetLayout.setIsDragOverlapping(false);
3257                    mDragTargetLayout.onDragExit();
3258                }
3259                mDragTargetLayout = layout;
3260                mDragTargetLayout.setIsDragOverlapping(true);
3261
3262                // Workspace is responsible for drawing the edge glow on adjacent pages,
3263                // so we need to redraw the workspace when this may have changed.
3264                invalidate();
3265                result = true;
3266            }
3267        }
3268        return result;
3269    }
3270
3271    @Override
3272    public boolean onExitScrollArea() {
3273        boolean result = false;
3274        if (mInScrollArea) {
3275            if (mDragTargetLayout != null) {
3276                mDragTargetLayout.setIsDragOverlapping(false);
3277                // Workspace is responsible for drawing the edge glow on adjacent pages,
3278                // so we need to redraw the workspace when this may have changed.
3279                invalidate();
3280            }
3281            if (mDragTargetLayout != null && mDragHasEnteredWorkspace) {
3282                // Unmark the overlapping layout and re-enter the current layout
3283                mDragTargetLayout = getCurrentDropLayout();
3284                mDragTargetLayout.onDragEnter();
3285            }
3286            result = true;
3287            mInScrollArea = false;
3288        }
3289        return result;
3290    }
3291
3292    private void onResetScrollArea() {
3293        if (mDragTargetLayout != null) {
3294            // Unmark the overlapping layout
3295            mDragTargetLayout.setIsDragOverlapping(false);
3296
3297            // Workspace is responsible for drawing the edge glow on adjacent pages,
3298            // so we need to redraw the workspace when this may have changed.
3299            invalidate();
3300        }
3301        mInScrollArea = false;
3302    }
3303
3304    /**
3305     * Returns a specific CellLayout
3306     */
3307    CellLayout getParentCellLayoutForView(View v) {
3308        ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts();
3309        for (CellLayout layout : layouts) {
3310            if (layout.getChildrenLayout().indexOfChild(v) > -1) {
3311                return layout;
3312            }
3313        }
3314        return null;
3315    }
3316
3317    /**
3318     * Returns a list of all the CellLayouts in the workspace.
3319     */
3320    ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() {
3321        ArrayList<CellLayout> layouts = new ArrayList<CellLayout>();
3322        int screenCount = getChildCount();
3323        for (int screen = 0; screen < screenCount; screen++) {
3324            layouts.add(((CellLayout) getChildAt(screen)));
3325        }
3326        if (mLauncher.getHotseat() != null) {
3327            layouts.add(mLauncher.getHotseat().getLayout());
3328        }
3329        return layouts;
3330    }
3331
3332    /**
3333     * We should only use this to search for specific children.  Do not use this method to modify
3334     * CellLayoutChildren directly.
3335     */
3336    ArrayList<CellLayoutChildren> getWorkspaceAndHotseatCellLayoutChildren() {
3337        ArrayList<CellLayoutChildren> childrenLayouts = new ArrayList<CellLayoutChildren>();
3338        int screenCount = getChildCount();
3339        for (int screen = 0; screen < screenCount; screen++) {
3340            childrenLayouts.add(((CellLayout) getChildAt(screen)).getChildrenLayout());
3341        }
3342        if (mLauncher.getHotseat() != null) {
3343            childrenLayouts.add(mLauncher.getHotseat().getLayout().getChildrenLayout());
3344        }
3345        return childrenLayouts;
3346    }
3347
3348    public Folder getFolderForTag(Object tag) {
3349        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3350        for (CellLayoutChildren layout: childrenLayouts) {
3351            int count = layout.getChildCount();
3352            for (int i = 0; i < count; i++) {
3353                View child = layout.getChildAt(i);
3354                if (child instanceof Folder) {
3355                    Folder f = (Folder) child;
3356                    if (f.getInfo() == tag && f.getInfo().opened) {
3357                        return f;
3358                    }
3359                }
3360            }
3361        }
3362        return null;
3363    }
3364
3365    public View getViewForTag(Object tag) {
3366        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3367        for (CellLayoutChildren layout: childrenLayouts) {
3368            int count = layout.getChildCount();
3369            for (int i = 0; i < count; i++) {
3370                View child = layout.getChildAt(i);
3371                if (child.getTag() == tag) {
3372                    return child;
3373                }
3374            }
3375        }
3376        return null;
3377    }
3378
3379    void clearDropTargets() {
3380        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3381        for (CellLayoutChildren layout: childrenLayouts) {
3382            int childCount = layout.getChildCount();
3383            for (int j = 0; j < childCount; j++) {
3384                View v = layout.getChildAt(j);
3385                if (v instanceof DropTarget) {
3386                    mDragController.removeDropTarget((DropTarget) v);
3387                }
3388            }
3389        }
3390    }
3391
3392    void removeItems(final ArrayList<ApplicationInfo> apps) {
3393        final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext());
3394
3395        final HashSet<String> packageNames = new HashSet<String>();
3396        final int appCount = apps.size();
3397        for (int i = 0; i < appCount; i++) {
3398            packageNames.add(apps.get(i).componentName.getPackageName());
3399        }
3400
3401        ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
3402        for (final CellLayout layoutParent: cellLayouts) {
3403            final ViewGroup layout = layoutParent.getChildrenLayout();
3404
3405            // Avoid ANRs by treating each screen separately
3406            post(new Runnable() {
3407                public void run() {
3408                    final ArrayList<View> childrenToRemove = new ArrayList<View>();
3409                    childrenToRemove.clear();
3410
3411                    int childCount = layout.getChildCount();
3412                    for (int j = 0; j < childCount; j++) {
3413                        final View view = layout.getChildAt(j);
3414                        Object tag = view.getTag();
3415
3416                        if (tag instanceof ShortcutInfo) {
3417                            final ShortcutInfo info = (ShortcutInfo) tag;
3418                            final Intent intent = info.intent;
3419                            final ComponentName name = intent.getComponent();
3420
3421                            if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3422                                for (String packageName: packageNames) {
3423                                    if (packageName.equals(name.getPackageName())) {
3424                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3425                                        childrenToRemove.add(view);
3426                                    }
3427                                }
3428                            }
3429                        } else if (tag instanceof FolderInfo) {
3430                            final FolderInfo info = (FolderInfo) tag;
3431                            final ArrayList<ShortcutInfo> contents = info.contents;
3432                            final int contentsCount = contents.size();
3433                            final ArrayList<ShortcutInfo> appsToRemoveFromFolder =
3434                                    new ArrayList<ShortcutInfo>();
3435
3436                            for (int k = 0; k < contentsCount; k++) {
3437                                final ShortcutInfo appInfo = contents.get(k);
3438                                final Intent intent = appInfo.intent;
3439                                final ComponentName name = intent.getComponent();
3440
3441                                if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3442                                    for (String packageName: packageNames) {
3443                                        if (packageName.equals(name.getPackageName())) {
3444                                            appsToRemoveFromFolder.add(appInfo);
3445                                        }
3446                                    }
3447                                }
3448                            }
3449                            for (ShortcutInfo item: appsToRemoveFromFolder) {
3450                                info.remove(item);
3451                                LauncherModel.deleteItemFromDatabase(mLauncher, item);
3452                            }
3453                        } else if (tag instanceof LauncherAppWidgetInfo) {
3454                            final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag;
3455                            final AppWidgetProviderInfo provider =
3456                                    widgets.getAppWidgetInfo(info.appWidgetId);
3457                            if (provider != null) {
3458                                for (String packageName: packageNames) {
3459                                    if (packageName.equals(provider.provider.getPackageName())) {
3460                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3461                                        childrenToRemove.add(view);
3462                                    }
3463                                }
3464                            }
3465                        }
3466                    }
3467
3468                    childCount = childrenToRemove.size();
3469                    for (int j = 0; j < childCount; j++) {
3470                        View child = childrenToRemove.get(j);
3471                        // Note: We can not remove the view directly from CellLayoutChildren as this
3472                        // does not re-mark the spaces as unoccupied.
3473                        layoutParent.removeViewInLayout(child);
3474                        if (child instanceof DropTarget) {
3475                            mDragController.removeDropTarget((DropTarget)child);
3476                        }
3477                    }
3478
3479                    if (childCount > 0) {
3480                        layout.requestLayout();
3481                        layout.invalidate();
3482                    }
3483                }
3484            });
3485        }
3486    }
3487
3488    void updateShortcuts(ArrayList<ApplicationInfo> apps) {
3489        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3490        for (CellLayoutChildren layout: childrenLayouts) {
3491            int childCount = layout.getChildCount();
3492            for (int j = 0; j < childCount; j++) {
3493                final View view = layout.getChildAt(j);
3494                Object tag = view.getTag();
3495                if (tag instanceof ShortcutInfo) {
3496                    ShortcutInfo info = (ShortcutInfo)tag;
3497                    // We need to check for ACTION_MAIN otherwise getComponent() might
3498                    // return null for some shortcuts (for instance, for shortcuts to
3499                    // web pages.)
3500                    final Intent intent = info.intent;
3501                    final ComponentName name = intent.getComponent();
3502                    if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3503                            Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3504                        final int appCount = apps.size();
3505                        for (int k = 0; k < appCount; k++) {
3506                            ApplicationInfo app = apps.get(k);
3507                            if (app.componentName.equals(name)) {
3508                                info.setIcon(mIconCache.getIcon(info.intent));
3509                                ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null,
3510                                        new FastBitmapDrawable(info.getIcon(mIconCache)),
3511                                        null, null);
3512                                }
3513                        }
3514                    }
3515                }
3516            }
3517        }
3518    }
3519
3520    void moveToDefaultScreen(boolean animate) {
3521        if (!isSmall()) {
3522            if (animate) {
3523                snapToPage(mDefaultPage);
3524            } else {
3525                setCurrentPage(mDefaultPage);
3526            }
3527        }
3528        getChildAt(mDefaultPage).requestFocus();
3529    }
3530
3531    @Override
3532    public void syncPages() {
3533    }
3534
3535    @Override
3536    public void syncPageItems(int page, boolean immediate) {
3537    }
3538
3539    @Override
3540    protected String getCurrentPageDescription() {
3541        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
3542        return String.format(mContext.getString(R.string.workspace_scroll_format),
3543                page + 1, getChildCount());
3544    }
3545
3546    public void getLocationInDragLayer(int[] loc) {
3547        mLauncher.getDragLayer().getLocationInDragLayer(this, loc);
3548    }
3549
3550    void setFadeForOverScroll(float fade) {
3551        if (!isScrollingIndicatorEnabled()) return;
3552
3553        mOverscrollFade = fade;
3554        float reducedFade = 0.5f + 0.5f * (1 - fade);
3555        final ViewGroup parent = (ViewGroup) getParent();
3556        final ImageView qsbDivider = (ImageView) (parent.findViewById(R.id.qsb_divider));
3557        final ImageView dockDivider = (ImageView) (parent.findViewById(R.id.dock_divider));
3558        final View scrollIndicator = getScrollingIndicator();
3559
3560        cancelScrollingIndicatorAnimations();
3561        if (qsbDivider != null) qsbDivider.setAlpha(reducedFade);
3562        if (dockDivider != null) dockDivider.setAlpha(reducedFade);
3563        scrollIndicator.setAlpha(1 - fade);
3564    }
3565}
3566