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