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