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