Workspace.java revision ce3cbd145b4222779abae32869da8dd3c2aefb67
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    private float mOverScrollMaxBackgroundAlpha = 0.0f;
98
99    private float mWallpaperScrollRatio = 1.0f;
100    private int mOriginalPageSpacing;
101
102    private final WallpaperManager mWallpaperManager;
103    private IBinder mWindowToken;
104    private static final float WALLPAPER_SCREENS_SPAN = 2f;
105
106    private int mDefaultPage;
107
108    /**
109     * CellInfo for the cell that is currently being dragged
110     */
111    private CellLayout.CellInfo mDragInfo;
112
113    /**
114     * Target drop area calculated during last acceptDrop call.
115     */
116    private int[] mTargetCell = new int[2];
117    private int mDragOverX = -1;
118    private int mDragOverY = -1;
119
120    static Rect mLandscapeCellLayoutMetrics = null;
121    static Rect mPortraitCellLayoutMetrics = null;
122
123    /**
124     * The CellLayout that is currently being dragged over
125     */
126    private CellLayout mDragTargetLayout = null;
127    /**
128     * The CellLayout that we will show as glowing
129     */
130    private CellLayout mDragOverlappingLayout = null;
131
132    /**
133     * The CellLayout which will be dropped to
134     */
135    private CellLayout mDropToLayout = null;
136
137    private Launcher mLauncher;
138    private IconCache mIconCache;
139    private DragController mDragController;
140
141    // These are temporary variables to prevent having to allocate a new object just to
142    // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
143    private int[] mTempCell = new int[2];
144    private int[] mTempEstimate = new int[2];
145    private float[] mDragViewVisualCenter = new float[2];
146    private float[] mTempDragCoordinates = new float[2];
147    private float[] mTempCellLayoutCenterCoordinates = new float[2];
148    private float[] mTempDragBottomRightCoordinates = new float[2];
149    private Matrix mTempInverseMatrix = new Matrix();
150
151    private SpringLoadedDragController mSpringLoadedDragController;
152    private float mSpringLoadedShrinkFactor;
153
154    private static final int DEFAULT_CELL_COUNT_X = 4;
155    private static final int DEFAULT_CELL_COUNT_Y = 4;
156
157    // State variable that indicates whether the pages are small (ie when you're
158    // in all apps or customize mode)
159
160    enum State { NORMAL, SPRING_LOADED, SMALL };
161    private State mState = State.NORMAL;
162    private boolean mIsSwitchingState = false;
163
164    boolean mAnimatingViewIntoPlace = false;
165    boolean mIsDragOccuring = false;
166    boolean mChildrenLayersEnabled = true;
167
168    /** Is the user is dragging an item near the edge of a page? */
169    private boolean mInScrollArea = false;
170
171    private final HolographicOutlineHelper mOutlineHelper = new HolographicOutlineHelper();
172    private Bitmap mDragOutline = null;
173    private final Rect mTempRect = new Rect();
174    private final int[] mTempXY = new int[2];
175    private int[] mTempVisiblePagesRange = new int[2];
176    private float mOverscrollFade = 0;
177    private boolean mOverscrollTransformsSet;
178    public static final int DRAG_BITMAP_PADDING = 2;
179    private boolean mWorkspaceFadeInAdjacentScreens;
180
181    enum WallpaperVerticalOffset { TOP, MIDDLE, BOTTOM };
182    int mWallpaperWidth;
183    int mWallpaperHeight;
184    WallpaperOffsetInterpolator mWallpaperOffset;
185    boolean mUpdateWallpaperOffsetImmediately = false;
186    private Runnable mDelayedResizeRunnable;
187    private Runnable mDelayedSnapToPageRunnable;
188    private Point mDisplaySize = new Point();
189    private boolean mIsStaticWallpaper;
190    private int mWallpaperTravelWidth;
191    private int mSpringLoadedPageSpacing;
192    private int mCameraDistance;
193
194    // Variables relating to the creation of user folders by hovering shortcuts over shortcuts
195    private static final int FOLDER_CREATION_TIMEOUT = 0;
196    private static final int REORDER_TIMEOUT = 250;
197    private final Alarm mFolderCreationAlarm = new Alarm();
198    private final Alarm mReorderAlarm = new Alarm();
199    private FolderRingAnimator mDragFolderRingAnimator = null;
200    private FolderIcon mDragOverFolderIcon = null;
201    private boolean mCreateUserFolderOnDrop = false;
202    private boolean mAddToExistingFolderOnDrop = false;
203    private DropTarget.DragEnforcer mDragEnforcer;
204    private float mMaxDistanceForFolderCreation;
205
206    // Variables relating to touch disambiguation (scrolling workspace vs. scrolling a widget)
207    private float mXDown;
208    private float mYDown;
209    final static float START_DAMPING_TOUCH_SLOP_ANGLE = (float) Math.PI / 6;
210    final static float MAX_SWIPE_ANGLE = (float) Math.PI / 3;
211    final static float TOUCH_SLOP_DAMPING_FACTOR = 4;
212
213    // Relating to the animation of items being dropped externally
214    public static final int ANIMATE_INTO_POSITION_AND_DISAPPEAR = 0;
215    public static final int ANIMATE_INTO_POSITION_AND_REMAIN = 1;
216    public static final int ANIMATE_INTO_POSITION_AND_RESIZE = 2;
217    public static final int COMPLETE_TWO_STAGE_WIDGET_DROP_ANIMATION = 3;
218    public static final int CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION = 4;
219
220    // Related to dragging, folder creation and reordering
221    private static final int DRAG_MODE_NONE = 0;
222    private static final int DRAG_MODE_CREATE_FOLDER = 1;
223    private static final int DRAG_MODE_ADD_TO_FOLDER = 2;
224    private static final int DRAG_MODE_REORDER = 3;
225    private int mDragMode = DRAG_MODE_NONE;
226    private int mLastReorderX = -1;
227    private int mLastReorderY = -1;
228
229    private SparseArray<Parcelable> mSavedStates;
230    private final ArrayList<Integer> mRestoredPages = new ArrayList<Integer>();
231
232    // These variables are used for storing the initial and final values during workspace animations
233    private int mSavedScrollX;
234    private float mSavedRotationY;
235    private float mSavedTranslationX;
236    private float mCurrentScaleX;
237    private float mCurrentScaleY;
238    private float mCurrentRotationY;
239    private float mCurrentTranslationX;
240    private float mCurrentTranslationY;
241    private float[] mOldTranslationXs;
242    private float[] mOldTranslationYs;
243    private float[] mOldScaleXs;
244    private float[] mOldScaleYs;
245    private float[] mOldBackgroundAlphas;
246    private float[] mOldAlphas;
247    private float[] mNewTranslationXs;
248    private float[] mNewTranslationYs;
249    private float[] mNewScaleXs;
250    private float[] mNewScaleYs;
251    private float[] mNewBackgroundAlphas;
252    private float[] mNewAlphas;
253    private float[] mNewRotationYs;
254    private float mTransitionProgress;
255
256    private final Runnable mBindPages = new Runnable() {
257        @Override
258        public void run() {
259            mLauncher.getModel().bindRemainingSynchronousPages();
260        }
261    };
262
263    /**
264     * Used to inflate the Workspace from XML.
265     *
266     * @param context The application's context.
267     * @param attrs The attributes set containing the Workspace's customization values.
268     */
269    public Workspace(Context context, AttributeSet attrs) {
270        this(context, attrs, 0);
271    }
272
273    /**
274     * Used to inflate the Workspace from XML.
275     *
276     * @param context The application's context.
277     * @param attrs The attributes set containing the Workspace's customization values.
278     * @param defStyle Unused.
279     */
280    public Workspace(Context context, AttributeSet attrs, int defStyle) {
281        super(context, attrs, defStyle);
282        mContentIsRefreshable = false;
283        mOriginalPageSpacing = mPageSpacing;
284
285        mDragEnforcer = new DropTarget.DragEnforcer(context);
286        // With workspace, data is available straight from the get-go
287        setDataIsReady();
288
289        mLauncher = (Launcher) context;
290        final Resources res = getResources();
291        mWorkspaceFadeInAdjacentScreens = res.getBoolean(R.bool.config_workspaceFadeAdjacentScreens);
292        mFadeInAdjacentScreens = false;
293        mWallpaperManager = WallpaperManager.getInstance(context);
294
295        int cellCountX = DEFAULT_CELL_COUNT_X;
296        int cellCountY = DEFAULT_CELL_COUNT_Y;
297
298        TypedArray a = context.obtainStyledAttributes(attrs,
299                R.styleable.Workspace, defStyle, 0);
300
301        if (LauncherApplication.isScreenLarge()) {
302            // Determine number of rows/columns dynamically
303            // TODO: This code currently fails on tablets with an aspect ratio < 1.3.
304            // Around that ratio we should make cells the same size in portrait and
305            // landscape
306            TypedArray actionBarSizeTypedArray =
307                context.obtainStyledAttributes(new int[] { android.R.attr.actionBarSize });
308            final float actionBarHeight = actionBarSizeTypedArray.getDimension(0, 0f);
309
310            Point minDims = new Point();
311            Point maxDims = new Point();
312            mLauncher.getWindowManager().getDefaultDisplay().getCurrentSizeRange(minDims, maxDims);
313
314            cellCountX = 1;
315            while (CellLayout.widthInPortrait(res, cellCountX + 1) <= minDims.x) {
316                cellCountX++;
317            }
318
319            cellCountY = 1;
320            while (actionBarHeight + CellLayout.heightInLandscape(res, cellCountY + 1)
321                <= minDims.y) {
322                cellCountY++;
323            }
324        }
325
326        mSpringLoadedShrinkFactor =
327            res.getInteger(R.integer.config_workspaceSpringLoadShrinkPercentage) / 100.0f;
328        mSpringLoadedPageSpacing =
329                res.getDimensionPixelSize(R.dimen.workspace_spring_loaded_page_spacing);
330        mCameraDistance = res.getInteger(R.integer.config_cameraDistance);
331
332        // if the value is manually specified, use that instead
333        cellCountX = a.getInt(R.styleable.Workspace_cellCountX, cellCountX);
334        cellCountY = a.getInt(R.styleable.Workspace_cellCountY, cellCountY);
335        mDefaultPage = a.getInt(R.styleable.Workspace_defaultScreen, 1);
336        a.recycle();
337
338        setOnHierarchyChangeListener(this);
339
340        LauncherModel.updateWorkspaceLayoutCells(cellCountX, cellCountY);
341        setHapticFeedbackEnabled(false);
342
343        initWorkspace();
344
345        // Disable multitouch across the workspace/all apps/customize tray
346        setMotionEventSplittingEnabled(true);
347
348        // Unless otherwise specified this view is important for accessibility.
349        if (getImportantForAccessibility() == View.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
350            setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
351        }
352    }
353
354    // estimate the size of a widget with spans hSpan, vSpan. return MAX_VALUE for each
355    // dimension if unsuccessful
356    public int[] estimateItemSize(int hSpan, int vSpan,
357            ItemInfo itemInfo, boolean springLoaded) {
358        int[] size = new int[2];
359        if (getChildCount() > 0) {
360            CellLayout cl = (CellLayout) mLauncher.getWorkspace().getChildAt(0);
361            Rect r = estimateItemPosition(cl, itemInfo, 0, 0, hSpan, vSpan);
362            size[0] = r.width();
363            size[1] = r.height();
364            if (springLoaded) {
365                size[0] *= mSpringLoadedShrinkFactor;
366                size[1] *= mSpringLoadedShrinkFactor;
367            }
368            return size;
369        } else {
370            size[0] = Integer.MAX_VALUE;
371            size[1] = Integer.MAX_VALUE;
372            return size;
373        }
374    }
375    public Rect estimateItemPosition(CellLayout cl, ItemInfo pendingInfo,
376            int hCell, int vCell, int hSpan, int vSpan) {
377        Rect r = new Rect();
378        cl.cellToRect(hCell, vCell, hSpan, vSpan, r);
379        return r;
380    }
381
382    public void onDragStart(DragSource source, Object info, int dragAction) {
383        mIsDragOccuring = true;
384        updateChildrenLayersEnabled(false);
385        mLauncher.lockScreenOrientation();
386        setChildrenBackgroundAlphaMultipliers(1f);
387        // Prevent any Un/InstallShortcutReceivers from updating the db while we are dragging
388        InstallShortcutReceiver.enableInstallQueue();
389        UninstallShortcutReceiver.enableUninstallQueue();
390    }
391
392    public void onDragEnd() {
393        mIsDragOccuring = false;
394        updateChildrenLayersEnabled(false);
395        mLauncher.unlockScreenOrientation(false);
396
397        // Re-enable any Un/InstallShortcutReceiver and now process any queued items
398        InstallShortcutReceiver.disableAndFlushInstallQueue(getContext());
399        UninstallShortcutReceiver.disableAndFlushUninstallQueue(getContext());
400    }
401
402    /**
403     * Initializes various states for this workspace.
404     */
405    protected void initWorkspace() {
406        Context context = getContext();
407        mCurrentPage = mDefaultPage;
408        Launcher.setScreen(mCurrentPage);
409        LauncherApplication app = (LauncherApplication)context.getApplicationContext();
410        mIconCache = app.getIconCache();
411        setWillNotDraw(false);
412        setClipChildren(false);
413        setClipToPadding(false);
414        setChildrenDrawnWithCacheEnabled(true);
415
416        final Resources res = getResources();
417        try {
418            mBackground = res.getDrawable(R.drawable.apps_customize_bg);
419        } catch (Resources.NotFoundException e) {
420            // In this case, we will skip drawing background protection
421        }
422
423        mWallpaperOffset = new WallpaperOffsetInterpolator();
424        Display display = mLauncher.getWindowManager().getDefaultDisplay();
425        display.getSize(mDisplaySize);
426        mWallpaperTravelWidth = (int) (mDisplaySize.x *
427                wallpaperTravelToScreenWidthRatio(mDisplaySize.x, mDisplaySize.y));
428
429        mMaxDistanceForFolderCreation = (0.55f * res.getDimensionPixelSize(R.dimen.app_icon_size));
430        mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
431    }
432
433    @Override
434    protected int getScrollMode() {
435        return SmoothPagedView.X_LARGE_MODE;
436    }
437
438    @Override
439    public void onChildViewAdded(View parent, View child) {
440        if (!(child instanceof CellLayout)) {
441            throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
442        }
443        CellLayout cl = ((CellLayout) child);
444        cl.setOnInterceptTouchListener(this);
445        cl.setClickable(true);
446        cl.setContentDescription(getContext().getString(
447                R.string.workspace_description_format, getChildCount()));
448    }
449
450    @Override
451    public void onChildViewRemoved(View parent, View child) {
452    }
453
454    protected boolean shouldDrawChild(View child) {
455        final CellLayout cl = (CellLayout) child;
456        return super.shouldDrawChild(child) &&
457            (cl.getShortcutsAndWidgets().getAlpha() > 0 ||
458             cl.getBackgroundAlpha() > 0);
459    }
460
461    /**
462     * @return The open folder on the current screen, or null if there is none
463     */
464    Folder getOpenFolder() {
465        DragLayer dragLayer = mLauncher.getDragLayer();
466        int count = dragLayer.getChildCount();
467        for (int i = 0; i < count; i++) {
468            View child = dragLayer.getChildAt(i);
469            if (child instanceof Folder) {
470                Folder folder = (Folder) child;
471                if (folder.getInfo().opened)
472                    return folder;
473            }
474        }
475        return null;
476    }
477
478    boolean isTouchActive() {
479        return mTouchState != TOUCH_STATE_REST;
480    }
481
482    /**
483     * Adds the specified child in the specified screen. The position and dimension of
484     * the child are defined by x, y, spanX and spanY.
485     *
486     * @param child The child to add in one of the workspace's screens.
487     * @param screen The screen in which to add the child.
488     * @param x The X position of the child in the screen's grid.
489     * @param y The Y position of the child in the screen's grid.
490     * @param spanX The number of cells spanned horizontally by the child.
491     * @param spanY The number of cells spanned vertically by the child.
492     */
493    void addInScreen(View child, long container, int screen, int x, int y, int spanX, int spanY) {
494        addInScreen(child, container, screen, x, y, spanX, spanY, false);
495    }
496
497    /**
498     * Adds the specified child in the specified screen. The position and dimension of
499     * the child are defined by x, y, spanX and spanY.
500     *
501     * @param child The child to add in one of the workspace's screens.
502     * @param screen The screen in which to add the child.
503     * @param x The X position of the child in the screen's grid.
504     * @param y The Y position of the child in the screen's grid.
505     * @param spanX The number of cells spanned horizontally by the child.
506     * @param spanY The number of cells spanned vertically by the child.
507     * @param insert When true, the child is inserted at the beginning of the children list.
508     */
509    void addInScreen(View child, long container, int screen, int x, int y, int spanX, int spanY,
510            boolean insert) {
511        if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
512            if (screen < 0 || screen >= getChildCount()) {
513                Log.e(TAG, "The screen must be >= 0 and < " + getChildCount()
514                    + " (was " + screen + "); skipping child");
515                return;
516            }
517        }
518
519        final CellLayout layout;
520        if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
521            layout = mLauncher.getHotseat().getLayout();
522            child.setOnKeyListener(null);
523
524            // Hide folder title in the hotseat
525            if (child instanceof FolderIcon) {
526                ((FolderIcon) child).setTextVisible(false);
527            }
528
529            if (screen < 0) {
530                screen = mLauncher.getHotseat().getOrderInHotseat(x, y);
531            } else {
532                // Note: We do this to ensure that the hotseat is always laid out in the orientation
533                // of the hotseat in order regardless of which orientation they were added
534                x = mLauncher.getHotseat().getCellXFromOrder(screen);
535                y = mLauncher.getHotseat().getCellYFromOrder(screen);
536            }
537        } else {
538            // Show folder title if not in the hotseat
539            if (child instanceof FolderIcon) {
540                ((FolderIcon) child).setTextVisible(true);
541            }
542
543            layout = (CellLayout) getChildAt(screen);
544            child.setOnKeyListener(new IconKeyEventListener());
545        }
546
547        LayoutParams genericLp = child.getLayoutParams();
548        CellLayout.LayoutParams lp;
549        if (genericLp == null || !(genericLp instanceof CellLayout.LayoutParams)) {
550            lp = new CellLayout.LayoutParams(x, y, spanX, spanY);
551        } else {
552            lp = (CellLayout.LayoutParams) genericLp;
553            lp.cellX = x;
554            lp.cellY = y;
555            lp.cellHSpan = spanX;
556            lp.cellVSpan = spanY;
557        }
558
559        if (spanX < 0 && spanY < 0) {
560            lp.isLockedToGrid = false;
561        }
562
563        // Get the canonical child id to uniquely represent this view in this screen
564        int childId = LauncherModel.getCellLayoutChildId(container, screen, x, y, spanX, spanY);
565        boolean markCellsAsOccupied = !(child instanceof Folder);
566        if (!layout.addViewToCellLayout(child, insert ? 0 : -1, childId, lp, markCellsAsOccupied)) {
567            // TODO: This branch occurs when the workspace is adding views
568            // outside of the defined grid
569            // maybe we should be deleting these items from the LauncherModel?
570            Log.w(TAG, "Failed to add to item at (" + lp.cellX + "," + lp.cellY + ") to CellLayout");
571        }
572
573        if (!(child instanceof Folder)) {
574            child.setHapticFeedbackEnabled(false);
575            child.setOnLongClickListener(mLongClickListener);
576        }
577        if (child instanceof DropTarget) {
578            mDragController.addDropTarget((DropTarget) child);
579        }
580    }
581
582    /**
583     * Check if the point (x, y) hits a given page.
584     */
585    private boolean hitsPage(int index, float x, float y) {
586        final View page = getChildAt(index);
587        if (page != null) {
588            float[] localXY = { x, y };
589            mapPointFromSelfToChild(page, localXY);
590            return (localXY[0] >= 0 && localXY[0] < page.getWidth()
591                    && localXY[1] >= 0 && localXY[1] < page.getHeight());
592        }
593        return false;
594    }
595
596    @Override
597    protected boolean hitsPreviousPage(float x, float y) {
598        // mNextPage is set to INVALID_PAGE whenever we are stationary.
599        // Calculating "next page" this way ensures that you scroll to whatever page you tap on
600        final int current = (mNextPage == INVALID_PAGE) ? mCurrentPage : mNextPage;
601
602        // Only allow tap to next page on large devices, where there's significant margin outside
603        // the active workspace
604        return LauncherApplication.isScreenLarge() && hitsPage(current - 1, x, y);
605    }
606
607    @Override
608    protected boolean hitsNextPage(float x, float y) {
609        // mNextPage is set to INVALID_PAGE whenever we are stationary.
610        // Calculating "next page" this way ensures that you scroll to whatever page you tap on
611        final int current = (mNextPage == INVALID_PAGE) ? mCurrentPage : mNextPage;
612
613        // Only allow tap to next page on large devices, where there's significant margin outside
614        // the active workspace
615        return LauncherApplication.isScreenLarge() && hitsPage(current + 1, x, y);
616    }
617
618    /**
619     * Called directly from a CellLayout (not by the framework), after we've been added as a
620     * listener via setOnInterceptTouchEventListener(). This allows us to tell the CellLayout
621     * that it should intercept touch events, which is not something that is normally supported.
622     */
623    @Override
624    public boolean onTouch(View v, MotionEvent event) {
625        return (isSmall() || !isFinishedSwitchingState());
626    }
627
628    public boolean isSwitchingState() {
629        return mIsSwitchingState;
630    }
631
632    /** This differs from isSwitchingState in that we take into account how far the transition
633     *  has completed. */
634    public boolean isFinishedSwitchingState() {
635        return !mIsSwitchingState || (mTransitionProgress > 0.5f);
636    }
637
638    protected void onWindowVisibilityChanged (int visibility) {
639        mLauncher.onWindowVisibilityChanged(visibility);
640    }
641
642    @Override
643    public boolean dispatchUnhandledMove(View focused, int direction) {
644        if (isSmall() || !isFinishedSwitchingState()) {
645            // when the home screens are shrunken, shouldn't allow side-scrolling
646            return false;
647        }
648        return super.dispatchUnhandledMove(focused, direction);
649    }
650
651    @Override
652    public boolean onInterceptTouchEvent(MotionEvent ev) {
653        switch (ev.getAction() & MotionEvent.ACTION_MASK) {
654        case MotionEvent.ACTION_DOWN:
655            mXDown = ev.getX();
656            mYDown = ev.getY();
657            break;
658        case MotionEvent.ACTION_POINTER_UP:
659        case MotionEvent.ACTION_UP:
660            if (mTouchState == TOUCH_STATE_REST) {
661                final CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage);
662                if (!currentPage.lastDownOnOccupiedCell()) {
663                    onWallpaperTap(ev);
664                }
665            }
666        }
667        return super.onInterceptTouchEvent(ev);
668    }
669
670    protected void reinflateWidgetsIfNecessary() {
671        final int clCount = getChildCount();
672        for (int i = 0; i < clCount; i++) {
673            CellLayout cl = (CellLayout) getChildAt(i);
674            ShortcutAndWidgetContainer swc = cl.getShortcutsAndWidgets();
675            final int itemCount = swc.getChildCount();
676            for (int j = 0; j < itemCount; j++) {
677                View v = swc.getChildAt(j);
678
679                if (v.getTag() instanceof LauncherAppWidgetInfo) {
680                    LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) v.getTag();
681                    LauncherAppWidgetHostView lahv = (LauncherAppWidgetHostView) info.hostView;
682                    if (lahv != null && lahv.orientationChangedSincedInflation()) {
683                        mLauncher.removeAppWidget(info);
684                        // Remove the current widget which is inflated with the wrong orientation
685                        cl.removeView(lahv);
686                        mLauncher.bindAppWidget(info);
687                    }
688                }
689            }
690        }
691    }
692
693    @Override
694    protected void determineScrollingStart(MotionEvent ev) {
695        if (isSmall()) return;
696        if (!isFinishedSwitchingState()) return;
697
698        float deltaX = Math.abs(ev.getX() - mXDown);
699        float deltaY = Math.abs(ev.getY() - mYDown);
700
701        if (Float.compare(deltaX, 0f) == 0) return;
702
703        float slope = deltaY / deltaX;
704        float theta = (float) Math.atan(slope);
705
706        if (deltaX > mTouchSlop || deltaY > mTouchSlop) {
707            cancelCurrentPageLongPress();
708        }
709
710        if (theta > MAX_SWIPE_ANGLE) {
711            // Above MAX_SWIPE_ANGLE, we don't want to ever start scrolling the workspace
712            return;
713        } else if (theta > START_DAMPING_TOUCH_SLOP_ANGLE) {
714            // Above START_DAMPING_TOUCH_SLOP_ANGLE and below MAX_SWIPE_ANGLE, we want to
715            // increase the touch slop to make it harder to begin scrolling the workspace. This
716            // results in vertically scrolling widgets to more easily. The higher the angle, the
717            // more we increase touch slop.
718            theta -= START_DAMPING_TOUCH_SLOP_ANGLE;
719            float extraRatio = (float)
720                    Math.sqrt((theta / (MAX_SWIPE_ANGLE - START_DAMPING_TOUCH_SLOP_ANGLE)));
721            super.determineScrollingStart(ev, 1 + TOUCH_SLOP_DAMPING_FACTOR * extraRatio);
722        } else {
723            // Below START_DAMPING_TOUCH_SLOP_ANGLE, we don't do anything special
724            super.determineScrollingStart(ev);
725        }
726    }
727
728    protected void onPageBeginMoving() {
729        super.onPageBeginMoving();
730
731        if (isHardwareAccelerated()) {
732            updateChildrenLayersEnabled(false);
733        } else {
734            if (mNextPage != INVALID_PAGE) {
735                // we're snapping to a particular screen
736                enableChildrenCache(mCurrentPage, mNextPage);
737            } else {
738                // this is when user is actively dragging a particular screen, they might
739                // swipe it either left or right (but we won't advance by more than one screen)
740                enableChildrenCache(mCurrentPage - 1, mCurrentPage + 1);
741            }
742        }
743
744        // Only show page outlines as we pan if we are on large screen
745        if (LauncherApplication.isScreenLarge()) {
746            showOutlines();
747            mIsStaticWallpaper = mWallpaperManager.getWallpaperInfo() == null;
748        }
749
750        // If we are not fading in adjacent screens, we still need to restore the alpha in case the
751        // user scrolls while we are transitioning (should not affect dispatchDraw optimizations)
752        if (!mWorkspaceFadeInAdjacentScreens) {
753            for (int i = 0; i < getChildCount(); ++i) {
754                ((CellLayout) getPageAt(i)).setShortcutAndWidgetAlpha(1f);
755            }
756        }
757
758        // Show the scroll indicator as you pan the page
759        showScrollingIndicator(false);
760    }
761
762    protected void onPageEndMoving() {
763        super.onPageEndMoving();
764
765        if (isHardwareAccelerated()) {
766            updateChildrenLayersEnabled(false);
767        } else {
768            clearChildrenCache();
769        }
770
771
772        if (mDragController.isDragging()) {
773            if (isSmall()) {
774                // If we are in springloaded mode, then force an event to check if the current touch
775                // is under a new page (to scroll to)
776                mDragController.forceMoveEvent();
777            }
778        } else {
779            // If we are not mid-dragging, hide the page outlines if we are on a large screen
780            if (LauncherApplication.isScreenLarge()) {
781                hideOutlines();
782            }
783
784            // Hide the scroll indicator as you pan the page
785            if (!mDragController.isDragging()) {
786                hideScrollingIndicator(false);
787            }
788        }
789        mOverScrollMaxBackgroundAlpha = 0.0f;
790
791        if (mDelayedResizeRunnable != null) {
792            mDelayedResizeRunnable.run();
793            mDelayedResizeRunnable = null;
794        }
795
796        if (mDelayedSnapToPageRunnable != null) {
797            mDelayedSnapToPageRunnable.run();
798            mDelayedSnapToPageRunnable = null;
799        }
800    }
801
802    @Override
803    protected void notifyPageSwitchListener() {
804        super.notifyPageSwitchListener();
805        Launcher.setScreen(mCurrentPage);
806    };
807
808    // As a ratio of screen height, the total distance we want the parallax effect to span
809    // horizontally
810    private float wallpaperTravelToScreenWidthRatio(int width, int height) {
811        float aspectRatio = width / (float) height;
812
813        // At an aspect ratio of 16/10, the wallpaper parallax effect should span 1.5 * screen width
814        // At an aspect ratio of 10/16, the wallpaper parallax effect should span 1.2 * screen width
815        // We will use these two data points to extrapolate how much the wallpaper parallax effect
816        // to span (ie travel) at any aspect ratio:
817
818        final float ASPECT_RATIO_LANDSCAPE = 16/10f;
819        final float ASPECT_RATIO_PORTRAIT = 10/16f;
820        final float WALLPAPER_WIDTH_TO_SCREEN_RATIO_LANDSCAPE = 1.5f;
821        final float WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT = 1.2f;
822
823        // To find out the desired width at different aspect ratios, we use the following two
824        // formulas, where the coefficient on x is the aspect ratio (width/height):
825        //   (16/10)x + y = 1.5
826        //   (10/16)x + y = 1.2
827        // We solve for x and y and end up with a final formula:
828        final float x =
829            (WALLPAPER_WIDTH_TO_SCREEN_RATIO_LANDSCAPE - WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT) /
830            (ASPECT_RATIO_LANDSCAPE - ASPECT_RATIO_PORTRAIT);
831        final float y = WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT - x * ASPECT_RATIO_PORTRAIT;
832        return x * aspectRatio + y;
833    }
834
835    // The range of scroll values for Workspace
836    private int getScrollRange() {
837        return getChildOffset(getChildCount() - 1) - getChildOffset(0);
838    }
839
840    protected void setWallpaperDimension() {
841        Point minDims = new Point();
842        Point maxDims = new Point();
843        mLauncher.getWindowManager().getDefaultDisplay().getCurrentSizeRange(minDims, maxDims);
844
845        final int maxDim = Math.max(maxDims.x, maxDims.y);
846        final int minDim = Math.min(minDims.x, minDims.y);
847
848        // We need to ensure that there is enough extra space in the wallpaper for the intended
849        // parallax effects
850        if (LauncherApplication.isScreenLarge()) {
851            mWallpaperWidth = (int) (maxDim * wallpaperTravelToScreenWidthRatio(maxDim, minDim));
852            mWallpaperHeight = maxDim;
853        } else {
854            mWallpaperWidth = Math.max((int) (minDim * WALLPAPER_SCREENS_SPAN), maxDim);
855            mWallpaperHeight = maxDim;
856        }
857        new Thread("setWallpaperDimension") {
858            public void run() {
859                mWallpaperManager.suggestDesiredDimensions(mWallpaperWidth, mWallpaperHeight);
860            }
861        }.start();
862    }
863
864    private float wallpaperOffsetForCurrentScroll() {
865        // Set wallpaper offset steps (1 / (number of screens - 1))
866        mWallpaperManager.setWallpaperOffsetSteps(1.0f / (getChildCount() - 1), 1.0f);
867
868        // For the purposes of computing the scrollRange and overScrollOffset, we assume
869        // that mLayoutScale is 1. This means that when we're in spring-loaded mode,
870        // there's no discrepancy between the wallpaper offset for a given page.
871        float layoutScale = mLayoutScale;
872        mLayoutScale = 1f;
873        int scrollRange = getScrollRange();
874
875        // Again, we adjust the wallpaper offset to be consistent between values of mLayoutScale
876        float adjustedScrollX = Math.max(0, Math.min(getScrollX(), mMaxScrollX));
877        adjustedScrollX *= mWallpaperScrollRatio;
878        mLayoutScale = layoutScale;
879
880        float scrollProgress =
881            adjustedScrollX / (float) scrollRange;
882
883        if (LauncherApplication.isScreenLarge() && mIsStaticWallpaper) {
884            // The wallpaper travel width is how far, from left to right, the wallpaper will move
885            // at this orientation. On tablets in portrait mode we don't move all the way to the
886            // edges of the wallpaper, or otherwise the parallax effect would be too strong.
887            int wallpaperTravelWidth = Math.min(mWallpaperTravelWidth, mWallpaperWidth);
888
889            float offsetInDips = wallpaperTravelWidth * scrollProgress +
890                (mWallpaperWidth - wallpaperTravelWidth) / 2; // center it
891            float offset = offsetInDips / (float) mWallpaperWidth;
892            return offset;
893        } else {
894            return scrollProgress;
895        }
896    }
897
898    private void syncWallpaperOffsetWithScroll() {
899        final boolean enableWallpaperEffects = isHardwareAccelerated();
900        if (enableWallpaperEffects) {
901            mWallpaperOffset.setFinalX(wallpaperOffsetForCurrentScroll());
902        }
903    }
904
905    public void updateWallpaperOffsetImmediately() {
906        mUpdateWallpaperOffsetImmediately = true;
907    }
908
909    private void updateWallpaperOffsets() {
910        boolean updateNow = false;
911        boolean keepUpdating = true;
912        if (mUpdateWallpaperOffsetImmediately) {
913            updateNow = true;
914            keepUpdating = false;
915            mWallpaperOffset.jumpToFinal();
916            mUpdateWallpaperOffsetImmediately = false;
917        } else {
918            updateNow = keepUpdating = mWallpaperOffset.computeScrollOffset();
919        }
920        if (updateNow) {
921            if (mWindowToken != null) {
922                mWallpaperManager.setWallpaperOffsets(mWindowToken,
923                        mWallpaperOffset.getCurrX(), mWallpaperOffset.getCurrY());
924            }
925        }
926        if (keepUpdating) {
927            invalidate();
928        }
929    }
930
931    @Override
932    protected void updateCurrentPageScroll() {
933        super.updateCurrentPageScroll();
934        computeWallpaperScrollRatio(mCurrentPage);
935    }
936
937    @Override
938    protected void snapToPage(int whichPage) {
939        super.snapToPage(whichPage);
940        computeWallpaperScrollRatio(whichPage);
941    }
942
943    @Override
944    protected void snapToPage(int whichPage, int duration) {
945        super.snapToPage(whichPage, duration);
946        computeWallpaperScrollRatio(whichPage);
947    }
948
949    protected void snapToPage(int whichPage, Runnable r) {
950        if (mDelayedSnapToPageRunnable != null) {
951            mDelayedSnapToPageRunnable.run();
952        }
953        mDelayedSnapToPageRunnable = r;
954        snapToPage(whichPage, SLOW_PAGE_SNAP_ANIMATION_DURATION);
955    }
956
957    private void computeWallpaperScrollRatio(int page) {
958        // Here, we determine what the desired scroll would be with and without a layout scale,
959        // and compute a ratio between the two. This allows us to adjust the wallpaper offset
960        // as though there is no layout scale.
961        float layoutScale = mLayoutScale;
962        int scaled = getChildOffset(page) - getRelativeChildOffset(page);
963        mLayoutScale = 1.0f;
964        float unscaled = getChildOffset(page) - getRelativeChildOffset(page);
965        mLayoutScale = layoutScale;
966        if (scaled > 0) {
967            mWallpaperScrollRatio = (1.0f * unscaled) / scaled;
968        } else {
969            mWallpaperScrollRatio = 1f;
970        }
971    }
972
973    class WallpaperOffsetInterpolator {
974        float mFinalHorizontalWallpaperOffset = 0.0f;
975        float mFinalVerticalWallpaperOffset = 0.5f;
976        float mHorizontalWallpaperOffset = 0.0f;
977        float mVerticalWallpaperOffset = 0.5f;
978        long mLastWallpaperOffsetUpdateTime;
979        boolean mIsMovingFast;
980        boolean mOverrideHorizontalCatchupConstant;
981        float mHorizontalCatchupConstant = 0.35f;
982        float mVerticalCatchupConstant = 0.35f;
983
984        public WallpaperOffsetInterpolator() {
985        }
986
987        public void setOverrideHorizontalCatchupConstant(boolean override) {
988            mOverrideHorizontalCatchupConstant = override;
989        }
990
991        public void setHorizontalCatchupConstant(float f) {
992            mHorizontalCatchupConstant = f;
993        }
994
995        public void setVerticalCatchupConstant(float f) {
996            mVerticalCatchupConstant = f;
997        }
998
999        public boolean computeScrollOffset() {
1000            if (Float.compare(mHorizontalWallpaperOffset, mFinalHorizontalWallpaperOffset) == 0 &&
1001                    Float.compare(mVerticalWallpaperOffset, mFinalVerticalWallpaperOffset) == 0) {
1002                mIsMovingFast = false;
1003                return false;
1004            }
1005            boolean isLandscape = mDisplaySize.x > mDisplaySize.y;
1006
1007            long currentTime = System.currentTimeMillis();
1008            long timeSinceLastUpdate = currentTime - mLastWallpaperOffsetUpdateTime;
1009            timeSinceLastUpdate = Math.min((long) (1000/30f), timeSinceLastUpdate);
1010            timeSinceLastUpdate = Math.max(1L, timeSinceLastUpdate);
1011
1012            float xdiff = Math.abs(mFinalHorizontalWallpaperOffset - mHorizontalWallpaperOffset);
1013            if (!mIsMovingFast && xdiff > 0.07) {
1014                mIsMovingFast = true;
1015            }
1016
1017            float fractionToCatchUpIn1MsHorizontal;
1018            if (mOverrideHorizontalCatchupConstant) {
1019                fractionToCatchUpIn1MsHorizontal = mHorizontalCatchupConstant;
1020            } else if (mIsMovingFast) {
1021                fractionToCatchUpIn1MsHorizontal = isLandscape ? 0.5f : 0.75f;
1022            } else {
1023                // slow
1024                fractionToCatchUpIn1MsHorizontal = isLandscape ? 0.27f : 0.5f;
1025            }
1026            float fractionToCatchUpIn1MsVertical = mVerticalCatchupConstant;
1027
1028            fractionToCatchUpIn1MsHorizontal /= 33f;
1029            fractionToCatchUpIn1MsVertical /= 33f;
1030
1031            final float UPDATE_THRESHOLD = 0.00001f;
1032            float hOffsetDelta = mFinalHorizontalWallpaperOffset - mHorizontalWallpaperOffset;
1033            float vOffsetDelta = mFinalVerticalWallpaperOffset - mVerticalWallpaperOffset;
1034            boolean jumpToFinalValue = Math.abs(hOffsetDelta) < UPDATE_THRESHOLD &&
1035                Math.abs(vOffsetDelta) < UPDATE_THRESHOLD;
1036
1037            // Don't have any lag between workspace and wallpaper on non-large devices
1038            if (!LauncherApplication.isScreenLarge() || jumpToFinalValue) {
1039                mHorizontalWallpaperOffset = mFinalHorizontalWallpaperOffset;
1040                mVerticalWallpaperOffset = mFinalVerticalWallpaperOffset;
1041            } else {
1042                float percentToCatchUpVertical =
1043                    Math.min(1.0f, timeSinceLastUpdate * fractionToCatchUpIn1MsVertical);
1044                float percentToCatchUpHorizontal =
1045                    Math.min(1.0f, timeSinceLastUpdate * fractionToCatchUpIn1MsHorizontal);
1046                mHorizontalWallpaperOffset += percentToCatchUpHorizontal * hOffsetDelta;
1047                mVerticalWallpaperOffset += percentToCatchUpVertical * vOffsetDelta;
1048            }
1049
1050            mLastWallpaperOffsetUpdateTime = System.currentTimeMillis();
1051            return true;
1052        }
1053
1054        public float getCurrX() {
1055            return mHorizontalWallpaperOffset;
1056        }
1057
1058        public float getFinalX() {
1059            return mFinalHorizontalWallpaperOffset;
1060        }
1061
1062        public float getCurrY() {
1063            return mVerticalWallpaperOffset;
1064        }
1065
1066        public float getFinalY() {
1067            return mFinalVerticalWallpaperOffset;
1068        }
1069
1070        public void setFinalX(float x) {
1071            mFinalHorizontalWallpaperOffset = Math.max(0f, Math.min(x, 1.0f));
1072        }
1073
1074        public void setFinalY(float y) {
1075            mFinalVerticalWallpaperOffset = Math.max(0f, Math.min(y, 1.0f));
1076        }
1077
1078        public void jumpToFinal() {
1079            mHorizontalWallpaperOffset = mFinalHorizontalWallpaperOffset;
1080            mVerticalWallpaperOffset = mFinalVerticalWallpaperOffset;
1081        }
1082    }
1083
1084    @Override
1085    public void computeScroll() {
1086        super.computeScroll();
1087        syncWallpaperOffsetWithScroll();
1088    }
1089
1090    void showOutlines() {
1091        if (!isSmall() && !mIsSwitchingState) {
1092            if (mChildrenOutlineFadeOutAnimation != null) mChildrenOutlineFadeOutAnimation.cancel();
1093            if (mChildrenOutlineFadeInAnimation != null) mChildrenOutlineFadeInAnimation.cancel();
1094            mChildrenOutlineFadeInAnimation = LauncherAnimUtils.ofFloat(this, "childrenOutlineAlpha", 1.0f);
1095            mChildrenOutlineFadeInAnimation.setDuration(CHILDREN_OUTLINE_FADE_IN_DURATION);
1096            mChildrenOutlineFadeInAnimation.start();
1097        }
1098    }
1099
1100    void hideOutlines() {
1101        if (!isSmall() && !mIsSwitchingState) {
1102            if (mChildrenOutlineFadeInAnimation != null) mChildrenOutlineFadeInAnimation.cancel();
1103            if (mChildrenOutlineFadeOutAnimation != null) mChildrenOutlineFadeOutAnimation.cancel();
1104            mChildrenOutlineFadeOutAnimation = LauncherAnimUtils.ofFloat(this, "childrenOutlineAlpha", 0.0f);
1105            mChildrenOutlineFadeOutAnimation.setDuration(CHILDREN_OUTLINE_FADE_OUT_DURATION);
1106            mChildrenOutlineFadeOutAnimation.setStartDelay(CHILDREN_OUTLINE_FADE_OUT_DELAY);
1107            mChildrenOutlineFadeOutAnimation.start();
1108        }
1109    }
1110
1111    public void showOutlinesTemporarily() {
1112        if (!mIsPageMoving && !isTouchActive()) {
1113            snapToPage(mCurrentPage);
1114        }
1115    }
1116
1117    public void setChildrenOutlineAlpha(float alpha) {
1118        mChildrenOutlineAlpha = alpha;
1119        for (int i = 0; i < getChildCount(); i++) {
1120            CellLayout cl = (CellLayout) getChildAt(i);
1121            cl.setBackgroundAlpha(alpha);
1122        }
1123    }
1124
1125    public float getChildrenOutlineAlpha() {
1126        return mChildrenOutlineAlpha;
1127    }
1128
1129    void disableBackground() {
1130        mDrawBackground = false;
1131    }
1132    void enableBackground() {
1133        mDrawBackground = true;
1134    }
1135
1136    private void animateBackgroundGradient(float finalAlpha, boolean animated) {
1137        if (mBackground == null) return;
1138        if (mBackgroundFadeInAnimation != null) {
1139            mBackgroundFadeInAnimation.cancel();
1140            mBackgroundFadeInAnimation = null;
1141        }
1142        if (mBackgroundFadeOutAnimation != null) {
1143            mBackgroundFadeOutAnimation.cancel();
1144            mBackgroundFadeOutAnimation = null;
1145        }
1146        float startAlpha = getBackgroundAlpha();
1147        if (finalAlpha != startAlpha) {
1148            if (animated) {
1149                mBackgroundFadeOutAnimation = LauncherAnimUtils.ofFloat(startAlpha, finalAlpha);
1150                mBackgroundFadeOutAnimation.addUpdateListener(new AnimatorUpdateListener() {
1151                    public void onAnimationUpdate(ValueAnimator animation) {
1152                        setBackgroundAlpha(((Float) animation.getAnimatedValue()).floatValue());
1153                    }
1154                });
1155                mBackgroundFadeOutAnimation.setInterpolator(new DecelerateInterpolator(1.5f));
1156                mBackgroundFadeOutAnimation.setDuration(BACKGROUND_FADE_OUT_DURATION);
1157                mBackgroundFadeOutAnimation.start();
1158            } else {
1159                setBackgroundAlpha(finalAlpha);
1160            }
1161        }
1162    }
1163
1164    public void setBackgroundAlpha(float alpha) {
1165        if (alpha != mBackgroundAlpha) {
1166            mBackgroundAlpha = alpha;
1167            invalidate();
1168        }
1169    }
1170
1171    public float getBackgroundAlpha() {
1172        return mBackgroundAlpha;
1173    }
1174
1175    float backgroundAlphaInterpolator(float r) {
1176        float pivotA = 0.1f;
1177        float pivotB = 0.4f;
1178        if (r < pivotA) {
1179            return 0;
1180        } else if (r > pivotB) {
1181            return 1.0f;
1182        } else {
1183            return (r - pivotA)/(pivotB - pivotA);
1184        }
1185    }
1186
1187    private void updatePageAlphaValues(int screenCenter) {
1188        boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
1189        if (mWorkspaceFadeInAdjacentScreens &&
1190                mState == State.NORMAL &&
1191                !mIsSwitchingState &&
1192                !isInOverscroll) {
1193            for (int i = 0; i < getChildCount(); i++) {
1194                CellLayout child = (CellLayout) getChildAt(i);
1195                if (child != null) {
1196                    float scrollProgress = getScrollProgress(screenCenter, child, i);
1197                    float alpha = 1 - Math.abs(scrollProgress);
1198                    child.getShortcutsAndWidgets().setAlpha(alpha);
1199                    if (!mIsDragOccuring) {
1200                        child.setBackgroundAlphaMultiplier(
1201                                backgroundAlphaInterpolator(Math.abs(scrollProgress)));
1202                    } else {
1203                        child.setBackgroundAlphaMultiplier(1f);
1204                    }
1205                }
1206            }
1207        }
1208    }
1209
1210    private void setChildrenBackgroundAlphaMultipliers(float a) {
1211        for (int i = 0; i < getChildCount(); i++) {
1212            CellLayout child = (CellLayout) getChildAt(i);
1213            child.setBackgroundAlphaMultiplier(a);
1214        }
1215    }
1216
1217    @Override
1218    protected void screenScrolled(int screenCenter) {
1219        final boolean isRtl = isLayoutRtl();
1220        super.screenScrolled(screenCenter);
1221
1222        updatePageAlphaValues(screenCenter);
1223        enableHwLayersOnVisiblePages();
1224
1225        if (mOverScrollX < 0 || mOverScrollX > mMaxScrollX) {
1226            int index = 0;
1227            float pivotX = 0f;
1228            final float leftBiasedPivot = 0.25f;
1229            final float rightBiasedPivot = 0.75f;
1230            final int lowerIndex = 0;
1231            final int upperIndex = getChildCount() - 1;
1232            if (isRtl) {
1233                index = mOverScrollX < 0 ? upperIndex : lowerIndex;
1234                pivotX = (index == 0 ? leftBiasedPivot : rightBiasedPivot);
1235            } else {
1236                index = mOverScrollX < 0 ? lowerIndex : upperIndex;
1237                pivotX = (index == 0 ? rightBiasedPivot : leftBiasedPivot);
1238            }
1239
1240            CellLayout cl = (CellLayout) getChildAt(index);
1241            float scrollProgress = getScrollProgress(screenCenter, cl, index);
1242            final boolean isLeftPage = (isRtl ? index > 0 : index == 0);
1243            cl.setOverScrollAmount(Math.abs(scrollProgress), isLeftPage);
1244            float rotation = -WORKSPACE_OVERSCROLL_ROTATION * scrollProgress;
1245            cl.setRotationY(rotation);
1246            setFadeForOverScroll(Math.abs(scrollProgress));
1247            if (!mOverscrollTransformsSet) {
1248                mOverscrollTransformsSet = true;
1249                cl.setCameraDistance(mDensity * mCameraDistance);
1250                cl.setPivotX(cl.getMeasuredWidth() * pivotX);
1251                cl.setPivotY(cl.getMeasuredHeight() * 0.5f);
1252                cl.setOverscrollTransformsDirty(true);
1253            }
1254        } else {
1255            if (mOverscrollFade != 0) {
1256                setFadeForOverScroll(0);
1257            }
1258            if (mOverscrollTransformsSet) {
1259                mOverscrollTransformsSet = false;
1260                ((CellLayout) getChildAt(0)).resetOverscrollTransforms();
1261                ((CellLayout) getChildAt(getChildCount() - 1)).resetOverscrollTransforms();
1262            }
1263        }
1264    }
1265
1266    @Override
1267    protected void overScroll(float amount) {
1268        acceleratedOverScroll(amount);
1269    }
1270
1271    protected void onAttachedToWindow() {
1272        super.onAttachedToWindow();
1273        mWindowToken = getWindowToken();
1274        computeScroll();
1275        mDragController.setWindowToken(mWindowToken);
1276    }
1277
1278    protected void onDetachedFromWindow() {
1279        mWindowToken = null;
1280    }
1281
1282    @Override
1283    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
1284        if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
1285            mUpdateWallpaperOffsetImmediately = true;
1286        }
1287        super.onLayout(changed, left, top, right, bottom);
1288    }
1289
1290    @Override
1291    protected void onDraw(Canvas canvas) {
1292        updateWallpaperOffsets();
1293
1294        // Draw the background gradient if necessary
1295        if (mBackground != null && mBackgroundAlpha > 0.0f && mDrawBackground) {
1296            int alpha = (int) (mBackgroundAlpha * 255);
1297            mBackground.setAlpha(alpha);
1298            mBackground.setBounds(getScrollX(), 0, getScrollX() + getMeasuredWidth(),
1299                    getMeasuredHeight());
1300            mBackground.draw(canvas);
1301        }
1302
1303        super.onDraw(canvas);
1304
1305        // Call back to LauncherModel to finish binding after the first draw
1306        post(mBindPages);
1307    }
1308
1309    boolean isDrawingBackgroundGradient() {
1310        return (mBackground != null && mBackgroundAlpha > 0.0f && mDrawBackground);
1311    }
1312
1313    @Override
1314    protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
1315        if (!mLauncher.isAllAppsVisible()) {
1316            final Folder openFolder = getOpenFolder();
1317            if (openFolder != null) {
1318                return openFolder.requestFocus(direction, previouslyFocusedRect);
1319            } else {
1320                return super.onRequestFocusInDescendants(direction, previouslyFocusedRect);
1321            }
1322        }
1323        return false;
1324    }
1325
1326    @Override
1327    public int getDescendantFocusability() {
1328        if (isSmall()) {
1329            return ViewGroup.FOCUS_BLOCK_DESCENDANTS;
1330        }
1331        return super.getDescendantFocusability();
1332    }
1333
1334    @Override
1335    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
1336        if (!mLauncher.isAllAppsVisible()) {
1337            final Folder openFolder = getOpenFolder();
1338            if (openFolder != null) {
1339                openFolder.addFocusables(views, direction);
1340            } else {
1341                super.addFocusables(views, direction, focusableMode);
1342            }
1343        }
1344    }
1345
1346    public boolean isSmall() {
1347        return mState == State.SMALL || mState == State.SPRING_LOADED;
1348    }
1349
1350    void enableChildrenCache(int fromPage, int toPage) {
1351        if (fromPage > toPage) {
1352            final int temp = fromPage;
1353            fromPage = toPage;
1354            toPage = temp;
1355        }
1356
1357        final int screenCount = getChildCount();
1358
1359        fromPage = Math.max(fromPage, 0);
1360        toPage = Math.min(toPage, screenCount - 1);
1361
1362        for (int i = fromPage; i <= toPage; i++) {
1363            final CellLayout layout = (CellLayout) getChildAt(i);
1364            layout.setChildrenDrawnWithCacheEnabled(true);
1365            layout.setChildrenDrawingCacheEnabled(true);
1366        }
1367    }
1368
1369    void clearChildrenCache() {
1370        final int screenCount = getChildCount();
1371        for (int i = 0; i < screenCount; i++) {
1372            final CellLayout layout = (CellLayout) getChildAt(i);
1373            layout.setChildrenDrawnWithCacheEnabled(false);
1374            // In software mode, we don't want the items to continue to be drawn into bitmaps
1375            if (!isHardwareAccelerated()) {
1376                layout.setChildrenDrawingCacheEnabled(false);
1377            }
1378        }
1379    }
1380
1381
1382    private void updateChildrenLayersEnabled(boolean force) {
1383        boolean small = mState == State.SMALL || mIsSwitchingState;
1384        boolean enableChildrenLayers = force || small || mAnimatingViewIntoPlace || isPageMoving();
1385
1386        if (enableChildrenLayers != mChildrenLayersEnabled) {
1387            mChildrenLayersEnabled = enableChildrenLayers;
1388            if (mChildrenLayersEnabled) {
1389                enableHwLayersOnVisiblePages();
1390            } else {
1391                for (int i = 0; i < getPageCount(); i++) {
1392                    final CellLayout cl = (CellLayout) getChildAt(i);
1393                    cl.disableHardwareLayers();
1394                }
1395            }
1396        }
1397    }
1398
1399    private void enableHwLayersOnVisiblePages() {
1400        if (mChildrenLayersEnabled) {
1401            final int screenCount = getChildCount();
1402            getVisiblePages(mTempVisiblePagesRange);
1403            int leftScreen = mTempVisiblePagesRange[0];
1404            int rightScreen = mTempVisiblePagesRange[1];
1405            if (leftScreen == rightScreen) {
1406                // make sure we're caching at least two pages always
1407                if (rightScreen < screenCount - 1) {
1408                    rightScreen++;
1409                } else if (leftScreen > 0) {
1410                    leftScreen--;
1411                }
1412            }
1413            for (int i = 0; i < screenCount; i++) {
1414                final CellLayout layout = (CellLayout) getPageAt(i);
1415                if (!(leftScreen <= i && i <= rightScreen && shouldDrawChild(layout))) {
1416                    layout.disableHardwareLayers();
1417                }
1418            }
1419            for (int i = 0; i < screenCount; i++) {
1420                final CellLayout layout = (CellLayout) getPageAt(i);
1421                if (leftScreen <= i && i <= rightScreen && shouldDrawChild(layout)) {
1422                    layout.enableHardwareLayers();
1423                }
1424            }
1425        }
1426    }
1427
1428    public void buildPageHardwareLayers() {
1429        // force layers to be enabled just for the call to buildLayer
1430        updateChildrenLayersEnabled(true);
1431        if (getWindowToken() != null) {
1432            final int childCount = getChildCount();
1433            for (int i = 0; i < childCount; i++) {
1434                CellLayout cl = (CellLayout) getChildAt(i);
1435                cl.buildHardwareLayer();
1436            }
1437        }
1438        updateChildrenLayersEnabled(false);
1439    }
1440
1441    protected void onWallpaperTap(MotionEvent ev) {
1442        final int[] position = mTempCell;
1443        getLocationOnScreen(position);
1444
1445        int pointerIndex = ev.getActionIndex();
1446        position[0] += (int) ev.getX(pointerIndex);
1447        position[1] += (int) ev.getY(pointerIndex);
1448
1449        mWallpaperManager.sendWallpaperCommand(getWindowToken(),
1450                ev.getAction() == MotionEvent.ACTION_UP
1451                        ? WallpaperManager.COMMAND_TAP : WallpaperManager.COMMAND_SECONDARY_TAP,
1452                position[0], position[1], 0, null);
1453    }
1454
1455    /*
1456     * This interpolator emulates the rate at which the perceived scale of an object changes
1457     * as its distance from a camera increases. When this interpolator is applied to a scale
1458     * animation on a view, it evokes the sense that the object is shrinking due to moving away
1459     * from the camera.
1460     */
1461    static class ZInterpolator implements TimeInterpolator {
1462        private float focalLength;
1463
1464        public ZInterpolator(float foc) {
1465            focalLength = foc;
1466        }
1467
1468        public float getInterpolation(float input) {
1469            return (1.0f - focalLength / (focalLength + input)) /
1470                (1.0f - focalLength / (focalLength + 1.0f));
1471        }
1472    }
1473
1474    /*
1475     * The exact reverse of ZInterpolator.
1476     */
1477    static class InverseZInterpolator implements TimeInterpolator {
1478        private ZInterpolator zInterpolator;
1479        public InverseZInterpolator(float foc) {
1480            zInterpolator = new ZInterpolator(foc);
1481        }
1482        public float getInterpolation(float input) {
1483            return 1 - zInterpolator.getInterpolation(1 - input);
1484        }
1485    }
1486
1487    /*
1488     * ZInterpolator compounded with an ease-out.
1489     */
1490    static class ZoomOutInterpolator implements TimeInterpolator {
1491        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(0.75f);
1492        private final ZInterpolator zInterpolator = new ZInterpolator(0.13f);
1493
1494        public float getInterpolation(float input) {
1495            return decelerate.getInterpolation(zInterpolator.getInterpolation(input));
1496        }
1497    }
1498
1499    /*
1500     * InvereZInterpolator compounded with an ease-out.
1501     */
1502    static class ZoomInInterpolator implements TimeInterpolator {
1503        private final InverseZInterpolator inverseZInterpolator = new InverseZInterpolator(0.35f);
1504        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(3.0f);
1505
1506        public float getInterpolation(float input) {
1507            return decelerate.getInterpolation(inverseZInterpolator.getInterpolation(input));
1508        }
1509    }
1510
1511    private final ZoomInInterpolator mZoomInInterpolator = new ZoomInInterpolator();
1512
1513    /*
1514    *
1515    * We call these methods (onDragStartedWithItemSpans/onDragStartedWithSize) whenever we
1516    * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace
1517    *
1518    * These methods mark the appropriate pages as accepting drops (which alters their visual
1519    * appearance).
1520    *
1521    */
1522    public void onDragStartedWithItem(View v) {
1523        final Canvas canvas = new Canvas();
1524
1525        // The outline is used to visualize where the item will land if dropped
1526        mDragOutline = createDragOutline(v, canvas, DRAG_BITMAP_PADDING);
1527    }
1528
1529    public void onDragStartedWithItem(PendingAddItemInfo info, Bitmap b, boolean clipAlpha) {
1530        final Canvas canvas = new Canvas();
1531
1532        int[] size = estimateItemSize(info.spanX, info.spanY, info, false);
1533
1534        // The outline is used to visualize where the item will land if dropped
1535        mDragOutline = createDragOutline(b, canvas, DRAG_BITMAP_PADDING, size[0],
1536                size[1], clipAlpha);
1537    }
1538
1539    public void exitWidgetResizeMode() {
1540        DragLayer dragLayer = mLauncher.getDragLayer();
1541        dragLayer.clearAllResizeFrames();
1542    }
1543
1544    private void initAnimationArrays() {
1545        final int childCount = getChildCount();
1546        if (mOldTranslationXs != null) return;
1547        mOldTranslationXs = new float[childCount];
1548        mOldTranslationYs = new float[childCount];
1549        mOldScaleXs = new float[childCount];
1550        mOldScaleYs = new float[childCount];
1551        mOldBackgroundAlphas = new float[childCount];
1552        mOldAlphas = new float[childCount];
1553        mNewTranslationXs = new float[childCount];
1554        mNewTranslationYs = new float[childCount];
1555        mNewScaleXs = new float[childCount];
1556        mNewScaleYs = new float[childCount];
1557        mNewBackgroundAlphas = new float[childCount];
1558        mNewAlphas = new float[childCount];
1559        mNewRotationYs = new float[childCount];
1560    }
1561
1562    Animator getChangeStateAnimation(final State state, boolean animated) {
1563        return getChangeStateAnimation(state, animated, 0);
1564    }
1565
1566    Animator getChangeStateAnimation(final State state, boolean animated, int delay) {
1567        if (mState == state) {
1568            return null;
1569        }
1570
1571        // Initialize animation arrays for the first time if necessary
1572        initAnimationArrays();
1573
1574        AnimatorSet anim = animated ? LauncherAnimUtils.createAnimatorSet() : null;
1575
1576        // Stop any scrolling, move to the current page right away
1577        setCurrentPage(getNextPage());
1578
1579        final State oldState = mState;
1580        final boolean oldStateIsNormal = (oldState == State.NORMAL);
1581        final boolean oldStateIsSpringLoaded = (oldState == State.SPRING_LOADED);
1582        final boolean oldStateIsSmall = (oldState == State.SMALL);
1583        mState = state;
1584        final boolean stateIsNormal = (state == State.NORMAL);
1585        final boolean stateIsSpringLoaded = (state == State.SPRING_LOADED);
1586        final boolean stateIsSmall = (state == State.SMALL);
1587        float finalScaleFactor = 1.0f;
1588        float finalBackgroundAlpha = stateIsSpringLoaded ? 1.0f : 0f;
1589        float translationX = 0;
1590        float translationY = 0;
1591        boolean zoomIn = true;
1592
1593        if (state != State.NORMAL) {
1594            finalScaleFactor = mSpringLoadedShrinkFactor - (stateIsSmall ? 0.1f : 0);
1595            setPageSpacing(mSpringLoadedPageSpacing);
1596            if (oldStateIsNormal && stateIsSmall) {
1597                zoomIn = false;
1598                setLayoutScale(finalScaleFactor);
1599                updateChildrenLayersEnabled(false);
1600            } else {
1601                finalBackgroundAlpha = 1.0f;
1602                setLayoutScale(finalScaleFactor);
1603            }
1604        } else {
1605            setPageSpacing(mOriginalPageSpacing);
1606            setLayoutScale(1.0f);
1607        }
1608
1609        final int duration = zoomIn ?
1610                getResources().getInteger(R.integer.config_workspaceUnshrinkTime) :
1611                getResources().getInteger(R.integer.config_appsCustomizeWorkspaceShrinkTime);
1612        for (int i = 0; i < getChildCount(); i++) {
1613            final CellLayout cl = (CellLayout) getChildAt(i);
1614            float finalAlpha = (!mWorkspaceFadeInAdjacentScreens || stateIsSpringLoaded ||
1615                    (i == mCurrentPage)) ? 1f : 0f;
1616            float currentAlpha = cl.getShortcutsAndWidgets().getAlpha();
1617            float initialAlpha = currentAlpha;
1618
1619            // Determine the pages alpha during the state transition
1620            if ((oldStateIsSmall && stateIsNormal) ||
1621                (oldStateIsNormal && stateIsSmall)) {
1622                // To/from workspace - only show the current page unless the transition is not
1623                //                     animated and the animation end callback below doesn't run;
1624                //                     or, if we're in spring-loaded mode
1625                if (i == mCurrentPage || !animated || oldStateIsSpringLoaded) {
1626                    finalAlpha = 1f;
1627                } else {
1628                    initialAlpha = 0f;
1629                    finalAlpha = 0f;
1630                }
1631            }
1632
1633            mOldAlphas[i] = initialAlpha;
1634            mNewAlphas[i] = finalAlpha;
1635            if (animated) {
1636                mOldTranslationXs[i] = cl.getTranslationX();
1637                mOldTranslationYs[i] = cl.getTranslationY();
1638                mOldScaleXs[i] = cl.getScaleX();
1639                mOldScaleYs[i] = cl.getScaleY();
1640                mOldBackgroundAlphas[i] = cl.getBackgroundAlpha();
1641
1642                mNewTranslationXs[i] = translationX;
1643                mNewTranslationYs[i] = translationY;
1644                mNewScaleXs[i] = finalScaleFactor;
1645                mNewScaleYs[i] = finalScaleFactor;
1646                mNewBackgroundAlphas[i] = finalBackgroundAlpha;
1647            } else {
1648                cl.setTranslationX(translationX);
1649                cl.setTranslationY(translationY);
1650                cl.setScaleX(finalScaleFactor);
1651                cl.setScaleY(finalScaleFactor);
1652                cl.setBackgroundAlpha(finalBackgroundAlpha);
1653                cl.setShortcutAndWidgetAlpha(finalAlpha);
1654            }
1655        }
1656
1657        if (animated) {
1658            for (int index = 0; index < getChildCount(); index++) {
1659                final int i = index;
1660                final CellLayout cl = (CellLayout) getChildAt(i);
1661                float currentAlpha = cl.getShortcutsAndWidgets().getAlpha();
1662                if (mOldAlphas[i] == 0 && mNewAlphas[i] == 0) {
1663                    cl.setTranslationX(mNewTranslationXs[i]);
1664                    cl.setTranslationY(mNewTranslationYs[i]);
1665                    cl.setScaleX(mNewScaleXs[i]);
1666                    cl.setScaleY(mNewScaleYs[i]);
1667                    cl.setBackgroundAlpha(mNewBackgroundAlphas[i]);
1668                    cl.setShortcutAndWidgetAlpha(mNewAlphas[i]);
1669                    cl.setRotationY(mNewRotationYs[i]);
1670                } else {
1671                    LauncherViewPropertyAnimator a = new LauncherViewPropertyAnimator(cl);
1672                    a.translationX(mNewTranslationXs[i])
1673                        .translationY(mNewTranslationYs[i])
1674                        .scaleX(mNewScaleXs[i])
1675                        .scaleY(mNewScaleYs[i])
1676                        .setDuration(duration)
1677                        .setInterpolator(mZoomInInterpolator);
1678                    anim.play(a);
1679
1680                    if (mOldAlphas[i] != mNewAlphas[i] || currentAlpha != mNewAlphas[i]) {
1681                        LauncherViewPropertyAnimator alphaAnim =
1682                            new LauncherViewPropertyAnimator(cl.getShortcutsAndWidgets());
1683                        alphaAnim.alpha(mNewAlphas[i])
1684                            .setDuration(duration)
1685                            .setInterpolator(mZoomInInterpolator);
1686                        anim.play(alphaAnim);
1687                    }
1688                    if (mOldBackgroundAlphas[i] != 0 ||
1689                        mNewBackgroundAlphas[i] != 0) {
1690                        ValueAnimator bgAnim = LauncherAnimUtils.ofFloat(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            buildPageHardwareLayers();
1704            anim.setStartDelay(delay);
1705        }
1706
1707        if (stateIsSpringLoaded) {
1708            // Right now we're covered by Apps Customize
1709            // Show the background gradient immediately, so the gradient will
1710            // be showing once AppsCustomize disappears
1711            animateBackgroundGradient(getResources().getInteger(
1712                    R.integer.config_appsCustomizeSpringLoadedBgAlpha) / 100f, false);
1713        } else {
1714            // Fade the background gradient away
1715            animateBackgroundGradient(0f, true);
1716        }
1717        return anim;
1718    }
1719
1720    @Override
1721    public void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace) {
1722        mIsSwitchingState = true;
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    void removeItems(final ArrayList<String> packages) {
3641        final HashSet<String> packageNames = new HashSet<String>();
3642        packageNames.addAll(packages);
3643
3644        ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
3645        for (final CellLayout layoutParent: cellLayouts) {
3646            final ViewGroup layout = layoutParent.getShortcutsAndWidgets();
3647
3648            // Avoid ANRs by treating each screen separately
3649            post(new Runnable() {
3650                public void run() {
3651                    final ArrayList<View> childrenToRemove = new ArrayList<View>();
3652                    childrenToRemove.clear();
3653
3654                    int childCount = layout.getChildCount();
3655                    for (int j = 0; j < childCount; j++) {
3656                        final View view = layout.getChildAt(j);
3657                        Object tag = view.getTag();
3658
3659                        if (tag instanceof ShortcutInfo) {
3660                            final ShortcutInfo info = (ShortcutInfo) tag;
3661                            final Intent intent = info.intent;
3662                            final ComponentName name = intent.getComponent();
3663
3664                            if (name != null) {
3665                                if (packageNames.contains(name.getPackageName())) {
3666                                    LauncherModel.deleteItemFromDatabase(mLauncher, info);
3667                                    childrenToRemove.add(view);
3668                                }
3669                            }
3670                        } else if (tag instanceof FolderInfo) {
3671                            final FolderInfo info = (FolderInfo) tag;
3672                            final ArrayList<ShortcutInfo> contents = info.contents;
3673                            final int contentsCount = contents.size();
3674                            final ArrayList<ShortcutInfo> appsToRemoveFromFolder =
3675                                    new ArrayList<ShortcutInfo>();
3676
3677                            for (int k = 0; k < contentsCount; k++) {
3678                                final ShortcutInfo appInfo = contents.get(k);
3679                                final Intent intent = appInfo.intent;
3680                                final ComponentName name = intent.getComponent();
3681
3682                                if (name != null) {
3683                                    if (packageNames.contains(name.getPackageName())) {
3684                                        appsToRemoveFromFolder.add(appInfo);
3685                                    }
3686                                }
3687                            }
3688                            for (ShortcutInfo item: appsToRemoveFromFolder) {
3689                                info.remove(item);
3690                                LauncherModel.deleteItemFromDatabase(mLauncher, item);
3691                            }
3692                        } else if (tag instanceof LauncherAppWidgetInfo) {
3693                            final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag;
3694                            final ComponentName provider = info.providerName;
3695                            if (provider != null) {
3696                                if (packageNames.contains(provider.getPackageName())) {
3697                                    LauncherModel.deleteItemFromDatabase(mLauncher, info);
3698                                    childrenToRemove.add(view);
3699                                }
3700                            }
3701                        }
3702                    }
3703
3704                    childCount = childrenToRemove.size();
3705                    for (int j = 0; j < childCount; j++) {
3706                        View child = childrenToRemove.get(j);
3707                        // Note: We can not remove the view directly from CellLayoutChildren as this
3708                        // does not re-mark the spaces as unoccupied.
3709                        layoutParent.removeViewInLayout(child);
3710                        if (child instanceof DropTarget) {
3711                            mDragController.removeDropTarget((DropTarget)child);
3712                        }
3713                    }
3714
3715                    if (childCount > 0) {
3716                        layout.requestLayout();
3717                        layout.invalidate();
3718                    }
3719                }
3720            });
3721        }
3722
3723        // Clean up new-apps animation list
3724        final Context context = getContext();
3725        post(new Runnable() {
3726            @Override
3727            public void run() {
3728                String spKey = LauncherApplication.getSharedPreferencesKey();
3729                SharedPreferences sp = context.getSharedPreferences(spKey,
3730                        Context.MODE_PRIVATE);
3731                Set<String> newApps = sp.getStringSet(InstallShortcutReceiver.NEW_APPS_LIST_KEY,
3732                        null);
3733
3734                // Remove all queued items that match the same package
3735                if (newApps != null) {
3736                    synchronized (newApps) {
3737                        Iterator<String> iter = newApps.iterator();
3738                        while (iter.hasNext()) {
3739                            try {
3740                                Intent intent = Intent.parseUri(iter.next(), 0);
3741                                String pn = ItemInfo.getPackageName(intent);
3742                                if (packageNames.contains(pn)) {
3743                                    iter.remove();
3744                                }
3745
3746                                // It is possible that we've queued an item to be loaded, yet it has
3747                                // not been added to the workspace, so remove those items as well.
3748                                ArrayList<ItemInfo> shortcuts;
3749                                shortcuts = LauncherModel.getWorkspaceShortcutItemInfosWithIntent(
3750                                        intent);
3751                                for (ItemInfo info : shortcuts) {
3752                                    LauncherModel.deleteItemFromDatabase(context, info);
3753                                }
3754                            } catch (URISyntaxException e) {}
3755                        }
3756                    }
3757                }
3758            }
3759        });
3760    }
3761
3762    void updateShortcuts(ArrayList<ApplicationInfo> apps) {
3763        ArrayList<ShortcutAndWidgetContainer> childrenLayouts = getAllShortcutAndWidgetContainers();
3764        for (ShortcutAndWidgetContainer layout: childrenLayouts) {
3765            int childCount = layout.getChildCount();
3766            for (int j = 0; j < childCount; j++) {
3767                final View view = layout.getChildAt(j);
3768                Object tag = view.getTag();
3769                if (tag instanceof ShortcutInfo) {
3770                    ShortcutInfo info = (ShortcutInfo) tag;
3771                    // We need to check for ACTION_MAIN otherwise getComponent() might
3772                    // return null for some shortcuts (for instance, for shortcuts to
3773                    // web pages.)
3774                    final Intent intent = info.intent;
3775                    final ComponentName name = intent.getComponent();
3776                    if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3777                            Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3778                        final int appCount = apps.size();
3779                        for (int k = 0; k < appCount; k++) {
3780                            ApplicationInfo app = apps.get(k);
3781                            if (app.componentName.equals(name)) {
3782                                BubbleTextView shortcut = (BubbleTextView) view;
3783                                info.updateIcon(mIconCache);
3784                                info.title = app.title.toString();
3785                                shortcut.applyFromShortcutInfo(info, mIconCache);
3786                            }
3787                        }
3788                    }
3789                }
3790            }
3791        }
3792    }
3793
3794    void moveToDefaultScreen(boolean animate) {
3795        if (!isSmall()) {
3796            if (animate) {
3797                snapToPage(mDefaultPage);
3798            } else {
3799                setCurrentPage(mDefaultPage);
3800            }
3801        }
3802        getChildAt(mDefaultPage).requestFocus();
3803    }
3804
3805    @Override
3806    public void syncPages() {
3807    }
3808
3809    @Override
3810    public void syncPageItems(int page, boolean immediate) {
3811    }
3812
3813    @Override
3814    protected String getCurrentPageDescription() {
3815        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
3816        return String.format(getContext().getString(R.string.workspace_scroll_format),
3817                page + 1, getChildCount());
3818    }
3819
3820    public void getLocationInDragLayer(int[] loc) {
3821        mLauncher.getDragLayer().getLocationInDragLayer(this, loc);
3822    }
3823
3824    void setFadeForOverScroll(float fade) {
3825        if (!isScrollingIndicatorEnabled()) return;
3826
3827        mOverscrollFade = fade;
3828        float reducedFade = 0.5f + 0.5f * (1 - fade);
3829        final ViewGroup parent = (ViewGroup) getParent();
3830        final ImageView qsbDivider = (ImageView) (parent.findViewById(R.id.qsb_divider));
3831        final ImageView dockDivider = (ImageView) (parent.findViewById(R.id.dock_divider));
3832        final View scrollIndicator = getScrollingIndicator();
3833
3834        cancelScrollingIndicatorAnimations();
3835        if (qsbDivider != null) qsbDivider.setAlpha(reducedFade);
3836        if (dockDivider != null) dockDivider.setAlpha(reducedFade);
3837        scrollIndicator.setAlpha(1 - fade);
3838    }
3839}
3840