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