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