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