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