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