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