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