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