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