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