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