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