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