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