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