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