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