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