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