Workspace.java revision ef3dd6efe03c988be1fe980fbed75333017e6760
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 float mOverscrollFade = 0;
176
177    // Paint used to draw external drop outline
178    private final Paint mExternalDragOutlinePaint = new Paint();
179
180    // Camera and Matrix used to determine the final position of a neighboring CellLayout
181    private final Matrix mMatrix = new Matrix();
182    private final Camera mCamera = new Camera();
183    private final float mTempFloat2[] = new float[2];
184
185    enum WallpaperVerticalOffset { TOP, MIDDLE, BOTTOM };
186    int mWallpaperWidth;
187    int mWallpaperHeight;
188    WallpaperOffsetInterpolator mWallpaperOffset;
189    boolean mUpdateWallpaperOffsetImmediately = false;
190    private Runnable mDelayedResizeRunnable;
191    private int mDisplayWidth;
192    private int mDisplayHeight;
193    private int mWallpaperTravelWidth;
194
195    // Variables relating to the creation of user folders by hovering shortcuts over shortcuts
196    private static final int FOLDER_CREATION_TIMEOUT = 250;
197    private final Alarm mFolderCreationAlarm = new Alarm();
198    private FolderRingAnimator mDragFolderRingAnimator = null;
199    private View mLastDragOverView = null;
200    private boolean mCreateUserFolderOnDrop = false;
201
202    // Variables relating to touch disambiguation (scrolling workspace vs. scrolling a widget)
203    private float mXDown;
204    private float mYDown;
205    final static float START_DAMPING_TOUCH_SLOP_ANGLE = (float) Math.PI / 6;
206    final static float MAX_SWIPE_ANGLE = (float) Math.PI / 3;
207    final static float TOUCH_SLOP_DAMPING_FACTOR = 4;
208
209    // Relating to the animation of items being dropped externally
210    public static final int ANIMATE_INTO_POSITION = 0;
211    public static final int COMPLETE_TWO_STAGE_WIDGET_DROP_ANIMATION = 1;
212    public static final int CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION = 2;
213
214    // These variables are used for storing the initial and final values during workspace animations
215    private int mSavedScrollX;
216    private float mSavedRotationY;
217    private float mSavedTranslationX;
218    private float mCurrentScaleX;
219    private float mCurrentScaleY;
220    private float mCurrentRotationY;
221    private float mCurrentTranslationX;
222    private float mCurrentTranslationY;
223    private float[] mOldTranslationXs;
224    private float[] mOldTranslationYs;
225    private float[] mOldScaleXs;
226    private float[] mOldScaleYs;
227    private float[] mOldBackgroundAlphas;
228    private float[] mOldBackgroundAlphaMultipliers;
229    private float[] mOldAlphas;
230    private float[] mOldRotationYs;
231    private float[] mNewTranslationXs;
232    private float[] mNewTranslationYs;
233    private float[] mNewScaleXs;
234    private float[] mNewScaleYs;
235    private float[] mNewBackgroundAlphas;
236    private float[] mNewBackgroundAlphaMultipliers;
237    private float[] mNewAlphas;
238    private float[] mNewRotationYs;
239    private float mTransitionProgress = 1f;
240
241    /**
242     * Used to inflate the Workspace from XML.
243     *
244     * @param context The application's context.
245     * @param attrs The attributes set containing the Workspace's customization values.
246     */
247    public Workspace(Context context, AttributeSet attrs) {
248        this(context, attrs, 0);
249    }
250
251    /**
252     * Used to inflate the Workspace from XML.
253     *
254     * @param context The application's context.
255     * @param attrs The attributes set containing the Workspace's customization values.
256     * @param defStyle Unused.
257     */
258    public Workspace(Context context, AttributeSet attrs, int defStyle) {
259        super(context, attrs, defStyle);
260        mContentIsRefreshable = false;
261
262        // With workspace, data is available straight from the get-go
263        setDataIsReady();
264
265        mFadeInAdjacentScreens =
266            getResources().getBoolean(R.bool.config_workspaceFadeAdjacentScreens);
267        mWallpaperManager = WallpaperManager.getInstance(context);
268
269        int cellCountX = DEFAULT_CELL_COUNT_X;
270        int cellCountY = DEFAULT_CELL_COUNT_Y;
271
272        TypedArray a = context.obtainStyledAttributes(attrs,
273                R.styleable.Workspace, defStyle, 0);
274
275        final Resources res = context.getResources();
276        if (LauncherApplication.isScreenLarge()) {
277            // Determine number of rows/columns dynamically
278            // TODO: This code currently fails on tablets with an aspect ratio < 1.3.
279            // Around that ratio we should make cells the same size in portrait and
280            // landscape
281            TypedArray actionBarSizeTypedArray =
282                context.obtainStyledAttributes(new int[] { android.R.attr.actionBarSize });
283            DisplayMetrics displayMetrics = res.getDisplayMetrics();
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                    displayMetrics.density;
288
289            cellCountX = 1;
290            while (CellLayout.widthInPortrait(res, cellCountX + 1) <= smallestScreenDim) {
291                cellCountX++;
292            }
293
294            cellCountY = 1;
295            while (actionBarHeight + CellLayout.heightInLandscape(res, cellCountY + 1)
296                <= smallestScreenDim - systemBarHeight) {
297                cellCountY++;
298            }
299        }
300
301        mSpringLoadedShrinkFactor =
302            res.getInteger(R.integer.config_workspaceSpringLoadShrinkPercentage) / 100.0f;
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.setBitmap(null);
1805
1806        return b;
1807    }
1808
1809    /**
1810     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
1811     * Responsibility for the bitmap is transferred to the caller.
1812     */
1813    private Bitmap createDragOutline(View v, Canvas canvas, int padding) {
1814        final int outlineColor = getResources().getColor(android.R.color.holo_blue_light);
1815        final Bitmap b = Bitmap.createBitmap(
1816                v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
1817
1818        canvas.setBitmap(b);
1819        drawDragView(v, canvas, padding, true);
1820        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1821        canvas.setBitmap(null);
1822        return b;
1823    }
1824
1825    /**
1826     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
1827     * Responsibility for the bitmap is transferred to the caller.
1828     */
1829    private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h,
1830            Paint alphaClipPaint) {
1831        final int outlineColor = getResources().getColor(android.R.color.holo_blue_light);
1832        final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
1833        canvas.setBitmap(b);
1834
1835        Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight());
1836        float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(),
1837                (h - padding) / (float) orig.getHeight());
1838        int scaledWidth = (int) (scaleFactor * orig.getWidth());
1839        int scaledHeight = (int) (scaleFactor * orig.getHeight());
1840        Rect dst = new Rect(0, 0, scaledWidth, scaledHeight);
1841
1842        // center the image
1843        dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2);
1844
1845        canvas.drawBitmap(orig, src, dst, null);
1846        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor,
1847                alphaClipPaint);
1848        canvas.setBitmap(null);
1849
1850        return b;
1851    }
1852
1853    /**
1854     * Creates a drag outline to represent a drop (that we don't have the actual information for
1855     * yet).  May be changed in the future to alter the drop outline slightly depending on the
1856     * clip description mime data.
1857     */
1858    private Bitmap createExternalDragOutline(Canvas canvas, int padding) {
1859        Resources r = getResources();
1860        final int outlineColor = r.getColor(android.R.color.holo_blue_light);
1861        final int iconWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width);
1862        final int iconHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height);
1863        final int rectRadius = r.getDimensionPixelSize(R.dimen.external_drop_icon_rect_radius);
1864        final int inset = (int) (Math.min(iconWidth, iconHeight) * 0.2f);
1865        final Bitmap b = Bitmap.createBitmap(
1866                iconWidth + padding, iconHeight + padding, Bitmap.Config.ARGB_8888);
1867
1868        canvas.setBitmap(b);
1869        canvas.drawRoundRect(new RectF(inset, inset, iconWidth - inset, iconHeight - inset),
1870                rectRadius, rectRadius, mExternalDragOutlinePaint);
1871        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1872        canvas.setBitmap(null);
1873        return b;
1874    }
1875
1876    void startDrag(CellLayout.CellInfo cellInfo) {
1877        View child = cellInfo.cell;
1878
1879        // Make sure the drag was started by a long press as opposed to a long click.
1880        if (!child.isInTouchMode()) {
1881            return;
1882        }
1883
1884        mDragInfo = cellInfo;
1885        child.setVisibility(GONE);
1886
1887        child.clearFocus();
1888        child.setPressed(false);
1889
1890        final Canvas canvas = new Canvas();
1891
1892        // We need to add extra padding to the bitmap to make room for the glow effect
1893        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1894
1895        // The outline is used to visualize where the item will land if dropped
1896        mDragOutline = createDragOutline(child, canvas, bitmapPadding);
1897        beginDragShared(child, this);
1898    }
1899
1900    public void beginDragShared(View child, DragSource source) {
1901        Resources r = getResources();
1902
1903        // We need to add extra padding to the bitmap to make room for the glow effect
1904        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1905
1906        // The drag bitmap follows the touch point around on the screen
1907        final Bitmap b = createDragBitmap(child, new Canvas(), bitmapPadding);
1908
1909        final int bmpWidth = b.getWidth();
1910
1911        mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY);
1912        final int dragLayerX = (int) mTempXY[0] + (child.getWidth() - bmpWidth) / 2;
1913        int dragLayerY = mTempXY[1] - bitmapPadding / 2;
1914
1915        Point dragVisualizeOffset = null;
1916        Rect dragRect = null;
1917        if (child instanceof BubbleTextView || child instanceof PagedViewIcon) {
1918            int iconSize = r.getDimensionPixelSize(R.dimen.app_icon_size);
1919            int iconPaddingTop = r.getDimensionPixelSize(R.dimen.app_icon_padding_top);
1920            int top = child.getPaddingTop();
1921            int left = (bmpWidth - iconSize) / 2;
1922            int right = left + iconSize;
1923            int bottom = top + iconSize;
1924            dragLayerY += top;
1925            // Note: The drag region is used to calculate drag layer offsets, but the
1926            // dragVisualizeOffset in addition to the dragRect (the size) to position the outline.
1927            dragVisualizeOffset = new Point(-bitmapPadding / 2, iconPaddingTop - bitmapPadding / 2);
1928            dragRect = new Rect(left, top, right, bottom);
1929        } else if (child instanceof FolderIcon) {
1930            int previewSize = r.getDimensionPixelSize(R.dimen.folder_preview_size);
1931            dragRect = new Rect(0, 0, child.getWidth(), previewSize);
1932        }
1933
1934        // Clear the pressed state if necessary
1935        if (child instanceof BubbleTextView) {
1936            BubbleTextView icon = (BubbleTextView) child;
1937            icon.clearPressedOrFocusedBackground();
1938        }
1939
1940        mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(),
1941                DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect);
1942        b.recycle();
1943
1944        // Show the scrolling indicator when you pick up an item
1945        showScrollingIndicator(false);
1946    }
1947
1948    void addApplicationShortcut(ShortcutInfo info, CellLayout target, long container, int screen,
1949            int cellX, int cellY, boolean insertAtFirst, int intersectX, int intersectY) {
1950        View view = mLauncher.createShortcut(R.layout.application, target, (ShortcutInfo) info);
1951
1952        final int[] cellXY = new int[2];
1953        target.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY);
1954        addInScreen(view, container, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst);
1955        LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen, cellXY[0],
1956                cellXY[1]);
1957    }
1958
1959    public boolean transitionStateShouldAllowDrop() {
1960        return ((!isSwitchingState() || mTransitionProgress > 0.5f) && mState != State.SMALL);
1961    }
1962
1963    /**
1964     * {@inheritDoc}
1965     */
1966    public boolean acceptDrop(DragObject d) {
1967        // If it's an external drop (e.g. from All Apps), check if it should be accepted
1968        if (d.dragSource != this) {
1969            // Don't accept the drop if we're not over a screen at time of drop
1970            if (mDragTargetLayout == null) {
1971                return false;
1972            }
1973            if (!transitionStateShouldAllowDrop()) return false;
1974
1975            mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
1976                    d.dragView, mDragViewVisualCenter);
1977
1978            // We want the point to be mapped to the dragTarget.
1979            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
1980                mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter);
1981            } else {
1982                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
1983            }
1984
1985            int spanX = 1;
1986            int spanY = 1;
1987            View ignoreView = null;
1988            if (mDragInfo != null) {
1989                final CellLayout.CellInfo dragCellInfo = mDragInfo;
1990                spanX = dragCellInfo.spanX;
1991                spanY = dragCellInfo.spanY;
1992                ignoreView = dragCellInfo.cell;
1993            } else {
1994                final ItemInfo dragInfo = (ItemInfo) d.dragInfo;
1995                spanX = dragInfo.spanX;
1996                spanY = dragInfo.spanY;
1997            }
1998
1999            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2000                    (int) mDragViewVisualCenter[1], spanX, spanY, mDragTargetLayout, mTargetCell);
2001            if (willCreateUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, mTargetCell, true)) {
2002                return true;
2003            }
2004            if (willAddToExistingUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout,
2005                    mTargetCell)) {
2006                return true;
2007            }
2008
2009            // Don't accept the drop if there's no room for the item
2010            if (!mDragTargetLayout.findCellForSpanIgnoring(null, spanX, spanY, ignoreView)) {
2011                // Don't show the message if we are dropping on the AllApps button and the hotseat
2012                // is full
2013                if (mTargetCell != null && mLauncher.isHotseatLayout(mDragTargetLayout)) {
2014                    Hotseat hotseat = mLauncher.getHotseat();
2015                    if (Hotseat.isAllAppsButtonRank(
2016                            hotseat.getOrderInHotseat(mTargetCell[0], mTargetCell[1]))) {
2017                        return false;
2018                    }
2019                }
2020
2021                mLauncher.showOutOfSpaceMessage();
2022                return false;
2023            }
2024        }
2025        return true;
2026    }
2027
2028    boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell,
2029            boolean considerTimeout) {
2030        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2031
2032        boolean hasntMoved = false;
2033        if (mDragInfo != null) {
2034            CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell);
2035            hasntMoved = (mDragInfo.cellX == targetCell[0] &&
2036                    mDragInfo.cellY == targetCell[1]) && (cellParent == target);
2037        }
2038
2039        if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) {
2040            return false;
2041        }
2042
2043        boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo);
2044        boolean willBecomeShortcut =
2045                (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
2046                info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT);
2047
2048        return (aboveShortcut && willBecomeShortcut);
2049    }
2050
2051    boolean willAddToExistingUserFolder(Object dragInfo, CellLayout target, int[] targetCell) {
2052        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2053        if (dropOverView instanceof FolderIcon) {
2054            FolderIcon fi = (FolderIcon) dropOverView;
2055            if (fi.acceptDrop(dragInfo)) {
2056                return true;
2057            }
2058        }
2059        return false;
2060    }
2061
2062    boolean createUserFolderIfNecessary(View newView, long container, CellLayout target,
2063            int[] targetCell, boolean external, DragView dragView, Runnable postAnimationRunnable) {
2064        View v = target.getChildAt(targetCell[0], targetCell[1]);
2065        boolean hasntMoved = false;
2066        if (mDragInfo != null) {
2067            CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell);
2068            hasntMoved = (mDragInfo.cellX == targetCell[0] &&
2069                    mDragInfo.cellY == targetCell[1]) && (cellParent == target);
2070        }
2071
2072        if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false;
2073        mCreateUserFolderOnDrop = false;
2074        final int screen = (targetCell == null) ? mDragInfo.screen : indexOfChild(target);
2075
2076        boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo);
2077        boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo);
2078
2079        if (aboveShortcut && willBecomeShortcut) {
2080            ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag();
2081            ShortcutInfo destInfo = (ShortcutInfo) v.getTag();
2082            // if the drag started here, we need to remove it from the workspace
2083            if (!external) {
2084                getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2085            }
2086
2087            Rect folderLocation = new Rect();
2088            float scale = mLauncher.getDragLayer().getDescendantRectRelativeToSelf(v, folderLocation);
2089            target.removeView(v);
2090
2091            FolderIcon fi =
2092                mLauncher.addFolder(target, container, screen, targetCell[0], targetCell[1]);
2093            destInfo.cellX = -1;
2094            destInfo.cellY = -1;
2095            sourceInfo.cellX = -1;
2096            sourceInfo.cellY = -1;
2097
2098            // If the dragView is null, we can't animate
2099            boolean animate = dragView != null;
2100            if (animate) {
2101                fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale,
2102                        postAnimationRunnable);
2103            } else {
2104                fi.addItem(destInfo);
2105                fi.addItem(sourceInfo);
2106            }
2107            return true;
2108        }
2109        return false;
2110    }
2111
2112    boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell,
2113            DragObject d, boolean external) {
2114        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2115        if (dropOverView instanceof FolderIcon) {
2116            FolderIcon fi = (FolderIcon) dropOverView;
2117            if (fi.acceptDrop(d.dragInfo)) {
2118                fi.onDrop(d);
2119
2120                // if the drag started here, we need to remove it from the workspace
2121                if (!external) {
2122                    getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2123                }
2124                return true;
2125            }
2126        }
2127        return false;
2128    }
2129
2130    public void onDrop(DragObject d) {
2131        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView,
2132                mDragViewVisualCenter);
2133
2134        // We want the point to be mapped to the dragTarget.
2135        if (mDragTargetLayout != null) {
2136            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
2137                mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter);
2138            } else {
2139                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
2140            }
2141        }
2142
2143        CellLayout dropTargetLayout = mDragTargetLayout;
2144
2145        int snapScreen = -1;
2146        if (d.dragSource != this) {
2147            final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0],
2148                    (int) mDragViewVisualCenter[1] };
2149            onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d);
2150        } else if (mDragInfo != null) {
2151            final View cell = mDragInfo.cell;
2152
2153            if (dropTargetLayout != null) {
2154                // Move internally
2155                boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout);
2156                boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout);
2157                long container = hasMovedIntoHotseat ?
2158                        LauncherSettings.Favorites.CONTAINER_HOTSEAT :
2159                        LauncherSettings.Favorites.CONTAINER_DESKTOP;
2160                int screen = (mTargetCell[0] < 0) ?
2161                        mDragInfo.screen : indexOfChild(dropTargetLayout);
2162                int spanX = mDragInfo != null ? mDragInfo.spanX : 1;
2163                int spanY = mDragInfo != null ? mDragInfo.spanY : 1;
2164                // First we find the cell nearest to point at which the item is
2165                // dropped, without any consideration to whether there is an item there.
2166                mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int)
2167                        mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell);
2168                // If the item being dropped is a shortcut and the nearest drop
2169                // cell also contains a shortcut, then create a folder with the two shortcuts.
2170                if (!mInScrollArea && createUserFolderIfNecessary(cell, container,
2171                        dropTargetLayout, mTargetCell, false, d.dragView, null)) {
2172                    return;
2173                }
2174
2175                if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell, d, false)) {
2176                    return;
2177                }
2178
2179                // Aside from the special case where we're dropping a shortcut onto a shortcut,
2180                // we need to find the nearest cell location that is vacant
2181                mTargetCell = findNearestVacantArea((int) mDragViewVisualCenter[0],
2182                        (int) mDragViewVisualCenter[1], mDragInfo.spanX, mDragInfo.spanY, cell,
2183                        dropTargetLayout, mTargetCell);
2184
2185                if (mCurrentPage != screen && !hasMovedIntoHotseat) {
2186                    snapScreen = screen;
2187                    snapToPage(screen);
2188                }
2189
2190                if (mTargetCell[0] >= 0 && mTargetCell[1] >= 0) {
2191                    if (hasMovedLayouts) {
2192                        // Reparent the view
2193                        getParentCellLayoutForView(cell).removeView(cell);
2194                        addInScreen(cell, container, screen, mTargetCell[0], mTargetCell[1],
2195                                mDragInfo.spanX, mDragInfo.spanY);
2196                    }
2197
2198                    // update the item's position after drop
2199                    final ItemInfo info = (ItemInfo) cell.getTag();
2200                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
2201                    dropTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1]);
2202                    lp.cellX = mTargetCell[0];
2203                    lp.cellY = mTargetCell[1];
2204                    cell.setId(LauncherModel.getCellLayoutChildId(container, mDragInfo.screen,
2205                            mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY));
2206
2207                    if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
2208                            cell instanceof LauncherAppWidgetHostView) {
2209                        final CellLayout cellLayout = dropTargetLayout;
2210                        // We post this call so that the widget has a chance to be placed
2211                        // in its final location
2212
2213                        final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell;
2214                        AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo();
2215                        if (pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) {
2216                            final Runnable resizeRunnable = new Runnable() {
2217                                public void run() {
2218                                    DragLayer dragLayer = mLauncher.getDragLayer();
2219                                    dragLayer.addResizeFrame(info, hostView, cellLayout);
2220                                }
2221                            };
2222                            post(new Runnable() {
2223                                public void run() {
2224                                    if (!isPageMoving()) {
2225                                        resizeRunnable.run();
2226                                    } else {
2227                                        mDelayedResizeRunnable = resizeRunnable;
2228                                    }
2229                                }
2230                            });
2231                        }
2232                    }
2233
2234                    LauncherModel.moveItemInDatabase(mLauncher, info, container, screen, lp.cellX,
2235                            lp.cellY);
2236                }
2237            }
2238
2239            final CellLayout parent = (CellLayout) cell.getParent().getParent();
2240
2241            // Prepare it to be animated into its new position
2242            // This must be called after the view has been re-parented
2243            final Runnable disableHardwareLayersRunnable = new Runnable() {
2244                @Override
2245                public void run() {
2246                    mAnimatingViewIntoPlace = false;
2247                    updateChildrenLayersEnabled();
2248                }
2249            };
2250            mAnimatingViewIntoPlace = true;
2251            if (d.dragView.hasDrawn()) {
2252                int duration = snapScreen < 0 ? -1 : ADJACENT_SCREEN_DROP_DURATION;
2253                mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration,
2254                        disableHardwareLayersRunnable, this);
2255            } else {
2256                d.deferDragViewCleanupPostAnimation = false;
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 || mIsSwitchingState || mState == State.SMALL) return;
2678
2679        Rect r = new Rect();
2680        CellLayout layout = null;
2681        ItemInfo item = (ItemInfo) d.dragInfo;
2682
2683        // Ensure that we have proper spans for the item that we are dropping
2684        if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found");
2685        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
2686            d.dragView, mDragViewVisualCenter);
2687
2688        // Identify whether we have dragged over a side page
2689        if (isSmall()) {
2690            if (mLauncher.getHotseat() != null && !isExternalDragWidget(d)) {
2691                mLauncher.getHotseat().getHitRect(r);
2692                if (r.contains(d.x, d.y)) {
2693                    layout = mLauncher.getHotseat().getLayout();
2694                }
2695            }
2696            if (layout == null) {
2697                layout = findMatchingPageForDragOver(d.dragView, d.x, d.y, false);
2698            }
2699            if (layout != mDragTargetLayout) {
2700                // Cancel all intermediate folder states
2701                cleanupFolderCreation(d);
2702
2703                if (mDragTargetLayout != null) {
2704                    mDragTargetLayout.setIsDragOverlapping(false);
2705                    mDragTargetLayout.onDragExit();
2706                }
2707                mDragTargetLayout = layout;
2708                if (mDragTargetLayout != null) {
2709                    mDragTargetLayout.setIsDragOverlapping(true);
2710                    mDragTargetLayout.onDragEnter();
2711                } else {
2712                    mLastDragOverView = null;
2713                }
2714
2715                boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED);
2716                if (isInSpringLoadedMode) {
2717                    if (mLauncher.isHotseatLayout(layout)) {
2718                        mSpringLoadedDragController.cancel();
2719                    } else {
2720                        mSpringLoadedDragController.setAlarm(mDragTargetLayout);
2721                    }
2722                }
2723            }
2724        } else {
2725            // Test to see if we are over the hotseat otherwise just use the current page
2726            if (mLauncher.getHotseat() != null && !isDragWidget(d)) {
2727                mLauncher.getHotseat().getHitRect(r);
2728                if (r.contains(d.x, d.y)) {
2729                    layout = mLauncher.getHotseat().getLayout();
2730                }
2731            }
2732            if (layout == null) {
2733                layout = getCurrentDropLayout();
2734            }
2735            if (layout != mDragTargetLayout) {
2736                if (mDragTargetLayout != null) {
2737                    mDragTargetLayout.setIsDragOverlapping(false);
2738                    mDragTargetLayout.onDragExit();
2739                }
2740                mDragTargetLayout = layout;
2741                mDragTargetLayout.setIsDragOverlapping(true);
2742                mDragTargetLayout.onDragEnter();
2743            }
2744        }
2745
2746        // Handle the drag over
2747        if (mDragTargetLayout != null) {
2748            final View child = (mDragInfo == null) ? null : mDragInfo.cell;
2749
2750            // We want the point to be mapped to the dragTarget.
2751            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
2752                mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter);
2753            } else {
2754                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
2755            }
2756            ItemInfo info = (ItemInfo) d.dragInfo;
2757
2758            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2759                    (int) mDragViewVisualCenter[1], 1, 1, mDragTargetLayout, mTargetCell);
2760            final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0],
2761                    mTargetCell[1]);
2762
2763            boolean userFolderPending = willCreateUserFolder(info, mDragTargetLayout,
2764                    mTargetCell, false);
2765            boolean isOverFolder = dragOverView instanceof FolderIcon;
2766            if (dragOverView != mLastDragOverView) {
2767                cancelFolderCreation();
2768                if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) {
2769                    ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo);
2770                }
2771            }
2772
2773            if (userFolderPending && dragOverView != mLastDragOverView) {
2774                mFolderCreationAlarm.setOnAlarmListener(new
2775                        FolderCreationAlarmListener(mDragTargetLayout, mTargetCell[0], mTargetCell[1]));
2776                mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT);
2777            }
2778
2779            if (dragOverView != mLastDragOverView && isOverFolder) {
2780                ((FolderIcon) dragOverView).onDragEnter(d.dragInfo);
2781                if (mDragTargetLayout != null) {
2782                    mDragTargetLayout.clearDragOutlines();
2783                }
2784            }
2785            mLastDragOverView = dragOverView;
2786
2787            if (!mCreateUserFolderOnDrop && !isOverFolder) {
2788                mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
2789                        (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
2790                        item.spanX, item.spanY, d.dragView.getDragVisualizeOffset(),
2791                        d.dragView.getDragRegion());
2792            }
2793        }
2794    }
2795
2796    private void cleanupFolderCreation(DragObject d) {
2797        if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) {
2798            mDragFolderRingAnimator.animateToNaturalState();
2799        }
2800        if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) {
2801            if (d != null) {
2802                ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo);
2803            }
2804        }
2805        mFolderCreationAlarm.cancelAlarm();
2806    }
2807
2808    private void cancelFolderCreation() {
2809        if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) {
2810            mDragFolderRingAnimator.animateToNaturalState();
2811        }
2812        mCreateUserFolderOnDrop = false;
2813        mFolderCreationAlarm.cancelAlarm();
2814    }
2815
2816    class FolderCreationAlarmListener implements OnAlarmListener {
2817        CellLayout layout;
2818        int cellX;
2819        int cellY;
2820
2821        public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) {
2822            this.layout = layout;
2823            this.cellX = cellX;
2824            this.cellY = cellY;
2825        }
2826
2827        public void onAlarm(Alarm alarm) {
2828            if (mDragFolderRingAnimator == null) {
2829                mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null);
2830            }
2831            mDragFolderRingAnimator.setCell(cellX, cellY);
2832            mDragFolderRingAnimator.setCellLayout(layout);
2833            mDragFolderRingAnimator.animateToAcceptState();
2834            layout.showFolderAccept(mDragFolderRingAnimator);
2835            layout.clearDragOutlines();
2836            mCreateUserFolderOnDrop = true;
2837        }
2838    }
2839
2840    @Override
2841    public void getHitRect(Rect outRect) {
2842        // We want the workspace to have the whole area of the display (it will find the correct
2843        // cell layout to drop to in the existing drag/drop logic.
2844        outRect.set(0, 0, mDisplayWidth, mDisplayHeight);
2845    }
2846
2847    /**
2848     * Add the item specified by dragInfo to the given layout.
2849     * @return true if successful
2850     */
2851    public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) {
2852        if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) {
2853            onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false);
2854            return true;
2855        }
2856        mLauncher.showOutOfSpaceMessage();
2857        return false;
2858    }
2859
2860    private void onDropExternal(int[] touchXY, Object dragInfo,
2861            CellLayout cellLayout, boolean insertAtFirst) {
2862        onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null);
2863    }
2864
2865    /**
2866     * Drop an item that didn't originate on one of the workspace screens.
2867     * It may have come from Launcher (e.g. from all apps or customize), or it may have
2868     * come from another app altogether.
2869     *
2870     * NOTE: This can also be called when we are outside of a drag event, when we want
2871     * to add an item to one of the workspace screens.
2872     */
2873    private void onDropExternal(final int[] touchXY, final Object dragInfo,
2874            final CellLayout cellLayout, boolean insertAtFirst, DragObject d) {
2875        final Runnable exitSpringLoadedRunnable = new Runnable() {
2876            @Override
2877            public void run() {
2878                mLauncher.exitSpringLoadedDragModeDelayed(true, false, null);
2879            }
2880        };
2881
2882        ItemInfo info = (ItemInfo) dragInfo;
2883        int spanX = info.spanX;
2884        int spanY = info.spanY;
2885        if (mDragInfo != null) {
2886            spanX = mDragInfo.spanX;
2887            spanY = mDragInfo.spanY;
2888        }
2889
2890        final long container = mLauncher.isHotseatLayout(cellLayout) ?
2891                LauncherSettings.Favorites.CONTAINER_HOTSEAT :
2892                    LauncherSettings.Favorites.CONTAINER_DESKTOP;
2893        final int screen = indexOfChild(cellLayout);
2894        if (!mLauncher.isHotseatLayout(cellLayout) && screen != mCurrentPage
2895                && mState != State.SPRING_LOADED) {
2896            snapToPage(screen);
2897        }
2898
2899        if (info instanceof PendingAddItemInfo) {
2900            final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo;
2901
2902            boolean findNearestVacantCell = true;
2903            if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
2904                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
2905                        cellLayout, mTargetCell);
2906                if (willCreateUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, mTargetCell,
2907                        true) || willAddToExistingUserFolder((ItemInfo) d.dragInfo,
2908                                mDragTargetLayout, mTargetCell)) {
2909                    findNearestVacantCell = false;
2910                }
2911            }
2912            if (findNearestVacantCell) {
2913                    mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], spanX, spanY, null,
2914                        cellLayout, mTargetCell);
2915            }
2916
2917            Runnable onAnimationCompleteRunnable = new Runnable() {
2918                @Override
2919                public void run() {
2920                    // When dragging and dropping from customization tray, we deal with creating
2921                    // widgets/shortcuts/folders in a slightly different way
2922                    switch (pendingInfo.itemType) {
2923                    case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2924                        mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) pendingInfo,
2925                                container, screen, mTargetCell, null);
2926                        break;
2927                    case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2928                        mLauncher.processShortcutFromDrop(pendingInfo.componentName,
2929                                container, screen, mTargetCell, null);
2930                        break;
2931                    default:
2932                        throw new IllegalStateException("Unknown item type: " +
2933                                pendingInfo.itemType);
2934                    }
2935                    cellLayout.onDragExit();
2936                }
2937            };
2938
2939            animateExternalDrop((PendingAddItemInfo) info, cellLayout, d.dragView,
2940                    onAnimationCompleteRunnable, ANIMATE_INTO_POSITION);
2941        } else {
2942            // This is for other drag/drop cases, like dragging from All Apps
2943            View view = null;
2944
2945            switch (info.itemType) {
2946            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
2947            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2948                if (info.container == NO_ID && info instanceof ApplicationInfo) {
2949                    // Came from all apps -- make a copy
2950                    info = new ShortcutInfo((ApplicationInfo) info);
2951                }
2952                view = mLauncher.createShortcut(R.layout.application, cellLayout,
2953                        (ShortcutInfo) info);
2954                break;
2955            case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2956                view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout,
2957                        (FolderInfo) info, mIconCache);
2958                break;
2959            default:
2960                throw new IllegalStateException("Unknown item type: " + info.itemType);
2961            }
2962
2963            // First we find the cell nearest to point at which the item is
2964            // dropped, without any consideration to whether there is an item there.
2965            if (touchXY != null) {
2966                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
2967                        cellLayout, mTargetCell);
2968                d.postAnimationRunnable = exitSpringLoadedRunnable;
2969                if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, true,
2970                        d.dragView, d.postAnimationRunnable)) {
2971                    return;
2972                }
2973                if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, d, true)) {
2974                    return;
2975                }
2976            }
2977
2978            if (touchXY != null) {
2979                // when dragging and dropping, just find the closest free spot
2980                mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, null,
2981                        cellLayout, mTargetCell);
2982            } else {
2983                cellLayout.findCellForSpan(mTargetCell, 1, 1);
2984            }
2985            addInScreen(view, container, screen, mTargetCell[0], mTargetCell[1], info.spanX,
2986                    info.spanY, insertAtFirst);
2987            cellLayout.onDropChild(view);
2988            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
2989            cellLayout.getChildrenLayout().measureChild(view);
2990
2991            LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen,
2992                    lp.cellX, lp.cellY);
2993
2994            if (d.dragView != null) {
2995                // We wrap the animation call in the temporary set and reset of the current
2996                // cellLayout to its final transform -- this means we animate the drag view to
2997                // the correct final location.
2998                setFinalTransitionTransform(cellLayout);
2999                mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view,
3000                        exitSpringLoadedRunnable);
3001                resetTransitionTransform(cellLayout);
3002            }
3003        }
3004    }
3005
3006    public Bitmap createWidgetBitmap(PendingAddWidgetInfo widgetInfo) {
3007        int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(widgetInfo.spanX,
3008                widgetInfo.spanY, widgetInfo, false);
3009        View layout = widgetInfo.boundWidget;
3010        mLauncher.getDragLayer().removeView(layout);
3011        layout.setVisibility(VISIBLE);
3012
3013        int width = MeasureSpec.makeMeasureSpec(unScaledSize[0], MeasureSpec.EXACTLY);
3014        int height = MeasureSpec.makeMeasureSpec(unScaledSize[1], MeasureSpec.EXACTLY);
3015        Bitmap b = Bitmap.createBitmap(unScaledSize[0], unScaledSize[1],
3016                Bitmap.Config.ARGB_8888);
3017        Canvas c = new Canvas(b);
3018
3019        layout.measure(width, height);
3020        layout.layout(0, 0, unScaledSize[0], unScaledSize[1]);
3021        layout.draw(c);
3022        c.setBitmap(null);
3023        return b;
3024    }
3025
3026    public void animateExternalDrop(PendingAddItemInfo pendingInfo, CellLayout cellLayout,
3027            DragView dragView, Runnable onCompleteRunnable, int animationType) {
3028        // Now we animate the dragView, (ie. the widget or shortcut preview) into its final
3029        // location and size on the home screen.
3030        int spanX = pendingInfo.spanX;
3031        int spanY = pendingInfo.spanY;
3032        RectF r = estimateItemPosition(cellLayout, pendingInfo,
3033                mTargetCell[0], mTargetCell[1], spanX, spanY);
3034        int loc[] = new int[2];
3035        loc[0] = (int) r.left;
3036        loc[1] = (int) r.top;
3037        setFinalTransitionTransform(cellLayout);
3038        float cellLayoutScale =
3039                mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(cellLayout, loc);
3040        resetTransitionTransform(cellLayout);
3041
3042        float dragViewScaleX = r.width() / dragView.getMeasuredWidth();
3043        float dragViewScaleY = r.height() / dragView.getMeasuredHeight();
3044        // The animation will scale the dragView about its center, so we need to center about
3045        // the final location.
3046        loc[0] -= (dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2;
3047        loc[1] -= (dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2;
3048
3049        float scaleX = dragViewScaleX * cellLayoutScale;
3050        float scaleY = dragViewScaleY * cellLayoutScale;
3051
3052        Resources res = mLauncher.getResources();
3053        int duration = res.getInteger(R.integer.config_dropAnimMaxDuration) - 200;
3054
3055        int animationEnd = DragLayer.ANIMATION_END_REMAIN_VISIBLE;
3056        if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
3057                (((PendingAddWidgetInfo) pendingInfo).info.configure == null ||
3058                animationType == COMPLETE_TWO_STAGE_WIDGET_DROP_ANIMATION)) {
3059            Bitmap crossFadeBitmap = createWidgetBitmap((PendingAddWidgetInfo) pendingInfo);
3060            dragView.setCrossFadeBitmap(crossFadeBitmap);
3061            dragView.crossFade((int) (duration * 0.8f));
3062            animationEnd = DragLayer.ANIMATION_END_DISAPPEAR;
3063        } else {
3064            scaleX = scaleY = Math.min(scaleX,  scaleY);
3065        }
3066
3067        if (animationType == CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION) {
3068            mLauncher.getDragLayer().animateViewIntoPosition(dragView, loc, 0f, 0.1f, 0.1f,
3069                    DragLayer.ANIMATION_END_DISAPPEAR, onCompleteRunnable, duration);
3070        } else {
3071            mLauncher.getDragLayer().animateViewIntoPosition(dragView, loc, 1f, scaleX, scaleY,
3072                animationEnd, onCompleteRunnable, duration);
3073        }
3074    }
3075
3076    public void setFinalTransitionTransform(CellLayout layout) {
3077        if (isSwitchingState()) {
3078            int index = indexOfChild(layout);
3079            mCurrentScaleX = layout.getScaleX();
3080            mCurrentScaleY = layout.getScaleY();
3081            mCurrentTranslationX = layout.getTranslationX();
3082            mCurrentTranslationY = layout.getTranslationY();
3083            mCurrentRotationY = layout.getRotationY();
3084            layout.setScaleX(mNewScaleXs[index]);
3085            layout.setScaleY(mNewScaleYs[index]);
3086            layout.setTranslationX(mNewTranslationXs[index]);
3087            layout.setTranslationY(mNewTranslationYs[index]);
3088            layout.setRotationY(mNewRotationYs[index]);
3089        }
3090    }
3091    public void resetTransitionTransform(CellLayout layout) {
3092        if (isSwitchingState()) {
3093            mCurrentScaleX = layout.getScaleX();
3094            mCurrentScaleY = layout.getScaleY();
3095            mCurrentTranslationX = layout.getTranslationX();
3096            mCurrentTranslationY = layout.getTranslationY();
3097            mCurrentRotationY = layout.getRotationY();
3098            layout.setScaleX(mCurrentScaleX);
3099            layout.setScaleY(mCurrentScaleY);
3100            layout.setTranslationX(mCurrentTranslationX);
3101            layout.setTranslationY(mCurrentTranslationY);
3102            layout.setRotationY(mCurrentRotationY);
3103        }
3104    }
3105
3106    /**
3107     * Return the current {@link CellLayout}, correctly picking the destination
3108     * screen while a scroll is in progress.
3109     */
3110    public CellLayout getCurrentDropLayout() {
3111        return (CellLayout) getChildAt(mNextPage == INVALID_PAGE ? mCurrentPage : mNextPage);
3112    }
3113
3114    /**
3115     * Return the current CellInfo describing our current drag; this method exists
3116     * so that Launcher can sync this object with the correct info when the activity is created/
3117     * destroyed
3118     *
3119     */
3120    public CellLayout.CellInfo getDragInfo() {
3121        return mDragInfo;
3122    }
3123
3124    /**
3125     * Calculate the nearest cell where the given object would be dropped.
3126     *
3127     * pixelX and pixelY should be in the coordinate system of layout
3128     */
3129    private int[] findNearestVacantArea(int pixelX, int pixelY,
3130            int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) {
3131        return layout.findNearestVacantArea(
3132                pixelX, pixelY, spanX, spanY, ignoreView, recycle);
3133    }
3134
3135    /**
3136     * Calculate the nearest cell where the given object would be dropped.
3137     *
3138     * pixelX and pixelY should be in the coordinate system of layout
3139     */
3140    private int[] findNearestArea(int pixelX, int pixelY,
3141            int spanX, int spanY, CellLayout layout, int[] recycle) {
3142        return layout.findNearestArea(
3143                pixelX, pixelY, spanX, spanY, recycle);
3144    }
3145
3146    void setup(DragController dragController) {
3147        mSpringLoadedDragController = new SpringLoadedDragController(mLauncher);
3148        mDragController = dragController;
3149
3150        // hardware layers on children are enabled on startup, but should be disabled until
3151        // needed
3152        updateChildrenLayersEnabled();
3153        setWallpaperDimension();
3154    }
3155
3156    /**
3157     * Called at the end of a drag which originated on the workspace.
3158     */
3159    public void onDropCompleted(View target, DragObject d, boolean success) {
3160        if (success) {
3161            if (target != this) {
3162                if (mDragInfo != null) {
3163                    getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
3164                    if (mDragInfo.cell instanceof DropTarget) {
3165                        mDragController.removeDropTarget((DropTarget) mDragInfo.cell);
3166                    }
3167                }
3168            }
3169        } else if (mDragInfo != null) {
3170            // NOTE: When 'success' is true, onDragExit is called by the DragController before
3171            // calling onDropCompleted(). We call it ourselves here, but maybe this should be
3172            // moved into DragController.cancelDrag().
3173            doDragExit(null);
3174            CellLayout cellLayout;
3175            if (mLauncher.isHotseatLayout(target)) {
3176                cellLayout = mLauncher.getHotseat().getLayout();
3177            } else {
3178                cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
3179            }
3180            cellLayout.onDropChild(mDragInfo.cell);
3181        }
3182        if (d.cancelled &&  mDragInfo.cell != null) {
3183                mDragInfo.cell.setVisibility(VISIBLE);
3184        }
3185        mDragOutline = null;
3186        mDragInfo = null;
3187
3188        // Hide the scrolling indicator after you pick up an item
3189        hideScrollingIndicator(false);
3190    }
3191
3192    public boolean isDropEnabled() {
3193        return true;
3194    }
3195
3196    @Override
3197    protected void onRestoreInstanceState(Parcelable state) {
3198        super.onRestoreInstanceState(state);
3199        Launcher.setScreen(mCurrentPage);
3200    }
3201
3202    @Override
3203    public void scrollLeft() {
3204        if (!isSmall() && !mIsSwitchingState) {
3205            super.scrollLeft();
3206        }
3207        Folder openFolder = getOpenFolder();
3208        if (openFolder != null) {
3209            openFolder.completeDragExit();
3210        }
3211    }
3212
3213    @Override
3214    public void scrollRight() {
3215        if (!isSmall() && !mIsSwitchingState) {
3216            super.scrollRight();
3217        }
3218        Folder openFolder = getOpenFolder();
3219        if (openFolder != null) {
3220            openFolder.completeDragExit();
3221        }
3222    }
3223
3224    @Override
3225    public boolean onEnterScrollArea(int x, int y, int direction) {
3226        // Ignore the scroll area if we are dragging over the hot seat
3227        if (mLauncher.getHotseat() != null) {
3228            Rect r = new Rect();
3229            mLauncher.getHotseat().getHitRect(r);
3230            if (r.contains(x, y)) {
3231                return false;
3232            }
3233        }
3234
3235        boolean result = false;
3236        if (!isSmall() && !mIsSwitchingState) {
3237            mInScrollArea = true;
3238
3239            final int page = (mNextPage != INVALID_PAGE ? mNextPage : mCurrentPage) +
3240                       (direction == DragController.SCROLL_LEFT ? -1 : 1);
3241            cancelFolderCreation();
3242
3243            if (0 <= page && page < getChildCount()) {
3244                CellLayout layout = (CellLayout) getChildAt(page);
3245                // Exit the current layout and mark the overlapping layout
3246                if (mDragTargetLayout != null) {
3247                    mDragTargetLayout.setIsDragOverlapping(false);
3248                    mDragTargetLayout.onDragExit();
3249                }
3250                mDragTargetLayout = layout;
3251                mDragTargetLayout.setIsDragOverlapping(true);
3252
3253                // Workspace is responsible for drawing the edge glow on adjacent pages,
3254                // so we need to redraw the workspace when this may have changed.
3255                invalidate();
3256                result = true;
3257            }
3258        }
3259        return result;
3260    }
3261
3262    @Override
3263    public boolean onExitScrollArea() {
3264        boolean result = false;
3265        if (mInScrollArea) {
3266            if (mDragTargetLayout != null) {
3267                mDragTargetLayout.setIsDragOverlapping(false);
3268                // Workspace is responsible for drawing the edge glow on adjacent pages,
3269                // so we need to redraw the workspace when this may have changed.
3270                invalidate();
3271            }
3272            if (mDragTargetLayout != null && mDragHasEnteredWorkspace) {
3273                // Unmark the overlapping layout and re-enter the current layout
3274                mDragTargetLayout = getCurrentDropLayout();
3275                mDragTargetLayout.onDragEnter();
3276            }
3277            result = true;
3278            mInScrollArea = false;
3279        }
3280        return result;
3281    }
3282
3283    private void onResetScrollArea() {
3284        if (mDragTargetLayout != null) {
3285            // Unmark the overlapping layout
3286            mDragTargetLayout.setIsDragOverlapping(false);
3287
3288            // Workspace is responsible for drawing the edge glow on adjacent pages,
3289            // so we need to redraw the workspace when this may have changed.
3290            invalidate();
3291        }
3292        mInScrollArea = false;
3293    }
3294
3295    /**
3296     * Returns a specific CellLayout
3297     */
3298    CellLayout getParentCellLayoutForView(View v) {
3299        ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts();
3300        for (CellLayout layout : layouts) {
3301            if (layout.getChildrenLayout().indexOfChild(v) > -1) {
3302                return layout;
3303            }
3304        }
3305        return null;
3306    }
3307
3308    /**
3309     * Returns a list of all the CellLayouts in the workspace.
3310     */
3311    ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() {
3312        ArrayList<CellLayout> layouts = new ArrayList<CellLayout>();
3313        int screenCount = getChildCount();
3314        for (int screen = 0; screen < screenCount; screen++) {
3315            layouts.add(((CellLayout) getChildAt(screen)));
3316        }
3317        if (mLauncher.getHotseat() != null) {
3318            layouts.add(mLauncher.getHotseat().getLayout());
3319        }
3320        return layouts;
3321    }
3322
3323    /**
3324     * We should only use this to search for specific children.  Do not use this method to modify
3325     * CellLayoutChildren directly.
3326     */
3327    ArrayList<CellLayoutChildren> getWorkspaceAndHotseatCellLayoutChildren() {
3328        ArrayList<CellLayoutChildren> childrenLayouts = new ArrayList<CellLayoutChildren>();
3329        int screenCount = getChildCount();
3330        for (int screen = 0; screen < screenCount; screen++) {
3331            childrenLayouts.add(((CellLayout) getChildAt(screen)).getChildrenLayout());
3332        }
3333        if (mLauncher.getHotseat() != null) {
3334            childrenLayouts.add(mLauncher.getHotseat().getLayout().getChildrenLayout());
3335        }
3336        return childrenLayouts;
3337    }
3338
3339    public Folder getFolderForTag(Object tag) {
3340        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3341        for (CellLayoutChildren layout: childrenLayouts) {
3342            int count = layout.getChildCount();
3343            for (int i = 0; i < count; i++) {
3344                View child = layout.getChildAt(i);
3345                if (child instanceof Folder) {
3346                    Folder f = (Folder) child;
3347                    if (f.getInfo() == tag && f.getInfo().opened) {
3348                        return f;
3349                    }
3350                }
3351            }
3352        }
3353        return null;
3354    }
3355
3356    public View getViewForTag(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.getTag() == tag) {
3363                    return child;
3364                }
3365            }
3366        }
3367        return null;
3368    }
3369
3370    void clearDropTargets() {
3371        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3372        for (CellLayoutChildren layout: childrenLayouts) {
3373            int childCount = layout.getChildCount();
3374            for (int j = 0; j < childCount; j++) {
3375                View v = layout.getChildAt(j);
3376                if (v instanceof DropTarget) {
3377                    mDragController.removeDropTarget((DropTarget) v);
3378                }
3379            }
3380        }
3381    }
3382
3383    void removeItems(final ArrayList<ApplicationInfo> apps) {
3384        final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext());
3385
3386        final HashSet<String> packageNames = new HashSet<String>();
3387        final int appCount = apps.size();
3388        for (int i = 0; i < appCount; i++) {
3389            packageNames.add(apps.get(i).componentName.getPackageName());
3390        }
3391
3392        ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
3393        for (final CellLayout layoutParent: cellLayouts) {
3394            final ViewGroup layout = layoutParent.getChildrenLayout();
3395
3396            // Avoid ANRs by treating each screen separately
3397            post(new Runnable() {
3398                public void run() {
3399                    final ArrayList<View> childrenToRemove = new ArrayList<View>();
3400                    childrenToRemove.clear();
3401
3402                    int childCount = layout.getChildCount();
3403                    for (int j = 0; j < childCount; j++) {
3404                        final View view = layout.getChildAt(j);
3405                        Object tag = view.getTag();
3406
3407                        if (tag instanceof ShortcutInfo) {
3408                            final ShortcutInfo info = (ShortcutInfo) tag;
3409                            final Intent intent = info.intent;
3410                            final ComponentName name = intent.getComponent();
3411
3412                            if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3413                                for (String packageName: packageNames) {
3414                                    if (packageName.equals(name.getPackageName())) {
3415                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3416                                        childrenToRemove.add(view);
3417                                    }
3418                                }
3419                            }
3420                        } else if (tag instanceof FolderInfo) {
3421                            final FolderInfo info = (FolderInfo) tag;
3422                            final ArrayList<ShortcutInfo> contents = info.contents;
3423                            final int contentsCount = contents.size();
3424                            final ArrayList<ShortcutInfo> appsToRemoveFromFolder =
3425                                    new ArrayList<ShortcutInfo>();
3426
3427                            for (int k = 0; k < contentsCount; k++) {
3428                                final ShortcutInfo appInfo = contents.get(k);
3429                                final Intent intent = appInfo.intent;
3430                                final ComponentName name = intent.getComponent();
3431
3432                                if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3433                                    for (String packageName: packageNames) {
3434                                        if (packageName.equals(name.getPackageName())) {
3435                                            appsToRemoveFromFolder.add(appInfo);
3436                                        }
3437                                    }
3438                                }
3439                            }
3440                            for (ShortcutInfo item: appsToRemoveFromFolder) {
3441                                info.remove(item);
3442                                LauncherModel.deleteItemFromDatabase(mLauncher, item);
3443                            }
3444                        } else if (tag instanceof LauncherAppWidgetInfo) {
3445                            final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag;
3446                            final AppWidgetProviderInfo provider =
3447                                    widgets.getAppWidgetInfo(info.appWidgetId);
3448                            if (provider != null) {
3449                                for (String packageName: packageNames) {
3450                                    if (packageName.equals(provider.provider.getPackageName())) {
3451                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3452                                        childrenToRemove.add(view);
3453                                    }
3454                                }
3455                            }
3456                        }
3457                    }
3458
3459                    childCount = childrenToRemove.size();
3460                    for (int j = 0; j < childCount; j++) {
3461                        View child = childrenToRemove.get(j);
3462                        // Note: We can not remove the view directly from CellLayoutChildren as this
3463                        // does not re-mark the spaces as unoccupied.
3464                        layoutParent.removeViewInLayout(child);
3465                        if (child instanceof DropTarget) {
3466                            mDragController.removeDropTarget((DropTarget)child);
3467                        }
3468                    }
3469
3470                    if (childCount > 0) {
3471                        layout.requestLayout();
3472                        layout.invalidate();
3473                    }
3474                }
3475            });
3476        }
3477    }
3478
3479    void updateShortcuts(ArrayList<ApplicationInfo> apps) {
3480        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3481        for (CellLayoutChildren layout: childrenLayouts) {
3482            int childCount = layout.getChildCount();
3483            for (int j = 0; j < childCount; j++) {
3484                final View view = layout.getChildAt(j);
3485                Object tag = view.getTag();
3486                if (tag instanceof ShortcutInfo) {
3487                    ShortcutInfo info = (ShortcutInfo)tag;
3488                    // We need to check for ACTION_MAIN otherwise getComponent() might
3489                    // return null for some shortcuts (for instance, for shortcuts to
3490                    // web pages.)
3491                    final Intent intent = info.intent;
3492                    final ComponentName name = intent.getComponent();
3493                    if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3494                            Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3495                        final int appCount = apps.size();
3496                        for (int k = 0; k < appCount; k++) {
3497                            ApplicationInfo app = apps.get(k);
3498                            if (app.componentName.equals(name)) {
3499                                info.setIcon(mIconCache.getIcon(info.intent));
3500                                ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null,
3501                                        new FastBitmapDrawable(info.getIcon(mIconCache)),
3502                                        null, null);
3503                                }
3504                        }
3505                    }
3506                }
3507            }
3508        }
3509    }
3510
3511    void moveToDefaultScreen(boolean animate) {
3512        if (!isSmall()) {
3513            if (animate) {
3514                snapToPage(mDefaultPage);
3515            } else {
3516                setCurrentPage(mDefaultPage);
3517            }
3518        }
3519        getChildAt(mDefaultPage).requestFocus();
3520    }
3521
3522    @Override
3523    public void syncPages() {
3524    }
3525
3526    @Override
3527    public void syncPageItems(int page, boolean immediate) {
3528    }
3529
3530    @Override
3531    protected String getCurrentPageDescription() {
3532        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
3533        return String.format(mContext.getString(R.string.workspace_scroll_format),
3534                page + 1, getChildCount());
3535    }
3536
3537    public void getLocationInDragLayer(int[] loc) {
3538        mLauncher.getDragLayer().getLocationInDragLayer(this, loc);
3539    }
3540
3541    void setFadeForOverScroll(float fade) {
3542        if (!isScrollingIndicatorEnabled()) return;
3543
3544        mOverscrollFade = fade;
3545        float reducedFade = 0.5f + 0.5f * (1 - fade);
3546        final ViewGroup parent = (ViewGroup) getParent();
3547        final ImageView qsbDivider = (ImageView) (parent.findViewById(R.id.qsb_divider));
3548        final ImageView dockDivider = (ImageView) (parent.findViewById(R.id.dock_divider));
3549        final View scrollIndicator = getScrollingIndicator();
3550
3551        cancelScrollingIndicatorAnimations();
3552        if (qsbDivider != null) qsbDivider.setAlpha(reducedFade);
3553        if (dockDivider != null) dockDivider.setAlpha(reducedFade);
3554        scrollIndicator.setAlpha(1 - fade);
3555    }
3556}
3557