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