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