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