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