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