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