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