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