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