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