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