Workspace.java revision 0f785720667ab8afe4b4620a6c333d382d8659ed
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;
74import com.android.launcher3.widget.PendingAddShortcutInfo;
75import com.android.launcher3.widget.PendingAddWidgetInfo;
76
77import java.util.ArrayList;
78import java.util.HashMap;
79import java.util.HashSet;
80import java.util.Iterator;
81import java.util.concurrent.atomic.AtomicInteger;
82
83/**
84 * The workspace is a wide area with a wallpaper and a finite number of pages.
85 * Each page contains a number of icons, folders or widgets the user can
86 * interact with. A workspace is meant to be used with a fixed width only.
87 */
88public class Workspace extends SmoothPagedView
89        implements DropTarget, DragSource, DragScroller, View.OnTouchListener,
90        DragController.DragListener, LauncherTransitionable, ViewGroup.OnHierarchyChangeListener,
91        Insettable {
92    private static final String TAG = "Launcher.Workspace";
93
94    private static final int CHILDREN_OUTLINE_FADE_OUT_DELAY = 0;
95    private static final int CHILDREN_OUTLINE_FADE_OUT_DURATION = 375;
96    private static final int CHILDREN_OUTLINE_FADE_IN_DURATION = 100;
97
98    protected static final int SNAP_OFF_EMPTY_SCREEN_DURATION = 400;
99    protected static final int FADE_EMPTY_SCREEN_DURATION = 150;
100
101    private static final int BACKGROUND_FADE_OUT_DURATION = 350;
102    private static final int ADJACENT_SCREEN_DROP_DURATION = 300;
103    private static final int FLING_THRESHOLD_VELOCITY = 500;
104
105    private static final float ALPHA_CUTOFF_THRESHOLD = 0.01f;
106
107    static final boolean MAP_NO_RECURSE = false;
108    static final boolean MAP_RECURSE = true;
109
110    // These animators are used to fade the children's outlines
111    private ObjectAnimator mChildrenOutlineFadeInAnimation;
112    private ObjectAnimator mChildrenOutlineFadeOutAnimation;
113    private float mChildrenOutlineAlpha = 0;
114
115    // These properties refer to the background protection gradient used for AllApps and Customize
116    private ValueAnimator mBackgroundFadeInAnimation;
117    private ValueAnimator mBackgroundFadeOutAnimation;
118
119    private static final long CUSTOM_CONTENT_GESTURE_DELAY = 200;
120    private long mTouchDownTime = -1;
121    private long mCustomContentShowTime = -1;
122
123    private LayoutTransition mLayoutTransition;
124    @Thunk final WallpaperManager mWallpaperManager;
125    @Thunk IBinder mWindowToken;
126
127    private int mOriginalDefaultPage;
128    private int mDefaultPage;
129
130    private ShortcutAndWidgetContainer mDragSourceInternal;
131    @Thunk static boolean sAccessibilityEnabled;
132
133    // The screen id used for the empty screen always present to the right.
134    final static long EXTRA_EMPTY_SCREEN_ID = -201;
135    private final static long CUSTOM_CONTENT_SCREEN_ID = -301;
136
137    @Thunk HashMap<Long, CellLayout> mWorkspaceScreens = new HashMap<Long, CellLayout>();
138    @Thunk ArrayList<Long> mScreenOrder = new ArrayList<Long>();
139
140    @Thunk Runnable mRemoveEmptyScreenRunnable;
141    @Thunk boolean mDeferRemoveExtraEmptyScreen = false;
142
143    /**
144     * CellInfo for the cell that is currently being dragged
145     */
146    private CellLayout.CellInfo mDragInfo;
147
148    /**
149     * Target drop area calculated during last acceptDrop call.
150     */
151    @Thunk int[] mTargetCell = new int[2];
152    private int mDragOverX = -1;
153    private int mDragOverY = -1;
154
155    static Rect mLandscapeCellLayoutMetrics = null;
156    static Rect mPortraitCellLayoutMetrics = null;
157
158    CustomContentCallbacks mCustomContentCallbacks;
159    boolean mCustomContentShowing;
160    private float mLastCustomContentScrollProgress = -1f;
161    private String mCustomContentDescription = "";
162
163    /**
164     * The CellLayout that is currently being dragged over
165     */
166    @Thunk CellLayout mDragTargetLayout = null;
167    /**
168     * The CellLayout that we will show as glowing
169     */
170    private CellLayout mDragOverlappingLayout = null;
171
172    /**
173     * The CellLayout which will be dropped to
174     */
175    private CellLayout mDropToLayout = null;
176
177    @Thunk Launcher mLauncher;
178    @Thunk IconCache mIconCache;
179    @Thunk DragController mDragController;
180
181    // These are temporary variables to prevent having to allocate a new object just to
182    // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
183    private int[] mTempCell = new int[2];
184    private int[] mTempPt = new int[2];
185    private int[] mTempEstimate = new int[2];
186    @Thunk float[] mDragViewVisualCenter = new float[2];
187    private float[] mTempCellLayoutCenterCoordinates = new float[2];
188    private Matrix mTempInverseMatrix = new Matrix();
189
190    private SpringLoadedDragController mSpringLoadedDragController;
191    private float mSpringLoadedShrinkFactor;
192    private float mOverviewModeShrinkFactor;
193
194    // State variable that indicates whether the pages are small (ie when you're
195    // in all apps or customize mode)
196
197    enum State { NORMAL, NORMAL_HIDDEN, SPRING_LOADED, OVERVIEW, OVERVIEW_HIDDEN};
198    private State mState = State.NORMAL;
199    private boolean mIsSwitchingState = false;
200
201    boolean mAnimatingViewIntoPlace = false;
202    boolean mIsDragOccuring = false;
203    boolean mChildrenLayersEnabled = true;
204
205    private boolean mStripScreensOnPageStopMoving = false;
206
207    /** Is the user is dragging an item near the edge of a page? */
208    private boolean mInScrollArea = false;
209
210    private HolographicOutlineHelper mOutlineHelper;
211    @Thunk Bitmap mDragOutline = null;
212    private static final Rect sTempRect = new Rect();
213    private final int[] mTempXY = new int[2];
214    private int[] mTempVisiblePagesRange = new int[2];
215    private boolean mOverscrollEffectSet;
216    public static final int DRAG_BITMAP_PADDING = 2;
217    private boolean mWorkspaceFadeInAdjacentScreens;
218
219    WallpaperOffsetInterpolator mWallpaperOffset;
220    @Thunk boolean mWallpaperIsLiveWallpaper;
221    @Thunk int mNumPagesForWallpaperParallax;
222    @Thunk float mLastSetWallpaperOffsetSteps = 0;
223
224    @Thunk Runnable mDelayedResizeRunnable;
225    private Runnable mDelayedSnapToPageRunnable;
226    private Point mDisplaySize = new Point();
227
228    // Variables relating to the creation of user folders by hovering shortcuts over shortcuts
229    private static final int FOLDER_CREATION_TIMEOUT = 0;
230    public static final int REORDER_TIMEOUT = 350;
231    private final Alarm mFolderCreationAlarm = new Alarm();
232    private final Alarm mReorderAlarm = new Alarm();
233    @Thunk FolderRingAnimator mDragFolderRingAnimator = null;
234    private FolderIcon mDragOverFolderIcon = null;
235    private boolean mCreateUserFolderOnDrop = false;
236    private boolean mAddToExistingFolderOnDrop = false;
237    private DropTarget.DragEnforcer mDragEnforcer;
238    private float mMaxDistanceForFolderCreation;
239
240    private final Canvas mCanvas = new Canvas();
241
242    // Variables relating to touch disambiguation (scrolling workspace vs. scrolling a widget)
243    private float mXDown;
244    private float mYDown;
245    final static float START_DAMPING_TOUCH_SLOP_ANGLE = (float) Math.PI / 6;
246    final static float MAX_SWIPE_ANGLE = (float) Math.PI / 3;
247    final static float TOUCH_SLOP_DAMPING_FACTOR = 4;
248
249    // Relating to the animation of items being dropped externally
250    public static final int ANIMATE_INTO_POSITION_AND_DISAPPEAR = 0;
251    public static final int ANIMATE_INTO_POSITION_AND_REMAIN = 1;
252    public static final int ANIMATE_INTO_POSITION_AND_RESIZE = 2;
253    public static final int COMPLETE_TWO_STAGE_WIDGET_DROP_ANIMATION = 3;
254    public static final int CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION = 4;
255
256    // Related to dragging, folder creation and reordering
257    private static final int DRAG_MODE_NONE = 0;
258    private static final int DRAG_MODE_CREATE_FOLDER = 1;
259    private static final int DRAG_MODE_ADD_TO_FOLDER = 2;
260    private static final int DRAG_MODE_REORDER = 3;
261    private int mDragMode = DRAG_MODE_NONE;
262    @Thunk int mLastReorderX = -1;
263    @Thunk int mLastReorderY = -1;
264
265    private SparseArray<Parcelable> mSavedStates;
266    private final ArrayList<Integer> mRestoredPages = new ArrayList<Integer>();
267
268    // These variables are used for storing the initial and final values during workspace animations
269    private int mSavedScrollX;
270    private float mSavedRotationY;
271    private float mSavedTranslationX;
272
273    private float mCurrentScale;
274    private float mNewScale;
275    @Thunk float[] mOldBackgroundAlphas;
276    private float[] mOldAlphas;
277    @Thunk float[] mNewBackgroundAlphas;
278    private float[] mNewAlphas;
279    private int mLastChildCount = -1;
280    private float mTransitionProgress;
281    @Thunk Animator mStateAnimator = null;
282
283    float mOverScrollEffect = 0f;
284
285    @Thunk Runnable mDeferredAction;
286    private boolean mDeferDropAfterUninstall;
287    private boolean mUninstallSuccessful;
288
289    // State related to Launcher Overlay
290    LauncherOverlay mLauncherOverlay;
291    boolean mScrollInteractionBegan;
292    boolean mStartedSendingScrollEvents;
293    boolean mShouldSendPageSettled;
294    int mLastOverlaySroll = 0;
295
296    private final Runnable mBindPages = new Runnable() {
297        @Override
298        public void run() {
299            mLauncher.getModel().bindRemainingSynchronousPages();
300        }
301    };
302
303    /**
304     * Used to inflate the Workspace from XML.
305     *
306     * @param context The application's context.
307     * @param attrs The attributes set containing the Workspace's customization values.
308     */
309    public Workspace(Context context, AttributeSet attrs) {
310        this(context, attrs, 0);
311    }
312
313    /**
314     * Used to inflate the Workspace from XML.
315     *
316     * @param context The application's context.
317     * @param attrs The attributes set containing the Workspace's customization values.
318     * @param defStyle Unused.
319     */
320    public Workspace(Context context, AttributeSet attrs, int defStyle) {
321        super(context, attrs, defStyle);
322        mContentIsRefreshable = false;
323
324        mOutlineHelper = HolographicOutlineHelper.obtain(context);
325
326        mDragEnforcer = new DropTarget.DragEnforcer(context);
327        // With workspace, data is available straight from the get-go
328        setDataIsReady();
329
330        mLauncher = (Launcher) context;
331        final Resources res = getResources();
332        mWorkspaceFadeInAdjacentScreens = LauncherAppState.getInstance().getDynamicGrid().
333                getDeviceProfile().shouldFadeAdjacentWorkspaceScreens();
334        mFadeInAdjacentScreens = false;
335        mWallpaperManager = WallpaperManager.getInstance(context);
336
337        LauncherAppState app = LauncherAppState.getInstance();
338        DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
339        TypedArray a = context.obtainStyledAttributes(attrs,
340                R.styleable.Workspace, defStyle, 0);
341        mSpringLoadedShrinkFactor =
342            res.getInteger(R.integer.config_workspaceSpringLoadShrinkPercentage) / 100.0f;
343        mOverviewModeShrinkFactor = grid.getOverviewModeScale();
344        mOriginalDefaultPage = mDefaultPage = a.getInt(R.styleable.Workspace_defaultScreen, 1);
345        a.recycle();
346
347        setOnHierarchyChangeListener(this);
348        setHapticFeedbackEnabled(false);
349
350        initWorkspace();
351
352        // Disable multitouch across the workspace/all apps/customize tray
353        setMotionEventSplittingEnabled(true);
354        setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
355    }
356
357    @Override
358    public void setInsets(Rect insets) {
359        mInsets.set(insets);
360
361        CellLayout customScreen = getScreenWithId(CUSTOM_CONTENT_SCREEN_ID);
362        if (customScreen != null) {
363            View customContent = customScreen.getShortcutsAndWidgets().getChildAt(0);
364            if (customContent instanceof Insettable) {
365                ((Insettable) customContent).setInsets(mInsets);
366            }
367        }
368    }
369
370    // estimate the size of a widget with spans hSpan, vSpan. return MAX_VALUE for each
371    // dimension if unsuccessful
372    public int[] estimateItemSize(ItemInfo itemInfo, boolean springLoaded) {
373        int[] size = new int[2];
374        if (getChildCount() > 0) {
375            // Use the first non-custom page to estimate the child position
376            CellLayout cl = (CellLayout) getChildAt(numCustomPages());
377            Rect r = estimateItemPosition(cl, itemInfo, 0, 0, itemInfo.spanX, itemInfo.spanY);
378            size[0] = r.width();
379            size[1] = r.height();
380            if (springLoaded) {
381                size[0] *= mSpringLoadedShrinkFactor;
382                size[1] *= mSpringLoadedShrinkFactor;
383            }
384            return size;
385        } else {
386            size[0] = Integer.MAX_VALUE;
387            size[1] = Integer.MAX_VALUE;
388            return size;
389        }
390    }
391
392    public Rect estimateItemPosition(CellLayout cl, ItemInfo pendingInfo,
393            int hCell, int vCell, int hSpan, int vSpan) {
394        Rect r = new Rect();
395        cl.cellToRect(hCell, vCell, hSpan, vSpan, r);
396        return r;
397    }
398
399    public void onDragStart(final DragSource source, Object info, int dragAction) {
400        mIsDragOccuring = true;
401        updateChildrenLayersEnabled(false);
402        mLauncher.lockScreenOrientation();
403        mLauncher.onInteractionBegin();
404        setChildrenBackgroundAlphaMultipliers(1f);
405        // Prevent any Un/InstallShortcutReceivers from updating the db while we are dragging
406        InstallShortcutReceiver.enableInstallQueue();
407        post(new Runnable() {
408            @Override
409            public void run() {
410                if (mIsDragOccuring) {
411                    mDeferRemoveExtraEmptyScreen = false;
412                    addExtraEmptyScreenOnDrag();
413                }
414            }
415        });
416    }
417
418
419    public void deferRemoveExtraEmptyScreen() {
420        mDeferRemoveExtraEmptyScreen = true;
421    }
422
423    public void onDragEnd() {
424        if (!mDeferRemoveExtraEmptyScreen) {
425            removeExtraEmptyScreen(true, mDragSourceInternal != null);
426        }
427
428        mIsDragOccuring = false;
429        updateChildrenLayersEnabled(false);
430        mLauncher.unlockScreenOrientation(false);
431
432        // Re-enable any Un/InstallShortcutReceiver and now process any queued items
433        InstallShortcutReceiver.disableAndFlushInstallQueue(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        // We should only update the drag layer background alpha if we are not in all apps or the
1704        // widgets tray
1705        if (mState == State.NORMAL) {
1706            mLauncher.getDragLayer().setBackgroundAlpha(progress * 0.8f);
1707        }
1708
1709        if (mLauncher.getHotseat() != null) {
1710            mLauncher.getHotseat().setTranslationX(translationX);
1711        }
1712
1713        if (getPageIndicator() != null) {
1714            getPageIndicator().setTranslationX(translationX);
1715        }
1716
1717        if (mCustomContentCallbacks != null) {
1718            mCustomContentCallbacks.onScrollProgressChanged(progress);
1719        }
1720    }
1721
1722    @Override
1723    protected OnClickListener getPageIndicatorClickListener() {
1724        AccessibilityManager am = (AccessibilityManager)
1725                getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
1726        if (!am.isTouchExplorationEnabled()) {
1727            return null;
1728        }
1729        OnClickListener listener = new OnClickListener() {
1730            @Override
1731            public void onClick(View arg0) {
1732                enterOverviewMode();
1733            }
1734        };
1735        return listener;
1736    }
1737
1738    @Override
1739    protected void screenScrolled(int screenCenter) {
1740        final boolean isRtl = isLayoutRtl();
1741        super.screenScrolled(screenCenter);
1742
1743        updatePageAlphaValues(screenCenter);
1744        updateStateForCustomContent(screenCenter);
1745        enableHwLayersOnVisiblePages();
1746
1747        boolean shouldOverScroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
1748
1749        if (shouldOverScroll) {
1750            int index = 0;
1751            final int lowerIndex = 0;
1752            final int upperIndex = getChildCount() - 1;
1753
1754            final boolean isLeftPage = mOverScrollX < 0;
1755            index = (!isRtl && isLeftPage) || (isRtl && !isLeftPage) ? lowerIndex : upperIndex;
1756
1757            CellLayout cl = (CellLayout) getChildAt(index);
1758            float effect = Math.abs(mOverScrollEffect);
1759            cl.setOverScrollAmount(Math.abs(effect), isLeftPage);
1760
1761            mOverscrollEffectSet = true;
1762        } else {
1763            if (mOverscrollEffectSet && getChildCount() > 0) {
1764                mOverscrollEffectSet = false;
1765                ((CellLayout) getChildAt(0)).setOverScrollAmount(0, false);
1766                ((CellLayout) getChildAt(getChildCount() - 1)).setOverScrollAmount(0, false);
1767            }
1768        }
1769    }
1770
1771    protected void onAttachedToWindow() {
1772        super.onAttachedToWindow();
1773        mWindowToken = getWindowToken();
1774        computeScroll();
1775        mDragController.setWindowToken(mWindowToken);
1776    }
1777
1778    protected void onDetachedFromWindow() {
1779        super.onDetachedFromWindow();
1780        mWindowToken = null;
1781    }
1782
1783    protected void onResume() {
1784        if (getPageIndicator() != null) {
1785            // In case accessibility state has changed, we need to perform this on every
1786            // attach to window
1787            OnClickListener listener = getPageIndicatorClickListener();
1788            if (listener != null) {
1789                getPageIndicator().setOnClickListener(listener);
1790            }
1791        }
1792        AccessibilityManager am = (AccessibilityManager)
1793                getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
1794        sAccessibilityEnabled = am.isEnabled();
1795
1796        // Update wallpaper dimensions if they were changed since last onResume
1797        // (we also always set the wallpaper dimensions in the constructor)
1798        if (LauncherAppState.getInstance().hasWallpaperChangedSinceLastCheck()) {
1799            setWallpaperDimension();
1800        }
1801        mWallpaperIsLiveWallpaper = mWallpaperManager.getWallpaperInfo() != null;
1802        // Force the wallpaper offset steps to be set again, because another app might have changed
1803        // them
1804        mLastSetWallpaperOffsetSteps = 0f;
1805    }
1806
1807    @Override
1808    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
1809        if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
1810            mWallpaperOffset.syncWithScroll();
1811            mWallpaperOffset.jumpToFinal();
1812        }
1813        super.onLayout(changed, left, top, right, bottom);
1814    }
1815
1816    @Override
1817    protected void onDraw(Canvas canvas) {
1818        super.onDraw(canvas);
1819
1820        // Call back to LauncherModel to finish binding after the first draw
1821        post(mBindPages);
1822    }
1823
1824    @Override
1825    protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
1826        if (!mLauncher.isAppsViewVisible()) {
1827            final Folder openFolder = getOpenFolder();
1828            if (openFolder != null) {
1829                return openFolder.requestFocus(direction, previouslyFocusedRect);
1830            } else {
1831                return super.onRequestFocusInDescendants(direction, previouslyFocusedRect);
1832            }
1833        }
1834        return false;
1835    }
1836
1837    @Override
1838    public int getDescendantFocusability() {
1839        if (workspaceInModalState()) {
1840            return ViewGroup.FOCUS_BLOCK_DESCENDANTS;
1841        }
1842        return super.getDescendantFocusability();
1843    }
1844
1845    @Override
1846    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
1847        if (!mLauncher.isAppsViewVisible()) {
1848            final Folder openFolder = getOpenFolder();
1849            if (openFolder != null) {
1850                openFolder.addFocusables(views, direction);
1851            } else {
1852                super.addFocusables(views, direction, focusableMode);
1853            }
1854        }
1855    }
1856
1857    public boolean workspaceInModalState() {
1858        return mState != State.NORMAL;
1859    }
1860
1861    void enableChildrenCache(int fromPage, int toPage) {
1862        if (fromPage > toPage) {
1863            final int temp = fromPage;
1864            fromPage = toPage;
1865            toPage = temp;
1866        }
1867
1868        final int screenCount = getChildCount();
1869
1870        fromPage = Math.max(fromPage, 0);
1871        toPage = Math.min(toPage, screenCount - 1);
1872
1873        for (int i = fromPage; i <= toPage; i++) {
1874            final CellLayout layout = (CellLayout) getChildAt(i);
1875            layout.setChildrenDrawnWithCacheEnabled(true);
1876            layout.setChildrenDrawingCacheEnabled(true);
1877        }
1878    }
1879
1880    void clearChildrenCache() {
1881        final int screenCount = getChildCount();
1882        for (int i = 0; i < screenCount; i++) {
1883            final CellLayout layout = (CellLayout) getChildAt(i);
1884            layout.setChildrenDrawnWithCacheEnabled(false);
1885            // In software mode, we don't want the items to continue to be drawn into bitmaps
1886            if (!isHardwareAccelerated()) {
1887                layout.setChildrenDrawingCacheEnabled(false);
1888            }
1889        }
1890    }
1891
1892    @Thunk void updateChildrenLayersEnabled(boolean force) {
1893        boolean small = mState == State.OVERVIEW || mIsSwitchingState;
1894        boolean enableChildrenLayers = force || small || mAnimatingViewIntoPlace || isPageMoving();
1895
1896        if (enableChildrenLayers != mChildrenLayersEnabled) {
1897            mChildrenLayersEnabled = enableChildrenLayers;
1898            if (mChildrenLayersEnabled) {
1899                enableHwLayersOnVisiblePages();
1900            } else {
1901                for (int i = 0; i < getPageCount(); i++) {
1902                    final CellLayout cl = (CellLayout) getChildAt(i);
1903                    cl.enableHardwareLayer(false);
1904                }
1905            }
1906        }
1907    }
1908
1909    private void enableHwLayersOnVisiblePages() {
1910        if (mChildrenLayersEnabled) {
1911            final int screenCount = getChildCount();
1912            getVisiblePages(mTempVisiblePagesRange);
1913            int leftScreen = mTempVisiblePagesRange[0];
1914            int rightScreen = mTempVisiblePagesRange[1];
1915            if (leftScreen == rightScreen) {
1916                // make sure we're caching at least two pages always
1917                if (rightScreen < screenCount - 1) {
1918                    rightScreen++;
1919                } else if (leftScreen > 0) {
1920                    leftScreen--;
1921                }
1922            }
1923
1924            final CellLayout customScreen = mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID);
1925            for (int i = 0; i < screenCount; i++) {
1926                final CellLayout layout = (CellLayout) getPageAt(i);
1927
1928                // enable layers between left and right screen inclusive, except for the
1929                // customScreen, which may animate its content during transitions.
1930                boolean enableLayer = layout != customScreen &&
1931                        leftScreen <= i && i <= rightScreen && shouldDrawChild(layout);
1932                layout.enableHardwareLayer(enableLayer);
1933            }
1934        }
1935    }
1936
1937    public void buildPageHardwareLayers() {
1938        // force layers to be enabled just for the call to buildLayer
1939        updateChildrenLayersEnabled(true);
1940        if (getWindowToken() != null) {
1941            final int childCount = getChildCount();
1942            for (int i = 0; i < childCount; i++) {
1943                CellLayout cl = (CellLayout) getChildAt(i);
1944                cl.buildHardwareLayer();
1945            }
1946        }
1947        updateChildrenLayersEnabled(false);
1948    }
1949
1950    protected void onWallpaperTap(MotionEvent ev) {
1951        final int[] position = mTempCell;
1952        getLocationOnScreen(position);
1953
1954        int pointerIndex = ev.getActionIndex();
1955        position[0] += (int) ev.getX(pointerIndex);
1956        position[1] += (int) ev.getY(pointerIndex);
1957
1958        mWallpaperManager.sendWallpaperCommand(getWindowToken(),
1959                ev.getAction() == MotionEvent.ACTION_UP
1960                        ? WallpaperManager.COMMAND_TAP : WallpaperManager.COMMAND_SECONDARY_TAP,
1961                position[0], position[1], 0, null);
1962    }
1963
1964    /*
1965     * This interpolator emulates the rate at which the perceived scale of an object changes
1966     * as its distance from a camera increases. When this interpolator is applied to a scale
1967     * animation on a view, it evokes the sense that the object is shrinking due to moving away
1968     * from the camera.
1969     */
1970    static class ZInterpolator implements TimeInterpolator {
1971        private float focalLength;
1972
1973        public ZInterpolator(float foc) {
1974            focalLength = foc;
1975        }
1976
1977        public float getInterpolation(float input) {
1978            return (1.0f - focalLength / (focalLength + input)) /
1979                (1.0f - focalLength / (focalLength + 1.0f));
1980        }
1981    }
1982
1983    /*
1984     * The exact reverse of ZInterpolator.
1985     */
1986    static class InverseZInterpolator implements TimeInterpolator {
1987        private ZInterpolator zInterpolator;
1988        public InverseZInterpolator(float foc) {
1989            zInterpolator = new ZInterpolator(foc);
1990        }
1991        public float getInterpolation(float input) {
1992            return 1 - zInterpolator.getInterpolation(1 - input);
1993        }
1994    }
1995
1996    /*
1997     * ZInterpolator compounded with an ease-out.
1998     */
1999    static class ZoomOutInterpolator implements TimeInterpolator {
2000        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(0.75f);
2001        private final ZInterpolator zInterpolator = new ZInterpolator(0.13f);
2002
2003        public float getInterpolation(float input) {
2004            return decelerate.getInterpolation(zInterpolator.getInterpolation(input));
2005        }
2006    }
2007
2008    /*
2009     * InvereZInterpolator compounded with an ease-out.
2010     */
2011    static class ZoomInInterpolator implements TimeInterpolator {
2012        private final InverseZInterpolator inverseZInterpolator = new InverseZInterpolator(0.35f);
2013        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(3.0f);
2014
2015        public float getInterpolation(float input) {
2016            return decelerate.getInterpolation(inverseZInterpolator.getInterpolation(input));
2017        }
2018    }
2019
2020    private final ZoomInInterpolator mZoomInInterpolator = new ZoomInInterpolator();
2021
2022    /*
2023    *
2024    * We call these methods (onDragStartedWithItemSpans/onDragStartedWithSize) whenever we
2025    * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace
2026    *
2027    * These methods mark the appropriate pages as accepting drops (which alters their visual
2028    * appearance).
2029    *
2030    */
2031    private static Rect getDrawableBounds(Drawable d) {
2032        Rect bounds = new Rect();
2033        d.copyBounds(bounds);
2034        if (bounds.width() == 0 || bounds.height() == 0) {
2035            bounds.set(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
2036        } else {
2037            bounds.offsetTo(0, 0);
2038        }
2039        if (d instanceof PreloadIconDrawable) {
2040            int inset = -((PreloadIconDrawable) d).getOutset();
2041            bounds.inset(inset, inset);
2042        }
2043        return bounds;
2044    }
2045
2046    public void onExternalDragStartedWithItem(View v) {
2047        // Compose a drag bitmap with the view scaled to the icon size
2048        LauncherAppState app = LauncherAppState.getInstance();
2049        DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
2050        int iconSize = grid.iconSizePx;
2051        int bmpWidth = v.getMeasuredWidth();
2052        int bmpHeight = v.getMeasuredHeight();
2053
2054        // If this is a text view, use its drawable instead
2055        if (v instanceof TextView) {
2056            Drawable d = getTextViewIcon((TextView) v);
2057            Rect bounds = getDrawableBounds(d);
2058            bmpWidth = bounds.width();
2059            bmpHeight = bounds.height();
2060        }
2061
2062        // Compose the bitmap to create the icon from
2063        Bitmap b = Bitmap.createBitmap(bmpWidth, bmpHeight,
2064                Bitmap.Config.ARGB_8888);
2065        mCanvas.setBitmap(b);
2066        drawDragView(v, mCanvas, 0);
2067        mCanvas.setBitmap(null);
2068
2069        // The outline is used to visualize where the item will land if dropped
2070        mDragOutline = createDragOutline(b, DRAG_BITMAP_PADDING, iconSize, iconSize, true);
2071    }
2072
2073    public void onDragStartedWithItem(PendingAddItemInfo info, Bitmap b, boolean clipAlpha) {
2074        int[] size = estimateItemSize(info, false);
2075
2076        // The outline is used to visualize where the item will land if dropped
2077        mDragOutline = createDragOutline(b, DRAG_BITMAP_PADDING, size[0], size[1], clipAlpha);
2078    }
2079
2080    public void exitWidgetResizeMode() {
2081        DragLayer dragLayer = mLauncher.getDragLayer();
2082        dragLayer.clearAllResizeFrames();
2083    }
2084
2085    private void initAnimationArrays() {
2086        final int childCount = getChildCount();
2087        if (mLastChildCount == childCount) return;
2088
2089        mOldBackgroundAlphas = new float[childCount];
2090        mOldAlphas = new float[childCount];
2091        mNewBackgroundAlphas = new float[childCount];
2092        mNewAlphas = new float[childCount];
2093    }
2094
2095    Animator getChangeStateAnimation(final State state, boolean animated,
2096            HashMap<View, Integer> layerViews) {
2097        return getChangeStateAnimation(state, animated, 0, -1, layerViews);
2098    }
2099
2100    @Override
2101    protected void getFreeScrollPageRange(int[] range) {
2102        getOverviewModePages(range);
2103    }
2104
2105    private void getOverviewModePages(int[] range) {
2106        int start = numCustomPages();
2107        int end = getChildCount() - 1;
2108
2109        range[0] = Math.max(0, Math.min(start, getChildCount() - 1));
2110        range[1] = Math.max(0,  end);
2111    }
2112
2113    protected void onStartReordering() {
2114        super.onStartReordering();
2115        showOutlines();
2116        // Reordering handles its own animations, disable the automatic ones.
2117        disableLayoutTransitions();
2118    }
2119
2120    protected void onEndReordering() {
2121        super.onEndReordering();
2122
2123        if (mLauncher.isWorkspaceLoading()) {
2124            // Invalid and dangerous operation if workspace is loading
2125            return;
2126        }
2127
2128        hideOutlines();
2129        mScreenOrder.clear();
2130        int count = getChildCount();
2131        for (int i = 0; i < count; i++) {
2132            CellLayout cl = ((CellLayout) getChildAt(i));
2133            mScreenOrder.add(getIdForScreen(cl));
2134        }
2135
2136        mLauncher.getModel().updateWorkspaceScreenOrder(mLauncher, mScreenOrder);
2137
2138        // Re-enable auto layout transitions for page deletion.
2139        enableLayoutTransitions();
2140    }
2141
2142    public boolean isInOverviewMode() {
2143        return mState == State.OVERVIEW;
2144    }
2145
2146    public boolean enterOverviewMode() {
2147        if (mTouchState != TOUCH_STATE_REST) {
2148            return false;
2149        }
2150        enableOverviewMode(true, -1, true);
2151        return true;
2152    }
2153
2154    public void exitOverviewMode(boolean animated) {
2155        exitOverviewMode(-1, animated);
2156    }
2157
2158    public void exitOverviewMode(int snapPage, boolean animated) {
2159        enableOverviewMode(false, snapPage, animated);
2160    }
2161
2162    private void enableOverviewMode(boolean enable, int snapPage, boolean animated) {
2163        State finalState = Workspace.State.OVERVIEW;
2164        if (!enable) {
2165            finalState = Workspace.State.NORMAL;
2166        }
2167
2168        Animator workspaceAnim = getChangeStateAnimation(finalState, animated, 0, snapPage);
2169        if (workspaceAnim != null) {
2170            onTransitionPrepare();
2171            workspaceAnim.addListener(new AnimatorListenerAdapter() {
2172                @Override
2173                public void onAnimationEnd(Animator arg0) {
2174                    onTransitionEnd();
2175                }
2176            });
2177            workspaceAnim.start();
2178        }
2179    }
2180
2181    int getOverviewModeTranslationY() {
2182        LauncherAppState app = LauncherAppState.getInstance();
2183        DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
2184        Rect overviewBar = grid.getOverviewModeButtonBarRect();
2185
2186        int availableHeight = getViewportHeight();
2187        int scaledHeight = (int) (mOverviewModeShrinkFactor * getNormalChildHeight());
2188        int offsetFromTopEdge = (availableHeight - scaledHeight) / 2;
2189        int offsetToCenterInOverview = (availableHeight - mInsets.top - overviewBar.height()
2190                - scaledHeight) / 2;
2191
2192        return -offsetFromTopEdge + mInsets.top + offsetToCenterInOverview;
2193    }
2194
2195    public void updateInteractionForState() {
2196        if (mState != State.NORMAL) {
2197            mLauncher.onInteractionBegin();
2198        } else {
2199            mLauncher.onInteractionEnd();
2200        }
2201    }
2202
2203    private void setState(State state) {
2204        mState = state;
2205        updateInteractionForState();
2206        updateAccessibilityFlags();
2207    }
2208
2209    State getState() {
2210        return mState;
2211    }
2212
2213    private void updateAccessibilityFlags() {
2214        int accessible = mState == State.NORMAL ?
2215                IMPORTANT_FOR_ACCESSIBILITY_NO :
2216                IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
2217        setImportantForAccessibility(accessible);
2218    }
2219
2220    private static final int HIDE_WORKSPACE_DURATION = 100;
2221
2222    Animator getChangeStateAnimation(final State state, boolean animated, int delay, int snapPage) {
2223        return getChangeStateAnimation(state, animated, delay, snapPage, null);
2224    }
2225
2226    Animator getChangeStateAnimation(final State state, boolean animated, int delay, int snapPage,
2227            HashMap<View, Integer> layerViews) {
2228        if (mState == state) {
2229            return null;
2230        }
2231
2232        // Initialize animation arrays for the first time if necessary
2233        initAnimationArrays();
2234
2235        AnimatorSet anim = animated ? LauncherAnimUtils.createAnimatorSet() : null;
2236
2237        // We only want a single instance of a workspace animation to be running at once, so
2238        // we cancel any incomplete transition.
2239        if (mStateAnimator != null) {
2240            mStateAnimator.cancel();
2241        }
2242        mStateAnimator = anim;
2243
2244        final State oldState = mState;
2245        final boolean oldStateIsNormal = (oldState == State.NORMAL);
2246        final boolean oldStateIsSpringLoaded = (oldState == State.SPRING_LOADED);
2247        final boolean oldStateIsNormalHidden = (oldState == State.NORMAL_HIDDEN);
2248        final boolean oldStateIsOverviewHidden = (oldState == State.OVERVIEW_HIDDEN);
2249        final boolean oldStateIsOverview = (oldState == State.OVERVIEW);
2250        setState(state);
2251        final boolean stateIsNormal = (state == State.NORMAL);
2252        final boolean stateIsSpringLoaded = (state == State.SPRING_LOADED);
2253        final boolean stateIsNormalHidden = (state == State.NORMAL_HIDDEN);
2254        final boolean stateIsOverviewHidden = (state == State.OVERVIEW_HIDDEN);
2255        final boolean stateIsOverview = (state == State.OVERVIEW);
2256        float finalBackgroundAlpha = (stateIsSpringLoaded || stateIsOverview) ? 1.0f : 0f;
2257        float finalHotseatAndPageIndicatorAlpha = (stateIsNormal || stateIsSpringLoaded) ? 1f : 0f;
2258        float finalOverviewPanelAlpha = stateIsOverview ? 1f : 0f;
2259        // We keep the search bar visible on the workspace and in AllApps now
2260        float finalSearchBarAlpha = (stateIsNormal || stateIsNormalHidden) ? 1f : 0f;
2261        float finalWorkspaceTranslationY = stateIsOverview || stateIsOverviewHidden ?
2262                getOverviewModeTranslationY() : 0;
2263
2264        boolean workspaceToAllApps = (oldStateIsNormal && stateIsNormalHidden);
2265        boolean overviewToAllApps = (oldStateIsOverview && stateIsOverviewHidden);
2266        boolean allAppsToWorkspace = (stateIsNormalHidden && stateIsNormal);
2267        boolean workspaceToOverview = (oldStateIsNormal && stateIsOverview);
2268        boolean overviewToWorkspace = (oldStateIsOverview && stateIsNormal);
2269
2270        mNewScale = 1.0f;
2271
2272        if (oldStateIsOverview) {
2273            disableFreeScroll();
2274        } else if (stateIsOverview) {
2275            enableFreeScroll();
2276        }
2277
2278        if (state != State.NORMAL) {
2279            if (stateIsSpringLoaded) {
2280                mNewScale = mSpringLoadedShrinkFactor;
2281            } else if (stateIsOverview || stateIsOverviewHidden) {
2282                mNewScale = mOverviewModeShrinkFactor;
2283            }
2284        }
2285
2286        final int duration;
2287        if (workspaceToAllApps || overviewToAllApps) {
2288            duration = HIDE_WORKSPACE_DURATION; //getResources().getInteger(R.integer.config_workspaceUnshrinkTime);
2289        } else if (workspaceToOverview || overviewToWorkspace) {
2290            duration = getResources().getInteger(R.integer.config_overviewTransitionTime);
2291        } else {
2292            duration = getResources().getInteger(R.integer.config_appsCustomizeWorkspaceShrinkTime);
2293        }
2294
2295        if (snapPage == -1) {
2296            snapPage = getPageNearestToCenterOfScreen();
2297        }
2298        snapToPage(snapPage, duration, mZoomInInterpolator);
2299
2300        for (int i = 0; i < getChildCount(); i++) {
2301            final CellLayout cl = (CellLayout) getChildAt(i);
2302            boolean isCurrentPage = (i == snapPage);
2303            float initialAlpha = cl.getShortcutsAndWidgets().getAlpha();
2304            float finalAlpha;
2305            if (stateIsNormalHidden || stateIsOverviewHidden) {
2306                finalAlpha = 0f;
2307            } else if (stateIsNormal && mWorkspaceFadeInAdjacentScreens) {
2308                finalAlpha = (i == snapPage || i < numCustomPages()) ? 1f : 0f;
2309            } else {
2310                finalAlpha = 1f;
2311            }
2312
2313            // If we are animating to/from the small state, then hide the side pages and fade the
2314            // current page in
2315            if (!mIsSwitchingState) {
2316                if (workspaceToAllApps || allAppsToWorkspace) {
2317                    if (allAppsToWorkspace && isCurrentPage) {
2318                        initialAlpha = 0f;
2319                    } else if (!isCurrentPage) {
2320                        initialAlpha = finalAlpha = 0f;
2321                    }
2322                    cl.setShortcutAndWidgetAlpha(initialAlpha);
2323                }
2324            }
2325
2326            mOldAlphas[i] = initialAlpha;
2327            mNewAlphas[i] = finalAlpha;
2328            if (animated) {
2329                mOldBackgroundAlphas[i] = cl.getBackgroundAlpha();
2330                mNewBackgroundAlphas[i] = finalBackgroundAlpha;
2331            } else {
2332                cl.setBackgroundAlpha(finalBackgroundAlpha);
2333                cl.setShortcutAndWidgetAlpha(finalAlpha);
2334            }
2335        }
2336
2337        final View searchBar = mLauncher.getOrCreateQsbBar();
2338        final View overviewPanel = mLauncher.getOverviewPanel();
2339        final View hotseat = mLauncher.getHotseat();
2340        final View pageIndicator = getPageIndicator();
2341        if (animated) {
2342            LauncherViewPropertyAnimator scale = new LauncherViewPropertyAnimator(this);
2343            scale.scaleX(mNewScale)
2344                .scaleY(mNewScale)
2345                .translationY(finalWorkspaceTranslationY)
2346                .setDuration(duration)
2347                .setInterpolator(mZoomInInterpolator);
2348            anim.play(scale);
2349            for (int index = 0; index < getChildCount(); index++) {
2350                final int i = index;
2351                final CellLayout cl = (CellLayout) getChildAt(i);
2352                float currentAlpha = cl.getShortcutsAndWidgets().getAlpha();
2353                if (mOldAlphas[i] == 0 && mNewAlphas[i] == 0) {
2354                    cl.setBackgroundAlpha(mNewBackgroundAlphas[i]);
2355                    cl.setShortcutAndWidgetAlpha(mNewAlphas[i]);
2356                } else {
2357                    if (layerViews != null) {
2358                        layerViews.put(cl, LauncherStateTransitionAnimation.BUILD_LAYER);
2359                    }
2360                    if (mOldAlphas[i] != mNewAlphas[i] || currentAlpha != mNewAlphas[i]) {
2361                        LauncherViewPropertyAnimator alphaAnim =
2362                            new LauncherViewPropertyAnimator(cl.getShortcutsAndWidgets());
2363                        alphaAnim.alpha(mNewAlphas[i])
2364                            .setDuration(duration)
2365                            .setInterpolator(mZoomInInterpolator);
2366                        anim.play(alphaAnim);
2367                    }
2368                    if (mOldBackgroundAlphas[i] != 0 ||
2369                        mNewBackgroundAlphas[i] != 0) {
2370                        ValueAnimator bgAnim =
2371                                LauncherAnimUtils.ofFloat(cl, 0f, 1f);
2372                        bgAnim.setInterpolator(mZoomInInterpolator);
2373                        bgAnim.setDuration(duration);
2374                        bgAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
2375                                public void onAnimationUpdate(float a, float b) {
2376                                    cl.setBackgroundAlpha(
2377                                            a * mOldBackgroundAlphas[i] +
2378                                            b * mNewBackgroundAlphas[i]);
2379                                }
2380                            });
2381                        anim.play(bgAnim);
2382                    }
2383                }
2384            }
2385            Animator pageIndicatorAlpha = null;
2386            if (pageIndicator != null) {
2387                pageIndicatorAlpha = new LauncherViewPropertyAnimator(pageIndicator)
2388                    .alpha(finalHotseatAndPageIndicatorAlpha).withLayer();
2389                pageIndicatorAlpha.addListener(new AlphaUpdateListener(pageIndicator));
2390            } else {
2391                // create a dummy animation so we don't need to do null checks later
2392                pageIndicatorAlpha = ValueAnimator.ofFloat(0, 0);
2393            }
2394
2395            LauncherViewPropertyAnimator hotseatAlpha = new LauncherViewPropertyAnimator(hotseat)
2396                .alpha(finalHotseatAndPageIndicatorAlpha);
2397            hotseatAlpha.addListener(new AlphaUpdateListener(hotseat));
2398
2399            LauncherViewPropertyAnimator overviewPanelAlpha =
2400                    new LauncherViewPropertyAnimator(overviewPanel).alpha(finalOverviewPanelAlpha);
2401            overviewPanelAlpha.addListener(new AlphaUpdateListener(overviewPanel));
2402
2403            // For animation optimations, we may need to provide the Launcher transition
2404            // with a set of views on which to force build layers in certain scenarios.
2405            hotseat.setLayerType(View.LAYER_TYPE_HARDWARE, null);
2406            overviewPanel.setLayerType(View.LAYER_TYPE_HARDWARE, null);
2407            if (layerViews != null) {
2408                // If layerViews is not null, we add these views, and indicate that
2409                // the caller can manage layer state.
2410                layerViews.put(hotseat, LauncherStateTransitionAnimation.BUILD_AND_SET_LAYER);
2411                layerViews.put(overviewPanel, LauncherStateTransitionAnimation.BUILD_AND_SET_LAYER);
2412            } else {
2413                // Otherwise let the animator handle layer management.
2414                hotseatAlpha.withLayer();
2415                overviewPanelAlpha.withLayer();
2416            }
2417
2418            if (workspaceToOverview) {
2419                pageIndicatorAlpha.setInterpolator(new DecelerateInterpolator(2));
2420                hotseatAlpha.setInterpolator(new DecelerateInterpolator(2));
2421                overviewPanelAlpha.setInterpolator(null);
2422            } else if (overviewToWorkspace) {
2423                pageIndicatorAlpha.setInterpolator(null);
2424                hotseatAlpha.setInterpolator(null);
2425                overviewPanelAlpha.setInterpolator(new DecelerateInterpolator(2));
2426            }
2427
2428            overviewPanelAlpha.setDuration(duration);
2429            pageIndicatorAlpha.setDuration(duration);
2430            hotseatAlpha.setDuration(duration);
2431
2432            if (searchBar != null) {
2433                LauncherViewPropertyAnimator searchBarAlpha = new LauncherViewPropertyAnimator(searchBar)
2434                    .alpha(finalSearchBarAlpha);
2435                searchBarAlpha.addListener(new AlphaUpdateListener(searchBar));
2436                searchBar.setLayerType(View.LAYER_TYPE_HARDWARE, null);
2437                if (layerViews != null) {
2438                    // If layerViews is not null, we add these views, and indicate that
2439                    // the caller can manage layer state.
2440                    layerViews.put(searchBar, LauncherStateTransitionAnimation.BUILD_AND_SET_LAYER);
2441                } else {
2442                    // Otherwise let the animator handle layer management.
2443                    searchBarAlpha.withLayer();
2444                }
2445                searchBarAlpha.setDuration(duration);
2446                anim.play(searchBarAlpha);
2447            }
2448
2449            anim.play(overviewPanelAlpha);
2450            anim.play(hotseatAlpha);
2451            anim.play(pageIndicatorAlpha);
2452            anim.setStartDelay(delay);
2453            anim.addListener(new AnimatorListenerAdapter() {
2454                @Override
2455                public void onAnimationEnd(Animator animation) {
2456                    mStateAnimator = null;
2457                }
2458            });
2459        } else {
2460            overviewPanel.setAlpha(finalOverviewPanelAlpha);
2461            AlphaUpdateListener.updateVisibility(overviewPanel);
2462            hotseat.setAlpha(finalHotseatAndPageIndicatorAlpha);
2463            AlphaUpdateListener.updateVisibility(hotseat);
2464            if (pageIndicator != null) {
2465                pageIndicator.setAlpha(finalHotseatAndPageIndicatorAlpha);
2466                AlphaUpdateListener.updateVisibility(pageIndicator);
2467            }
2468            if (searchBar != null) {
2469                searchBar.setAlpha(finalSearchBarAlpha);
2470                AlphaUpdateListener.updateVisibility(searchBar);
2471            }
2472            updateCustomContentVisibility();
2473            setScaleX(mNewScale);
2474            setScaleY(mNewScale);
2475            setTranslationY(finalWorkspaceTranslationY);
2476        }
2477
2478        if (stateIsNormal) {
2479            animateBackgroundGradient(0f, animated);
2480        } else {
2481            animateBackgroundGradient(getResources().getInteger(
2482                    R.integer.config_workspaceScrimAlpha) / 100f, animated);
2483        }
2484        return anim;
2485    }
2486
2487    static class AlphaUpdateListener implements AnimatorUpdateListener, AnimatorListener {
2488        View view;
2489        public AlphaUpdateListener(View v) {
2490            view = v;
2491        }
2492
2493        @Override
2494        public void onAnimationUpdate(ValueAnimator arg0) {
2495            updateVisibility(view);
2496        }
2497
2498        public static void updateVisibility(View view) {
2499            // We want to avoid the extra layout pass by setting the views to GONE unless
2500            // accessibility is on, in which case not setting them to GONE causes a glitch.
2501            int invisibleState = sAccessibilityEnabled ? GONE : INVISIBLE;
2502            if (view.getAlpha() < ALPHA_CUTOFF_THRESHOLD && view.getVisibility() != invisibleState) {
2503                view.setVisibility(invisibleState);
2504            } else if (view.getAlpha() > ALPHA_CUTOFF_THRESHOLD
2505                    && view.getVisibility() != VISIBLE) {
2506                view.setVisibility(VISIBLE);
2507            }
2508        }
2509
2510        @Override
2511        public void onAnimationCancel(Animator arg0) {
2512        }
2513
2514        @Override
2515        public void onAnimationEnd(Animator arg0) {
2516            updateVisibility(view);
2517        }
2518
2519        @Override
2520        public void onAnimationRepeat(Animator arg0) {
2521        }
2522
2523        @Override
2524        public void onAnimationStart(Animator arg0) {
2525            // We want the views to be visible for animation, so fade-in/out is visible
2526            view.setVisibility(VISIBLE);
2527        }
2528    }
2529
2530    @Override
2531    public void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace) {
2532        onTransitionPrepare();
2533    }
2534
2535    @Override
2536    public void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace) {
2537    }
2538
2539    @Override
2540    public void onLauncherTransitionStep(Launcher l, float t) {
2541        mTransitionProgress = t;
2542    }
2543
2544    @Override
2545    public void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace) {
2546        onTransitionEnd();
2547    }
2548
2549    private void onTransitionPrepare() {
2550        mIsSwitchingState = true;
2551
2552        // Invalidate here to ensure that the pages are rendered during the state change transition.
2553        invalidate();
2554
2555        updateChildrenLayersEnabled(false);
2556        hideCustomContentIfNecessary();
2557    }
2558
2559    void updateCustomContentVisibility() {
2560        int visibility = mState == Workspace.State.NORMAL ? VISIBLE : INVISIBLE;
2561        if (hasCustomContent()) {
2562            mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID).setVisibility(visibility);
2563        }
2564    }
2565
2566    void showCustomContentIfNecessary() {
2567        boolean show  = mState == Workspace.State.NORMAL;
2568        if (show && hasCustomContent()) {
2569            mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID).setVisibility(VISIBLE);
2570        }
2571    }
2572
2573    void hideCustomContentIfNecessary() {
2574        boolean hide  = mState != Workspace.State.NORMAL;
2575        if (hide && hasCustomContent()) {
2576            disableLayoutTransitions();
2577            mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID).setVisibility(INVISIBLE);
2578            enableLayoutTransitions();
2579        }
2580    }
2581
2582    @Thunk void onTransitionEnd() {
2583        mIsSwitchingState = false;
2584        updateChildrenLayersEnabled(false);
2585        showCustomContentIfNecessary();
2586    }
2587
2588    @Override
2589    public View getContent() {
2590        return this;
2591    }
2592
2593    /**
2594     * Returns the drawable for the given text view.
2595     */
2596    public static Drawable getTextViewIcon(TextView tv) {
2597        final Drawable[] drawables = tv.getCompoundDrawables();
2598        for (int i = 0; i < drawables.length; i++) {
2599            if (drawables[i] != null) {
2600                return drawables[i];
2601            }
2602        }
2603        return null;
2604    }
2605
2606    /**
2607     * Draw the View v into the given Canvas.
2608     *
2609     * @param v the view to draw
2610     * @param destCanvas the canvas to draw on
2611     * @param padding the horizontal and vertical padding to use when drawing
2612     */
2613    private static void drawDragView(View v, Canvas destCanvas, int padding) {
2614        final Rect clipRect = sTempRect;
2615        v.getDrawingRect(clipRect);
2616
2617        boolean textVisible = false;
2618
2619        destCanvas.save();
2620        if (v instanceof TextView) {
2621            Drawable d = getTextViewIcon((TextView) v);
2622            Rect bounds = getDrawableBounds(d);
2623            clipRect.set(0, 0, bounds.width() + padding, bounds.height() + padding);
2624            destCanvas.translate(padding / 2 - bounds.left, padding / 2 - bounds.top);
2625            d.draw(destCanvas);
2626        } else {
2627            if (v instanceof FolderIcon) {
2628                // For FolderIcons the text can bleed into the icon area, and so we need to
2629                // hide the text completely (which can't be achieved by clipping).
2630                if (((FolderIcon) v).getTextVisible()) {
2631                    ((FolderIcon) v).setTextVisible(false);
2632                    textVisible = true;
2633                }
2634            }
2635            destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2);
2636            destCanvas.clipRect(clipRect, Op.REPLACE);
2637            v.draw(destCanvas);
2638
2639            // Restore text visibility of FolderIcon if necessary
2640            if (textVisible) {
2641                ((FolderIcon) v).setTextVisible(true);
2642            }
2643        }
2644        destCanvas.restore();
2645    }
2646
2647    /**
2648     * Returns a new bitmap to show when the given View is being dragged around.
2649     * Responsibility for the bitmap is transferred to the caller.
2650     * @param expectedPadding padding to add to the drag view. If a different padding was used
2651     * its value will be changed
2652     */
2653    public Bitmap createDragBitmap(View v, AtomicInteger expectedPadding) {
2654        Bitmap b;
2655
2656        int padding = expectedPadding.get();
2657        if (v instanceof TextView) {
2658            Drawable d = getTextViewIcon((TextView) v);
2659            Rect bounds = getDrawableBounds(d);
2660            b = Bitmap.createBitmap(bounds.width() + padding,
2661                    bounds.height() + padding, Bitmap.Config.ARGB_8888);
2662            expectedPadding.set(padding - bounds.left - bounds.top);
2663        } else {
2664            b = Bitmap.createBitmap(
2665                    v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
2666        }
2667
2668        mCanvas.setBitmap(b);
2669        drawDragView(v, mCanvas, padding);
2670        mCanvas.setBitmap(null);
2671
2672        return b;
2673    }
2674
2675    /**
2676     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
2677     * Responsibility for the bitmap is transferred to the caller.
2678     */
2679    private Bitmap createDragOutline(View v, int padding) {
2680        final int outlineColor = getResources().getColor(R.color.outline_color);
2681        final Bitmap b = Bitmap.createBitmap(
2682                v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
2683
2684        mCanvas.setBitmap(b);
2685        drawDragView(v, mCanvas, padding);
2686        mOutlineHelper.applyExpensiveOutlineWithBlur(b, mCanvas, outlineColor, outlineColor);
2687        mCanvas.setBitmap(null);
2688        return b;
2689    }
2690
2691    /**
2692     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
2693     * Responsibility for the bitmap is transferred to the caller.
2694     */
2695    private Bitmap createDragOutline(Bitmap orig, int padding, int w, int h,
2696            boolean clipAlpha) {
2697        final int outlineColor = getResources().getColor(R.color.outline_color);
2698        final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
2699        mCanvas.setBitmap(b);
2700
2701        Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight());
2702        float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(),
2703                (h - padding) / (float) orig.getHeight());
2704        int scaledWidth = (int) (scaleFactor * orig.getWidth());
2705        int scaledHeight = (int) (scaleFactor * orig.getHeight());
2706        Rect dst = new Rect(0, 0, scaledWidth, scaledHeight);
2707
2708        // center the image
2709        dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2);
2710
2711        mCanvas.drawBitmap(orig, src, dst, null);
2712        mOutlineHelper.applyExpensiveOutlineWithBlur(b, mCanvas, outlineColor, outlineColor,
2713                clipAlpha);
2714        mCanvas.setBitmap(null);
2715
2716        return b;
2717    }
2718
2719    public void startDrag(CellLayout.CellInfo cellInfo) {
2720        startDrag(cellInfo, false);
2721    }
2722
2723    public void startDrag(CellLayout.CellInfo cellInfo, boolean accessible) {
2724        View child = cellInfo.cell;
2725
2726        // Make sure the drag was started by a long press as opposed to a long click.
2727        if (!child.isInTouchMode()) {
2728            return;
2729        }
2730
2731        mDragInfo = cellInfo;
2732        child.setVisibility(INVISIBLE);
2733        CellLayout layout = (CellLayout) child.getParent().getParent();
2734        layout.prepareChildForDrag(child);
2735
2736        beginDragShared(child, this, accessible);
2737    }
2738
2739    public void beginDragShared(View child, DragSource source, boolean accessible) {
2740        beginDragShared(child, new Point(), source, accessible);
2741    }
2742
2743    public void beginDragShared(View child, Point relativeTouchPos, DragSource source,
2744            boolean accessible) {
2745        child.clearFocus();
2746        child.setPressed(false);
2747
2748        // The outline is used to visualize where the item will land if dropped
2749        mDragOutline = createDragOutline(child, DRAG_BITMAP_PADDING);
2750
2751        mLauncher.onDragStarted(child);
2752        // The drag bitmap follows the touch point around on the screen
2753        AtomicInteger padding = new AtomicInteger(DRAG_BITMAP_PADDING);
2754        final Bitmap b = createDragBitmap(child, padding);
2755
2756        final int bmpWidth = b.getWidth();
2757        final int bmpHeight = b.getHeight();
2758
2759        float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY);
2760        int dragLayerX = Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2);
2761        int dragLayerY = Math.round(mTempXY[1] - (bmpHeight - scale * bmpHeight) / 2
2762                        - padding.get() / 2);
2763
2764        LauncherAppState app = LauncherAppState.getInstance();
2765        DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
2766        Point dragVisualizeOffset = null;
2767        Rect dragRect = null;
2768        if (child instanceof BubbleTextView) {
2769            BubbleTextView icon = (BubbleTextView) child;
2770            int iconSize = grid.iconSizePx;
2771            int top = child.getPaddingTop();
2772            int left = (bmpWidth - iconSize) / 2;
2773            int right = left + iconSize;
2774            int bottom = top + iconSize;
2775            if (icon.isLayoutHorizontal()) {
2776                // If the layout is horizontal, then if we are just picking up the icon, then just
2777                // use the child position since the icon is top-left aligned.  Otherwise, offset
2778                // the drag layer position horizontally so that the icon is under the current
2779                // touch position.
2780                if (icon.getIcon().getBounds().contains(relativeTouchPos.x, relativeTouchPos.y)) {
2781                    dragLayerX = Math.round(mTempXY[0]);
2782                } else {
2783                    dragLayerX = Math.round(mTempXY[0] + relativeTouchPos.x - (bmpWidth / 2));
2784                }
2785            }
2786            dragLayerY += top;
2787            // Note: The drag region is used to calculate drag layer offsets, but the
2788            // dragVisualizeOffset in addition to the dragRect (the size) to position the outline.
2789            dragVisualizeOffset = new Point(-padding.get() / 2, padding.get() / 2);
2790            dragRect = new Rect(left, top, right, bottom);
2791        } else if (child instanceof FolderIcon) {
2792            int previewSize = grid.folderIconSizePx;
2793            dragRect = new Rect(0, child.getPaddingTop(), child.getWidth(), previewSize);
2794        }
2795
2796        // Clear the pressed state if necessary
2797        if (child instanceof BubbleTextView) {
2798            BubbleTextView icon = (BubbleTextView) child;
2799            icon.clearPressedBackground();
2800        }
2801
2802        if (child.getTag() == null || !(child.getTag() instanceof ItemInfo)) {
2803            String msg = "Drag started with a view that has no tag set. This "
2804                    + "will cause a crash (issue 11627249) down the line. "
2805                    + "View: " + child + "  tag: " + child.getTag();
2806            throw new IllegalStateException(msg);
2807        }
2808
2809        DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(),
2810                DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect, scale, accessible);
2811        dv.setIntrinsicIconScaleFactor(source.getIntrinsicIconScaleFactor());
2812
2813        if (child.getParent() instanceof ShortcutAndWidgetContainer) {
2814            mDragSourceInternal = (ShortcutAndWidgetContainer) child.getParent();
2815        }
2816
2817        b.recycle();
2818    }
2819
2820    public void beginExternalDragShared(View child, DragSource source) {
2821        LauncherAppState app = LauncherAppState.getInstance();
2822        DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
2823        int iconSize = grid.iconSizePx;
2824
2825        // Notify launcher of drag start
2826        mLauncher.onDragStarted(child);
2827
2828        // Compose a new drag bitmap that is of the icon size
2829        AtomicInteger padding = new AtomicInteger(DRAG_BITMAP_PADDING);
2830        final Bitmap tmpB = createDragBitmap(child, padding);
2831        Bitmap b = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888);
2832        Paint p = new Paint();
2833        p.setFilterBitmap(true);
2834        mCanvas.setBitmap(b);
2835        mCanvas.drawBitmap(tmpB, new Rect(0, 0, tmpB.getWidth(), tmpB.getHeight()),
2836                new Rect(0, 0, iconSize, iconSize), p);
2837        mCanvas.setBitmap(null);
2838
2839        // Find the child's location on the screen
2840        int bmpWidth = tmpB.getWidth();
2841        float iconScale = (float) bmpWidth / iconSize;
2842        float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY) * iconScale;
2843        int dragLayerX = Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2);
2844        int dragLayerY = Math.round(mTempXY[1]);
2845
2846        // Note: The drag region is used to calculate drag layer offsets, but the
2847        // dragVisualizeOffset in addition to the dragRect (the size) to position the outline.
2848        Point dragVisualizeOffset = new Point(-padding.get() / 2, padding.get() / 2);
2849        Rect dragRect = new Rect(0, 0, iconSize, iconSize);
2850
2851        if (child.getTag() == null || !(child.getTag() instanceof ItemInfo)) {
2852            String msg = "Drag started with a view that has no tag set. This "
2853                    + "will cause a crash (issue 11627249) down the line. "
2854                    + "View: " + child + "  tag: " + child.getTag();
2855            throw new IllegalStateException(msg);
2856        }
2857
2858        // Start the drag
2859        DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(),
2860                DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect, scale, false);
2861        dv.setIntrinsicIconScaleFactor(source.getIntrinsicIconScaleFactor());
2862
2863        // Recycle temporary bitmaps
2864        tmpB.recycle();
2865    }
2866
2867    public boolean transitionStateShouldAllowDrop() {
2868        return ((!isSwitchingState() || mTransitionProgress > 0.5f) &&
2869                (mState == State.NORMAL || mState == State.SPRING_LOADED));
2870    }
2871
2872    /**
2873     * {@inheritDoc}
2874     */
2875    public boolean acceptDrop(DragObject d) {
2876        // If it's an external drop (e.g. from All Apps), check if it should be accepted
2877        CellLayout dropTargetLayout = mDropToLayout;
2878        if (d.dragSource != this) {
2879            // Don't accept the drop if we're not over a screen at time of drop
2880            if (dropTargetLayout == null) {
2881                return false;
2882            }
2883            if (!transitionStateShouldAllowDrop()) return false;
2884
2885            mDragViewVisualCenter = d.getVisualCenter(mDragViewVisualCenter);
2886
2887            // We want the point to be mapped to the dragTarget.
2888            if (mLauncher.isHotseatLayout(dropTargetLayout)) {
2889                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
2890            } else {
2891                mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter, null);
2892            }
2893
2894            int spanX = 1;
2895            int spanY = 1;
2896            if (mDragInfo != null) {
2897                final CellLayout.CellInfo dragCellInfo = mDragInfo;
2898                spanX = dragCellInfo.spanX;
2899                spanY = dragCellInfo.spanY;
2900            } else {
2901                final ItemInfo dragInfo = (ItemInfo) d.dragInfo;
2902                spanX = dragInfo.spanX;
2903                spanY = dragInfo.spanY;
2904            }
2905
2906            int minSpanX = spanX;
2907            int minSpanY = spanY;
2908            if (d.dragInfo instanceof PendingAddWidgetInfo) {
2909                minSpanX = ((PendingAddWidgetInfo) d.dragInfo).minSpanX;
2910                minSpanY = ((PendingAddWidgetInfo) d.dragInfo).minSpanY;
2911            }
2912
2913            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2914                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, dropTargetLayout,
2915                    mTargetCell);
2916            float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0],
2917                    mDragViewVisualCenter[1], mTargetCell);
2918            if (mCreateUserFolderOnDrop && willCreateUserFolder((ItemInfo) d.dragInfo,
2919                    dropTargetLayout, mTargetCell, distance, true)) {
2920                return true;
2921            }
2922
2923            if (mAddToExistingFolderOnDrop && willAddToExistingUserFolder((ItemInfo) d.dragInfo,
2924                    dropTargetLayout, mTargetCell, distance)) {
2925                return true;
2926            }
2927
2928            int[] resultSpan = new int[2];
2929            mTargetCell = dropTargetLayout.performReorder((int) mDragViewVisualCenter[0],
2930                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY,
2931                    null, mTargetCell, resultSpan, CellLayout.MODE_ACCEPT_DROP);
2932            boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0;
2933
2934            // Don't accept the drop if there's no room for the item
2935            if (!foundCell) {
2936                // Don't show the message if we are dropping on the AllApps button and the hotseat
2937                // is full
2938                boolean isHotseat = mLauncher.isHotseatLayout(dropTargetLayout);
2939                if (mTargetCell != null && isHotseat) {
2940                    Hotseat hotseat = mLauncher.getHotseat();
2941                    if (hotseat.isAllAppsButtonRank(
2942                            hotseat.getOrderInHotseat(mTargetCell[0], mTargetCell[1]))) {
2943                        return false;
2944                    }
2945                }
2946
2947                mLauncher.showOutOfSpaceMessage(isHotseat);
2948                return false;
2949            }
2950        }
2951
2952        long screenId = getIdForScreen(dropTargetLayout);
2953        if (screenId == EXTRA_EMPTY_SCREEN_ID) {
2954            commitExtraEmptyScreen();
2955        }
2956
2957        return true;
2958    }
2959
2960    boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell, float
2961            distance, boolean considerTimeout) {
2962        if (distance > mMaxDistanceForFolderCreation) return false;
2963        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2964
2965        if (dropOverView != null) {
2966            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams();
2967            if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.tmpCellY)) {
2968                return false;
2969            }
2970        }
2971
2972        boolean hasntMoved = false;
2973        if (mDragInfo != null) {
2974            hasntMoved = dropOverView == mDragInfo.cell;
2975        }
2976
2977        if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) {
2978            return false;
2979        }
2980
2981        boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo);
2982        boolean willBecomeShortcut =
2983                (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
2984                info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT);
2985
2986        return (aboveShortcut && willBecomeShortcut);
2987    }
2988
2989    boolean willAddToExistingUserFolder(Object dragInfo, CellLayout target, int[] targetCell,
2990            float distance) {
2991        if (distance > mMaxDistanceForFolderCreation) return false;
2992        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2993
2994        if (dropOverView != null) {
2995            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams();
2996            if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.tmpCellY)) {
2997                return false;
2998            }
2999        }
3000
3001        if (dropOverView instanceof FolderIcon) {
3002            FolderIcon fi = (FolderIcon) dropOverView;
3003            if (fi.acceptDrop(dragInfo)) {
3004                return true;
3005            }
3006        }
3007        return false;
3008    }
3009
3010    boolean createUserFolderIfNecessary(View newView, long container, CellLayout target,
3011            int[] targetCell, float distance, boolean external, DragView dragView,
3012            Runnable postAnimationRunnable) {
3013        if (distance > mMaxDistanceForFolderCreation) return false;
3014        View v = target.getChildAt(targetCell[0], targetCell[1]);
3015
3016        boolean hasntMoved = false;
3017        if (mDragInfo != null) {
3018            CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell);
3019            hasntMoved = (mDragInfo.cellX == targetCell[0] &&
3020                    mDragInfo.cellY == targetCell[1]) && (cellParent == target);
3021        }
3022
3023        if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false;
3024        mCreateUserFolderOnDrop = false;
3025        final long screenId = (targetCell == null) ? mDragInfo.screenId : getIdForScreen(target);
3026
3027        boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo);
3028        boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo);
3029
3030        if (aboveShortcut && willBecomeShortcut) {
3031            ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag();
3032            ShortcutInfo destInfo = (ShortcutInfo) v.getTag();
3033            // if the drag started here, we need to remove it from the workspace
3034            if (!external) {
3035                getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
3036            }
3037
3038            Rect folderLocation = new Rect();
3039            float scale = mLauncher.getDragLayer().getDescendantRectRelativeToSelf(v, folderLocation);
3040            target.removeView(v);
3041
3042            FolderIcon fi =
3043                mLauncher.addFolder(target, container, screenId, targetCell[0], targetCell[1]);
3044            destInfo.cellX = -1;
3045            destInfo.cellY = -1;
3046            sourceInfo.cellX = -1;
3047            sourceInfo.cellY = -1;
3048
3049            // If the dragView is null, we can't animate
3050            boolean animate = dragView != null;
3051            if (animate) {
3052                fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale,
3053                        postAnimationRunnable);
3054            } else {
3055                fi.addItem(destInfo);
3056                fi.addItem(sourceInfo);
3057            }
3058            return true;
3059        }
3060        return false;
3061    }
3062
3063    boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell,
3064            float distance, DragObject d, boolean external) {
3065        if (distance > mMaxDistanceForFolderCreation) return false;
3066
3067        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
3068        if (!mAddToExistingFolderOnDrop) return false;
3069        mAddToExistingFolderOnDrop = false;
3070
3071        if (dropOverView instanceof FolderIcon) {
3072            FolderIcon fi = (FolderIcon) dropOverView;
3073            if (fi.acceptDrop(d.dragInfo)) {
3074                fi.onDrop(d);
3075
3076                // if the drag started here, we need to remove it from the workspace
3077                if (!external) {
3078                    getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
3079                }
3080                return true;
3081            }
3082        }
3083        return false;
3084    }
3085
3086    public void onDrop(final DragObject d) {
3087        mDragViewVisualCenter = d.getVisualCenter(mDragViewVisualCenter);
3088        CellLayout dropTargetLayout = mDropToLayout;
3089
3090        // We want the point to be mapped to the dragTarget.
3091        if (dropTargetLayout != null) {
3092            if (mLauncher.isHotseatLayout(dropTargetLayout)) {
3093                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
3094            } else {
3095                mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter, null);
3096            }
3097        }
3098
3099        int snapScreen = -1;
3100        boolean resizeOnDrop = false;
3101        if (d.dragSource != this) {
3102            final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0],
3103                    (int) mDragViewVisualCenter[1] };
3104            onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d);
3105        } else if (mDragInfo != null) {
3106            final View cell = mDragInfo.cell;
3107
3108            Runnable resizeRunnable = null;
3109            if (dropTargetLayout != null && !d.cancelled) {
3110                // Move internally
3111                boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout);
3112                boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout);
3113                long container = hasMovedIntoHotseat ?
3114                        LauncherSettings.Favorites.CONTAINER_HOTSEAT :
3115                        LauncherSettings.Favorites.CONTAINER_DESKTOP;
3116                long screenId = (mTargetCell[0] < 0) ?
3117                        mDragInfo.screenId : getIdForScreen(dropTargetLayout);
3118                int spanX = mDragInfo != null ? mDragInfo.spanX : 1;
3119                int spanY = mDragInfo != null ? mDragInfo.spanY : 1;
3120                // First we find the cell nearest to point at which the item is
3121                // dropped, without any consideration to whether there is an item there.
3122
3123                mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int)
3124                        mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell);
3125                float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0],
3126                        mDragViewVisualCenter[1], mTargetCell);
3127
3128                // If the item being dropped is a shortcut and the nearest drop
3129                // cell also contains a shortcut, then create a folder with the two shortcuts.
3130                if (!mInScrollArea && createUserFolderIfNecessary(cell, container,
3131                        dropTargetLayout, mTargetCell, distance, false, d.dragView, null)) {
3132                    return;
3133                }
3134
3135                if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell,
3136                        distance, d, false)) {
3137                    return;
3138                }
3139
3140                // Aside from the special case where we're dropping a shortcut onto a shortcut,
3141                // we need to find the nearest cell location that is vacant
3142                ItemInfo item = (ItemInfo) d.dragInfo;
3143                int minSpanX = item.spanX;
3144                int minSpanY = item.spanY;
3145                if (item.minSpanX > 0 && item.minSpanY > 0) {
3146                    minSpanX = item.minSpanX;
3147                    minSpanY = item.minSpanY;
3148                }
3149
3150                int[] resultSpan = new int[2];
3151                mTargetCell = dropTargetLayout.performReorder((int) mDragViewVisualCenter[0],
3152                        (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, cell,
3153                        mTargetCell, resultSpan, CellLayout.MODE_ON_DROP);
3154
3155                boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0;
3156
3157                // if the widget resizes on drop
3158                if (foundCell && (cell instanceof AppWidgetHostView) &&
3159                        (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY)) {
3160                    resizeOnDrop = true;
3161                    item.spanX = resultSpan[0];
3162                    item.spanY = resultSpan[1];
3163                    AppWidgetHostView awhv = (AppWidgetHostView) cell;
3164                    AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, resultSpan[0],
3165                            resultSpan[1]);
3166                }
3167
3168                if (getScreenIdForPageIndex(mCurrentPage) != screenId && !hasMovedIntoHotseat) {
3169                    snapScreen = getPageIndexForScreenId(screenId);
3170                    snapToPage(snapScreen);
3171                }
3172
3173                if (foundCell) {
3174                    final ItemInfo info = (ItemInfo) cell.getTag();
3175                    if (hasMovedLayouts) {
3176                        // Reparent the view
3177                        CellLayout parentCell = getParentCellLayoutForView(cell);
3178                        if (parentCell != null) {
3179                            parentCell.removeView(cell);
3180                        } else if (LauncherAppState.isDogfoodBuild()) {
3181                            throw new NullPointerException("mDragInfo.cell has null parent");
3182                        }
3183                        addInScreen(cell, container, screenId, mTargetCell[0], mTargetCell[1],
3184                                info.spanX, info.spanY);
3185                    }
3186
3187                    // update the item's position after drop
3188                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
3189                    lp.cellX = lp.tmpCellX = mTargetCell[0];
3190                    lp.cellY = lp.tmpCellY = mTargetCell[1];
3191                    lp.cellHSpan = item.spanX;
3192                    lp.cellVSpan = item.spanY;
3193                    lp.isLockedToGrid = true;
3194
3195                    if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
3196                            cell instanceof LauncherAppWidgetHostView) {
3197                        final CellLayout cellLayout = dropTargetLayout;
3198                        // We post this call so that the widget has a chance to be placed
3199                        // in its final location
3200
3201                        final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell;
3202                        AppWidgetProviderInfo pInfo = hostView.getAppWidgetInfo();
3203                        if (pInfo != null && pInfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE
3204                                && !d.accessibleDrag) {
3205                            final Runnable addResizeFrame = new Runnable() {
3206                                public void run() {
3207                                    DragLayer dragLayer = mLauncher.getDragLayer();
3208                                    dragLayer.addResizeFrame(info, hostView, cellLayout);
3209                                }
3210                            };
3211                            resizeRunnable = (new Runnable() {
3212                                public void run() {
3213                                    if (!isPageMoving()) {
3214                                        addResizeFrame.run();
3215                                    } else {
3216                                        mDelayedResizeRunnable = addResizeFrame;
3217                                    }
3218                                }
3219                            });
3220                        }
3221                    }
3222
3223                    LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId, lp.cellX,
3224                            lp.cellY, item.spanX, item.spanY);
3225                } else {
3226                    // If we can't find a drop location, we return the item to its original position
3227                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
3228                    mTargetCell[0] = lp.cellX;
3229                    mTargetCell[1] = lp.cellY;
3230                    CellLayout layout = (CellLayout) cell.getParent().getParent();
3231                    layout.markCellsAsOccupiedForView(cell);
3232                }
3233            }
3234
3235            final CellLayout parent = (CellLayout) cell.getParent().getParent();
3236            final Runnable finalResizeRunnable = resizeRunnable;
3237            // Prepare it to be animated into its new position
3238            // This must be called after the view has been re-parented
3239            final Runnable onCompleteRunnable = new Runnable() {
3240                @Override
3241                public void run() {
3242                    mAnimatingViewIntoPlace = false;
3243                    updateChildrenLayersEnabled(false);
3244                    if (finalResizeRunnable != null) {
3245                        finalResizeRunnable.run();
3246                    }
3247                }
3248            };
3249            mAnimatingViewIntoPlace = true;
3250            if (d.dragView.hasDrawn()) {
3251                final ItemInfo info = (ItemInfo) cell.getTag();
3252                boolean isWidget = info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET
3253                        || info.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
3254                if (isWidget) {
3255                    int animationType = resizeOnDrop ? ANIMATE_INTO_POSITION_AND_RESIZE :
3256                            ANIMATE_INTO_POSITION_AND_DISAPPEAR;
3257                    animateWidgetDrop(info, parent, d.dragView,
3258                            onCompleteRunnable, animationType, cell, false);
3259                } else {
3260                    int duration = snapScreen < 0 ? -1 : ADJACENT_SCREEN_DROP_DURATION;
3261                    mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration,
3262                            onCompleteRunnable, this);
3263                }
3264            } else {
3265                d.deferDragViewCleanupPostAnimation = false;
3266                cell.setVisibility(VISIBLE);
3267            }
3268            parent.onDropChild(cell);
3269        }
3270    }
3271
3272    public void setFinalScrollForPageChange(int pageIndex) {
3273        CellLayout cl = (CellLayout) getChildAt(pageIndex);
3274        if (cl != null) {
3275            mSavedScrollX = getScrollX();
3276            mSavedTranslationX = cl.getTranslationX();
3277            mSavedRotationY = cl.getRotationY();
3278            final int newX = getScrollForPage(pageIndex);
3279            setScrollX(newX);
3280            cl.setTranslationX(0f);
3281            cl.setRotationY(0f);
3282        }
3283    }
3284
3285    public void resetFinalScrollForPageChange(int pageIndex) {
3286        if (pageIndex >= 0) {
3287            CellLayout cl = (CellLayout) getChildAt(pageIndex);
3288            setScrollX(mSavedScrollX);
3289            cl.setTranslationX(mSavedTranslationX);
3290            cl.setRotationY(mSavedRotationY);
3291        }
3292    }
3293
3294    public void getViewLocationRelativeToSelf(View v, int[] location) {
3295        getLocationInWindow(location);
3296        int x = location[0];
3297        int y = location[1];
3298
3299        v.getLocationInWindow(location);
3300        int vX = location[0];
3301        int vY = location[1];
3302
3303        location[0] = vX - x;
3304        location[1] = vY - y;
3305    }
3306
3307    public void onDragEnter(DragObject d) {
3308        mDragEnforcer.onDragEnter();
3309        mCreateUserFolderOnDrop = false;
3310        mAddToExistingFolderOnDrop = false;
3311
3312        mDropToLayout = null;
3313        CellLayout layout = getCurrentDropLayout();
3314        setCurrentDropLayout(layout);
3315        setCurrentDragOverlappingLayout(layout);
3316
3317        if (!workspaceInModalState()) {
3318            mLauncher.getDragLayer().showPageHints();
3319        }
3320    }
3321
3322    /** Return a rect that has the cellWidth/cellHeight (left, top), and
3323     * widthGap/heightGap (right, bottom) */
3324    static Rect getCellLayoutMetrics(Launcher launcher, int orientation) {
3325        LauncherAppState app = LauncherAppState.getInstance();
3326        DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
3327
3328        Display display = launcher.getWindowManager().getDefaultDisplay();
3329        Point smallestSize = new Point();
3330        Point largestSize = new Point();
3331        display.getCurrentSizeRange(smallestSize, largestSize);
3332        int countX = (int) grid.numColumns;
3333        int countY = (int) grid.numRows;
3334        if (orientation == CellLayout.LANDSCAPE) {
3335            if (mLandscapeCellLayoutMetrics == null) {
3336                Rect padding = grid.getWorkspacePadding(CellLayout.LANDSCAPE);
3337                int width = largestSize.x - padding.left - padding.right;
3338                int height = smallestSize.y - padding.top - padding.bottom;
3339                mLandscapeCellLayoutMetrics = new Rect();
3340                mLandscapeCellLayoutMetrics.set(
3341                        grid.calculateCellWidth(width, countX),
3342                        grid.calculateCellHeight(height, countY), 0, 0);
3343            }
3344            return mLandscapeCellLayoutMetrics;
3345        } else if (orientation == CellLayout.PORTRAIT) {
3346            if (mPortraitCellLayoutMetrics == null) {
3347                Rect padding = grid.getWorkspacePadding(CellLayout.PORTRAIT);
3348                int width = smallestSize.x - padding.left - padding.right;
3349                int height = largestSize.y - padding.top - padding.bottom;
3350                mPortraitCellLayoutMetrics = new Rect();
3351                mPortraitCellLayoutMetrics.set(
3352                        grid.calculateCellWidth(width, countX),
3353                        grid.calculateCellHeight(height, countY), 0, 0);
3354            }
3355            return mPortraitCellLayoutMetrics;
3356        }
3357        return null;
3358    }
3359
3360    public void onDragExit(DragObject d) {
3361        mDragEnforcer.onDragExit();
3362
3363        // Here we store the final page that will be dropped to, if the workspace in fact
3364        // receives the drop
3365        if (mInScrollArea) {
3366            if (isPageMoving()) {
3367                // If the user drops while the page is scrolling, we should use that page as the
3368                // destination instead of the page that is being hovered over.
3369                mDropToLayout = (CellLayout) getPageAt(getNextPage());
3370            } else {
3371                mDropToLayout = mDragOverlappingLayout;
3372            }
3373        } else {
3374            mDropToLayout = mDragTargetLayout;
3375        }
3376
3377        if (mDragMode == DRAG_MODE_CREATE_FOLDER) {
3378            mCreateUserFolderOnDrop = true;
3379        } else if (mDragMode == DRAG_MODE_ADD_TO_FOLDER) {
3380            mAddToExistingFolderOnDrop = true;
3381        }
3382
3383        // Reset the scroll area and previous drag target
3384        onResetScrollArea();
3385        setCurrentDropLayout(null);
3386        setCurrentDragOverlappingLayout(null);
3387
3388        mSpringLoadedDragController.cancel();
3389
3390        if (!mIsPageMoving) {
3391            hideOutlines();
3392        }
3393        mLauncher.getDragLayer().hidePageHints();
3394    }
3395
3396    void setCurrentDropLayout(CellLayout layout) {
3397        if (mDragTargetLayout != null) {
3398            mDragTargetLayout.revertTempState();
3399            mDragTargetLayout.onDragExit();
3400        }
3401        mDragTargetLayout = layout;
3402        if (mDragTargetLayout != null) {
3403            mDragTargetLayout.onDragEnter();
3404        }
3405        cleanupReorder(true);
3406        cleanupFolderCreation();
3407        setCurrentDropOverCell(-1, -1);
3408    }
3409
3410    void setCurrentDragOverlappingLayout(CellLayout layout) {
3411        if (mDragOverlappingLayout != null) {
3412            mDragOverlappingLayout.setIsDragOverlapping(false);
3413        }
3414        mDragOverlappingLayout = layout;
3415        if (mDragOverlappingLayout != null) {
3416            mDragOverlappingLayout.setIsDragOverlapping(true);
3417        }
3418        invalidate();
3419    }
3420
3421    void setCurrentDropOverCell(int x, int y) {
3422        if (x != mDragOverX || y != mDragOverY) {
3423            mDragOverX = x;
3424            mDragOverY = y;
3425            setDragMode(DRAG_MODE_NONE);
3426        }
3427    }
3428
3429    void setDragMode(int dragMode) {
3430        if (dragMode != mDragMode) {
3431            if (dragMode == DRAG_MODE_NONE) {
3432                cleanupAddToFolder();
3433                // We don't want to cancel the re-order alarm every time the target cell changes
3434                // as this feels to slow / unresponsive.
3435                cleanupReorder(false);
3436                cleanupFolderCreation();
3437            } else if (dragMode == DRAG_MODE_ADD_TO_FOLDER) {
3438                cleanupReorder(true);
3439                cleanupFolderCreation();
3440            } else if (dragMode == DRAG_MODE_CREATE_FOLDER) {
3441                cleanupAddToFolder();
3442                cleanupReorder(true);
3443            } else if (dragMode == DRAG_MODE_REORDER) {
3444                cleanupAddToFolder();
3445                cleanupFolderCreation();
3446            }
3447            mDragMode = dragMode;
3448        }
3449    }
3450
3451    private void cleanupFolderCreation() {
3452        if (mDragFolderRingAnimator != null) {
3453            mDragFolderRingAnimator.animateToNaturalState();
3454            mDragFolderRingAnimator = null;
3455        }
3456        mFolderCreationAlarm.setOnAlarmListener(null);
3457        mFolderCreationAlarm.cancelAlarm();
3458    }
3459
3460    private void cleanupAddToFolder() {
3461        if (mDragOverFolderIcon != null) {
3462            mDragOverFolderIcon.onDragExit(null);
3463            mDragOverFolderIcon = null;
3464        }
3465    }
3466
3467    private void cleanupReorder(boolean cancelAlarm) {
3468        // Any pending reorders are canceled
3469        if (cancelAlarm) {
3470            mReorderAlarm.cancelAlarm();
3471        }
3472        mLastReorderX = -1;
3473        mLastReorderY = -1;
3474    }
3475
3476   /*
3477    *
3478    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
3479    * coordinate space. The argument xy is modified with the return result.
3480    *
3481    * if cachedInverseMatrix is not null, this method will just use that matrix instead of
3482    * computing it itself; we use this to avoid redundant matrix inversions in
3483    * findMatchingPageForDragOver
3484    *
3485    */
3486   void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) {
3487       xy[0] = xy[0] - v.getLeft();
3488       xy[1] = xy[1] - v.getTop();
3489   }
3490
3491   boolean isPointInSelfOverHotseat(int x, int y, Rect r) {
3492       if (r == null) {
3493           r = new Rect();
3494       }
3495       mTempPt[0] = x;
3496       mTempPt[1] = y;
3497       mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempPt, true);
3498
3499       LauncherAppState app = LauncherAppState.getInstance();
3500       DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
3501       r = grid.getHotseatRect();
3502       if (r.contains(mTempPt[0], mTempPt[1])) {
3503           return true;
3504       }
3505       return false;
3506   }
3507
3508   void mapPointFromSelfToHotseatLayout(Hotseat hotseat, float[] xy) {
3509       mTempPt[0] = (int) xy[0];
3510       mTempPt[1] = (int) xy[1];
3511       mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempPt, true);
3512       mLauncher.getDragLayer().mapCoordInSelfToDescendent(hotseat.getLayout(), mTempPt);
3513
3514       xy[0] = mTempPt[0];
3515       xy[1] = mTempPt[1];
3516   }
3517
3518   /*
3519    *
3520    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
3521    * the parent View's coordinate space. The argument xy is modified with the return result.
3522    *
3523    */
3524   void mapPointFromChildToSelf(View v, float[] xy) {
3525       xy[0] += v.getLeft();
3526       xy[1] += v.getTop();
3527   }
3528
3529   static private float squaredDistance(float[] point1, float[] point2) {
3530        float distanceX = point1[0] - point2[0];
3531        float distanceY = point2[1] - point2[1];
3532        return distanceX * distanceX + distanceY * distanceY;
3533   }
3534
3535    /*
3536     *
3537     * This method returns the CellLayout that is currently being dragged to. In order to drag
3538     * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
3539     * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
3540     *
3541     * Return null if no CellLayout is currently being dragged over
3542     *
3543     */
3544    private CellLayout findMatchingPageForDragOver(
3545            DragView dragView, float originX, float originY, boolean exact) {
3546        // We loop through all the screens (ie CellLayouts) and see which ones overlap
3547        // with the item being dragged and then choose the one that's closest to the touch point
3548        final int screenCount = getChildCount();
3549        CellLayout bestMatchingScreen = null;
3550        float smallestDistSoFar = Float.MAX_VALUE;
3551
3552        for (int i = 0; i < screenCount; i++) {
3553            // The custom content screen is not a valid drag over option
3554            if (mScreenOrder.get(i) == CUSTOM_CONTENT_SCREEN_ID) {
3555                continue;
3556            }
3557
3558            CellLayout cl = (CellLayout) getChildAt(i);
3559
3560            final float[] touchXy = {originX, originY};
3561            // Transform the touch coordinates to the CellLayout's local coordinates
3562            // If the touch point is within the bounds of the cell layout, we can return immediately
3563            cl.getMatrix().invert(mTempInverseMatrix);
3564            mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix);
3565
3566            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
3567                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
3568                return cl;
3569            }
3570
3571            if (!exact) {
3572                // Get the center of the cell layout in screen coordinates
3573                final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
3574                cellLayoutCenter[0] = cl.getWidth()/2;
3575                cellLayoutCenter[1] = cl.getHeight()/2;
3576                mapPointFromChildToSelf(cl, cellLayoutCenter);
3577
3578                touchXy[0] = originX;
3579                touchXy[1] = originY;
3580
3581                // Calculate the distance between the center of the CellLayout
3582                // and the touch point
3583                float dist = squaredDistance(touchXy, cellLayoutCenter);
3584
3585                if (dist < smallestDistSoFar) {
3586                    smallestDistSoFar = dist;
3587                    bestMatchingScreen = cl;
3588                }
3589            }
3590        }
3591        return bestMatchingScreen;
3592    }
3593
3594    private boolean isDragWidget(DragObject d) {
3595        return (d.dragInfo instanceof LauncherAppWidgetInfo ||
3596                d.dragInfo instanceof PendingAddWidgetInfo);
3597    }
3598    private boolean isExternalDragWidget(DragObject d) {
3599        return d.dragSource != this && isDragWidget(d);
3600    }
3601
3602    public void onDragOver(DragObject d) {
3603        // Skip drag over events while we are dragging over side pages
3604        if (mInScrollArea || !transitionStateShouldAllowDrop()) return;
3605
3606        Rect r = new Rect();
3607        CellLayout layout = null;
3608        ItemInfo item = (ItemInfo) d.dragInfo;
3609        if (item == null) {
3610            if (LauncherAppState.isDogfoodBuild()) {
3611                throw new NullPointerException("DragObject has null info");
3612            }
3613            return;
3614        }
3615
3616        // Ensure that we have proper spans for the item that we are dropping
3617        if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found");
3618        mDragViewVisualCenter = d.getVisualCenter(mDragViewVisualCenter);
3619
3620        final View child = (mDragInfo == null) ? null : mDragInfo.cell;
3621        // Identify whether we have dragged over a side page
3622        if (workspaceInModalState()) {
3623            if (mLauncher.getHotseat() != null && !isExternalDragWidget(d)) {
3624                if (isPointInSelfOverHotseat(d.x, d.y, r)) {
3625                    layout = mLauncher.getHotseat().getLayout();
3626                }
3627            }
3628            if (layout == null) {
3629                layout = findMatchingPageForDragOver(d.dragView, d.x, d.y, false);
3630            }
3631            if (layout != mDragTargetLayout) {
3632                setCurrentDropLayout(layout);
3633                setCurrentDragOverlappingLayout(layout);
3634
3635                boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED);
3636                if (isInSpringLoadedMode) {
3637                    if (mLauncher.isHotseatLayout(layout)) {
3638                        mSpringLoadedDragController.cancel();
3639                    } else {
3640                        mSpringLoadedDragController.setAlarm(mDragTargetLayout);
3641                    }
3642                }
3643            }
3644        } else {
3645            // Test to see if we are over the hotseat otherwise just use the current page
3646            if (mLauncher.getHotseat() != null && !isDragWidget(d)) {
3647                if (isPointInSelfOverHotseat(d.x, d.y, r)) {
3648                    layout = mLauncher.getHotseat().getLayout();
3649                }
3650            }
3651            if (layout == null) {
3652                layout = getCurrentDropLayout();
3653            }
3654            if (layout != mDragTargetLayout) {
3655                setCurrentDropLayout(layout);
3656                setCurrentDragOverlappingLayout(layout);
3657            }
3658        }
3659
3660        // Handle the drag over
3661        if (mDragTargetLayout != null) {
3662            // We want the point to be mapped to the dragTarget.
3663            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
3664                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
3665            } else {
3666                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
3667            }
3668
3669            ItemInfo info = (ItemInfo) d.dragInfo;
3670
3671            int minSpanX = item.spanX;
3672            int minSpanY = item.spanY;
3673            if (item.minSpanX > 0 && item.minSpanY > 0) {
3674                minSpanX = item.minSpanX;
3675                minSpanY = item.minSpanY;
3676            }
3677
3678            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
3679                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY,
3680                    mDragTargetLayout, mTargetCell);
3681            int reorderX = mTargetCell[0];
3682            int reorderY = mTargetCell[1];
3683
3684            setCurrentDropOverCell(mTargetCell[0], mTargetCell[1]);
3685
3686            float targetCellDistance = mDragTargetLayout.getDistanceFromCell(
3687                    mDragViewVisualCenter[0], mDragViewVisualCenter[1], mTargetCell);
3688
3689            final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0],
3690                    mTargetCell[1]);
3691
3692            manageFolderFeedback(info, mDragTargetLayout, mTargetCell,
3693                    targetCellDistance, dragOverView, d.accessibleDrag);
3694
3695            boolean nearestDropOccupied = mDragTargetLayout.isNearestDropLocationOccupied((int)
3696                    mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], item.spanX,
3697                    item.spanY, child, mTargetCell);
3698
3699            if (!nearestDropOccupied) {
3700                mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
3701                        (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
3702                        mTargetCell[0], mTargetCell[1], item.spanX, item.spanY, false,
3703                        d.dragView.getDragVisualizeOffset(), d.dragView.getDragRegion());
3704            } else if ((mDragMode == DRAG_MODE_NONE || mDragMode == DRAG_MODE_REORDER)
3705                    && !mReorderAlarm.alarmPending() && (mLastReorderX != reorderX ||
3706                    mLastReorderY != reorderY)) {
3707
3708                int[] resultSpan = new int[2];
3709                mDragTargetLayout.performReorder((int) mDragViewVisualCenter[0],
3710                        (int) mDragViewVisualCenter[1], minSpanX, minSpanY, item.spanX, item.spanY,
3711                        child, mTargetCell, resultSpan, CellLayout.MODE_SHOW_REORDER_HINT);
3712
3713                // Otherwise, if we aren't adding to or creating a folder and there's no pending
3714                // reorder, then we schedule a reorder
3715                ReorderAlarmListener listener = new ReorderAlarmListener(mDragViewVisualCenter,
3716                        minSpanX, minSpanY, item.spanX, item.spanY, d.dragView, child);
3717                mReorderAlarm.setOnAlarmListener(listener);
3718                mReorderAlarm.setAlarm(REORDER_TIMEOUT);
3719            }
3720
3721            if (mDragMode == DRAG_MODE_CREATE_FOLDER || mDragMode == DRAG_MODE_ADD_TO_FOLDER ||
3722                    !nearestDropOccupied) {
3723                if (mDragTargetLayout != null) {
3724                    mDragTargetLayout.revertTempState();
3725                }
3726            }
3727        }
3728    }
3729
3730    private void manageFolderFeedback(ItemInfo info, CellLayout targetLayout,
3731            int[] targetCell, float distance, View dragOverView, boolean accessibleDrag) {
3732        boolean userFolderPending = willCreateUserFolder(info, targetLayout, targetCell, distance,
3733                false);
3734        if (mDragMode == DRAG_MODE_NONE && userFolderPending &&
3735                !mFolderCreationAlarm.alarmPending()) {
3736
3737            FolderCreationAlarmListener listener = new
3738                    FolderCreationAlarmListener(targetLayout, targetCell[0], targetCell[1]);
3739
3740            if (!accessibleDrag) {
3741                mFolderCreationAlarm.setOnAlarmListener(listener);
3742                mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT);
3743            } else {
3744                listener.onAlarm(mFolderCreationAlarm);
3745            }
3746            return;
3747        }
3748
3749        boolean willAddToFolder =
3750                willAddToExistingUserFolder(info, targetLayout, targetCell, distance);
3751
3752        if (willAddToFolder && mDragMode == DRAG_MODE_NONE) {
3753            mDragOverFolderIcon = ((FolderIcon) dragOverView);
3754            mDragOverFolderIcon.onDragEnter(info);
3755            if (targetLayout != null) {
3756                targetLayout.clearDragOutlines();
3757            }
3758            setDragMode(DRAG_MODE_ADD_TO_FOLDER);
3759            return;
3760        }
3761
3762        if (mDragMode == DRAG_MODE_ADD_TO_FOLDER && !willAddToFolder) {
3763            setDragMode(DRAG_MODE_NONE);
3764        }
3765        if (mDragMode == DRAG_MODE_CREATE_FOLDER && !userFolderPending) {
3766            setDragMode(DRAG_MODE_NONE);
3767        }
3768
3769        return;
3770    }
3771
3772    class FolderCreationAlarmListener implements OnAlarmListener {
3773        CellLayout layout;
3774        int cellX;
3775        int cellY;
3776
3777        public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) {
3778            this.layout = layout;
3779            this.cellX = cellX;
3780            this.cellY = cellY;
3781        }
3782
3783        public void onAlarm(Alarm alarm) {
3784            if (mDragFolderRingAnimator != null) {
3785                // This shouldn't happen ever, but just in case, make sure we clean up the mess.
3786                mDragFolderRingAnimator.animateToNaturalState();
3787            }
3788            mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null);
3789            mDragFolderRingAnimator.setCell(cellX, cellY);
3790            mDragFolderRingAnimator.setCellLayout(layout);
3791            mDragFolderRingAnimator.animateToAcceptState();
3792            layout.showFolderAccept(mDragFolderRingAnimator);
3793            layout.clearDragOutlines();
3794            setDragMode(DRAG_MODE_CREATE_FOLDER);
3795        }
3796    }
3797
3798    class ReorderAlarmListener implements OnAlarmListener {
3799        float[] dragViewCenter;
3800        int minSpanX, minSpanY, spanX, spanY;
3801        DragView dragView;
3802        View child;
3803
3804        public ReorderAlarmListener(float[] dragViewCenter, int minSpanX, int minSpanY, int spanX,
3805                int spanY, DragView dragView, View child) {
3806            this.dragViewCenter = dragViewCenter;
3807            this.minSpanX = minSpanX;
3808            this.minSpanY = minSpanY;
3809            this.spanX = spanX;
3810            this.spanY = spanY;
3811            this.child = child;
3812            this.dragView = dragView;
3813        }
3814
3815        public void onAlarm(Alarm alarm) {
3816            int[] resultSpan = new int[2];
3817            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
3818                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, mDragTargetLayout,
3819                    mTargetCell);
3820            mLastReorderX = mTargetCell[0];
3821            mLastReorderY = mTargetCell[1];
3822
3823            mTargetCell = mDragTargetLayout.performReorder((int) mDragViewVisualCenter[0],
3824                (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY,
3825                child, mTargetCell, resultSpan, CellLayout.MODE_DRAG_OVER);
3826
3827            if (mTargetCell[0] < 0 || mTargetCell[1] < 0) {
3828                mDragTargetLayout.revertTempState();
3829            } else {
3830                setDragMode(DRAG_MODE_REORDER);
3831            }
3832
3833            boolean resize = resultSpan[0] != spanX || resultSpan[1] != spanY;
3834            mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
3835                (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
3836                mTargetCell[0], mTargetCell[1], resultSpan[0], resultSpan[1], resize,
3837                dragView.getDragVisualizeOffset(), dragView.getDragRegion());
3838        }
3839    }
3840
3841    @Override
3842    public void getHitRectRelativeToDragLayer(Rect outRect) {
3843        // We want the workspace to have the whole area of the display (it will find the correct
3844        // cell layout to drop to in the existing drag/drop logic.
3845        mLauncher.getDragLayer().getDescendantRectRelativeToSelf(this, outRect);
3846    }
3847
3848    /**
3849     * Add the item specified by dragInfo to the given layout.
3850     * @return true if successful
3851     */
3852    public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) {
3853        if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) {
3854            onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false);
3855            return true;
3856        }
3857        mLauncher.showOutOfSpaceMessage(mLauncher.isHotseatLayout(layout));
3858        return false;
3859    }
3860
3861    private void onDropExternal(int[] touchXY, Object dragInfo,
3862            CellLayout cellLayout, boolean insertAtFirst) {
3863        onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null);
3864    }
3865
3866    /**
3867     * Drop an item that didn't originate on one of the workspace screens.
3868     * It may have come from Launcher (e.g. from all apps or customize), or it may have
3869     * come from another app altogether.
3870     *
3871     * NOTE: This can also be called when we are outside of a drag event, when we want
3872     * to add an item to one of the workspace screens.
3873     */
3874    private void onDropExternal(final int[] touchXY, final Object dragInfo,
3875            final CellLayout cellLayout, boolean insertAtFirst, DragObject d) {
3876        final Runnable exitSpringLoadedRunnable = new Runnable() {
3877            @Override
3878            public void run() {
3879                mLauncher.exitSpringLoadedDragModeDelayed(true,
3880                        Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, null);
3881            }
3882        };
3883
3884        ItemInfo info = (ItemInfo) dragInfo;
3885        int spanX = info.spanX;
3886        int spanY = info.spanY;
3887        if (mDragInfo != null) {
3888            spanX = mDragInfo.spanX;
3889            spanY = mDragInfo.spanY;
3890        }
3891
3892        final long container = mLauncher.isHotseatLayout(cellLayout) ?
3893                LauncherSettings.Favorites.CONTAINER_HOTSEAT :
3894                    LauncherSettings.Favorites.CONTAINER_DESKTOP;
3895        final long screenId = getIdForScreen(cellLayout);
3896        if (!mLauncher.isHotseatLayout(cellLayout)
3897                && screenId != getScreenIdForPageIndex(mCurrentPage)
3898                && mState != State.SPRING_LOADED) {
3899            snapToScreenId(screenId, null);
3900        }
3901
3902        if (info instanceof PendingAddItemInfo) {
3903            final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo;
3904
3905            boolean findNearestVacantCell = true;
3906            if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
3907                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
3908                        cellLayout, mTargetCell);
3909                float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0],
3910                        mDragViewVisualCenter[1], mTargetCell);
3911                if (willCreateUserFolder((ItemInfo) d.dragInfo, cellLayout, mTargetCell,
3912                        distance, true) || willAddToExistingUserFolder((ItemInfo) d.dragInfo,
3913                                cellLayout, mTargetCell, distance)) {
3914                    findNearestVacantCell = false;
3915                }
3916            }
3917
3918            final ItemInfo item = (ItemInfo) d.dragInfo;
3919            boolean updateWidgetSize = false;
3920            if (findNearestVacantCell) {
3921                int minSpanX = item.spanX;
3922                int minSpanY = item.spanY;
3923                if (item.minSpanX > 0 && item.minSpanY > 0) {
3924                    minSpanX = item.minSpanX;
3925                    minSpanY = item.minSpanY;
3926                }
3927                int[] resultSpan = new int[2];
3928                mTargetCell = cellLayout.performReorder((int) mDragViewVisualCenter[0],
3929                        (int) mDragViewVisualCenter[1], minSpanX, minSpanY, info.spanX, info.spanY,
3930                        null, mTargetCell, resultSpan, CellLayout.MODE_ON_DROP_EXTERNAL);
3931
3932                if (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY) {
3933                    updateWidgetSize = true;
3934                }
3935                item.spanX = resultSpan[0];
3936                item.spanY = resultSpan[1];
3937            }
3938
3939            Runnable onAnimationCompleteRunnable = new Runnable() {
3940                @Override
3941                public void run() {
3942                    // Normally removeExtraEmptyScreen is called in Workspace#onDragEnd, but when
3943                    // adding an item that may not be dropped right away (due to a config activity)
3944                    // we defer the removal until the activity returns.
3945                    deferRemoveExtraEmptyScreen();
3946
3947                    // When dragging and dropping from customization tray, we deal with creating
3948                    // widgets/shortcuts/folders in a slightly different way
3949                    mLauncher.addPendingItem(pendingInfo, container, screenId, mTargetCell,
3950                            item.spanX, item.spanY);
3951                }
3952            };
3953            boolean isWidget = pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET
3954                    || pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
3955
3956            View finalView = isWidget ? ((PendingAddWidgetInfo) pendingInfo).boundWidget : null;
3957
3958            if (finalView instanceof AppWidgetHostView && updateWidgetSize) {
3959                AppWidgetHostView awhv = (AppWidgetHostView) finalView;
3960                AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, item.spanX,
3961                        item.spanY);
3962            }
3963
3964            int animationStyle = ANIMATE_INTO_POSITION_AND_DISAPPEAR;
3965            if (isWidget && ((PendingAddWidgetInfo) pendingInfo).info != null &&
3966                    ((PendingAddWidgetInfo) pendingInfo).info.configure != null) {
3967                animationStyle = ANIMATE_INTO_POSITION_AND_REMAIN;
3968            }
3969            animateWidgetDrop(info, cellLayout, d.dragView, onAnimationCompleteRunnable,
3970                    animationStyle, finalView, true);
3971        } else {
3972            // This is for other drag/drop cases, like dragging from All Apps
3973            View view = null;
3974
3975            switch (info.itemType) {
3976            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
3977            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3978                if (info.container == NO_ID && info instanceof AppInfo) {
3979                    // Came from all apps -- make a copy
3980                    info = ((AppInfo) info).makeShortcut();
3981                }
3982                view = mLauncher.createShortcut(R.layout.application, cellLayout,
3983                        (ShortcutInfo) info);
3984                break;
3985            case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
3986                view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout,
3987                        (FolderInfo) info, mIconCache);
3988                break;
3989            default:
3990                throw new IllegalStateException("Unknown item type: " + info.itemType);
3991            }
3992
3993            // First we find the cell nearest to point at which the item is
3994            // dropped, without any consideration to whether there is an item there.
3995            if (touchXY != null) {
3996                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
3997                        cellLayout, mTargetCell);
3998                float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0],
3999                        mDragViewVisualCenter[1], mTargetCell);
4000                d.postAnimationRunnable = exitSpringLoadedRunnable;
4001                if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, distance,
4002                        true, d.dragView, d.postAnimationRunnable)) {
4003                    return;
4004                }
4005                if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, distance, d,
4006                        true)) {
4007                    return;
4008                }
4009            }
4010
4011            if (touchXY != null) {
4012                // when dragging and dropping, just find the closest free spot
4013                mTargetCell = cellLayout.performReorder((int) mDragViewVisualCenter[0],
4014                        (int) mDragViewVisualCenter[1], 1, 1, 1, 1,
4015                        null, mTargetCell, null, CellLayout.MODE_ON_DROP_EXTERNAL);
4016            } else {
4017                cellLayout.findCellForSpan(mTargetCell, 1, 1);
4018            }
4019            // Add the item to DB before adding to screen ensures that the container and other
4020            // values of the info is properly updated.
4021            LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screenId,
4022                    mTargetCell[0], mTargetCell[1]);
4023
4024            addInScreen(view, container, screenId, mTargetCell[0], mTargetCell[1], info.spanX,
4025                    info.spanY, insertAtFirst);
4026            cellLayout.onDropChild(view);
4027            cellLayout.getShortcutsAndWidgets().measureChild(view);
4028
4029            if (d.dragView != null) {
4030                // We wrap the animation call in the temporary set and reset of the current
4031                // cellLayout to its final transform -- this means we animate the drag view to
4032                // the correct final location.
4033                setFinalTransitionTransform(cellLayout);
4034                mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view,
4035                        exitSpringLoadedRunnable, this);
4036                resetTransitionTransform(cellLayout);
4037            }
4038        }
4039    }
4040
4041    public Bitmap createWidgetBitmap(ItemInfo widgetInfo, View layout) {
4042        int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(widgetInfo, false);
4043        int visibility = layout.getVisibility();
4044        layout.setVisibility(VISIBLE);
4045
4046        int width = MeasureSpec.makeMeasureSpec(unScaledSize[0], MeasureSpec.EXACTLY);
4047        int height = MeasureSpec.makeMeasureSpec(unScaledSize[1], MeasureSpec.EXACTLY);
4048        Bitmap b = Bitmap.createBitmap(unScaledSize[0], unScaledSize[1],
4049                Bitmap.Config.ARGB_8888);
4050        mCanvas.setBitmap(b);
4051
4052        layout.measure(width, height);
4053        layout.layout(0, 0, unScaledSize[0], unScaledSize[1]);
4054        layout.draw(mCanvas);
4055        mCanvas.setBitmap(null);
4056        layout.setVisibility(visibility);
4057        return b;
4058    }
4059
4060    private void getFinalPositionForDropAnimation(int[] loc, float[] scaleXY,
4061            DragView dragView, CellLayout layout, ItemInfo info, int[] targetCell,
4062            boolean external, boolean scale) {
4063        // Now we animate the dragView, (ie. the widget or shortcut preview) into its final
4064        // location and size on the home screen.
4065        int spanX = info.spanX;
4066        int spanY = info.spanY;
4067
4068        Rect r = estimateItemPosition(layout, info, targetCell[0], targetCell[1], spanX, spanY);
4069        loc[0] = r.left;
4070        loc[1] = r.top;
4071
4072        setFinalTransitionTransform(layout);
4073        float cellLayoutScale =
4074                mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(layout, loc, true);
4075        resetTransitionTransform(layout);
4076
4077        float dragViewScaleX;
4078        float dragViewScaleY;
4079        if (scale) {
4080            dragViewScaleX = (1.0f * r.width()) / dragView.getMeasuredWidth();
4081            dragViewScaleY = (1.0f * r.height()) / dragView.getMeasuredHeight();
4082        } else {
4083            dragViewScaleX = 1f;
4084            dragViewScaleY = 1f;
4085        }
4086
4087        // The animation will scale the dragView about its center, so we need to center about
4088        // the final location.
4089        loc[0] -= (dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2;
4090        loc[1] -= (dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2;
4091
4092        scaleXY[0] = dragViewScaleX * cellLayoutScale;
4093        scaleXY[1] = dragViewScaleY * cellLayoutScale;
4094    }
4095
4096    public void animateWidgetDrop(ItemInfo info, CellLayout cellLayout, DragView dragView,
4097            final Runnable onCompleteRunnable, int animationType, final View finalView,
4098            boolean external) {
4099        Rect from = new Rect();
4100        mLauncher.getDragLayer().getViewRectRelativeToSelf(dragView, from);
4101
4102        int[] finalPos = new int[2];
4103        float scaleXY[] = new float[2];
4104        boolean scalePreview = !(info instanceof PendingAddShortcutInfo);
4105        getFinalPositionForDropAnimation(finalPos, scaleXY, dragView, cellLayout, info, mTargetCell,
4106                external, scalePreview);
4107
4108        Resources res = mLauncher.getResources();
4109        final int duration = res.getInteger(R.integer.config_dropAnimMaxDuration) - 200;
4110
4111        // In the case where we've prebound the widget, we remove it from the DragLayer
4112        if (finalView instanceof AppWidgetHostView && external) {
4113            mLauncher.getDragLayer().removeView(finalView);
4114        }
4115
4116        boolean isWidget = info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET ||
4117                info.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
4118        if ((animationType == ANIMATE_INTO_POSITION_AND_RESIZE || external) && finalView != null) {
4119            Bitmap crossFadeBitmap = createWidgetBitmap(info, finalView);
4120            dragView.setCrossFadeBitmap(crossFadeBitmap);
4121            dragView.crossFade((int) (duration * 0.8f));
4122        } else if (isWidget && external) {
4123            scaleXY[0] = scaleXY[1] = Math.min(scaleXY[0],  scaleXY[1]);
4124        }
4125
4126        DragLayer dragLayer = mLauncher.getDragLayer();
4127        if (animationType == CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION) {
4128            mLauncher.getDragLayer().animateViewIntoPosition(dragView, finalPos, 0f, 0.1f, 0.1f,
4129                    DragLayer.ANIMATION_END_DISAPPEAR, onCompleteRunnable, duration);
4130        } else {
4131            int endStyle;
4132            if (animationType == ANIMATE_INTO_POSITION_AND_REMAIN) {
4133                endStyle = DragLayer.ANIMATION_END_REMAIN_VISIBLE;
4134            } else {
4135                endStyle = DragLayer.ANIMATION_END_DISAPPEAR;;
4136            }
4137
4138            Runnable onComplete = new Runnable() {
4139                @Override
4140                public void run() {
4141                    if (finalView != null) {
4142                        finalView.setVisibility(VISIBLE);
4143                    }
4144                    if (onCompleteRunnable != null) {
4145                        onCompleteRunnable.run();
4146                    }
4147                }
4148            };
4149            dragLayer.animateViewIntoPosition(dragView, from.left, from.top, finalPos[0],
4150                    finalPos[1], 1, 1, 1, scaleXY[0], scaleXY[1], onComplete, endStyle,
4151                    duration, this);
4152        }
4153    }
4154
4155    public void setFinalTransitionTransform(CellLayout layout) {
4156        if (isSwitchingState()) {
4157            mCurrentScale = getScaleX();
4158            setScaleX(mNewScale);
4159            setScaleY(mNewScale);
4160        }
4161    }
4162    public void resetTransitionTransform(CellLayout layout) {
4163        if (isSwitchingState()) {
4164            setScaleX(mCurrentScale);
4165            setScaleY(mCurrentScale);
4166        }
4167    }
4168
4169    /**
4170     * Return the current {@link CellLayout}, correctly picking the destination
4171     * screen while a scroll is in progress.
4172     */
4173    public CellLayout getCurrentDropLayout() {
4174        return (CellLayout) getChildAt(getNextPage());
4175    }
4176
4177    /**
4178     * Return the current CellInfo describing our current drag; this method exists
4179     * so that Launcher can sync this object with the correct info when the activity is created/
4180     * destroyed
4181     *
4182     */
4183    public CellLayout.CellInfo getDragInfo() {
4184        return mDragInfo;
4185    }
4186
4187    public int getCurrentPageOffsetFromCustomContent() {
4188        return getNextPage() - numCustomPages();
4189    }
4190
4191    /**
4192     * Calculate the nearest cell where the given object would be dropped.
4193     *
4194     * pixelX and pixelY should be in the coordinate system of layout
4195     */
4196    @Thunk int[] findNearestArea(int pixelX, int pixelY,
4197            int spanX, int spanY, CellLayout layout, int[] recycle) {
4198        return layout.findNearestArea(
4199                pixelX, pixelY, spanX, spanY, recycle);
4200    }
4201
4202    void setup(DragController dragController) {
4203        mSpringLoadedDragController = new SpringLoadedDragController(mLauncher);
4204        mDragController = dragController;
4205
4206        // hardware layers on children are enabled on startup, but should be disabled until
4207        // needed
4208        updateChildrenLayersEnabled(false);
4209    }
4210
4211    /**
4212     * Called at the end of a drag which originated on the workspace.
4213     */
4214    public void onDropCompleted(final View target, final DragObject d,
4215            final boolean isFlingToDelete, final boolean success) {
4216        if (mDeferDropAfterUninstall) {
4217            mDeferredAction = new Runnable() {
4218                public void run() {
4219                    onDropCompleted(target, d, isFlingToDelete, success);
4220                    mDeferredAction = null;
4221                }
4222            };
4223            return;
4224        }
4225
4226        boolean beingCalledAfterUninstall = mDeferredAction != null;
4227
4228        if (success && !(beingCalledAfterUninstall && !mUninstallSuccessful)) {
4229            if (target != this && mDragInfo != null) {
4230                removeWorkspaceItem(mDragInfo.cell);
4231            }
4232        } else if (mDragInfo != null) {
4233            final CellLayout cellLayout = mLauncher.getCellLayout(
4234                    mDragInfo.container, mDragInfo.screenId);
4235            if (cellLayout != null) {
4236                cellLayout.onDropChild(mDragInfo.cell);
4237            } else if (LauncherAppState.isDogfoodBuild()) {
4238                throw new RuntimeException("Invalid state: cellLayout == null in "
4239                        + "Workspace#onDropCompleted. Please file a bug. ");
4240            };
4241        }
4242        if ((d.cancelled || (beingCalledAfterUninstall && !mUninstallSuccessful))
4243                && mDragInfo.cell != null) {
4244            mDragInfo.cell.setVisibility(VISIBLE);
4245        }
4246        mDragOutline = null;
4247        mDragInfo = null;
4248    }
4249
4250    /**
4251     * For opposite operation. See {@link #addInScreen}.
4252     */
4253    public void removeWorkspaceItem(View v) {
4254        CellLayout parentCell = getParentCellLayoutForView(v);
4255        if (parentCell != null) {
4256            parentCell.removeView(v);
4257        } else if (LauncherAppState.isDogfoodBuild()) {
4258            throw new NullPointerException("mDragInfo.cell has null parent");
4259        }
4260        if (v instanceof DropTarget) {
4261            mDragController.removeDropTarget((DropTarget) v);
4262        }
4263    }
4264
4265    public void deferCompleteDropAfterUninstallActivity() {
4266        mDeferDropAfterUninstall = true;
4267    }
4268
4269    /// maybe move this into a smaller part
4270    public void onUninstallActivityReturned(boolean success) {
4271        mDeferDropAfterUninstall = false;
4272        mUninstallSuccessful = success;
4273        if (mDeferredAction != null) {
4274            mDeferredAction.run();
4275        }
4276    }
4277
4278    void updateItemLocationsInDatabase(CellLayout cl) {
4279        int count = cl.getShortcutsAndWidgets().getChildCount();
4280
4281        long screenId = getIdForScreen(cl);
4282        int container = Favorites.CONTAINER_DESKTOP;
4283
4284        if (mLauncher.isHotseatLayout(cl)) {
4285            screenId = -1;
4286            container = Favorites.CONTAINER_HOTSEAT;
4287        }
4288
4289        for (int i = 0; i < count; i++) {
4290            View v = cl.getShortcutsAndWidgets().getChildAt(i);
4291            ItemInfo info = (ItemInfo) v.getTag();
4292            // Null check required as the AllApps button doesn't have an item info
4293            if (info != null && info.requiresDbUpdate) {
4294                info.requiresDbUpdate = false;
4295                LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId, info.cellX,
4296                        info.cellY, info.spanX, info.spanY);
4297            }
4298        }
4299    }
4300
4301    void saveWorkspaceToDb() {
4302        saveWorkspaceScreenToDb((CellLayout) mLauncher.getHotseat().getLayout());
4303        int count = getChildCount();
4304        for (int i = 0; i < count; i++) {
4305            CellLayout cl = (CellLayout) getChildAt(i);
4306            saveWorkspaceScreenToDb(cl);
4307        }
4308    }
4309
4310    void saveWorkspaceScreenToDb(CellLayout cl) {
4311        int count = cl.getShortcutsAndWidgets().getChildCount();
4312
4313        long screenId = getIdForScreen(cl);
4314        int container = Favorites.CONTAINER_DESKTOP;
4315
4316        Hotseat hotseat = mLauncher.getHotseat();
4317        if (mLauncher.isHotseatLayout(cl)) {
4318            screenId = -1;
4319            container = Favorites.CONTAINER_HOTSEAT;
4320        }
4321
4322        for (int i = 0; i < count; i++) {
4323            View v = cl.getShortcutsAndWidgets().getChildAt(i);
4324            ItemInfo info = (ItemInfo) v.getTag();
4325            // Null check required as the AllApps button doesn't have an item info
4326            if (info != null) {
4327                int cellX = info.cellX;
4328                int cellY = info.cellY;
4329                if (container == Favorites.CONTAINER_HOTSEAT) {
4330                    cellX = hotseat.getCellXFromOrder((int) info.screenId);
4331                    cellY = hotseat.getCellYFromOrder((int) info.screenId);
4332                }
4333                LauncherModel.addItemToDatabase(mLauncher, info, container, screenId, cellX, cellY);
4334            }
4335            if (v instanceof FolderIcon) {
4336                FolderIcon fi = (FolderIcon) v;
4337                fi.getFolder().addItemLocationsInDatabase();
4338            }
4339        }
4340    }
4341
4342    @Override
4343    public float getIntrinsicIconScaleFactor() {
4344        return 1f;
4345    }
4346
4347    @Override
4348    public boolean supportsFlingToDelete() {
4349        return true;
4350    }
4351
4352    @Override
4353    public boolean supportsAppInfoDropTarget() {
4354        return false;
4355    }
4356
4357    @Override
4358    public boolean supportsDeleteDropTarget() {
4359        return true;
4360    }
4361
4362    @Override
4363    public void onFlingToDelete(DragObject d, int x, int y, PointF vec) {
4364        // Do nothing
4365    }
4366
4367    @Override
4368    public void onFlingToDeleteCompleted() {
4369        // Do nothing
4370    }
4371
4372    public boolean isDropEnabled() {
4373        return true;
4374    }
4375
4376    @Override
4377    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
4378        // We don't dispatch restoreInstanceState to our children using this code path.
4379        // Some pages will be restored immediately as their items are bound immediately, and
4380        // others we will need to wait until after their items are bound.
4381        mSavedStates = container;
4382    }
4383
4384    public void restoreInstanceStateForChild(int child) {
4385        if (mSavedStates != null) {
4386            mRestoredPages.add(child);
4387            CellLayout cl = (CellLayout) getChildAt(child);
4388            if (cl != null) {
4389                cl.restoreInstanceState(mSavedStates);
4390            }
4391        }
4392    }
4393
4394    public void restoreInstanceStateForRemainingPages() {
4395        int count = getChildCount();
4396        for (int i = 0; i < count; i++) {
4397            if (!mRestoredPages.contains(i)) {
4398                restoreInstanceStateForChild(i);
4399            }
4400        }
4401        mRestoredPages.clear();
4402        mSavedStates = null;
4403    }
4404
4405    @Override
4406    public void scrollLeft() {
4407        if (!workspaceInModalState() && !mIsSwitchingState) {
4408            super.scrollLeft();
4409        }
4410        Folder openFolder = getOpenFolder();
4411        if (openFolder != null) {
4412            openFolder.completeDragExit();
4413        }
4414    }
4415
4416    @Override
4417    public void scrollRight() {
4418        if (!workspaceInModalState() && !mIsSwitchingState) {
4419            super.scrollRight();
4420        }
4421        Folder openFolder = getOpenFolder();
4422        if (openFolder != null) {
4423            openFolder.completeDragExit();
4424        }
4425    }
4426
4427    @Override
4428    public boolean onEnterScrollArea(int x, int y, int direction) {
4429        // Ignore the scroll area if we are dragging over the hot seat
4430        boolean isPortrait = !LauncherAppState.isScreenLandscape(getContext());
4431        if (mLauncher.getHotseat() != null && isPortrait) {
4432            Rect r = new Rect();
4433            mLauncher.getHotseat().getHitRect(r);
4434            if (r.contains(x, y)) {
4435                return false;
4436            }
4437        }
4438
4439        boolean result = false;
4440        if (!workspaceInModalState() && !mIsSwitchingState && getOpenFolder() == null) {
4441            mInScrollArea = true;
4442
4443            final int page = getNextPage() +
4444                       (direction == DragController.SCROLL_LEFT ? -1 : 1);
4445            // We always want to exit the current layout to ensure parity of enter / exit
4446            setCurrentDropLayout(null);
4447
4448            if (0 <= page && page < getChildCount()) {
4449                // Ensure that we are not dragging over to the custom content screen
4450                if (getScreenIdForPageIndex(page) == CUSTOM_CONTENT_SCREEN_ID) {
4451                    return false;
4452                }
4453
4454                CellLayout layout = (CellLayout) getChildAt(page);
4455                setCurrentDragOverlappingLayout(layout);
4456
4457                // Workspace is responsible for drawing the edge glow on adjacent pages,
4458                // so we need to redraw the workspace when this may have changed.
4459                invalidate();
4460                result = true;
4461            }
4462        }
4463        return result;
4464    }
4465
4466    @Override
4467    public boolean onExitScrollArea() {
4468        boolean result = false;
4469        if (mInScrollArea) {
4470            invalidate();
4471            CellLayout layout = getCurrentDropLayout();
4472            setCurrentDropLayout(layout);
4473            setCurrentDragOverlappingLayout(layout);
4474
4475            result = true;
4476            mInScrollArea = false;
4477        }
4478        return result;
4479    }
4480
4481    private void onResetScrollArea() {
4482        setCurrentDragOverlappingLayout(null);
4483        mInScrollArea = false;
4484    }
4485
4486    /**
4487     * Returns a specific CellLayout
4488     */
4489    CellLayout getParentCellLayoutForView(View v) {
4490        ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts();
4491        for (CellLayout layout : layouts) {
4492            if (layout.getShortcutsAndWidgets().indexOfChild(v) > -1) {
4493                return layout;
4494            }
4495        }
4496        return null;
4497    }
4498
4499    /**
4500     * Returns a list of all the CellLayouts in the workspace.
4501     */
4502    ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() {
4503        ArrayList<CellLayout> layouts = new ArrayList<CellLayout>();
4504        int screenCount = getChildCount();
4505        for (int screen = 0; screen < screenCount; screen++) {
4506            layouts.add(((CellLayout) getChildAt(screen)));
4507        }
4508        if (mLauncher.getHotseat() != null) {
4509            layouts.add(mLauncher.getHotseat().getLayout());
4510        }
4511        return layouts;
4512    }
4513
4514    /**
4515     * We should only use this to search for specific children.  Do not use this method to modify
4516     * ShortcutsAndWidgetsContainer directly. Includes ShortcutAndWidgetContainers from
4517     * the hotseat and workspace pages
4518     */
4519    ArrayList<ShortcutAndWidgetContainer> getAllShortcutAndWidgetContainers() {
4520        ArrayList<ShortcutAndWidgetContainer> childrenLayouts =
4521                new ArrayList<ShortcutAndWidgetContainer>();
4522        int screenCount = getChildCount();
4523        for (int screen = 0; screen < screenCount; screen++) {
4524            childrenLayouts.add(((CellLayout) getChildAt(screen)).getShortcutsAndWidgets());
4525        }
4526        if (mLauncher.getHotseat() != null) {
4527            childrenLayouts.add(mLauncher.getHotseat().getLayout().getShortcutsAndWidgets());
4528        }
4529        return childrenLayouts;
4530    }
4531
4532    public Folder getFolderForTag(final Object tag) {
4533        return (Folder) getFirstMatch(new ItemOperator() {
4534
4535            @Override
4536            public boolean evaluate(ItemInfo info, View v, View parent) {
4537                return (v instanceof Folder) && (((Folder) v).getInfo() == tag)
4538                        && ((Folder) v).getInfo().opened;
4539            }
4540        });
4541    }
4542
4543    public View getViewForTag(final Object tag) {
4544        return getFirstMatch(new ItemOperator() {
4545
4546            @Override
4547            public boolean evaluate(ItemInfo info, View v, View parent) {
4548                return info == tag;
4549            }
4550        });
4551    }
4552
4553    public LauncherAppWidgetHostView getWidgetForAppWidgetId(final int appWidgetId) {
4554        return (LauncherAppWidgetHostView) getFirstMatch(new ItemOperator() {
4555
4556            @Override
4557            public boolean evaluate(ItemInfo info, View v, View parent) {
4558                return (info instanceof LauncherAppWidgetInfo) &&
4559                        ((LauncherAppWidgetInfo) info).appWidgetId == appWidgetId;
4560            }
4561        });
4562    }
4563
4564    private View getFirstMatch(final ItemOperator operator) {
4565        final View[] value = new View[1];
4566        mapOverItems(MAP_NO_RECURSE, new ItemOperator() {
4567            @Override
4568            public boolean evaluate(ItemInfo info, View v, View parent) {
4569                if (operator.evaluate(info, v, parent)) {
4570                    value[0] = v;
4571                    return true;
4572                }
4573                return false;
4574            }
4575        });
4576        return value[0];
4577    }
4578
4579    void clearDropTargets() {
4580        mapOverItems(MAP_NO_RECURSE, new ItemOperator() {
4581            @Override
4582            public boolean evaluate(ItemInfo info, View v, View parent) {
4583                if (v instanceof DropTarget) {
4584                    mDragController.removeDropTarget((DropTarget) v);
4585                }
4586                // not done, process all the shortcuts
4587                return false;
4588            }
4589        });
4590    }
4591
4592    public void disableShortcutsByPackageName(final ArrayList<String> packages,
4593            final UserHandleCompat user, final int reason) {
4594        final HashSet<String> packageNames = new HashSet<String>();
4595        packageNames.addAll(packages);
4596
4597        mapOverItems(MAP_RECURSE, new ItemOperator() {
4598            @Override
4599            public boolean evaluate(ItemInfo info, View v, View parent) {
4600                if (info instanceof ShortcutInfo && v instanceof BubbleTextView) {
4601                    ShortcutInfo shortcutInfo = (ShortcutInfo) info;
4602                    ComponentName cn = shortcutInfo.getTargetComponent();
4603                    if (user.equals(shortcutInfo.user) && cn != null
4604                            && packageNames.contains(cn.getPackageName())) {
4605                        shortcutInfo.isDisabled |= reason;
4606                        BubbleTextView shortcut = (BubbleTextView) v;
4607                        shortcut.applyFromShortcutInfo(shortcutInfo, mIconCache, true, false);
4608
4609                        if (parent != null) {
4610                            parent.invalidate();
4611                        }
4612                    }
4613                }
4614                // process all the shortcuts
4615                return false;
4616            }
4617        });
4618    }
4619
4620    // Removes ALL items that match a given package name, this is usually called when a package
4621    // has been removed and we want to remove all components (widgets, shortcuts, apps) that
4622    // belong to that package.
4623    void removeItemsByPackageName(final ArrayList<String> packages, final UserHandleCompat user) {
4624        final HashSet<String> packageNames = new HashSet<String>();
4625        packageNames.addAll(packages);
4626
4627        // Filter out all the ItemInfos that this is going to affect
4628        final HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
4629        final HashSet<ComponentName> cns = new HashSet<ComponentName>();
4630        ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
4631        for (CellLayout layoutParent : cellLayouts) {
4632            ViewGroup layout = layoutParent.getShortcutsAndWidgets();
4633            int childCount = layout.getChildCount();
4634            for (int i = 0; i < childCount; ++i) {
4635                View view = layout.getChildAt(i);
4636                infos.add((ItemInfo) view.getTag());
4637            }
4638        }
4639        LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() {
4640            @Override
4641            public boolean filterItem(ItemInfo parent, ItemInfo info,
4642                                      ComponentName cn) {
4643                if (packageNames.contains(cn.getPackageName())
4644                        && info.user.equals(user)) {
4645                    cns.add(cn);
4646                    return true;
4647                }
4648                return false;
4649            }
4650        };
4651        LauncherModel.filterItemInfos(infos, filter);
4652
4653        // Remove the affected components
4654        removeItemsByComponentName(cns, user);
4655    }
4656
4657    /**
4658     * Removes items that match the item info specified. When applications are removed
4659     * as a part of an update, this is called to ensure that other widgets and application
4660     * shortcuts are not removed.
4661     */
4662    void removeItemsByComponentName(final HashSet<ComponentName> componentNames,
4663            final UserHandleCompat user) {
4664        ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
4665        for (final CellLayout layoutParent: cellLayouts) {
4666            final ViewGroup layout = layoutParent.getShortcutsAndWidgets();
4667
4668            final HashMap<ItemInfo, View> children = new HashMap<ItemInfo, View>();
4669            for (int j = 0; j < layout.getChildCount(); j++) {
4670                final View view = layout.getChildAt(j);
4671                children.put((ItemInfo) view.getTag(), view);
4672            }
4673
4674            final ArrayList<View> childrenToRemove = new ArrayList<View>();
4675            final HashMap<FolderInfo, ArrayList<ShortcutInfo>> folderAppsToRemove =
4676                    new HashMap<FolderInfo, ArrayList<ShortcutInfo>>();
4677            LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() {
4678                @Override
4679                public boolean filterItem(ItemInfo parent, ItemInfo info,
4680                                          ComponentName cn) {
4681                    if (parent instanceof FolderInfo) {
4682                        if (componentNames.contains(cn) && info.user.equals(user)) {
4683                            FolderInfo folder = (FolderInfo) parent;
4684                            ArrayList<ShortcutInfo> appsToRemove;
4685                            if (folderAppsToRemove.containsKey(folder)) {
4686                                appsToRemove = folderAppsToRemove.get(folder);
4687                            } else {
4688                                appsToRemove = new ArrayList<ShortcutInfo>();
4689                                folderAppsToRemove.put(folder, appsToRemove);
4690                            }
4691                            appsToRemove.add((ShortcutInfo) info);
4692                            return true;
4693                        }
4694                    } else {
4695                        if (componentNames.contains(cn) && info.user.equals(user)) {
4696                            childrenToRemove.add(children.get(info));
4697                            return true;
4698                        }
4699                    }
4700                    return false;
4701                }
4702            };
4703            LauncherModel.filterItemInfos(children.keySet(), filter);
4704
4705            // Remove all the apps from their folders
4706            for (FolderInfo folder : folderAppsToRemove.keySet()) {
4707                ArrayList<ShortcutInfo> appsToRemove = folderAppsToRemove.get(folder);
4708                for (ShortcutInfo info : appsToRemove) {
4709                    folder.remove(info);
4710                }
4711            }
4712
4713            // Remove all the other children
4714            for (View child : childrenToRemove) {
4715                // Note: We can not remove the view directly from CellLayoutChildren as this
4716                // does not re-mark the spaces as unoccupied.
4717                layoutParent.removeViewInLayout(child);
4718                if (child instanceof DropTarget) {
4719                    mDragController.removeDropTarget((DropTarget) child);
4720                }
4721            }
4722
4723            if (childrenToRemove.size() > 0) {
4724                layout.requestLayout();
4725                layout.invalidate();
4726            }
4727        }
4728
4729        // Strip all the empty screens
4730        stripEmptyScreens();
4731    }
4732
4733    interface ItemOperator {
4734        /**
4735         * Process the next itemInfo, possibly with side-effect on {@link ItemOperator#value}.
4736         *
4737         * @param info info for the shortcut
4738         * @param view view for the shortcut
4739         * @param parent containing folder, or null
4740         * @return true if done, false to continue the map
4741         */
4742        public boolean evaluate(ItemInfo info, View view, View parent);
4743    }
4744
4745    /**
4746     * Map the operator over the shortcuts and widgets, return the first-non-null value.
4747     *
4748     * @param recurse true: iterate over folder children. false: op get the folders themselves.
4749     * @param op the operator to map over the shortcuts
4750     */
4751    void mapOverItems(boolean recurse, ItemOperator op) {
4752        ArrayList<ShortcutAndWidgetContainer> containers = getAllShortcutAndWidgetContainers();
4753        final int containerCount = containers.size();
4754        for (int containerIdx = 0; containerIdx < containerCount; containerIdx++) {
4755            ShortcutAndWidgetContainer container = containers.get(containerIdx);
4756            // map over all the shortcuts on the workspace
4757            final int itemCount = container.getChildCount();
4758            for (int itemIdx = 0; itemIdx < itemCount; itemIdx++) {
4759                View item = container.getChildAt(itemIdx);
4760                ItemInfo info = (ItemInfo) item.getTag();
4761                if (recurse && info instanceof FolderInfo && item instanceof FolderIcon) {
4762                    FolderIcon folder = (FolderIcon) item;
4763                    ArrayList<View> folderChildren = folder.getFolder().getItemsInReadingOrder();
4764                    // map over all the children in the folder
4765                    final int childCount = folderChildren.size();
4766                    for (int childIdx = 0; childIdx < childCount; childIdx++) {
4767                        View child = folderChildren.get(childIdx);
4768                        info = (ItemInfo) child.getTag();
4769                        if (op.evaluate(info, child, folder)) {
4770                            return;
4771                        }
4772                    }
4773                } else {
4774                    if (op.evaluate(info, item, null)) {
4775                        return;
4776                    }
4777                }
4778            }
4779        }
4780    }
4781
4782    void updateShortcuts(ArrayList<ShortcutInfo> shortcuts) {
4783        final HashSet<ShortcutInfo> updates = new HashSet<ShortcutInfo>(shortcuts);
4784        mapOverItems(MAP_RECURSE, new ItemOperator() {
4785            @Override
4786            public boolean evaluate(ItemInfo info, View v, View parent) {
4787                if (info instanceof ShortcutInfo && v instanceof BubbleTextView &&
4788                        updates.contains(info)) {
4789                    ShortcutInfo si = (ShortcutInfo) info;
4790                    BubbleTextView shortcut = (BubbleTextView) v;
4791                    boolean oldPromiseState = getTextViewIcon(shortcut)
4792                            instanceof PreloadIconDrawable;
4793                    shortcut.applyFromShortcutInfo(si, mIconCache, true,
4794                            si.isPromise() != oldPromiseState);
4795
4796                    if (parent != null) {
4797                        parent.invalidate();
4798                    }
4799                }
4800                // process all the shortcuts
4801                return false;
4802            }
4803        });
4804    }
4805
4806    public void removeAbandonedPromise(String packageName, UserHandleCompat user) {
4807        ArrayList<String> packages = new ArrayList<String>(1);
4808        packages.add(packageName);
4809        LauncherModel.deletePackageFromDatabase(mLauncher, packageName, user);
4810        removeItemsByPackageName(packages, user);
4811    }
4812
4813    public void updatePackageBadge(final String packageName, final UserHandleCompat user) {
4814        mapOverItems(MAP_RECURSE, new ItemOperator() {
4815            @Override
4816            public boolean evaluate(ItemInfo info, View v, View parent) {
4817                if (info instanceof ShortcutInfo && v instanceof BubbleTextView) {
4818                    ShortcutInfo shortcutInfo = (ShortcutInfo) info;
4819                    ComponentName cn = shortcutInfo.getTargetComponent();
4820                    if (user.equals(shortcutInfo.user) && cn != null
4821                            && shortcutInfo.isPromise()
4822                            && packageName.equals(cn.getPackageName())) {
4823                        if (shortcutInfo.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
4824                            // For auto install apps update the icon as well as label.
4825                            mIconCache.getTitleAndIcon(shortcutInfo,
4826                                    shortcutInfo.promisedIntent, user,
4827                                    shortcutInfo.shouldUseLowResIcon());
4828                        } else {
4829                            // Only update the icon for restored apps.
4830                            shortcutInfo.updateIcon(mIconCache);
4831                        }
4832                        BubbleTextView shortcut = (BubbleTextView) v;
4833                        shortcut.applyFromShortcutInfo(shortcutInfo, mIconCache, true, false);
4834
4835                        if (parent != null) {
4836                            parent.invalidate();
4837                        }
4838                    }
4839                }
4840                // process all the shortcuts
4841                return false;
4842            }
4843        });
4844    }
4845
4846    public void updatePackageState(ArrayList<PackageInstallInfo> installInfos) {
4847        for (final PackageInstallInfo installInfo : installInfos) {
4848            if (installInfo.state == PackageInstallerCompat.STATUS_INSTALLED) {
4849                continue;
4850            }
4851
4852            mapOverItems(MAP_RECURSE, new ItemOperator() {
4853                @Override
4854                public boolean evaluate(ItemInfo info, View v, View parent) {
4855                    if (info instanceof ShortcutInfo && v instanceof BubbleTextView) {
4856                        ShortcutInfo si = (ShortcutInfo) info;
4857                        ComponentName cn = si.getTargetComponent();
4858                        if (si.isPromise() && (cn != null)
4859                                && installInfo.packageName.equals(cn.getPackageName())) {
4860                            si.setInstallProgress(installInfo.progress);
4861                            if (installInfo.state == PackageInstallerCompat.STATUS_FAILED) {
4862                                // Mark this info as broken.
4863                                si.status &= ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE;
4864                            }
4865                            ((BubbleTextView)v).applyState(false);
4866                        }
4867                    } else if (v instanceof PendingAppWidgetHostView
4868                            && info instanceof LauncherAppWidgetInfo
4869                            && ((LauncherAppWidgetInfo) info).providerName.getPackageName()
4870                                .equals(installInfo.packageName)) {
4871                        ((LauncherAppWidgetInfo) info).installProgress = installInfo.progress;
4872                        ((PendingAppWidgetHostView) v).applyState();
4873                    }
4874
4875                    // process all the shortcuts
4876                    return false;
4877                }
4878            });
4879        }
4880    }
4881
4882    void widgetsRestored(ArrayList<LauncherAppWidgetInfo> changedInfo) {
4883        if (!changedInfo.isEmpty()) {
4884            DeferredWidgetRefresh widgetRefresh = new DeferredWidgetRefresh(changedInfo,
4885                    mLauncher.getAppWidgetHost());
4886            if (LauncherModel.getProviderInfo(getContext(),
4887                    changedInfo.get(0).providerName,
4888                    changedInfo.get(0).user) != null) {
4889                // Re-inflate the widgets which have changed status
4890                widgetRefresh.run();
4891            } else {
4892                // widgetRefresh will automatically run when the packages are updated.
4893                // For now just update the progress bars
4894                for (LauncherAppWidgetInfo info : changedInfo) {
4895                    if (info.hostView instanceof PendingAppWidgetHostView) {
4896                        info.installProgress = 100;
4897                        ((PendingAppWidgetHostView) info.hostView).applyState();
4898                    }
4899                }
4900            }
4901        }
4902    }
4903
4904    private void moveToScreen(int page, boolean animate) {
4905        if (!workspaceInModalState()) {
4906            if (animate) {
4907                snapToPage(page);
4908            } else {
4909                setCurrentPage(page);
4910            }
4911        }
4912        View child = getChildAt(page);
4913        if (child != null) {
4914            child.requestFocus();
4915        }
4916    }
4917
4918    void moveToDefaultScreen(boolean animate) {
4919        moveToScreen(mDefaultPage, animate);
4920    }
4921
4922    void moveToCustomContentScreen(boolean animate) {
4923        if (hasCustomContent()) {
4924            int ccIndex = getPageIndexForScreenId(CUSTOM_CONTENT_SCREEN_ID);
4925            if (animate) {
4926                snapToPage(ccIndex);
4927            } else {
4928                setCurrentPage(ccIndex);
4929            }
4930            View child = getChildAt(ccIndex);
4931            if (child != null) {
4932                child.requestFocus();
4933            }
4934         }
4935        exitWidgetResizeMode();
4936    }
4937
4938    @Override
4939    protected PageIndicator.PageMarkerResources getPageIndicatorMarker(int pageIndex) {
4940        long screenId = getScreenIdForPageIndex(pageIndex);
4941        if (screenId == EXTRA_EMPTY_SCREEN_ID) {
4942            int count = mScreenOrder.size() - numCustomPages();
4943            if (count > 1) {
4944                return new PageIndicator.PageMarkerResources(R.drawable.ic_pageindicator_current,
4945                        R.drawable.ic_pageindicator_add);
4946            }
4947        }
4948
4949        return super.getPageIndicatorMarker(pageIndex);
4950    }
4951
4952    @Override
4953    public void syncPages() {
4954    }
4955
4956    @Override
4957    public void syncPageItems(int page, boolean immediate) {
4958    }
4959
4960    protected String getPageIndicatorDescription() {
4961        String settings = getResources().getString(R.string.settings_button_text);
4962        return getCurrentPageDescription() + ", " + settings;
4963    }
4964
4965    protected String getCurrentPageDescription() {
4966        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
4967        int delta = numCustomPages();
4968        if (hasCustomContent() && getNextPage() == 0) {
4969            return mCustomContentDescription;
4970        }
4971        return String.format(getContext().getString(R.string.workspace_scroll_format),
4972                page + 1 - delta, getChildCount() - delta);
4973    }
4974
4975    public void getLocationInDragLayer(int[] loc) {
4976        mLauncher.getDragLayer().getLocationInDragLayer(this, loc);
4977    }
4978
4979    /**
4980     * Used as a workaround to ensure that the AppWidgetService receives the
4981     * PACKAGE_ADDED broadcast before updating widgets.
4982     */
4983    private class DeferredWidgetRefresh implements Runnable {
4984        private final ArrayList<LauncherAppWidgetInfo> mInfos;
4985        private final LauncherAppWidgetHost mHost;
4986        private final Handler mHandler;
4987
4988        private boolean mRefreshPending;
4989
4990        public DeferredWidgetRefresh(ArrayList<LauncherAppWidgetInfo> infos,
4991                LauncherAppWidgetHost host) {
4992            mInfos = infos;
4993            mHost = host;
4994            mHandler = new Handler();
4995            mRefreshPending = true;
4996
4997            mHost.addProviderChangeListener(this);
4998            // Force refresh after 10 seconds, if we don't get the provider changed event.
4999            // This could happen when the provider is no longer available in the app.
5000            mHandler.postDelayed(this, 10000);
5001        }
5002
5003        @Override
5004        public void run() {
5005            mHost.removeProviderChangeListener(this);
5006            mHandler.removeCallbacks(this);
5007
5008            if (!mRefreshPending) {
5009                return;
5010            }
5011
5012            mRefreshPending = false;
5013
5014            for (LauncherAppWidgetInfo info : mInfos) {
5015                if (info.hostView instanceof PendingAppWidgetHostView) {
5016                    PendingAppWidgetHostView view = (PendingAppWidgetHostView) info.hostView;
5017                    mLauncher.removeAppWidget(info);
5018
5019                    CellLayout cl = (CellLayout) view.getParent().getParent();
5020                    // Remove the current widget
5021                    cl.removeView(view);
5022                    mLauncher.bindAppWidget(info);
5023                }
5024            }
5025        }
5026    }
5027}
5028