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