Workspace.java revision 6670073de833cb56dabecb1eb751b6625a5aed78
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
1714        Log.w(TAG, "10249126 - onEndReordering()");
1715        mLauncher.getModel().updateWorkspaceScreenOrder(mLauncher, mScreenOrder);
1716
1717        // Re-enable auto layout transitions for page deletion.
1718        setLayoutTransition(mLayoutTransition);
1719    }
1720
1721    public boolean isInOverviewMode() {
1722        return mState == State.OVERVIEW;
1723    }
1724
1725    public void enterOverviewMode() {
1726        enableOverviewMode(true, -1);
1727    }
1728
1729    public void exitOverviewMode() {
1730        exitOverviewMode(-1);
1731    }
1732
1733    public void exitOverviewMode(int snapPage) {
1734        enableOverviewMode(false, snapPage);
1735    }
1736
1737    private void enableOverviewMode(boolean enable, int snapPage) {
1738        State finalState = Workspace.State.OVERVIEW;
1739        if (!enable) {
1740            finalState = Workspace.State.NORMAL;
1741        }
1742
1743        Animator workspaceAnim = getChangeStateAnimation(finalState, true, 0, snapPage);
1744        workspaceAnim.addListener(new AnimatorListenerAdapter() {
1745            @Override
1746            public void onAnimationEnd(Animator arg0) {
1747                mIsSwitchingState = false;
1748            }
1749            @Override
1750            public void onAnimationStart(Animator arg0) {
1751                mIsSwitchingState = true;
1752            }
1753        });
1754        workspaceAnim.start();
1755    }
1756
1757    Animator getChangeStateAnimation(final State state, boolean animated, int delay, int snapPage) {
1758        if (mState == state) {
1759            return null;
1760        }
1761
1762        // Initialize animation arrays for the first time if necessary
1763        initAnimationArrays();
1764
1765        AnimatorSet anim = animated ? LauncherAnimUtils.createAnimatorSet() : null;
1766
1767        final State oldState = mState;
1768        final boolean oldStateIsNormal = (oldState == State.NORMAL);
1769        final boolean oldStateIsSpringLoaded = (oldState == State.SPRING_LOADED);
1770        final boolean oldStateIsSmall = (oldState == State.SMALL);
1771        final boolean oldStateIsOverview = (oldState == State.OVERVIEW);
1772        mState = state;
1773        final boolean stateIsNormal = (state == State.NORMAL);
1774        final boolean stateIsSpringLoaded = (state == State.SPRING_LOADED);
1775        final boolean stateIsSmall = (state == State.SMALL);
1776        final boolean stateIsOverview = (state == State.OVERVIEW);
1777        float finalBackgroundAlpha = stateIsSpringLoaded ? 1.0f : 0f;
1778        float finalHotseatAndPageIndicatorAlpha = (stateIsOverview || stateIsSmall) ? 0f : 1f;
1779        float finalOverviewPanelAlpha = stateIsOverview ? 1f : 0f;
1780
1781        boolean zoomIn = true;
1782        mNewScale = 1.0f;
1783
1784        if (oldStateIsOverview) {
1785            disableFreeScroll(snapPage);
1786        } else if (stateIsOverview) {
1787            enableFreeScroll();
1788        }
1789
1790        if (state != State.NORMAL) {
1791            if (stateIsSpringLoaded) {
1792                mNewScale = mSpringLoadedShrinkFactor;
1793            } else if (stateIsOverview) {
1794                mNewScale = mOverviewModeShrinkFactor;
1795            } else if (stateIsSmall){
1796                mNewScale = mOverviewModeShrinkFactor - 0.1f;
1797            }
1798            if (oldStateIsNormal && stateIsSmall) {
1799                zoomIn = false;
1800                updateChildrenLayersEnabled(false);
1801            } else {
1802                finalBackgroundAlpha = 1.0f;
1803            }
1804        }
1805        final int duration = zoomIn ?
1806                getResources().getInteger(R.integer.config_workspaceUnshrinkTime) :
1807                getResources().getInteger(R.integer.config_appsCustomizeWorkspaceShrinkTime);
1808        for (int i = 0; i < getChildCount(); i++) {
1809            final CellLayout cl = (CellLayout) getChildAt(i);
1810            float finalAlpha = (!mWorkspaceFadeInAdjacentScreens || stateIsSpringLoaded ||
1811                    (i == mCurrentPage)) ? 1f : 0f;
1812            float currentAlpha = cl.getShortcutsAndWidgets().getAlpha();
1813            float initialAlpha = currentAlpha;
1814
1815            // Determine the pages alpha during the state transition
1816            if ((oldStateIsSmall && stateIsNormal) ||
1817                (oldStateIsNormal && stateIsSmall)) {
1818                // To/from workspace - only show the current page unless the transition is not
1819                //                     animated and the animation end callback below doesn't run;
1820                //                     or, if we're in spring-loaded mode
1821                if (i == mCurrentPage || !animated || oldStateIsSpringLoaded) {
1822                    finalAlpha = 1f;
1823                } else {
1824                    initialAlpha = 0f;
1825                    finalAlpha = 0f;
1826                }
1827            }
1828
1829            mOldAlphas[i] = initialAlpha;
1830            mNewAlphas[i] = finalAlpha;
1831            if (animated) {
1832                mOldBackgroundAlphas[i] = cl.getBackgroundAlpha();
1833                mNewBackgroundAlphas[i] = finalBackgroundAlpha;
1834            } else {
1835                setScaleX(mNewScale);
1836                setScaleY(mNewScale);
1837                cl.setBackgroundAlpha(finalBackgroundAlpha);
1838                cl.setShortcutAndWidgetAlpha(finalAlpha);
1839            }
1840        }
1841
1842        if (animated) {
1843            LauncherViewPropertyAnimator scale = new LauncherViewPropertyAnimator(this);
1844            scale.scaleX(mNewScale)
1845                .scaleY(mNewScale)
1846                .setInterpolator(mZoomInInterpolator);
1847            anim.play(scale);
1848            for (int index = 0; index < getChildCount(); index++) {
1849                final int i = index;
1850                final CellLayout cl = (CellLayout) getChildAt(i);
1851                float currentAlpha = cl.getShortcutsAndWidgets().getAlpha();
1852                if (mOldAlphas[i] == 0 && mNewAlphas[i] == 0) {
1853                    cl.setBackgroundAlpha(mNewBackgroundAlphas[i]);
1854                    cl.setShortcutAndWidgetAlpha(mNewAlphas[i]);
1855                } else {
1856
1857                    if (mOldAlphas[i] != mNewAlphas[i] || currentAlpha != mNewAlphas[i]) {
1858                        LauncherViewPropertyAnimator alphaAnim =
1859                            new LauncherViewPropertyAnimator(cl.getShortcutsAndWidgets());
1860                        alphaAnim.alpha(mNewAlphas[i])
1861                            .setDuration(duration)
1862                            .setInterpolator(mZoomInInterpolator);
1863                        anim.play(alphaAnim);
1864                    }
1865                    if (mOldBackgroundAlphas[i] != 0 ||
1866                        mNewBackgroundAlphas[i] != 0) {
1867                        ValueAnimator bgAnim =
1868                                LauncherAnimUtils.ofFloat(cl, 0f, 1f).setDuration(duration);
1869                        bgAnim.setInterpolator(mZoomInInterpolator);
1870                        bgAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
1871                                public void onAnimationUpdate(float a, float b) {
1872                                    cl.setBackgroundAlpha(
1873                                            a * mOldBackgroundAlphas[i] +
1874                                            b * mNewBackgroundAlphas[i]);
1875                                }
1876                            });
1877                        anim.play(bgAnim);
1878                    }
1879                }
1880            }
1881            ObjectAnimator pageIndicatorAlpha = null;
1882            if (getPageIndicator() != null) {
1883                pageIndicatorAlpha = ObjectAnimator.ofFloat(getPageIndicator(), "alpha",
1884                        finalHotseatAndPageIndicatorAlpha);
1885            }
1886            ObjectAnimator hotseatAlpha = ObjectAnimator.ofFloat(mLauncher.getHotseat(), "alpha",
1887                    finalHotseatAndPageIndicatorAlpha);
1888            ObjectAnimator overviewPanelAlpha = ObjectAnimator.ofFloat(mLauncher.getOverviewPanel(),
1889                    "alpha", finalOverviewPanelAlpha);
1890            overviewPanelAlpha.addUpdateListener(new AlphaUpdateListener(
1891                    mLauncher.getOverviewPanel()));
1892            hotseatAlpha.addUpdateListener(new AlphaUpdateListener(mLauncher.getHotseat()));
1893            if (getPageIndicator() != null) {
1894                pageIndicatorAlpha.addUpdateListener(new AlphaUpdateListener(getPageIndicator()));
1895            }
1896            anim.play(overviewPanelAlpha);
1897            anim.play(hotseatAlpha);
1898            anim.play(pageIndicatorAlpha);
1899            anim.setStartDelay(delay);
1900        } else {
1901            mLauncher.getOverviewPanel().setAlpha(finalOverviewPanelAlpha);
1902            mLauncher.getHotseat().setAlpha(finalHotseatAndPageIndicatorAlpha);
1903            if (getPageIndicator() != null) {
1904                getPageIndicator().setAlpha(finalHotseatAndPageIndicatorAlpha);
1905            }
1906        }
1907
1908        if (stateIsSpringLoaded) {
1909            // Right now we're covered by Apps Customize
1910            // Show the background gradient immediately, so the gradient will
1911            // be showing once AppsCustomize disappears
1912            animateBackgroundGradient(getResources().getInteger(
1913                    R.integer.config_appsCustomizeSpringLoadedBgAlpha) / 100f, false);
1914        } else {
1915            // Fade the background gradient away
1916            animateBackgroundGradient(0f, true);
1917        }
1918        return anim;
1919    }
1920
1921    class AlphaUpdateListener implements AnimatorUpdateListener {
1922        View view;
1923        public AlphaUpdateListener(View v) {
1924            view = v;
1925        }
1926
1927        @Override
1928        public void onAnimationUpdate(ValueAnimator arg0) {
1929            if (view.getAlpha() < ALPHA_CUTOFF_THRESHOLD && view.getVisibility() != INVISIBLE) {
1930                view.setVisibility(INVISIBLE);
1931            } else if (view.getAlpha() > ALPHA_CUTOFF_THRESHOLD
1932                    && view.getVisibility() != VISIBLE) {
1933                view.setVisibility(VISIBLE);
1934            }
1935        }
1936
1937    }
1938
1939    @Override
1940    public void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace) {
1941        mIsSwitchingState = true;
1942        updateChildrenLayersEnabled(false);
1943    }
1944
1945    @Override
1946    public void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace) {
1947    }
1948
1949    @Override
1950    public void onLauncherTransitionStep(Launcher l, float t) {
1951        mTransitionProgress = t;
1952    }
1953
1954    @Override
1955    public void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace) {
1956        mIsSwitchingState = false;
1957        mWallpaperOffset.setOverrideHorizontalCatchupConstant(false);
1958        updateChildrenLayersEnabled(false);
1959        // The code in getChangeStateAnimation to determine initialAlpha and finalAlpha will ensure
1960        // ensure that only the current page is visible during (and subsequently, after) the
1961        // transition animation.  If fade adjacent pages is disabled, then re-enable the page
1962        // visibility after the transition animation.
1963        if (!mWorkspaceFadeInAdjacentScreens) {
1964            for (int i = 0; i < getChildCount(); i++) {
1965                final CellLayout cl = (CellLayout) getChildAt(i);
1966                cl.setShortcutAndWidgetAlpha(1f);
1967            }
1968        }
1969    }
1970
1971    @Override
1972    public View getContent() {
1973        return this;
1974    }
1975
1976    /**
1977     * Draw the View v into the given Canvas.
1978     *
1979     * @param v the view to draw
1980     * @param destCanvas the canvas to draw on
1981     * @param padding the horizontal and vertical padding to use when drawing
1982     */
1983    private void drawDragView(View v, Canvas destCanvas, int padding, boolean pruneToDrawable) {
1984        final Rect clipRect = mTempRect;
1985        v.getDrawingRect(clipRect);
1986
1987        boolean textVisible = false;
1988
1989        destCanvas.save();
1990        if (v instanceof TextView && pruneToDrawable) {
1991            Drawable d = ((TextView) v).getCompoundDrawables()[1];
1992            clipRect.set(0, 0, d.getIntrinsicWidth() + padding, d.getIntrinsicHeight() + padding);
1993            destCanvas.translate(padding / 2, padding / 2);
1994            d.draw(destCanvas);
1995        } else {
1996            if (v instanceof FolderIcon) {
1997                // For FolderIcons the text can bleed into the icon area, and so we need to
1998                // hide the text completely (which can't be achieved by clipping).
1999                if (((FolderIcon) v).getTextVisible()) {
2000                    ((FolderIcon) v).setTextVisible(false);
2001                    textVisible = true;
2002                }
2003            } else if (v instanceof BubbleTextView) {
2004                final BubbleTextView tv = (BubbleTextView) v;
2005                clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V +
2006                        tv.getLayout().getLineTop(0);
2007            } else if (v instanceof TextView) {
2008                final TextView tv = (TextView) v;
2009                clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() +
2010                        tv.getLayout().getLineTop(0);
2011            }
2012            destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2);
2013            destCanvas.clipRect(clipRect, Op.REPLACE);
2014            v.draw(destCanvas);
2015
2016            // Restore text visibility of FolderIcon if necessary
2017            if (textVisible) {
2018                ((FolderIcon) v).setTextVisible(true);
2019            }
2020        }
2021        destCanvas.restore();
2022    }
2023
2024    /**
2025     * Returns a new bitmap to show when the given View is being dragged around.
2026     * Responsibility for the bitmap is transferred to the caller.
2027     */
2028    public Bitmap createDragBitmap(View v, Canvas canvas, int padding) {
2029        Bitmap b;
2030
2031        if (v instanceof TextView) {
2032            Drawable d = ((TextView) v).getCompoundDrawables()[1];
2033            b = Bitmap.createBitmap(d.getIntrinsicWidth() + padding,
2034                    d.getIntrinsicHeight() + padding, Bitmap.Config.ARGB_8888);
2035        } else {
2036            b = Bitmap.createBitmap(
2037                    v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
2038        }
2039
2040        canvas.setBitmap(b);
2041        drawDragView(v, canvas, padding, true);
2042        canvas.setBitmap(null);
2043
2044        return b;
2045    }
2046
2047    /**
2048     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
2049     * Responsibility for the bitmap is transferred to the caller.
2050     */
2051    private Bitmap createDragOutline(View v, Canvas canvas, int padding) {
2052        final int outlineColor = getResources().getColor(android.R.color.holo_blue_light);
2053        final Bitmap b = Bitmap.createBitmap(
2054                v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
2055
2056        canvas.setBitmap(b);
2057        drawDragView(v, canvas, padding, true);
2058        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
2059        canvas.setBitmap(null);
2060        return b;
2061    }
2062
2063    /**
2064     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
2065     * Responsibility for the bitmap is transferred to the caller.
2066     */
2067    private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h,
2068            boolean clipAlpha) {
2069        final int outlineColor = getResources().getColor(android.R.color.holo_blue_light);
2070        final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
2071        canvas.setBitmap(b);
2072
2073        Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight());
2074        float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(),
2075                (h - padding) / (float) orig.getHeight());
2076        int scaledWidth = (int) (scaleFactor * orig.getWidth());
2077        int scaledHeight = (int) (scaleFactor * orig.getHeight());
2078        Rect dst = new Rect(0, 0, scaledWidth, scaledHeight);
2079
2080        // center the image
2081        dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2);
2082
2083        canvas.drawBitmap(orig, src, dst, null);
2084        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor,
2085                clipAlpha);
2086        canvas.setBitmap(null);
2087
2088        return b;
2089    }
2090
2091    void startDrag(CellLayout.CellInfo cellInfo) {
2092        View child = cellInfo.cell;
2093
2094        // Make sure the drag was started by a long press as opposed to a long click.
2095        if (!child.isInTouchMode()) {
2096            return;
2097        }
2098
2099        mDragInfo = cellInfo;
2100        child.setVisibility(INVISIBLE);
2101        CellLayout layout = (CellLayout) child.getParent().getParent();
2102        layout.prepareChildForDrag(child);
2103
2104        child.clearFocus();
2105        child.setPressed(false);
2106
2107        final Canvas canvas = new Canvas();
2108
2109        // The outline is used to visualize where the item will land if dropped
2110        mDragOutline = createDragOutline(child, canvas, DRAG_BITMAP_PADDING);
2111        beginDragShared(child, this);
2112    }
2113
2114    public void beginDragShared(View child, DragSource source) {
2115        Resources r = getResources();
2116
2117        // The drag bitmap follows the touch point around on the screen
2118        final Bitmap b = createDragBitmap(child, new Canvas(), DRAG_BITMAP_PADDING);
2119
2120        final int bmpWidth = b.getWidth();
2121        final int bmpHeight = b.getHeight();
2122
2123        float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY);
2124        int dragLayerX =
2125                Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2);
2126        int dragLayerY =
2127                Math.round(mTempXY[1] - (bmpHeight - scale * bmpHeight) / 2
2128                        - DRAG_BITMAP_PADDING / 2);
2129
2130        LauncherAppState app = LauncherAppState.getInstance();
2131        DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
2132        Point dragVisualizeOffset = null;
2133        Rect dragRect = null;
2134        if (child instanceof BubbleTextView || child instanceof PagedViewIcon) {
2135            int iconSize = grid.iconSizePx;
2136            int top = child.getPaddingTop();
2137            int left = (bmpWidth - iconSize) / 2;
2138            int right = left + iconSize;
2139            int bottom = top + iconSize;
2140            dragLayerY += top;
2141            // Note: The drag region is used to calculate drag layer offsets, but the
2142            // dragVisualizeOffset in addition to the dragRect (the size) to position the outline.
2143            dragVisualizeOffset = new Point(-DRAG_BITMAP_PADDING / 2, DRAG_BITMAP_PADDING / 2);
2144            dragRect = new Rect(left, top, right, bottom);
2145        } else if (child instanceof FolderIcon) {
2146            int previewSize = grid.folderIconSizePx;
2147            dragRect = new Rect(0, child.getPaddingTop(), child.getWidth(), previewSize);
2148        }
2149
2150        // Clear the pressed state if necessary
2151        if (child instanceof BubbleTextView) {
2152            BubbleTextView icon = (BubbleTextView) child;
2153            icon.clearPressedOrFocusedBackground();
2154        }
2155
2156        mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(),
2157                DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect, scale);
2158        b.recycle();
2159    }
2160
2161    void addApplicationShortcut(ShortcutInfo info, CellLayout target, long container, long screenId,
2162            int cellX, int cellY, boolean insertAtFirst, int intersectX, int intersectY) {
2163        View view = mLauncher.createShortcut(R.layout.application, target, (ShortcutInfo) info);
2164
2165        final int[] cellXY = new int[2];
2166        target.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY);
2167        addInScreen(view, container, screenId, cellXY[0], cellXY[1], 1, 1, insertAtFirst);
2168
2169        LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screenId, cellXY[0],
2170                cellXY[1]);
2171    }
2172
2173    public boolean transitionStateShouldAllowDrop() {
2174        return ((!isSwitchingState() || mTransitionProgress > 0.5f) && mState != State.SMALL);
2175    }
2176
2177    /**
2178     * {@inheritDoc}
2179     */
2180    public boolean acceptDrop(DragObject d) {
2181        // If it's an external drop (e.g. from All Apps), check if it should be accepted
2182        CellLayout dropTargetLayout = mDropToLayout;
2183        if (d.dragSource != this) {
2184            // Don't accept the drop if we're not over a screen at time of drop
2185            if (dropTargetLayout == null) {
2186                return false;
2187            }
2188            if (!transitionStateShouldAllowDrop()) return false;
2189
2190            mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
2191                    d.dragView, mDragViewVisualCenter);
2192
2193            // We want the point to be mapped to the dragTarget.
2194            if (mLauncher.isHotseatLayout(dropTargetLayout)) {
2195                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
2196            } else {
2197                mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter, null);
2198            }
2199
2200            int spanX = 1;
2201            int spanY = 1;
2202            if (mDragInfo != null) {
2203                final CellLayout.CellInfo dragCellInfo = mDragInfo;
2204                spanX = dragCellInfo.spanX;
2205                spanY = dragCellInfo.spanY;
2206            } else {
2207                final ItemInfo dragInfo = (ItemInfo) d.dragInfo;
2208                spanX = dragInfo.spanX;
2209                spanY = dragInfo.spanY;
2210            }
2211
2212            int minSpanX = spanX;
2213            int minSpanY = spanY;
2214            if (d.dragInfo instanceof PendingAddWidgetInfo) {
2215                minSpanX = ((PendingAddWidgetInfo) d.dragInfo).minSpanX;
2216                minSpanY = ((PendingAddWidgetInfo) d.dragInfo).minSpanY;
2217            }
2218
2219            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2220                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, dropTargetLayout,
2221                    mTargetCell);
2222            float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0],
2223                    mDragViewVisualCenter[1], mTargetCell);
2224            if (willCreateUserFolder((ItemInfo) d.dragInfo, dropTargetLayout,
2225                    mTargetCell, distance, true)) {
2226                return true;
2227            }
2228            if (willAddToExistingUserFolder((ItemInfo) d.dragInfo, dropTargetLayout,
2229                    mTargetCell, distance)) {
2230                return true;
2231            }
2232
2233            int[] resultSpan = new int[2];
2234            mTargetCell = dropTargetLayout.createArea((int) mDragViewVisualCenter[0],
2235                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY,
2236                    null, mTargetCell, resultSpan, CellLayout.MODE_ACCEPT_DROP);
2237            boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0;
2238
2239            // Don't accept the drop if there's no room for the item
2240            if (!foundCell) {
2241                // Don't show the message if we are dropping on the AllApps button and the hotseat
2242                // is full
2243                boolean isHotseat = mLauncher.isHotseatLayout(dropTargetLayout);
2244                if (mTargetCell != null && isHotseat) {
2245                    Hotseat hotseat = mLauncher.getHotseat();
2246                    if (hotseat.isAllAppsButtonRank(
2247                            hotseat.getOrderInHotseat(mTargetCell[0], mTargetCell[1]))) {
2248                        return false;
2249                    }
2250                }
2251
2252                mLauncher.showOutOfSpaceMessage(isHotseat);
2253                return false;
2254            }
2255        }
2256
2257        long screenId = getIdForScreen(dropTargetLayout);
2258        if (screenId == EXTRA_EMPTY_SCREEN_ID) {
2259            commitExtraEmptyScreen();
2260        }
2261
2262        return true;
2263    }
2264
2265    boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell, float
2266            distance, boolean considerTimeout) {
2267        if (distance > mMaxDistanceForFolderCreation) return false;
2268        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2269
2270        if (dropOverView != null) {
2271            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams();
2272            if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.tmpCellY)) {
2273                return false;
2274            }
2275        }
2276
2277        boolean hasntMoved = false;
2278        if (mDragInfo != null) {
2279            hasntMoved = dropOverView == mDragInfo.cell;
2280        }
2281
2282        if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) {
2283            return false;
2284        }
2285
2286        boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo);
2287        boolean willBecomeShortcut =
2288                (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
2289                info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT);
2290
2291        return (aboveShortcut && willBecomeShortcut);
2292    }
2293
2294    boolean willAddToExistingUserFolder(Object dragInfo, CellLayout target, int[] targetCell,
2295            float distance) {
2296        if (distance > mMaxDistanceForFolderCreation) return false;
2297        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2298
2299        if (dropOverView != null) {
2300            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams();
2301            if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.tmpCellY)) {
2302                return false;
2303            }
2304        }
2305
2306        if (dropOverView instanceof FolderIcon) {
2307            FolderIcon fi = (FolderIcon) dropOverView;
2308            if (fi.acceptDrop(dragInfo)) {
2309                return true;
2310            }
2311        }
2312        return false;
2313    }
2314
2315    boolean createUserFolderIfNecessary(View newView, long container, CellLayout target,
2316            int[] targetCell, float distance, boolean external, DragView dragView,
2317            Runnable postAnimationRunnable) {
2318        if (distance > mMaxDistanceForFolderCreation) return false;
2319        View v = target.getChildAt(targetCell[0], targetCell[1]);
2320
2321        boolean hasntMoved = false;
2322        if (mDragInfo != null) {
2323            CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell);
2324            hasntMoved = (mDragInfo.cellX == targetCell[0] &&
2325                    mDragInfo.cellY == targetCell[1]) && (cellParent == target);
2326        }
2327
2328        if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false;
2329        mCreateUserFolderOnDrop = false;
2330        final long screenId = (targetCell == null) ? mDragInfo.screenId : getIdForScreen(target);
2331
2332        boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo);
2333        boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo);
2334
2335        if (aboveShortcut && willBecomeShortcut) {
2336            ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag();
2337            ShortcutInfo destInfo = (ShortcutInfo) v.getTag();
2338            // if the drag started here, we need to remove it from the workspace
2339            if (!external) {
2340                getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2341            }
2342
2343            Rect folderLocation = new Rect();
2344            float scale = mLauncher.getDragLayer().getDescendantRectRelativeToSelf(v, folderLocation);
2345            target.removeView(v);
2346
2347            FolderIcon fi =
2348                mLauncher.addFolder(target, container, screenId, targetCell[0], targetCell[1]);
2349            destInfo.cellX = -1;
2350            destInfo.cellY = -1;
2351            sourceInfo.cellX = -1;
2352            sourceInfo.cellY = -1;
2353
2354            // If the dragView is null, we can't animate
2355            boolean animate = dragView != null;
2356            if (animate) {
2357                fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale,
2358                        postAnimationRunnable);
2359            } else {
2360                fi.addItem(destInfo);
2361                fi.addItem(sourceInfo);
2362            }
2363            return true;
2364        }
2365        return false;
2366    }
2367
2368    boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell,
2369            float distance, DragObject d, boolean external) {
2370        if (distance > mMaxDistanceForFolderCreation) return false;
2371
2372        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2373        if (!mAddToExistingFolderOnDrop) return false;
2374        mAddToExistingFolderOnDrop = false;
2375
2376        if (dropOverView instanceof FolderIcon) {
2377            FolderIcon fi = (FolderIcon) dropOverView;
2378            if (fi.acceptDrop(d.dragInfo)) {
2379                fi.onDrop(d);
2380
2381                // if the drag started here, we need to remove it from the workspace
2382                if (!external) {
2383                    getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2384                }
2385                return true;
2386            }
2387        }
2388        return false;
2389    }
2390
2391    public void onDrop(final DragObject d) {
2392        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView,
2393                mDragViewVisualCenter);
2394
2395        CellLayout dropTargetLayout = mDropToLayout;
2396
2397        // We want the point to be mapped to the dragTarget.
2398        if (dropTargetLayout != null) {
2399            if (mLauncher.isHotseatLayout(dropTargetLayout)) {
2400                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
2401            } else {
2402                mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter, null);
2403            }
2404        }
2405
2406        int snapScreen = -1;
2407        boolean resizeOnDrop = false;
2408        if (d.dragSource != this) {
2409            final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0],
2410                    (int) mDragViewVisualCenter[1] };
2411            onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d);
2412        } else if (mDragInfo != null) {
2413            final View cell = mDragInfo.cell;
2414
2415            Runnable resizeRunnable = null;
2416            if (dropTargetLayout != null && !d.cancelled) {
2417                // Move internally
2418                boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout);
2419                boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout);
2420                long container = hasMovedIntoHotseat ?
2421                        LauncherSettings.Favorites.CONTAINER_HOTSEAT :
2422                        LauncherSettings.Favorites.CONTAINER_DESKTOP;
2423                long screenId = (mTargetCell[0] < 0) ?
2424                        mDragInfo.screenId : getIdForScreen(dropTargetLayout);
2425                int spanX = mDragInfo != null ? mDragInfo.spanX : 1;
2426                int spanY = mDragInfo != null ? mDragInfo.spanY : 1;
2427                // First we find the cell nearest to point at which the item is
2428                // dropped, without any consideration to whether there is an item there.
2429
2430                mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int)
2431                        mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell);
2432                float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0],
2433                        mDragViewVisualCenter[1], mTargetCell);
2434
2435                // If the item being dropped is a shortcut and the nearest drop
2436                // cell also contains a shortcut, then create a folder with the two shortcuts.
2437                if (!mInScrollArea && createUserFolderIfNecessary(cell, container,
2438                        dropTargetLayout, mTargetCell, distance, false, d.dragView, null)) {
2439                    stripEmptyScreens();
2440                    return;
2441                }
2442
2443                if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell,
2444                        distance, d, false)) {
2445                    stripEmptyScreens();
2446                    return;
2447                }
2448
2449                // Aside from the special case where we're dropping a shortcut onto a shortcut,
2450                // we need to find the nearest cell location that is vacant
2451                ItemInfo item = (ItemInfo) d.dragInfo;
2452                int minSpanX = item.spanX;
2453                int minSpanY = item.spanY;
2454                if (item.minSpanX > 0 && item.minSpanY > 0) {
2455                    minSpanX = item.minSpanX;
2456                    minSpanY = item.minSpanY;
2457                }
2458
2459                int[] resultSpan = new int[2];
2460                mTargetCell = dropTargetLayout.createArea((int) mDragViewVisualCenter[0],
2461                        (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, cell,
2462                        mTargetCell, resultSpan, CellLayout.MODE_ON_DROP);
2463
2464                boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0;
2465
2466                // if the widget resizes on drop
2467                if (foundCell && (cell instanceof AppWidgetHostView) &&
2468                        (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY)) {
2469                    resizeOnDrop = true;
2470                    item.spanX = resultSpan[0];
2471                    item.spanY = resultSpan[1];
2472                    AppWidgetHostView awhv = (AppWidgetHostView) cell;
2473                    AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, resultSpan[0],
2474                            resultSpan[1]);
2475                }
2476
2477                if (getScreenIdForPageIndex(mCurrentPage) != screenId && !hasMovedIntoHotseat) {
2478                    snapScreen = getPageIndexForScreenId(screenId);
2479                    snapToPage(snapScreen);
2480                }
2481
2482                if (foundCell) {
2483                    final ItemInfo info = (ItemInfo) cell.getTag();
2484                    if (hasMovedLayouts) {
2485                        // Reparent the view
2486                        getParentCellLayoutForView(cell).removeView(cell);
2487                        addInScreen(cell, container, screenId, mTargetCell[0], mTargetCell[1],
2488                                info.spanX, info.spanY);
2489                    }
2490
2491                    // update the item's position after drop
2492                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
2493                    lp.cellX = lp.tmpCellX = mTargetCell[0];
2494                    lp.cellY = lp.tmpCellY = mTargetCell[1];
2495                    lp.cellHSpan = item.spanX;
2496                    lp.cellVSpan = item.spanY;
2497                    lp.isLockedToGrid = true;
2498                    cell.setId(LauncherModel.getCellLayoutChildId(container, mDragInfo.screenId,
2499                            mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY));
2500
2501                    if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
2502                            cell instanceof LauncherAppWidgetHostView) {
2503                        final CellLayout cellLayout = dropTargetLayout;
2504                        // We post this call so that the widget has a chance to be placed
2505                        // in its final location
2506
2507                        final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell;
2508                        AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo();
2509                        if (pinfo != null &&
2510                                pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) {
2511                            final Runnable addResizeFrame = new Runnable() {
2512                                public void run() {
2513                                    DragLayer dragLayer = mLauncher.getDragLayer();
2514                                    dragLayer.addResizeFrame(info, hostView, cellLayout);
2515                                }
2516                            };
2517                            resizeRunnable = (new Runnable() {
2518                                public void run() {
2519                                    if (!isPageMoving()) {
2520                                        addResizeFrame.run();
2521                                    } else {
2522                                        mDelayedResizeRunnable = addResizeFrame;
2523                                    }
2524                                }
2525                            });
2526                        }
2527                    }
2528
2529                    LauncherModel.moveItemInDatabase(mLauncher, info, container, screenId, lp.cellX,
2530                            lp.cellY);
2531                } else {
2532                    // If we can't find a drop location, we return the item to its original position
2533                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
2534                    mTargetCell[0] = lp.cellX;
2535                    mTargetCell[1] = lp.cellY;
2536                    CellLayout layout = (CellLayout) cell.getParent().getParent();
2537                    layout.markCellsAsOccupiedForView(cell);
2538                }
2539            }
2540
2541            final CellLayout parent = (CellLayout) cell.getParent().getParent();
2542            final Runnable finalResizeRunnable = resizeRunnable;
2543            // Prepare it to be animated into its new position
2544            // This must be called after the view has been re-parented
2545            final Runnable onCompleteRunnable = new Runnable() {
2546                @Override
2547                public void run() {
2548                    mAnimatingViewIntoPlace = false;
2549                    updateChildrenLayersEnabled(false);
2550                    if (finalResizeRunnable != null) {
2551                        finalResizeRunnable.run();
2552                    }
2553                    stripEmptyScreens();
2554                }
2555            };
2556            mAnimatingViewIntoPlace = true;
2557            if (d.dragView.hasDrawn()) {
2558                final ItemInfo info = (ItemInfo) cell.getTag();
2559                if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET) {
2560                    int animationType = resizeOnDrop ? ANIMATE_INTO_POSITION_AND_RESIZE :
2561                            ANIMATE_INTO_POSITION_AND_DISAPPEAR;
2562                    animateWidgetDrop(info, parent, d.dragView,
2563                            onCompleteRunnable, animationType, cell, false);
2564                } else {
2565                    int duration = snapScreen < 0 ? -1 : ADJACENT_SCREEN_DROP_DURATION;
2566                    mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration,
2567                            onCompleteRunnable, this);
2568                }
2569            } else {
2570                d.deferDragViewCleanupPostAnimation = false;
2571                cell.setVisibility(VISIBLE);
2572            }
2573            parent.onDropChild(cell);
2574        }
2575    }
2576
2577    public void setFinalScrollForPageChange(int pageIndex) {
2578        CellLayout cl = (CellLayout) getChildAt(pageIndex);
2579        if (cl != null) {
2580            mSavedScrollX = getScrollX();
2581            mSavedTranslationX = cl.getTranslationX();
2582            mSavedRotationY = cl.getRotationY();
2583            final int newX = getScrollForPage(pageIndex);
2584            setScrollX(newX);
2585            cl.setTranslationX(0f);
2586            cl.setRotationY(0f);
2587        }
2588    }
2589
2590    public void resetFinalScrollForPageChange(int pageIndex) {
2591        if (pageIndex >= 0) {
2592            CellLayout cl = (CellLayout) getChildAt(pageIndex);
2593            setScrollX(mSavedScrollX);
2594            cl.setTranslationX(mSavedTranslationX);
2595            cl.setRotationY(mSavedRotationY);
2596        }
2597    }
2598
2599    public void getViewLocationRelativeToSelf(View v, int[] location) {
2600        getLocationInWindow(location);
2601        int x = location[0];
2602        int y = location[1];
2603
2604        v.getLocationInWindow(location);
2605        int vX = location[0];
2606        int vY = location[1];
2607
2608        location[0] = vX - x;
2609        location[1] = vY - y;
2610    }
2611
2612    public void onDragEnter(DragObject d) {
2613        mDragEnforcer.onDragEnter();
2614        mCreateUserFolderOnDrop = false;
2615        mAddToExistingFolderOnDrop = false;
2616
2617        mDropToLayout = null;
2618        CellLayout layout = getCurrentDropLayout();
2619        setCurrentDropLayout(layout);
2620        setCurrentDragOverlappingLayout(layout);
2621
2622        // Because we don't have space in the Phone UI (the CellLayouts run to the edge) we
2623        // don't need to show the outlines
2624        if (LauncherAppState.getInstance().isScreenLarge()) {
2625            showOutlines();
2626        }
2627    }
2628
2629    static Rect getCellLayoutMetrics(Launcher launcher, int orientation) {
2630        LauncherAppState app = LauncherAppState.getInstance();
2631        DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
2632
2633        Resources res = launcher.getResources();
2634        Display display = launcher.getWindowManager().getDefaultDisplay();
2635        Point smallestSize = new Point();
2636        Point largestSize = new Point();
2637        display.getCurrentSizeRange(smallestSize, largestSize);
2638        if (orientation == CellLayout.LANDSCAPE) {
2639            if (mLandscapeCellLayoutMetrics == null) {
2640                Rect padding = grid.getWorkspacePadding(CellLayout.LANDSCAPE);
2641                int width = largestSize.x - padding.left - padding.right;
2642                int height = smallestSize.y - padding.top - padding.bottom;
2643                mLandscapeCellLayoutMetrics = new Rect();
2644                CellLayout.getMetrics(mLandscapeCellLayoutMetrics, width, height,
2645                        LauncherModel.getCellCountX(), LauncherModel.getCellCountY());
2646            }
2647            return mLandscapeCellLayoutMetrics;
2648        } else if (orientation == CellLayout.PORTRAIT) {
2649            if (mPortraitCellLayoutMetrics == null) {
2650                Rect padding = grid.getWorkspacePadding(CellLayout.PORTRAIT);
2651                int width = smallestSize.x - padding.left - padding.right;
2652                int height = largestSize.y - padding.top - padding.bottom;
2653                mPortraitCellLayoutMetrics = new Rect();
2654                CellLayout.getMetrics(mPortraitCellLayoutMetrics, width, height,
2655                        LauncherModel.getCellCountX(), LauncherModel.getCellCountY());
2656            }
2657            return mPortraitCellLayoutMetrics;
2658        }
2659        return null;
2660    }
2661
2662    public void onDragExit(DragObject d) {
2663        mDragEnforcer.onDragExit();
2664
2665        // Here we store the final page that will be dropped to, if the workspace in fact
2666        // receives the drop
2667        if (mInScrollArea) {
2668            if (isPageMoving()) {
2669                // If the user drops while the page is scrolling, we should use that page as the
2670                // destination instead of the page that is being hovered over.
2671                mDropToLayout = (CellLayout) getPageAt(getNextPage());
2672            } else {
2673                mDropToLayout = mDragOverlappingLayout;
2674            }
2675        } else {
2676            mDropToLayout = mDragTargetLayout;
2677        }
2678
2679        if (mDragMode == DRAG_MODE_CREATE_FOLDER) {
2680            mCreateUserFolderOnDrop = true;
2681        } else if (mDragMode == DRAG_MODE_ADD_TO_FOLDER) {
2682            mAddToExistingFolderOnDrop = true;
2683        }
2684
2685        // Reset the scroll area and previous drag target
2686        onResetScrollArea();
2687        setCurrentDropLayout(null);
2688        setCurrentDragOverlappingLayout(null);
2689
2690        mSpringLoadedDragController.cancel();
2691
2692        if (!mIsPageMoving) {
2693            hideOutlines();
2694        }
2695    }
2696
2697    void setCurrentDropLayout(CellLayout layout) {
2698        if (mDragTargetLayout != null) {
2699            mDragTargetLayout.revertTempState();
2700            mDragTargetLayout.onDragExit();
2701        }
2702        mDragTargetLayout = layout;
2703        if (mDragTargetLayout != null) {
2704            mDragTargetLayout.onDragEnter();
2705        }
2706        cleanupReorder(true);
2707        cleanupFolderCreation();
2708        setCurrentDropOverCell(-1, -1);
2709    }
2710
2711    void setCurrentDragOverlappingLayout(CellLayout layout) {
2712        if (mDragOverlappingLayout != null) {
2713            mDragOverlappingLayout.setIsDragOverlapping(false);
2714        }
2715        mDragOverlappingLayout = layout;
2716        if (mDragOverlappingLayout != null) {
2717            mDragOverlappingLayout.setIsDragOverlapping(true);
2718        }
2719        invalidate();
2720    }
2721
2722    void setCurrentDropOverCell(int x, int y) {
2723        if (x != mDragOverX || y != mDragOverY) {
2724            mDragOverX = x;
2725            mDragOverY = y;
2726            setDragMode(DRAG_MODE_NONE);
2727        }
2728    }
2729
2730    void setDragMode(int dragMode) {
2731        if (dragMode != mDragMode) {
2732            if (dragMode == DRAG_MODE_NONE) {
2733                cleanupAddToFolder();
2734                // We don't want to cancel the re-order alarm every time the target cell changes
2735                // as this feels to slow / unresponsive.
2736                cleanupReorder(false);
2737                cleanupFolderCreation();
2738            } else if (dragMode == DRAG_MODE_ADD_TO_FOLDER) {
2739                cleanupReorder(true);
2740                cleanupFolderCreation();
2741            } else if (dragMode == DRAG_MODE_CREATE_FOLDER) {
2742                cleanupAddToFolder();
2743                cleanupReorder(true);
2744            } else if (dragMode == DRAG_MODE_REORDER) {
2745                cleanupAddToFolder();
2746                cleanupFolderCreation();
2747            }
2748            mDragMode = dragMode;
2749        }
2750    }
2751
2752    private void cleanupFolderCreation() {
2753        if (mDragFolderRingAnimator != null) {
2754            mDragFolderRingAnimator.animateToNaturalState();
2755        }
2756        mFolderCreationAlarm.cancelAlarm();
2757    }
2758
2759    private void cleanupAddToFolder() {
2760        if (mDragOverFolderIcon != null) {
2761            mDragOverFolderIcon.onDragExit(null);
2762            mDragOverFolderIcon = null;
2763        }
2764    }
2765
2766    private void cleanupReorder(boolean cancelAlarm) {
2767        // Any pending reorders are canceled
2768        if (cancelAlarm) {
2769            mReorderAlarm.cancelAlarm();
2770        }
2771        mLastReorderX = -1;
2772        mLastReorderY = -1;
2773    }
2774
2775   /*
2776    *
2777    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2778    * coordinate space. The argument xy is modified with the return result.
2779    *
2780    * if cachedInverseMatrix is not null, this method will just use that matrix instead of
2781    * computing it itself; we use this to avoid redundant matrix inversions in
2782    * findMatchingPageForDragOver
2783    *
2784    */
2785   void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) {
2786       xy[0] = xy[0] - v.getLeft();
2787       xy[1] = xy[1] - v.getTop();
2788   }
2789
2790   boolean isPointInSelfOverHotseat(int x, int y, Rect r) {
2791       if (r == null) {
2792           r = new Rect();
2793       }
2794       mTempPt[0] = x;
2795       mTempPt[1] = y;
2796       mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempPt, true);
2797       mLauncher.getHotseat().getHitRect(r);
2798       if (r.contains(mTempPt[0], mTempPt[1])) {
2799           return true;
2800       }
2801       return false;
2802   }
2803
2804   void mapPointFromSelfToHotseatLayout(Hotseat hotseat, float[] xy) {
2805       mTempPt[0] = (int) xy[0];
2806       mTempPt[1] = (int) xy[1];
2807       mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempPt, true);
2808       mLauncher.getDragLayer().mapCoordInSelfToDescendent(hotseat.getLayout(), mTempPt);
2809
2810       xy[0] = mTempPt[0];
2811       xy[1] = mTempPt[1];
2812   }
2813
2814   /*
2815    *
2816    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
2817    * the parent View's coordinate space. The argument xy is modified with the return result.
2818    *
2819    */
2820   void mapPointFromChildToSelf(View v, float[] xy) {
2821       xy[0] += v.getLeft();
2822       xy[1] += v.getTop();
2823   }
2824
2825   static private float squaredDistance(float[] point1, float[] point2) {
2826        float distanceX = point1[0] - point2[0];
2827        float distanceY = point2[1] - point2[1];
2828        return distanceX * distanceX + distanceY * distanceY;
2829   }
2830
2831    /*
2832     *
2833     * This method returns the CellLayout that is currently being dragged to. In order to drag
2834     * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
2835     * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
2836     *
2837     * Return null if no CellLayout is currently being dragged over
2838     *
2839     */
2840    private CellLayout findMatchingPageForDragOver(
2841            DragView dragView, float originX, float originY, boolean exact) {
2842        // We loop through all the screens (ie CellLayouts) and see which ones overlap
2843        // with the item being dragged and then choose the one that's closest to the touch point
2844        final int screenCount = getChildCount();
2845        CellLayout bestMatchingScreen = null;
2846        float smallestDistSoFar = Float.MAX_VALUE;
2847
2848        for (int i = 0; i < screenCount; i++) {
2849            CellLayout cl = (CellLayout) getChildAt(i);
2850
2851            final float[] touchXy = {originX, originY};
2852            // Transform the touch coordinates to the CellLayout's local coordinates
2853            // If the touch point is within the bounds of the cell layout, we can return immediately
2854            cl.getMatrix().invert(mTempInverseMatrix);
2855            mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix);
2856
2857            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
2858                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
2859                return cl;
2860            }
2861
2862            if (!exact) {
2863                // Get the center of the cell layout in screen coordinates
2864                final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
2865                cellLayoutCenter[0] = cl.getWidth()/2;
2866                cellLayoutCenter[1] = cl.getHeight()/2;
2867                mapPointFromChildToSelf(cl, cellLayoutCenter);
2868
2869                touchXy[0] = originX;
2870                touchXy[1] = originY;
2871
2872                // Calculate the distance between the center of the CellLayout
2873                // and the touch point
2874                float dist = squaredDistance(touchXy, cellLayoutCenter);
2875
2876                if (dist < smallestDistSoFar) {
2877                    smallestDistSoFar = dist;
2878                    bestMatchingScreen = cl;
2879                }
2880            }
2881        }
2882        return bestMatchingScreen;
2883    }
2884
2885    // This is used to compute the visual center of the dragView. This point is then
2886    // used to visualize drop locations and determine where to drop an item. The idea is that
2887    // the visual center represents the user's interpretation of where the item is, and hence
2888    // is the appropriate point to use when determining drop location.
2889    private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset,
2890            DragView dragView, float[] recycle) {
2891        float res[];
2892        if (recycle == null) {
2893            res = new float[2];
2894        } else {
2895            res = recycle;
2896        }
2897
2898        // First off, the drag view has been shifted in a way that is not represented in the
2899        // x and y values or the x/yOffsets. Here we account for that shift.
2900        x += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX);
2901        y += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
2902
2903        // These represent the visual top and left of drag view if a dragRect was provided.
2904        // If a dragRect was not provided, then they correspond to the actual view left and
2905        // top, as the dragRect is in that case taken to be the entire dragView.
2906        // R.dimen.dragViewOffsetY.
2907        int left = x - xOffset;
2908        int top = y - yOffset;
2909
2910        // In order to find the visual center, we shift by half the dragRect
2911        res[0] = left + dragView.getDragRegion().width() / 2;
2912        res[1] = top + dragView.getDragRegion().height() / 2;
2913
2914        return res;
2915    }
2916
2917    private boolean isDragWidget(DragObject d) {
2918        return (d.dragInfo instanceof LauncherAppWidgetInfo ||
2919                d.dragInfo instanceof PendingAddWidgetInfo);
2920    }
2921    private boolean isExternalDragWidget(DragObject d) {
2922        return d.dragSource != this && isDragWidget(d);
2923    }
2924
2925    public void onDragOver(DragObject d) {
2926        // Skip drag over events while we are dragging over side pages
2927        if (mInScrollArea || mIsSwitchingState || mState == State.SMALL) return;
2928
2929        Rect r = new Rect();
2930        CellLayout layout = null;
2931        ItemInfo item = (ItemInfo) d.dragInfo;
2932
2933        // Ensure that we have proper spans for the item that we are dropping
2934        if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found");
2935        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
2936            d.dragView, mDragViewVisualCenter);
2937
2938        final View child = (mDragInfo == null) ? null : mDragInfo.cell;
2939        // Identify whether we have dragged over a side page
2940        if (isSmall()) {
2941            if (mLauncher.getHotseat() != null && !isExternalDragWidget(d)) {
2942                if (isPointInSelfOverHotseat(d.x, d.y, r)) {
2943                    layout = mLauncher.getHotseat().getLayout();
2944                }
2945            }
2946            if (layout == null) {
2947                layout = findMatchingPageForDragOver(d.dragView, d.x, d.y, false);
2948            }
2949            if (layout != mDragTargetLayout) {
2950                setCurrentDropLayout(layout);
2951                setCurrentDragOverlappingLayout(layout);
2952
2953                boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED);
2954                if (isInSpringLoadedMode) {
2955                    if (mLauncher.isHotseatLayout(layout)) {
2956                        mSpringLoadedDragController.cancel();
2957                    } else {
2958                        mSpringLoadedDragController.setAlarm(mDragTargetLayout);
2959                    }
2960                }
2961            }
2962        } else {
2963            // Test to see if we are over the hotseat otherwise just use the current page
2964            if (mLauncher.getHotseat() != null && !isDragWidget(d)) {
2965                if (isPointInSelfOverHotseat(d.x, d.y, r)) {
2966                    layout = mLauncher.getHotseat().getLayout();
2967                }
2968            }
2969            if (layout == null) {
2970                layout = getCurrentDropLayout();
2971            }
2972            if (layout != mDragTargetLayout) {
2973                setCurrentDropLayout(layout);
2974                setCurrentDragOverlappingLayout(layout);
2975            }
2976        }
2977
2978        // Handle the drag over
2979        if (mDragTargetLayout != null) {
2980            // We want the point to be mapped to the dragTarget.
2981            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
2982                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
2983            } else {
2984                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
2985            }
2986
2987            ItemInfo info = (ItemInfo) d.dragInfo;
2988
2989            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2990                    (int) mDragViewVisualCenter[1], item.spanX, item.spanY,
2991                    mDragTargetLayout, mTargetCell);
2992
2993            setCurrentDropOverCell(mTargetCell[0], mTargetCell[1]);
2994
2995            float targetCellDistance = mDragTargetLayout.getDistanceFromCell(
2996                    mDragViewVisualCenter[0], mDragViewVisualCenter[1], mTargetCell);
2997
2998            final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0],
2999                    mTargetCell[1]);
3000
3001            manageFolderFeedback(info, mDragTargetLayout, mTargetCell,
3002                    targetCellDistance, dragOverView);
3003
3004            int minSpanX = item.spanX;
3005            int minSpanY = item.spanY;
3006            if (item.minSpanX > 0 && item.minSpanY > 0) {
3007                minSpanX = item.minSpanX;
3008                minSpanY = item.minSpanY;
3009            }
3010
3011            boolean nearestDropOccupied = mDragTargetLayout.isNearestDropLocationOccupied((int)
3012                    mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], item.spanX,
3013                    item.spanY, child, mTargetCell);
3014
3015            if (!nearestDropOccupied) {
3016                mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
3017                        (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
3018                        mTargetCell[0], mTargetCell[1], item.spanX, item.spanY, false,
3019                        d.dragView.getDragVisualizeOffset(), d.dragView.getDragRegion());
3020            } else if ((mDragMode == DRAG_MODE_NONE || mDragMode == DRAG_MODE_REORDER)
3021                    && !mReorderAlarm.alarmPending() && (mLastReorderX != mTargetCell[0] ||
3022                    mLastReorderY != mTargetCell[1])) {
3023
3024                // Otherwise, if we aren't adding to or creating a folder and there's no pending
3025                // reorder, then we schedule a reorder
3026                ReorderAlarmListener listener = new ReorderAlarmListener(mDragViewVisualCenter,
3027                        minSpanX, minSpanY, item.spanX, item.spanY, d.dragView, child);
3028                mReorderAlarm.setOnAlarmListener(listener);
3029                mReorderAlarm.setAlarm(REORDER_TIMEOUT);
3030            }
3031
3032            if (mDragMode == DRAG_MODE_CREATE_FOLDER || mDragMode == DRAG_MODE_ADD_TO_FOLDER ||
3033                    !nearestDropOccupied) {
3034                if (mDragTargetLayout != null) {
3035                    mDragTargetLayout.revertTempState();
3036                }
3037            }
3038        }
3039    }
3040
3041    private void manageFolderFeedback(ItemInfo info, CellLayout targetLayout,
3042            int[] targetCell, float distance, View dragOverView) {
3043        boolean userFolderPending = willCreateUserFolder(info, targetLayout, targetCell, distance,
3044                false);
3045
3046        if (mDragMode == DRAG_MODE_NONE && userFolderPending &&
3047                !mFolderCreationAlarm.alarmPending()) {
3048            mFolderCreationAlarm.setOnAlarmListener(new
3049                    FolderCreationAlarmListener(targetLayout, targetCell[0], targetCell[1]));
3050            mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT);
3051            return;
3052        }
3053
3054        boolean willAddToFolder =
3055                willAddToExistingUserFolder(info, targetLayout, targetCell, distance);
3056
3057        if (willAddToFolder && mDragMode == DRAG_MODE_NONE) {
3058            mDragOverFolderIcon = ((FolderIcon) dragOverView);
3059            mDragOverFolderIcon.onDragEnter(info);
3060            if (targetLayout != null) {
3061                targetLayout.clearDragOutlines();
3062            }
3063            setDragMode(DRAG_MODE_ADD_TO_FOLDER);
3064            return;
3065        }
3066
3067        if (mDragMode == DRAG_MODE_ADD_TO_FOLDER && !willAddToFolder) {
3068            setDragMode(DRAG_MODE_NONE);
3069        }
3070        if (mDragMode == DRAG_MODE_CREATE_FOLDER && !userFolderPending) {
3071            setDragMode(DRAG_MODE_NONE);
3072        }
3073
3074        return;
3075    }
3076
3077    class FolderCreationAlarmListener implements OnAlarmListener {
3078        CellLayout layout;
3079        int cellX;
3080        int cellY;
3081
3082        public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) {
3083            this.layout = layout;
3084            this.cellX = cellX;
3085            this.cellY = cellY;
3086        }
3087
3088        public void onAlarm(Alarm alarm) {
3089            if (mDragFolderRingAnimator == null) {
3090                mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null);
3091            }
3092            mDragFolderRingAnimator.setCell(cellX, cellY);
3093            mDragFolderRingAnimator.setCellLayout(layout);
3094            mDragFolderRingAnimator.animateToAcceptState();
3095            layout.showFolderAccept(mDragFolderRingAnimator);
3096            layout.clearDragOutlines();
3097            setDragMode(DRAG_MODE_CREATE_FOLDER);
3098        }
3099    }
3100
3101    class ReorderAlarmListener implements OnAlarmListener {
3102        float[] dragViewCenter;
3103        int minSpanX, minSpanY, spanX, spanY;
3104        DragView dragView;
3105        View child;
3106
3107        public ReorderAlarmListener(float[] dragViewCenter, int minSpanX, int minSpanY, int spanX,
3108                int spanY, DragView dragView, View child) {
3109            this.dragViewCenter = dragViewCenter;
3110            this.minSpanX = minSpanX;
3111            this.minSpanY = minSpanY;
3112            this.spanX = spanX;
3113            this.spanY = spanY;
3114            this.child = child;
3115            this.dragView = dragView;
3116        }
3117
3118        public void onAlarm(Alarm alarm) {
3119            int[] resultSpan = new int[2];
3120            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
3121                    (int) mDragViewVisualCenter[1], spanX, spanY, mDragTargetLayout, mTargetCell);
3122            mLastReorderX = mTargetCell[0];
3123            mLastReorderY = mTargetCell[1];
3124
3125            mTargetCell = mDragTargetLayout.createArea((int) mDragViewVisualCenter[0],
3126                (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY,
3127                child, mTargetCell, resultSpan, CellLayout.MODE_DRAG_OVER);
3128
3129            if (mTargetCell[0] < 0 || mTargetCell[1] < 0) {
3130                mDragTargetLayout.revertTempState();
3131            } else {
3132                setDragMode(DRAG_MODE_REORDER);
3133            }
3134
3135            boolean resize = resultSpan[0] != spanX || resultSpan[1] != spanY;
3136            mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
3137                (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
3138                mTargetCell[0], mTargetCell[1], resultSpan[0], resultSpan[1], resize,
3139                dragView.getDragVisualizeOffset(), dragView.getDragRegion());
3140        }
3141    }
3142
3143    @Override
3144    public void getHitRectRelativeToDragLayer(Rect outRect) {
3145        // We want the workspace to have the whole area of the display (it will find the correct
3146        // cell layout to drop to in the existing drag/drop logic.
3147        mLauncher.getDragLayer().getDescendantRectRelativeToSelf(this, outRect);
3148    }
3149
3150    /**
3151     * Add the item specified by dragInfo to the given layout.
3152     * @return true if successful
3153     */
3154    public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) {
3155        if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) {
3156            onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false);
3157            return true;
3158        }
3159        mLauncher.showOutOfSpaceMessage(mLauncher.isHotseatLayout(layout));
3160        return false;
3161    }
3162
3163    private void onDropExternal(int[] touchXY, Object dragInfo,
3164            CellLayout cellLayout, boolean insertAtFirst) {
3165        onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null);
3166    }
3167
3168    /**
3169     * Drop an item that didn't originate on one of the workspace screens.
3170     * It may have come from Launcher (e.g. from all apps or customize), or it may have
3171     * come from another app altogether.
3172     *
3173     * NOTE: This can also be called when we are outside of a drag event, when we want
3174     * to add an item to one of the workspace screens.
3175     */
3176    private void onDropExternal(final int[] touchXY, final Object dragInfo,
3177            final CellLayout cellLayout, boolean insertAtFirst, DragObject d) {
3178        final Runnable exitSpringLoadedRunnable = new Runnable() {
3179            @Override
3180            public void run() {
3181                mLauncher.exitSpringLoadedDragModeDelayed(true, false, null);
3182            }
3183        };
3184
3185        ItemInfo info = (ItemInfo) dragInfo;
3186        int spanX = info.spanX;
3187        int spanY = info.spanY;
3188        if (mDragInfo != null) {
3189            spanX = mDragInfo.spanX;
3190            spanY = mDragInfo.spanY;
3191        }
3192
3193        final long container = mLauncher.isHotseatLayout(cellLayout) ?
3194                LauncherSettings.Favorites.CONTAINER_HOTSEAT :
3195                    LauncherSettings.Favorites.CONTAINER_DESKTOP;
3196        final long screenId = getIdForScreen(cellLayout);
3197        if (!mLauncher.isHotseatLayout(cellLayout)
3198                && screenId != getScreenIdForPageIndex(mCurrentPage)
3199                && mState != State.SPRING_LOADED) {
3200            snapToScreenId(screenId, null);
3201        }
3202
3203        if (info instanceof PendingAddItemInfo) {
3204            final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo;
3205
3206            boolean findNearestVacantCell = true;
3207            if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
3208                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
3209                        cellLayout, mTargetCell);
3210                float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0],
3211                        mDragViewVisualCenter[1], mTargetCell);
3212                if (willCreateUserFolder((ItemInfo) d.dragInfo, cellLayout, mTargetCell,
3213                        distance, true) || willAddToExistingUserFolder((ItemInfo) d.dragInfo,
3214                                cellLayout, mTargetCell, distance)) {
3215                    findNearestVacantCell = false;
3216                }
3217            }
3218
3219            final ItemInfo item = (ItemInfo) d.dragInfo;
3220            boolean updateWidgetSize = false;
3221            if (findNearestVacantCell) {
3222                int minSpanX = item.spanX;
3223                int minSpanY = item.spanY;
3224                if (item.minSpanX > 0 && item.minSpanY > 0) {
3225                    minSpanX = item.minSpanX;
3226                    minSpanY = item.minSpanY;
3227                }
3228                int[] resultSpan = new int[2];
3229                mTargetCell = cellLayout.createArea((int) mDragViewVisualCenter[0],
3230                        (int) mDragViewVisualCenter[1], minSpanX, minSpanY, info.spanX, info.spanY,
3231                        null, mTargetCell, resultSpan, CellLayout.MODE_ON_DROP_EXTERNAL);
3232
3233                if (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY) {
3234                    updateWidgetSize = true;
3235                }
3236                item.spanX = resultSpan[0];
3237                item.spanY = resultSpan[1];
3238            }
3239
3240            Runnable onAnimationCompleteRunnable = new Runnable() {
3241                @Override
3242                public void run() {
3243                    // When dragging and dropping from customization tray, we deal with creating
3244                    // widgets/shortcuts/folders in a slightly different way
3245                    switch (pendingInfo.itemType) {
3246                    case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
3247                        int span[] = new int[2];
3248                        span[0] = item.spanX;
3249                        span[1] = item.spanY;
3250                        mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) pendingInfo,
3251                                container, screenId, mTargetCell, span, null);
3252                        break;
3253                    case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3254                        mLauncher.processShortcutFromDrop(pendingInfo.componentName,
3255                                container, screenId, mTargetCell, null);
3256                        break;
3257                    default:
3258                        throw new IllegalStateException("Unknown item type: " +
3259                                pendingInfo.itemType);
3260                    }
3261                }
3262            };
3263            View finalView = pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET
3264                    ? ((PendingAddWidgetInfo) pendingInfo).boundWidget : null;
3265
3266            if (finalView instanceof AppWidgetHostView && updateWidgetSize) {
3267                AppWidgetHostView awhv = (AppWidgetHostView) finalView;
3268                AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, item.spanX,
3269                        item.spanY);
3270            }
3271
3272            int animationStyle = ANIMATE_INTO_POSITION_AND_DISAPPEAR;
3273            if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
3274                    ((PendingAddWidgetInfo) pendingInfo).info.configure != null) {
3275                animationStyle = ANIMATE_INTO_POSITION_AND_REMAIN;
3276            }
3277            animateWidgetDrop(info, cellLayout, d.dragView, onAnimationCompleteRunnable,
3278                    animationStyle, finalView, true);
3279        } else {
3280            // This is for other drag/drop cases, like dragging from All Apps
3281            View view = null;
3282
3283            switch (info.itemType) {
3284            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
3285            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3286                if (info.container == NO_ID && info instanceof ApplicationInfo) {
3287                    // Came from all apps -- make a copy
3288                    info = new ShortcutInfo((ApplicationInfo) info);
3289                }
3290                view = mLauncher.createShortcut(R.layout.application, cellLayout,
3291                        (ShortcutInfo) info);
3292                break;
3293            case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
3294                view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout,
3295                        (FolderInfo) info, mIconCache);
3296                break;
3297            default:
3298                throw new IllegalStateException("Unknown item type: " + info.itemType);
3299            }
3300
3301            // First we find the cell nearest to point at which the item is
3302            // dropped, without any consideration to whether there is an item there.
3303            if (touchXY != null) {
3304                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
3305                        cellLayout, mTargetCell);
3306                float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0],
3307                        mDragViewVisualCenter[1], mTargetCell);
3308                d.postAnimationRunnable = exitSpringLoadedRunnable;
3309                if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, distance,
3310                        true, d.dragView, d.postAnimationRunnable)) {
3311                    return;
3312                }
3313                if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, distance, d,
3314                        true)) {
3315                    return;
3316                }
3317            }
3318
3319            if (touchXY != null) {
3320                // when dragging and dropping, just find the closest free spot
3321                mTargetCell = cellLayout.createArea((int) mDragViewVisualCenter[0],
3322                        (int) mDragViewVisualCenter[1], 1, 1, 1, 1,
3323                        null, mTargetCell, null, CellLayout.MODE_ON_DROP_EXTERNAL);
3324            } else {
3325                cellLayout.findCellForSpan(mTargetCell, 1, 1);
3326            }
3327            addInScreen(view, container, screenId, mTargetCell[0], mTargetCell[1], info.spanX,
3328                    info.spanY, insertAtFirst);
3329            cellLayout.onDropChild(view);
3330            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
3331            cellLayout.getShortcutsAndWidgets().measureChild(view);
3332
3333            LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screenId,
3334                    lp.cellX, lp.cellY);
3335
3336            if (d.dragView != null) {
3337                // We wrap the animation call in the temporary set and reset of the current
3338                // cellLayout to its final transform -- this means we animate the drag view to
3339                // the correct final location.
3340                setFinalTransitionTransform(cellLayout);
3341                mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view,
3342                        exitSpringLoadedRunnable);
3343                resetTransitionTransform(cellLayout);
3344            }
3345        }
3346    }
3347
3348    public Bitmap createWidgetBitmap(ItemInfo widgetInfo, View layout) {
3349        int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(widgetInfo.spanX,
3350                widgetInfo.spanY, widgetInfo, false);
3351        int visibility = layout.getVisibility();
3352        layout.setVisibility(VISIBLE);
3353
3354        int width = MeasureSpec.makeMeasureSpec(unScaledSize[0], MeasureSpec.EXACTLY);
3355        int height = MeasureSpec.makeMeasureSpec(unScaledSize[1], MeasureSpec.EXACTLY);
3356        Bitmap b = Bitmap.createBitmap(unScaledSize[0], unScaledSize[1],
3357                Bitmap.Config.ARGB_8888);
3358        Canvas c = new Canvas(b);
3359
3360        layout.measure(width, height);
3361        layout.layout(0, 0, unScaledSize[0], unScaledSize[1]);
3362        layout.draw(c);
3363        c.setBitmap(null);
3364        layout.setVisibility(visibility);
3365        return b;
3366    }
3367
3368    private void getFinalPositionForDropAnimation(int[] loc, float[] scaleXY,
3369            DragView dragView, CellLayout layout, ItemInfo info, int[] targetCell,
3370            boolean external, boolean scale) {
3371        // Now we animate the dragView, (ie. the widget or shortcut preview) into its final
3372        // location and size on the home screen.
3373        int spanX = info.spanX;
3374        int spanY = info.spanY;
3375
3376        Rect r = estimateItemPosition(layout, info, targetCell[0], targetCell[1], spanX, spanY);
3377        loc[0] = r.left;
3378        loc[1] = r.top;
3379
3380        setFinalTransitionTransform(layout);
3381        float cellLayoutScale =
3382                mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(layout, loc, true);
3383        resetTransitionTransform(layout);
3384
3385        float dragViewScaleX;
3386        float dragViewScaleY;
3387        if (scale) {
3388            dragViewScaleX = (1.0f * r.width()) / dragView.getMeasuredWidth();
3389            dragViewScaleY = (1.0f * r.height()) / dragView.getMeasuredHeight();
3390        } else {
3391            dragViewScaleX = 1f;
3392            dragViewScaleY = 1f;
3393        }
3394
3395        // The animation will scale the dragView about its center, so we need to center about
3396        // the final location.
3397        loc[0] -= (dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2;
3398        loc[1] -= (dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2;
3399
3400        scaleXY[0] = dragViewScaleX * cellLayoutScale;
3401        scaleXY[1] = dragViewScaleY * cellLayoutScale;
3402    }
3403
3404    public void animateWidgetDrop(ItemInfo info, CellLayout cellLayout, DragView dragView,
3405            final Runnable onCompleteRunnable, int animationType, final View finalView,
3406            boolean external) {
3407        Rect from = new Rect();
3408        mLauncher.getDragLayer().getViewRectRelativeToSelf(dragView, from);
3409
3410        int[] finalPos = new int[2];
3411        float scaleXY[] = new float[2];
3412        boolean scalePreview = !(info instanceof PendingAddShortcutInfo);
3413        getFinalPositionForDropAnimation(finalPos, scaleXY, dragView, cellLayout, info, mTargetCell,
3414                external, scalePreview);
3415
3416        Resources res = mLauncher.getResources();
3417        int duration = res.getInteger(R.integer.config_dropAnimMaxDuration) - 200;
3418
3419        // In the case where we've prebound the widget, we remove it from the DragLayer
3420        if (finalView instanceof AppWidgetHostView && external) {
3421            Log.d(TAG, "6557954 Animate widget drop, final view is appWidgetHostView");
3422            mLauncher.getDragLayer().removeView(finalView);
3423        }
3424        if ((animationType == ANIMATE_INTO_POSITION_AND_RESIZE || external) && finalView != null) {
3425            Bitmap crossFadeBitmap = createWidgetBitmap(info, finalView);
3426            dragView.setCrossFadeBitmap(crossFadeBitmap);
3427            dragView.crossFade((int) (duration * 0.8f));
3428        } else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET && external) {
3429            scaleXY[0] = scaleXY[1] = Math.min(scaleXY[0],  scaleXY[1]);
3430        }
3431
3432        DragLayer dragLayer = mLauncher.getDragLayer();
3433        if (animationType == CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION) {
3434            mLauncher.getDragLayer().animateViewIntoPosition(dragView, finalPos, 0f, 0.1f, 0.1f,
3435                    DragLayer.ANIMATION_END_DISAPPEAR, onCompleteRunnable, duration);
3436        } else {
3437            int endStyle;
3438            if (animationType == ANIMATE_INTO_POSITION_AND_REMAIN) {
3439                endStyle = DragLayer.ANIMATION_END_REMAIN_VISIBLE;
3440            } else {
3441                endStyle = DragLayer.ANIMATION_END_DISAPPEAR;;
3442            }
3443
3444            Runnable onComplete = new Runnable() {
3445                @Override
3446                public void run() {
3447                    if (finalView != null) {
3448                        finalView.setVisibility(VISIBLE);
3449                    }
3450                    if (onCompleteRunnable != null) {
3451                        onCompleteRunnable.run();
3452                    }
3453                }
3454            };
3455            dragLayer.animateViewIntoPosition(dragView, from.left, from.top, finalPos[0],
3456                    finalPos[1], 1, 1, 1, scaleXY[0], scaleXY[1], onComplete, endStyle,
3457                    duration, this);
3458        }
3459    }
3460
3461    public void setFinalTransitionTransform(CellLayout layout) {
3462        if (isSwitchingState()) {
3463            mCurrentScale = getScaleX();
3464            setScaleX(mNewScale);
3465            setScaleY(mNewScale);
3466        }
3467    }
3468    public void resetTransitionTransform(CellLayout layout) {
3469        if (isSwitchingState()) {
3470            setScaleX(mCurrentScale);
3471            setScaleY(mCurrentScale);
3472        }
3473    }
3474
3475    /**
3476     * Return the current {@link CellLayout}, correctly picking the destination
3477     * screen while a scroll is in progress.
3478     */
3479    public CellLayout getCurrentDropLayout() {
3480        return (CellLayout) getChildAt(getNextPage());
3481    }
3482
3483    /**
3484     * Return the current CellInfo describing our current drag; this method exists
3485     * so that Launcher can sync this object with the correct info when the activity is created/
3486     * destroyed
3487     *
3488     */
3489    public CellLayout.CellInfo getDragInfo() {
3490        return mDragInfo;
3491    }
3492
3493    /**
3494     * Calculate the nearest cell where the given object would be dropped.
3495     *
3496     * pixelX and pixelY should be in the coordinate system of layout
3497     */
3498    private int[] findNearestArea(int pixelX, int pixelY,
3499            int spanX, int spanY, CellLayout layout, int[] recycle) {
3500        return layout.findNearestArea(
3501                pixelX, pixelY, spanX, spanY, recycle);
3502    }
3503
3504    void setup(DragController dragController) {
3505        mSpringLoadedDragController = new SpringLoadedDragController(mLauncher);
3506        mDragController = dragController;
3507
3508        // hardware layers on children are enabled on startup, but should be disabled until
3509        // needed
3510        updateChildrenLayersEnabled(false);
3511        setWallpaperDimension();
3512    }
3513
3514    /**
3515     * Called at the end of a drag which originated on the workspace.
3516     */
3517    public void onDropCompleted(final View target, final DragObject d,
3518            final boolean isFlingToDelete, final boolean success) {
3519        if (mDeferDropAfterUninstall) {
3520            mDeferredAction = new Runnable() {
3521                    public void run() {
3522                        onDropCompleted(target, d, isFlingToDelete, success);
3523                        mDeferredAction = null;
3524                    }
3525                };
3526            return;
3527        }
3528
3529        boolean beingCalledAfterUninstall = mDeferredAction != null;
3530
3531        if (success && !(beingCalledAfterUninstall && !mUninstallSuccessful)) {
3532            if (target != this && mDragInfo != null) {
3533                getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
3534                if (mDragInfo.cell instanceof DropTarget) {
3535                    mDragController.removeDropTarget((DropTarget) mDragInfo.cell);
3536                }
3537                // If we move the item to anything not on the Workspace, check if any empty
3538                // screens need to be removed. If we dropped back on the workspace, this will
3539                // be done post drop animation.
3540                stripEmptyScreens();
3541            }
3542        } else if (mDragInfo != null) {
3543            CellLayout cellLayout;
3544            if (mLauncher.isHotseatLayout(target)) {
3545                cellLayout = mLauncher.getHotseat().getLayout();
3546            } else {
3547                cellLayout = getScreenWithId(mDragInfo.screenId);
3548            }
3549            cellLayout.onDropChild(mDragInfo.cell);
3550        }
3551        if ((d.cancelled || (beingCalledAfterUninstall && !mUninstallSuccessful))
3552                && mDragInfo.cell != null) {
3553            mDragInfo.cell.setVisibility(VISIBLE);
3554        }
3555        mDragOutline = null;
3556        mDragInfo = null;
3557    }
3558
3559    public void deferCompleteDropAfterUninstallActivity() {
3560        mDeferDropAfterUninstall = true;
3561    }
3562
3563    /// maybe move this into a smaller part
3564    public void onUninstallActivityReturned(boolean success) {
3565        mDeferDropAfterUninstall = false;
3566        mUninstallSuccessful = success;
3567        if (mDeferredAction != null) {
3568            mDeferredAction.run();
3569        }
3570    }
3571
3572    void updateItemLocationsInDatabase(CellLayout cl) {
3573        int count = cl.getShortcutsAndWidgets().getChildCount();
3574
3575        long screenId = getIdForScreen(cl);
3576        int container = Favorites.CONTAINER_DESKTOP;
3577
3578        if (mLauncher.isHotseatLayout(cl)) {
3579            screenId = -1;
3580            container = Favorites.CONTAINER_HOTSEAT;
3581        }
3582
3583        for (int i = 0; i < count; i++) {
3584            View v = cl.getShortcutsAndWidgets().getChildAt(i);
3585            ItemInfo info = (ItemInfo) v.getTag();
3586            // Null check required as the AllApps button doesn't have an item info
3587            if (info != null && info.requiresDbUpdate) {
3588                info.requiresDbUpdate = false;
3589                LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId, info.cellX,
3590                        info.cellY, info.spanX, info.spanY);
3591            }
3592        }
3593    }
3594
3595    ArrayList<ComponentName> stripDuplicateApps() {
3596        ArrayList<ComponentName> uniqueIntents = new ArrayList<ComponentName>();
3597        stripDuplicateApps((CellLayout) mLauncher.getHotseat().getLayout(), uniqueIntents);
3598        int count = getChildCount();
3599        for (int i = 0; i < count; i++) {
3600            CellLayout cl = (CellLayout) getChildAt(i);
3601            stripDuplicateApps(cl, uniqueIntents);
3602        }
3603        return uniqueIntents;
3604    }
3605
3606    void stripDuplicateApps(CellLayout cl, ArrayList<ComponentName> uniqueIntents) {
3607        int count = cl.getShortcutsAndWidgets().getChildCount();
3608
3609        ArrayList<View> children = new ArrayList<View>();
3610        for (int i = 0; i < count; i++) {
3611            View v = cl.getShortcutsAndWidgets().getChildAt(i);
3612            children.add(v);
3613        }
3614
3615        for (int i = 0; i < count; i++) {
3616            View v = children.get(i);
3617            ItemInfo info = (ItemInfo) v.getTag();
3618            // Null check required as the AllApps button doesn't have an item info
3619            if (info instanceof ShortcutInfo) {
3620                ShortcutInfo si = (ShortcutInfo) info;
3621                ComponentName cn = si.intent.getComponent();
3622
3623                if (si.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
3624                    continue;
3625                }
3626
3627                if (!uniqueIntents.contains(cn)) {
3628                    uniqueIntents.add(cn);
3629                } else {
3630                    cl.removeViewInLayout(v);
3631                    LauncherModel.deleteItemFromDatabase(mLauncher, si);
3632                }
3633            }
3634            if (v instanceof FolderIcon) {
3635                FolderIcon fi = (FolderIcon) v;
3636                ArrayList<View> items = fi.getFolder().getItemsInReadingOrder();
3637                for (int j = 0; j < items.size(); j++) {
3638                    if (items.get(j).getTag() instanceof ShortcutInfo) {
3639                        ShortcutInfo si = (ShortcutInfo) items.get(j).getTag();
3640                        ComponentName cn = si.intent.getComponent();
3641
3642                        if (si.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
3643                            continue;
3644                        }
3645                        if (!uniqueIntents.contains(cn)) {
3646                            uniqueIntents.add(cn);
3647                        } else {
3648                            fi.getFolderInfo().remove(si);
3649                            LauncherModel.deleteItemFromDatabase(mLauncher, si);
3650                        }
3651                    }
3652                }
3653            }
3654        }
3655    }
3656
3657    void saveWorkspaceToDb() {
3658        saveWorkspaceScreenToDb((CellLayout) mLauncher.getHotseat().getLayout());
3659        int count = getChildCount();
3660        for (int i = 0; i < count; i++) {
3661            CellLayout cl = (CellLayout) getChildAt(i);
3662            saveWorkspaceScreenToDb(cl);
3663        }
3664    }
3665
3666    void saveWorkspaceScreenToDb(CellLayout cl) {
3667        int count = cl.getShortcutsAndWidgets().getChildCount();
3668
3669        long screenId = getIdForScreen(cl);
3670        int container = Favorites.CONTAINER_DESKTOP;
3671
3672        Hotseat hotseat = mLauncher.getHotseat();
3673        if (mLauncher.isHotseatLayout(cl)) {
3674            screenId = -1;
3675            container = Favorites.CONTAINER_HOTSEAT;
3676        }
3677
3678        for (int i = 0; i < count; i++) {
3679            View v = cl.getShortcutsAndWidgets().getChildAt(i);
3680            ItemInfo info = (ItemInfo) v.getTag();
3681            // Null check required as the AllApps button doesn't have an item info
3682            if (info != null) {
3683                int cellX = info.cellX;
3684                int cellY = info.cellY;
3685                if (container == Favorites.CONTAINER_HOTSEAT) {
3686                    cellX = hotseat.getCellXFromOrder((int) info.screenId);
3687                    cellY = hotseat.getCellYFromOrder((int) info.screenId);
3688                }
3689                LauncherModel.addItemToDatabase(mLauncher, info, container, screenId, cellX,
3690                        cellY, false);
3691            }
3692            if (v instanceof FolderIcon) {
3693                FolderIcon fi = (FolderIcon) v;
3694                fi.getFolder().addItemLocationsInDatabase();
3695            }
3696        }
3697    }
3698
3699    @Override
3700    public boolean supportsFlingToDelete() {
3701        return true;
3702    }
3703
3704    @Override
3705    public void onFlingToDelete(DragObject d, int x, int y, PointF vec) {
3706        // Do nothing
3707    }
3708
3709    @Override
3710    public void onFlingToDeleteCompleted() {
3711        // Do nothing
3712    }
3713
3714    public boolean isDropEnabled() {
3715        return true;
3716    }
3717
3718    @Override
3719    protected void onRestoreInstanceState(Parcelable state) {
3720        super.onRestoreInstanceState(state);
3721        Launcher.setScreen(mCurrentPage);
3722    }
3723
3724    @Override
3725    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
3726        // We don't dispatch restoreInstanceState to our children using this code path.
3727        // Some pages will be restored immediately as their items are bound immediately, and
3728        // others we will need to wait until after their items are bound.
3729        mSavedStates = container;
3730    }
3731
3732    public void restoreInstanceStateForChild(int child) {
3733        if (mSavedStates != null) {
3734            mRestoredPages.add(child);
3735            CellLayout cl = (CellLayout) getChildAt(child);
3736            cl.restoreInstanceState(mSavedStates);
3737        }
3738    }
3739
3740    public void restoreInstanceStateForRemainingPages() {
3741        int count = getChildCount();
3742        for (int i = 0; i < count; i++) {
3743            if (!mRestoredPages.contains(i)) {
3744                restoreInstanceStateForChild(i);
3745            }
3746        }
3747        mRestoredPages.clear();
3748    }
3749
3750    @Override
3751    public void scrollLeft() {
3752        if (!isSmall() && !mIsSwitchingState) {
3753            super.scrollLeft();
3754        }
3755        Folder openFolder = getOpenFolder();
3756        if (openFolder != null) {
3757            openFolder.completeDragExit();
3758        }
3759    }
3760
3761    @Override
3762    public void scrollRight() {
3763        if (!isSmall() && !mIsSwitchingState) {
3764            super.scrollRight();
3765        }
3766        Folder openFolder = getOpenFolder();
3767        if (openFolder != null) {
3768            openFolder.completeDragExit();
3769        }
3770    }
3771
3772    @Override
3773    public boolean onEnterScrollArea(int x, int y, int direction) {
3774        // Ignore the scroll area if we are dragging over the hot seat
3775        boolean isPortrait = !LauncherAppState.isScreenLandscape(getContext());
3776        if (mLauncher.getHotseat() != null && isPortrait) {
3777            Rect r = new Rect();
3778            mLauncher.getHotseat().getHitRect(r);
3779            if (r.contains(x, y)) {
3780                return false;
3781            }
3782        }
3783
3784        boolean result = false;
3785        if (!isSmall() && !mIsSwitchingState && getOpenFolder() == null) {
3786            mInScrollArea = true;
3787
3788            final int page = getNextPage() +
3789                       (direction == DragController.SCROLL_LEFT ? -1 : 1);
3790            // We always want to exit the current layout to ensure parity of enter / exit
3791            setCurrentDropLayout(null);
3792
3793            if (0 <= page && page < getChildCount()) {
3794                // Ensure that we are not dragging over to the custom content screen
3795                if (getScreenIdForPageIndex(page) == CUSTOM_CONTENT_SCREEN_ID) {
3796                    return false;
3797                }
3798
3799                CellLayout layout = (CellLayout) getChildAt(page);
3800                setCurrentDragOverlappingLayout(layout);
3801
3802                // Workspace is responsible for drawing the edge glow on adjacent pages,
3803                // so we need to redraw the workspace when this may have changed.
3804                invalidate();
3805                result = true;
3806            }
3807        }
3808        return result;
3809    }
3810
3811    @Override
3812    public boolean onExitScrollArea() {
3813        boolean result = false;
3814        if (mInScrollArea) {
3815            invalidate();
3816            CellLayout layout = getCurrentDropLayout();
3817            setCurrentDropLayout(layout);
3818            setCurrentDragOverlappingLayout(layout);
3819
3820            result = true;
3821            mInScrollArea = false;
3822        }
3823        return result;
3824    }
3825
3826    private void onResetScrollArea() {
3827        setCurrentDragOverlappingLayout(null);
3828        mInScrollArea = false;
3829    }
3830
3831    /**
3832     * Returns a specific CellLayout
3833     */
3834    CellLayout getParentCellLayoutForView(View v) {
3835        ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts();
3836        for (CellLayout layout : layouts) {
3837            if (layout.getShortcutsAndWidgets().indexOfChild(v) > -1) {
3838                return layout;
3839            }
3840        }
3841        return null;
3842    }
3843
3844    /**
3845     * Returns a list of all the CellLayouts in the workspace.
3846     */
3847    ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() {
3848        ArrayList<CellLayout> layouts = new ArrayList<CellLayout>();
3849        int screenCount = getChildCount();
3850        for (int screen = 0; screen < screenCount; screen++) {
3851            layouts.add(((CellLayout) getChildAt(screen)));
3852        }
3853        if (mLauncher.getHotseat() != null) {
3854            layouts.add(mLauncher.getHotseat().getLayout());
3855        }
3856        return layouts;
3857    }
3858
3859    /**
3860     * We should only use this to search for specific children.  Do not use this method to modify
3861     * ShortcutsAndWidgetsContainer directly. Includes ShortcutAndWidgetContainers from
3862     * the hotseat and workspace pages
3863     */
3864    ArrayList<ShortcutAndWidgetContainer> getAllShortcutAndWidgetContainers() {
3865        ArrayList<ShortcutAndWidgetContainer> childrenLayouts =
3866                new ArrayList<ShortcutAndWidgetContainer>();
3867        int screenCount = getChildCount();
3868        for (int screen = 0; screen < screenCount; screen++) {
3869            childrenLayouts.add(((CellLayout) getChildAt(screen)).getShortcutsAndWidgets());
3870        }
3871        if (mLauncher.getHotseat() != null) {
3872            childrenLayouts.add(mLauncher.getHotseat().getLayout().getShortcutsAndWidgets());
3873        }
3874        return childrenLayouts;
3875    }
3876
3877    public Folder getFolderForTag(Object tag) {
3878        ArrayList<ShortcutAndWidgetContainer> childrenLayouts =
3879                getAllShortcutAndWidgetContainers();
3880        for (ShortcutAndWidgetContainer layout: childrenLayouts) {
3881            int count = layout.getChildCount();
3882            for (int i = 0; i < count; i++) {
3883                View child = layout.getChildAt(i);
3884                if (child instanceof Folder) {
3885                    Folder f = (Folder) child;
3886                    if (f.getInfo() == tag && f.getInfo().opened) {
3887                        return f;
3888                    }
3889                }
3890            }
3891        }
3892        return null;
3893    }
3894
3895    public View getViewForTag(Object tag) {
3896        ArrayList<ShortcutAndWidgetContainer> childrenLayouts =
3897                getAllShortcutAndWidgetContainers();
3898        for (ShortcutAndWidgetContainer layout: childrenLayouts) {
3899            int count = layout.getChildCount();
3900            for (int i = 0; i < count; i++) {
3901                View child = layout.getChildAt(i);
3902                if (child.getTag() == tag) {
3903                    return child;
3904                }
3905            }
3906        }
3907        return null;
3908    }
3909
3910    void clearDropTargets() {
3911        ArrayList<ShortcutAndWidgetContainer> childrenLayouts =
3912                getAllShortcutAndWidgetContainers();
3913        for (ShortcutAndWidgetContainer layout: childrenLayouts) {
3914            int childCount = layout.getChildCount();
3915            for (int j = 0; j < childCount; j++) {
3916                View v = layout.getChildAt(j);
3917                if (v instanceof DropTarget) {
3918                    mDragController.removeDropTarget((DropTarget) v);
3919                }
3920            }
3921        }
3922    }
3923
3924    // Removes ALL items that match a given package name, this is usually called when a package
3925    // has been removed and we want to remove all components (widgets, shortcuts, apps) that
3926    // belong to that package.
3927    void removeItemsByPackageName(final ArrayList<String> packages) {
3928        final HashSet<String> packageNames = new HashSet<String>();
3929        packageNames.addAll(packages);
3930
3931        // Filter out all the ItemInfos that this is going to affect
3932        final HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
3933        final HashSet<ComponentName> cns = new HashSet<ComponentName>();
3934        ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
3935        for (CellLayout layoutParent : cellLayouts) {
3936            ViewGroup layout = layoutParent.getShortcutsAndWidgets();
3937            int childCount = layout.getChildCount();
3938            for (int i = 0; i < childCount; ++i) {
3939                View view = layout.getChildAt(i);
3940                infos.add((ItemInfo) view.getTag());
3941            }
3942        }
3943        LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() {
3944            @Override
3945            public boolean filterItem(ItemInfo parent, ItemInfo info,
3946                                      ComponentName cn) {
3947                if (packageNames.contains(cn.getPackageName())) {
3948                    cns.add(cn);
3949                    return true;
3950                }
3951                return false;
3952            }
3953        };
3954        LauncherModel.filterItemInfos(infos, filter);
3955
3956        // Remove the affected components
3957        removeItemsByComponentName(cns);
3958    }
3959
3960    // Removes items that match the application info specified, when applications are removed
3961    // as a part of an update, this is called to ensure that other widgets and application
3962    // shortcuts are not removed.
3963    void removeItemsByApplicationInfo(final ArrayList<ApplicationInfo> appInfos) {
3964        // Just create a hash table of all the specific components that this will affect
3965        HashSet<ComponentName> cns = new HashSet<ComponentName>();
3966        for (ApplicationInfo info : appInfos) {
3967            cns.add(info.componentName);
3968        }
3969
3970        // Remove all the things
3971        removeItemsByComponentName(cns);
3972    }
3973
3974    void removeItemsByComponentName(final HashSet<ComponentName> componentNames) {
3975        ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
3976        for (final CellLayout layoutParent: cellLayouts) {
3977            final ViewGroup layout = layoutParent.getShortcutsAndWidgets();
3978
3979            final HashMap<ItemInfo, View> children = new HashMap<ItemInfo, View>();
3980            for (int j = 0; j < layout.getChildCount(); j++) {
3981                final View view = layout.getChildAt(j);
3982                children.put((ItemInfo) view.getTag(), view);
3983            }
3984
3985            final ArrayList<View> childrenToRemove = new ArrayList<View>();
3986            final HashMap<FolderInfo, ArrayList<ShortcutInfo>> folderAppsToRemove =
3987                    new HashMap<FolderInfo, ArrayList<ShortcutInfo>>();
3988            LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() {
3989                @Override
3990                public boolean filterItem(ItemInfo parent, ItemInfo info,
3991                                          ComponentName cn) {
3992                    if (parent instanceof FolderInfo) {
3993                        if (componentNames.contains(cn)) {
3994                            FolderInfo folder = (FolderInfo) parent;
3995                            ArrayList<ShortcutInfo> appsToRemove;
3996                            if (folderAppsToRemove.containsKey(folder)) {
3997                                appsToRemove = folderAppsToRemove.get(folder);
3998                            } else {
3999                                appsToRemove = new ArrayList<ShortcutInfo>();
4000                                folderAppsToRemove.put(folder, appsToRemove);
4001                            }
4002                            appsToRemove.add((ShortcutInfo) info);
4003                            return true;
4004                        }
4005                    } else {
4006                        if (componentNames.contains(cn)) {
4007                            childrenToRemove.add(children.get(info));
4008                            return true;
4009                        }
4010                    }
4011                    return false;
4012                }
4013            };
4014            LauncherModel.filterItemInfos(children.keySet(), filter);
4015
4016            // Remove all the apps from their folders
4017            for (FolderInfo folder : folderAppsToRemove.keySet()) {
4018                ArrayList<ShortcutInfo> appsToRemove = folderAppsToRemove.get(folder);
4019                for (ShortcutInfo info : appsToRemove) {
4020                    folder.remove(info);
4021                }
4022            }
4023
4024            // Remove all the other children
4025            for (View child : childrenToRemove) {
4026                // Note: We can not remove the view directly from CellLayoutChildren as this
4027                // does not re-mark the spaces as unoccupied.
4028                layoutParent.removeViewInLayout(child);
4029                if (child instanceof DropTarget) {
4030                    mDragController.removeDropTarget((DropTarget) child);
4031                }
4032            }
4033
4034            if (childrenToRemove.size() > 0) {
4035                layout.requestLayout();
4036                layout.invalidate();
4037            }
4038        }
4039
4040        // Strip all the empty screens
4041        stripEmptyScreens();
4042    }
4043
4044    void updateShortcuts(ArrayList<ApplicationInfo> apps) {
4045        ArrayList<ShortcutAndWidgetContainer> childrenLayouts = getAllShortcutAndWidgetContainers();
4046        for (ShortcutAndWidgetContainer layout: childrenLayouts) {
4047            int childCount = layout.getChildCount();
4048            for (int j = 0; j < childCount; j++) {
4049                final View view = layout.getChildAt(j);
4050                Object tag = view.getTag();
4051
4052                if (LauncherModel.isShortcutInfoUpdateable((ItemInfo) tag)) {
4053                    ShortcutInfo info = (ShortcutInfo) tag;
4054
4055                    final Intent intent = info.intent;
4056                    final ComponentName name = intent.getComponent();
4057                    final int appCount = apps.size();
4058                    for (int k = 0; k < appCount; k++) {
4059                        ApplicationInfo app = apps.get(k);
4060                        if (app.componentName.equals(name)) {
4061                            BubbleTextView shortcut = (BubbleTextView) view;
4062                            info.updateIcon(mIconCache);
4063                            info.title = app.title.toString();
4064                            shortcut.applyFromShortcutInfo(info, mIconCache);
4065                        }
4066                    }
4067                }
4068            }
4069        }
4070    }
4071
4072    void moveToDefaultScreen(boolean animate) {
4073        if (!isSmall()) {
4074            if (animate) {
4075                snapToPage(mDefaultPage);
4076            } else {
4077                setCurrentPage(mDefaultPage);
4078            }
4079        }
4080        View child = getChildAt(mDefaultPage);
4081        if (child != null) {
4082            child.requestFocus();
4083        }
4084    }
4085
4086    @Override
4087    protected int getPageIndicatorMarker(int pageIndex) {
4088        if (getScreenIdForPageIndex(pageIndex) == CUSTOM_CONTENT_SCREEN_ID) {
4089            return R.layout.custom_content_page_indicator_marker;
4090        }
4091        return super.getPageIndicatorMarker(pageIndex);
4092    }
4093
4094    @Override
4095    public void syncPages() {
4096    }
4097
4098    @Override
4099    public void syncPageItems(int page, boolean immediate) {
4100    }
4101
4102    protected String getCurrentPageDescription() {
4103        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
4104        return String.format(getContext().getString(R.string.workspace_scroll_format),
4105                page + 1, getChildCount());
4106    }
4107
4108    public void getLocationInDragLayer(int[] loc) {
4109        mLauncher.getDragLayer().getLocationInDragLayer(this, loc);
4110    }
4111}
4112