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