Workspace.java revision 4cab3b550b3c296cd120bdf23f524f34b155dca5
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
2361    public void beginExternalDragShared(View child, DragSource source) {
2362        DeviceProfile grid = mLauncher.getDeviceProfile();
2363        int iconSize = grid.iconSizePx;
2364
2365        // Notify launcher of drag start
2366        mLauncher.onDragStarted(child);
2367
2368        // Compose a new drag bitmap that is of the icon size
2369        AtomicInteger padding = new AtomicInteger(DRAG_BITMAP_PADDING);
2370        final Bitmap tmpB = createDragBitmap(child, padding);
2371        Bitmap b = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888);
2372        Paint p = new Paint();
2373        p.setFilterBitmap(true);
2374        mCanvas.setBitmap(b);
2375        mCanvas.drawBitmap(tmpB, new Rect(0, 0, tmpB.getWidth(), tmpB.getHeight()),
2376                new Rect(0, 0, iconSize, iconSize), p);
2377        mCanvas.setBitmap(null);
2378
2379        // Find the child's location on the screen
2380        int bmpWidth = tmpB.getWidth();
2381        float iconScale = (float) bmpWidth / iconSize;
2382        float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY) * iconScale;
2383        int dragLayerX = Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2);
2384        int dragLayerY = Math.round(mTempXY[1]);
2385
2386        // Note: The drag region is used to calculate drag layer offsets, but the
2387        // dragVisualizeOffset in addition to the dragRect (the size) to position the outline.
2388        Point dragVisualizeOffset = new Point(-padding.get() / 2, padding.get() / 2);
2389        Rect dragRect = new Rect(0, 0, iconSize, iconSize);
2390
2391        Object dragObject = child.getTag();
2392        if (!(dragObject instanceof ItemInfo)) {
2393            String msg = "Drag started with a view that has no tag set. This "
2394                    + "will cause a crash (issue 11627249) down the line. "
2395                    + "View: " + child + "  tag: " + child.getTag();
2396            throw new IllegalStateException(msg);
2397        }
2398
2399        // Start the drag
2400        DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source,
2401                (ItemInfo) dragObject, DragController.DRAG_ACTION_MOVE, dragVisualizeOffset,
2402                dragRect, scale, false);
2403        dv.setIntrinsicIconScaleFactor(source.getIntrinsicIconScaleFactor());
2404
2405        // Recycle temporary bitmaps
2406        tmpB.recycle();
2407    }
2408
2409    public boolean transitionStateShouldAllowDrop() {
2410        return ((!isSwitchingState() || mTransitionProgress > 0.5f) &&
2411                (mState == State.NORMAL || mState == State.SPRING_LOADED));
2412    }
2413
2414    /**
2415     * {@inheritDoc}
2416     */
2417    public boolean acceptDrop(DragObject d) {
2418        // If it's an external drop (e.g. from All Apps), check if it should be accepted
2419        CellLayout dropTargetLayout = mDropToLayout;
2420        if (d.dragSource != this) {
2421            // Don't accept the drop if we're not over a screen at time of drop
2422            if (dropTargetLayout == null) {
2423                return false;
2424            }
2425            if (!transitionStateShouldAllowDrop()) return false;
2426
2427            mDragViewVisualCenter = d.getVisualCenter(mDragViewVisualCenter);
2428
2429            // We want the point to be mapped to the dragTarget.
2430            if (mLauncher.isHotseatLayout(dropTargetLayout)) {
2431                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
2432            } else {
2433                mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter);
2434            }
2435
2436            int spanX = 1;
2437            int spanY = 1;
2438            if (mDragInfo != null) {
2439                final CellLayout.CellInfo dragCellInfo = mDragInfo;
2440                spanX = dragCellInfo.spanX;
2441                spanY = dragCellInfo.spanY;
2442            } else {
2443                spanX = d.dragInfo.spanX;
2444                spanY = d.dragInfo.spanY;
2445            }
2446
2447            int minSpanX = spanX;
2448            int minSpanY = spanY;
2449            if (d.dragInfo instanceof PendingAddWidgetInfo) {
2450                minSpanX = ((PendingAddWidgetInfo) d.dragInfo).minSpanX;
2451                minSpanY = ((PendingAddWidgetInfo) d.dragInfo).minSpanY;
2452            }
2453
2454            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2455                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, dropTargetLayout,
2456                    mTargetCell);
2457            float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0],
2458                    mDragViewVisualCenter[1], mTargetCell);
2459            if (mCreateUserFolderOnDrop && willCreateUserFolder(d.dragInfo,
2460                    dropTargetLayout, mTargetCell, distance, true)) {
2461                return true;
2462            }
2463
2464            if (mAddToExistingFolderOnDrop && willAddToExistingUserFolder(d.dragInfo,
2465                    dropTargetLayout, mTargetCell, distance)) {
2466                return true;
2467            }
2468
2469            int[] resultSpan = new int[2];
2470            mTargetCell = dropTargetLayout.performReorder((int) mDragViewVisualCenter[0],
2471                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY,
2472                    null, mTargetCell, resultSpan, CellLayout.MODE_ACCEPT_DROP);
2473            boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0;
2474
2475            // Don't accept the drop if there's no room for the item
2476            if (!foundCell) {
2477                // Don't show the message if we are dropping on the AllApps button and the hotseat
2478                // is full
2479                boolean isHotseat = mLauncher.isHotseatLayout(dropTargetLayout);
2480                if (mTargetCell != null && isHotseat) {
2481                    Hotseat hotseat = mLauncher.getHotseat();
2482                    if (hotseat.isAllAppsButtonRank(
2483                            hotseat.getOrderInHotseat(mTargetCell[0], mTargetCell[1]))) {
2484                        return false;
2485                    }
2486                }
2487
2488                mLauncher.showOutOfSpaceMessage(isHotseat);
2489                return false;
2490            }
2491        }
2492
2493        long screenId = getIdForScreen(dropTargetLayout);
2494        if (screenId == EXTRA_EMPTY_SCREEN_ID) {
2495            commitExtraEmptyScreen();
2496        }
2497
2498        return true;
2499    }
2500
2501    boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell, float
2502            distance, boolean considerTimeout) {
2503        if (distance > mMaxDistanceForFolderCreation) return false;
2504        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2505
2506        if (dropOverView != null) {
2507            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams();
2508            if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.tmpCellY)) {
2509                return false;
2510            }
2511        }
2512
2513        boolean hasntMoved = false;
2514        if (mDragInfo != null) {
2515            hasntMoved = dropOverView == mDragInfo.cell;
2516        }
2517
2518        if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) {
2519            return false;
2520        }
2521
2522        boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo);
2523        boolean willBecomeShortcut =
2524                (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
2525                info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT);
2526
2527        return (aboveShortcut && willBecomeShortcut);
2528    }
2529
2530    boolean willAddToExistingUserFolder(ItemInfo dragInfo, CellLayout target, int[] targetCell,
2531            float distance) {
2532        if (distance > mMaxDistanceForFolderCreation) return false;
2533        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2534
2535        if (dropOverView != null) {
2536            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams();
2537            if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.tmpCellY)) {
2538                return false;
2539            }
2540        }
2541
2542        if (dropOverView instanceof FolderIcon) {
2543            FolderIcon fi = (FolderIcon) dropOverView;
2544            if (fi.acceptDrop(dragInfo)) {
2545                return true;
2546            }
2547        }
2548        return false;
2549    }
2550
2551    boolean createUserFolderIfNecessary(View newView, long container, CellLayout target,
2552            int[] targetCell, float distance, boolean external, DragView dragView,
2553            Runnable postAnimationRunnable) {
2554        if (distance > mMaxDistanceForFolderCreation) return false;
2555        View v = target.getChildAt(targetCell[0], targetCell[1]);
2556
2557        boolean hasntMoved = false;
2558        if (mDragInfo != null) {
2559            CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell);
2560            hasntMoved = (mDragInfo.cellX == targetCell[0] &&
2561                    mDragInfo.cellY == targetCell[1]) && (cellParent == target);
2562        }
2563
2564        if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false;
2565        mCreateUserFolderOnDrop = false;
2566        final long screenId = (targetCell == null) ? mDragInfo.screenId : getIdForScreen(target);
2567
2568        boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo);
2569        boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo);
2570
2571        if (aboveShortcut && willBecomeShortcut) {
2572            ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag();
2573            ShortcutInfo destInfo = (ShortcutInfo) v.getTag();
2574            // if the drag started here, we need to remove it from the workspace
2575            if (!external) {
2576                getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2577            }
2578
2579            Rect folderLocation = new Rect();
2580            float scale = mLauncher.getDragLayer().getDescendantRectRelativeToSelf(v, folderLocation);
2581            target.removeView(v);
2582
2583            FolderIcon fi =
2584                mLauncher.addFolder(target, container, screenId, targetCell[0], targetCell[1]);
2585            destInfo.cellX = -1;
2586            destInfo.cellY = -1;
2587            sourceInfo.cellX = -1;
2588            sourceInfo.cellY = -1;
2589
2590            // If the dragView is null, we can't animate
2591            boolean animate = dragView != null;
2592            if (animate) {
2593                fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale,
2594                        postAnimationRunnable);
2595            } else {
2596                fi.addItem(destInfo);
2597                fi.addItem(sourceInfo);
2598            }
2599            return true;
2600        }
2601        return false;
2602    }
2603
2604    boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell,
2605            float distance, DragObject d, boolean external) {
2606        if (distance > mMaxDistanceForFolderCreation) return false;
2607
2608        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2609        if (!mAddToExistingFolderOnDrop) return false;
2610        mAddToExistingFolderOnDrop = false;
2611
2612        if (dropOverView instanceof FolderIcon) {
2613            FolderIcon fi = (FolderIcon) dropOverView;
2614            if (fi.acceptDrop(d.dragInfo)) {
2615                fi.onDrop(d);
2616
2617                // if the drag started here, we need to remove it from the workspace
2618                if (!external) {
2619                    getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2620                }
2621                return true;
2622            }
2623        }
2624        return false;
2625    }
2626
2627    @Override
2628    public void prepareAccessibilityDrop() { }
2629
2630    public void onDrop(final DragObject d) {
2631        mDragViewVisualCenter = d.getVisualCenter(mDragViewVisualCenter);
2632        CellLayout dropTargetLayout = mDropToLayout;
2633
2634        // We want the point to be mapped to the dragTarget.
2635        if (dropTargetLayout != null) {
2636            if (mLauncher.isHotseatLayout(dropTargetLayout)) {
2637                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
2638            } else {
2639                mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter);
2640            }
2641        }
2642
2643        int snapScreen = -1;
2644        boolean resizeOnDrop = false;
2645        if (d.dragSource != this) {
2646            final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0],
2647                    (int) mDragViewVisualCenter[1] };
2648            onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d);
2649        } else if (mDragInfo != null) {
2650            final View cell = mDragInfo.cell;
2651
2652            Runnable resizeRunnable = null;
2653            if (dropTargetLayout != null && !d.cancelled) {
2654                // Move internally
2655                boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout);
2656                boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout);
2657                long container = hasMovedIntoHotseat ?
2658                        LauncherSettings.Favorites.CONTAINER_HOTSEAT :
2659                        LauncherSettings.Favorites.CONTAINER_DESKTOP;
2660                long screenId = (mTargetCell[0] < 0) ?
2661                        mDragInfo.screenId : getIdForScreen(dropTargetLayout);
2662                int spanX = mDragInfo != null ? mDragInfo.spanX : 1;
2663                int spanY = mDragInfo != null ? mDragInfo.spanY : 1;
2664                // First we find the cell nearest to point at which the item is
2665                // dropped, without any consideration to whether there is an item there.
2666
2667                mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int)
2668                        mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell);
2669                float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0],
2670                        mDragViewVisualCenter[1], mTargetCell);
2671
2672                // If the item being dropped is a shortcut and the nearest drop
2673                // cell also contains a shortcut, then create a folder with the two shortcuts.
2674                if (!mInScrollArea && createUserFolderIfNecessary(cell, container,
2675                        dropTargetLayout, mTargetCell, distance, false, d.dragView, null)) {
2676                    return;
2677                }
2678
2679                if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell,
2680                        distance, d, false)) {
2681                    return;
2682                }
2683
2684                // Aside from the special case where we're dropping a shortcut onto a shortcut,
2685                // we need to find the nearest cell location that is vacant
2686                ItemInfo item = d.dragInfo;
2687                int minSpanX = item.spanX;
2688                int minSpanY = item.spanY;
2689                if (item.minSpanX > 0 && item.minSpanY > 0) {
2690                    minSpanX = item.minSpanX;
2691                    minSpanY = item.minSpanY;
2692                }
2693
2694                int[] resultSpan = new int[2];
2695                mTargetCell = dropTargetLayout.performReorder((int) mDragViewVisualCenter[0],
2696                        (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, cell,
2697                        mTargetCell, resultSpan, CellLayout.MODE_ON_DROP);
2698
2699                boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0;
2700
2701                // if the widget resizes on drop
2702                if (foundCell && (cell instanceof AppWidgetHostView) &&
2703                        (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY)) {
2704                    resizeOnDrop = true;
2705                    item.spanX = resultSpan[0];
2706                    item.spanY = resultSpan[1];
2707                    AppWidgetHostView awhv = (AppWidgetHostView) cell;
2708                    AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, resultSpan[0],
2709                            resultSpan[1]);
2710                }
2711
2712                if (getScreenIdForPageIndex(mCurrentPage) != screenId && !hasMovedIntoHotseat) {
2713                    snapScreen = getPageIndexForScreenId(screenId);
2714                    snapToPage(snapScreen);
2715                }
2716
2717                if (foundCell) {
2718                    final ItemInfo info = (ItemInfo) cell.getTag();
2719                    if (hasMovedLayouts) {
2720                        // Reparent the view
2721                        CellLayout parentCell = getParentCellLayoutForView(cell);
2722                        if (parentCell != null) {
2723                            parentCell.removeView(cell);
2724                        } else if (ProviderConfig.IS_DOGFOOD_BUILD) {
2725                            throw new NullPointerException("mDragInfo.cell has null parent");
2726                        }
2727                        addInScreen(cell, container, screenId, mTargetCell[0], mTargetCell[1],
2728                                info.spanX, info.spanY);
2729                    }
2730
2731                    // update the item's position after drop
2732                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
2733                    lp.cellX = lp.tmpCellX = mTargetCell[0];
2734                    lp.cellY = lp.tmpCellY = mTargetCell[1];
2735                    lp.cellHSpan = item.spanX;
2736                    lp.cellVSpan = item.spanY;
2737                    lp.isLockedToGrid = true;
2738
2739                    if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
2740                            cell instanceof LauncherAppWidgetHostView) {
2741                        final CellLayout cellLayout = dropTargetLayout;
2742                        // We post this call so that the widget has a chance to be placed
2743                        // in its final location
2744
2745                        final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell;
2746                        AppWidgetProviderInfo pInfo = hostView.getAppWidgetInfo();
2747                        if (pInfo != null && pInfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE
2748                                && !d.accessibleDrag) {
2749                            final Runnable addResizeFrame = new Runnable() {
2750                                public void run() {
2751                                    DragLayer dragLayer = mLauncher.getDragLayer();
2752                                    dragLayer.addResizeFrame(info, hostView, cellLayout);
2753                                }
2754                            };
2755                            resizeRunnable = (new Runnable() {
2756                                public void run() {
2757                                    if (!isPageMoving()) {
2758                                        addResizeFrame.run();
2759                                    } else {
2760                                        mDelayedResizeRunnable = addResizeFrame;
2761                                    }
2762                                }
2763                            });
2764                        }
2765                    }
2766
2767                    LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId, lp.cellX,
2768                            lp.cellY, item.spanX, item.spanY);
2769                } else {
2770                    // If we can't find a drop location, we return the item to its original position
2771                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
2772                    mTargetCell[0] = lp.cellX;
2773                    mTargetCell[1] = lp.cellY;
2774                    CellLayout layout = (CellLayout) cell.getParent().getParent();
2775                    layout.markCellsAsOccupiedForView(cell);
2776                }
2777            }
2778
2779            final CellLayout parent = (CellLayout) cell.getParent().getParent();
2780            final Runnable finalResizeRunnable = resizeRunnable;
2781            // Prepare it to be animated into its new position
2782            // This must be called after the view has been re-parented
2783            final Runnable onCompleteRunnable = new Runnable() {
2784                @Override
2785                public void run() {
2786                    mAnimatingViewIntoPlace = false;
2787                    updateChildrenLayersEnabled(false);
2788                    if (finalResizeRunnable != null) {
2789                        finalResizeRunnable.run();
2790                    }
2791                }
2792            };
2793            mAnimatingViewIntoPlace = true;
2794            if (d.dragView.hasDrawn()) {
2795                final ItemInfo info = (ItemInfo) cell.getTag();
2796                boolean isWidget = info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET
2797                        || info.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
2798                if (isWidget) {
2799                    int animationType = resizeOnDrop ? ANIMATE_INTO_POSITION_AND_RESIZE :
2800                            ANIMATE_INTO_POSITION_AND_DISAPPEAR;
2801                    animateWidgetDrop(info, parent, d.dragView,
2802                            onCompleteRunnable, animationType, cell, false);
2803                } else {
2804                    int duration = snapScreen < 0 ? -1 : ADJACENT_SCREEN_DROP_DURATION;
2805                    mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration,
2806                            onCompleteRunnable, this);
2807                }
2808            } else {
2809                d.deferDragViewCleanupPostAnimation = false;
2810                cell.setVisibility(VISIBLE);
2811            }
2812            parent.onDropChild(cell);
2813        }
2814    }
2815
2816    /**
2817     * Computes the area relative to dragLayer which is used to display a page.
2818     */
2819    public void getPageAreaRelativeToDragLayer(Rect outArea) {
2820        CellLayout child = (CellLayout) getChildAt(getNextPage());
2821        if (child == null) {
2822            return;
2823        }
2824        ShortcutAndWidgetContainer boundingLayout = child.getShortcutsAndWidgets();
2825
2826        // Use the absolute left instead of the child left, as we want the visible area
2827        // irrespective of the visible child. Since the view can only scroll horizontally, the
2828        // top position is not affected.
2829        mTempXY[0] = getViewportOffsetX() + getPaddingLeft() + boundingLayout.getLeft();
2830        mTempXY[1] = child.getTop() + boundingLayout.getTop();
2831
2832        float scale = mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempXY);
2833        outArea.set(mTempXY[0], mTempXY[1],
2834                (int) (mTempXY[0] + scale * boundingLayout.getMeasuredWidth()),
2835                (int) (mTempXY[1] + scale * boundingLayout.getMeasuredHeight()));
2836    }
2837
2838    public void getViewLocationRelativeToSelf(View v, int[] location) {
2839        getLocationInWindow(location);
2840        int x = location[0];
2841        int y = location[1];
2842
2843        v.getLocationInWindow(location);
2844        int vX = location[0];
2845        int vY = location[1];
2846
2847        location[0] = vX - x;
2848        location[1] = vY - y;
2849    }
2850
2851    @Override
2852    public void onDragEnter(DragObject d) {
2853        if (ENFORCE_DRAG_EVENT_ORDER) {
2854            enfoceDragParity("onDragEnter", 1, 1);
2855        }
2856
2857        mCreateUserFolderOnDrop = false;
2858        mAddToExistingFolderOnDrop = false;
2859
2860        mDropToLayout = null;
2861        CellLayout layout = getCurrentDropLayout();
2862        setCurrentDropLayout(layout);
2863        setCurrentDragOverlappingLayout(layout);
2864
2865        if (!workspaceInModalState()) {
2866            mLauncher.getDragLayer().showPageHints();
2867        }
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        mLauncher.getDragLayer().hidePageHints();
2904    }
2905
2906    private void enfoceDragParity(String event, int update, int expectedValue) {
2907        enfoceDragParity(this, event, update, expectedValue);
2908        for (int i = 0; i < getChildCount(); i++) {
2909            enfoceDragParity(getChildAt(i), event, update, expectedValue);
2910        }
2911    }
2912
2913    private void enfoceDragParity(View v, String event, int update, int expectedValue) {
2914        Object tag = v.getTag(R.id.drag_event_parity);
2915        int value = tag == null ? 0 : (Integer) tag;
2916        value += update;
2917        v.setTag(R.id.drag_event_parity, value);
2918
2919        if (value != expectedValue) {
2920            Log.e(TAG, event + ": Drag contract violated: " + value);
2921        }
2922    }
2923
2924    void setCurrentDropLayout(CellLayout layout) {
2925        if (mDragTargetLayout != null) {
2926            mDragTargetLayout.revertTempState();
2927            mDragTargetLayout.onDragExit();
2928        }
2929        mDragTargetLayout = layout;
2930        if (mDragTargetLayout != null) {
2931            mDragTargetLayout.onDragEnter();
2932        }
2933        cleanupReorder(true);
2934        cleanupFolderCreation();
2935        setCurrentDropOverCell(-1, -1);
2936    }
2937
2938    void setCurrentDragOverlappingLayout(CellLayout layout) {
2939        if (mDragOverlappingLayout != null) {
2940            mDragOverlappingLayout.setIsDragOverlapping(false);
2941        }
2942        mDragOverlappingLayout = layout;
2943        if (mDragOverlappingLayout != null) {
2944            mDragOverlappingLayout.setIsDragOverlapping(true);
2945        }
2946        invalidate();
2947    }
2948
2949    void setCurrentDropOverCell(int x, int y) {
2950        if (x != mDragOverX || y != mDragOverY) {
2951            mDragOverX = x;
2952            mDragOverY = y;
2953            setDragMode(DRAG_MODE_NONE);
2954        }
2955    }
2956
2957    void setDragMode(int dragMode) {
2958        if (dragMode != mDragMode) {
2959            if (dragMode == DRAG_MODE_NONE) {
2960                cleanupAddToFolder();
2961                // We don't want to cancel the re-order alarm every time the target cell changes
2962                // as this feels to slow / unresponsive.
2963                cleanupReorder(false);
2964                cleanupFolderCreation();
2965            } else if (dragMode == DRAG_MODE_ADD_TO_FOLDER) {
2966                cleanupReorder(true);
2967                cleanupFolderCreation();
2968            } else if (dragMode == DRAG_MODE_CREATE_FOLDER) {
2969                cleanupAddToFolder();
2970                cleanupReorder(true);
2971            } else if (dragMode == DRAG_MODE_REORDER) {
2972                cleanupAddToFolder();
2973                cleanupFolderCreation();
2974            }
2975            mDragMode = dragMode;
2976        }
2977    }
2978
2979    private void cleanupFolderCreation() {
2980        if (mDragFolderRingAnimator != null) {
2981            mDragFolderRingAnimator.animateToNaturalState();
2982            mDragFolderRingAnimator = null;
2983        }
2984        mFolderCreationAlarm.setOnAlarmListener(null);
2985        mFolderCreationAlarm.cancelAlarm();
2986    }
2987
2988    private void cleanupAddToFolder() {
2989        if (mDragOverFolderIcon != null) {
2990            mDragOverFolderIcon.onDragExit(null);
2991            mDragOverFolderIcon = null;
2992        }
2993    }
2994
2995    private void cleanupReorder(boolean cancelAlarm) {
2996        // Any pending reorders are canceled
2997        if (cancelAlarm) {
2998            mReorderAlarm.cancelAlarm();
2999        }
3000        mLastReorderX = -1;
3001        mLastReorderY = -1;
3002    }
3003
3004   /*
3005    *
3006    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
3007    * coordinate space. The argument xy is modified with the return result.
3008    */
3009   void mapPointFromSelfToChild(View v, float[] xy) {
3010       xy[0] = xy[0] - v.getLeft();
3011       xy[1] = xy[1] - v.getTop();
3012   }
3013
3014   boolean isPointInSelfOverHotseat(int x, int y) {
3015       mTempXY[0] = x;
3016       mTempXY[1] = y;
3017       mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempXY, true);
3018       return mLauncher.getDeviceProfile().isInHotseatRect(mTempXY[0], mTempXY[1]);
3019   }
3020
3021   void mapPointFromSelfToHotseatLayout(Hotseat hotseat, float[] xy) {
3022       mTempXY[0] = (int) xy[0];
3023       mTempXY[1] = (int) xy[1];
3024       mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempXY, true);
3025       mLauncher.getDragLayer().mapCoordInSelfToDescendent(hotseat.getLayout(), mTempXY);
3026
3027       xy[0] = mTempXY[0];
3028       xy[1] = mTempXY[1];
3029   }
3030
3031   /*
3032    *
3033    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
3034    * the parent View's coordinate space. The argument xy is modified with the return result.
3035    *
3036    */
3037   void mapPointFromChildToSelf(View v, float[] xy) {
3038       xy[0] += v.getLeft();
3039       xy[1] += v.getTop();
3040   }
3041
3042   static private float squaredDistance(float[] point1, float[] point2) {
3043        float distanceX = point1[0] - point2[0];
3044        float distanceY = point2[1] - point2[1];
3045        return distanceX * distanceX + distanceY * distanceY;
3046   }
3047
3048    /*
3049     *
3050     * This method returns the CellLayout that is currently being dragged to. In order to drag
3051     * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
3052     * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
3053     *
3054     * Return null if no CellLayout is currently being dragged over
3055     *
3056     */
3057    private CellLayout findMatchingPageForDragOver(
3058            DragView dragView, float originX, float originY, boolean exact) {
3059        // We loop through all the screens (ie CellLayouts) and see which ones overlap
3060        // with the item being dragged and then choose the one that's closest to the touch point
3061        final int screenCount = getChildCount();
3062        CellLayout bestMatchingScreen = null;
3063        float smallestDistSoFar = Float.MAX_VALUE;
3064
3065        for (int i = 0; i < screenCount; i++) {
3066            // The custom content screen is not a valid drag over option
3067            if (mScreenOrder.get(i) == CUSTOM_CONTENT_SCREEN_ID) {
3068                continue;
3069            }
3070
3071            CellLayout cl = (CellLayout) getChildAt(i);
3072
3073            final float[] touchXy = {originX, originY};
3074            mapPointFromSelfToChild(cl, touchXy);
3075
3076            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
3077                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
3078                return cl;
3079            }
3080
3081            if (!exact) {
3082                // Get the center of the cell layout in screen coordinates
3083                final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
3084                cellLayoutCenter[0] = cl.getWidth()/2;
3085                cellLayoutCenter[1] = cl.getHeight()/2;
3086                mapPointFromChildToSelf(cl, cellLayoutCenter);
3087
3088                touchXy[0] = originX;
3089                touchXy[1] = originY;
3090
3091                // Calculate the distance between the center of the CellLayout
3092                // and the touch point
3093                float dist = squaredDistance(touchXy, cellLayoutCenter);
3094
3095                if (dist < smallestDistSoFar) {
3096                    smallestDistSoFar = dist;
3097                    bestMatchingScreen = cl;
3098                }
3099            }
3100        }
3101        return bestMatchingScreen;
3102    }
3103
3104    private boolean isDragWidget(DragObject d) {
3105        return (d.dragInfo instanceof LauncherAppWidgetInfo ||
3106                d.dragInfo instanceof PendingAddWidgetInfo);
3107    }
3108    private boolean isExternalDragWidget(DragObject d) {
3109        return d.dragSource != this && isDragWidget(d);
3110    }
3111
3112    public void onDragOver(DragObject d) {
3113        // Skip drag over events while we are dragging over side pages
3114        if (mInScrollArea || !transitionStateShouldAllowDrop()) return;
3115
3116        CellLayout layout = null;
3117        ItemInfo item = d.dragInfo;
3118        if (item == null) {
3119            if (ProviderConfig.IS_DOGFOOD_BUILD) {
3120                throw new NullPointerException("DragObject has null info");
3121            }
3122            return;
3123        }
3124
3125        // Ensure that we have proper spans for the item that we are dropping
3126        if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found");
3127        mDragViewVisualCenter = d.getVisualCenter(mDragViewVisualCenter);
3128
3129        final View child = (mDragInfo == null) ? null : mDragInfo.cell;
3130        // Identify whether we have dragged over a side page
3131        if (workspaceInModalState()) {
3132            if (mLauncher.getHotseat() != null && !isExternalDragWidget(d)) {
3133                if (isPointInSelfOverHotseat(d.x, d.y)) {
3134                    layout = mLauncher.getHotseat().getLayout();
3135                }
3136            }
3137            if (layout == null) {
3138                layout = findMatchingPageForDragOver(d.dragView, d.x, d.y, false);
3139            }
3140            if (layout != mDragTargetLayout) {
3141                setCurrentDropLayout(layout);
3142                setCurrentDragOverlappingLayout(layout);
3143
3144                boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED);
3145                if (isInSpringLoadedMode) {
3146                    if (mLauncher.isHotseatLayout(layout)) {
3147                        mSpringLoadedDragController.cancel();
3148                    } else {
3149                        mSpringLoadedDragController.setAlarm(mDragTargetLayout);
3150                    }
3151                }
3152            }
3153        } else {
3154            // Test to see if we are over the hotseat otherwise just use the current page
3155            if (mLauncher.getHotseat() != null && !isDragWidget(d)) {
3156                if (isPointInSelfOverHotseat(d.x, d.y)) {
3157                    layout = mLauncher.getHotseat().getLayout();
3158                }
3159            }
3160            if (layout == null) {
3161                layout = getCurrentDropLayout();
3162            }
3163            if (layout != mDragTargetLayout) {
3164                setCurrentDropLayout(layout);
3165                setCurrentDragOverlappingLayout(layout);
3166            }
3167        }
3168
3169        // Handle the drag over
3170        if (mDragTargetLayout != null) {
3171            // We want the point to be mapped to the dragTarget.
3172            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
3173                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
3174            } else {
3175                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter);
3176            }
3177
3178            ItemInfo info = d.dragInfo;
3179
3180            int minSpanX = item.spanX;
3181            int minSpanY = item.spanY;
3182            if (item.minSpanX > 0 && item.minSpanY > 0) {
3183                minSpanX = item.minSpanX;
3184                minSpanY = item.minSpanY;
3185            }
3186
3187            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
3188                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY,
3189                    mDragTargetLayout, mTargetCell);
3190            int reorderX = mTargetCell[0];
3191            int reorderY = mTargetCell[1];
3192
3193            setCurrentDropOverCell(mTargetCell[0], mTargetCell[1]);
3194
3195            float targetCellDistance = mDragTargetLayout.getDistanceFromCell(
3196                    mDragViewVisualCenter[0], mDragViewVisualCenter[1], mTargetCell);
3197
3198            final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0],
3199                    mTargetCell[1]);
3200
3201            manageFolderFeedback(info, mDragTargetLayout, mTargetCell,
3202                    targetCellDistance, dragOverView, d.accessibleDrag);
3203
3204            boolean nearestDropOccupied = mDragTargetLayout.isNearestDropLocationOccupied((int)
3205                    mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], item.spanX,
3206                    item.spanY, child, mTargetCell);
3207
3208            if (!nearestDropOccupied) {
3209                mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
3210                        (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
3211                        mTargetCell[0], mTargetCell[1], item.spanX, item.spanY, false,
3212                        d.dragView.getDragVisualizeOffset(), d.dragView.getDragRegion());
3213            } else if ((mDragMode == DRAG_MODE_NONE || mDragMode == DRAG_MODE_REORDER)
3214                    && !mReorderAlarm.alarmPending() && (mLastReorderX != reorderX ||
3215                    mLastReorderY != reorderY)) {
3216
3217                int[] resultSpan = new int[2];
3218                mDragTargetLayout.performReorder((int) mDragViewVisualCenter[0],
3219                        (int) mDragViewVisualCenter[1], minSpanX, minSpanY, item.spanX, item.spanY,
3220                        child, mTargetCell, resultSpan, CellLayout.MODE_SHOW_REORDER_HINT);
3221
3222                // Otherwise, if we aren't adding to or creating a folder and there's no pending
3223                // reorder, then we schedule a reorder
3224                ReorderAlarmListener listener = new ReorderAlarmListener(mDragViewVisualCenter,
3225                        minSpanX, minSpanY, item.spanX, item.spanY, d.dragView, child);
3226                mReorderAlarm.setOnAlarmListener(listener);
3227                mReorderAlarm.setAlarm(REORDER_TIMEOUT);
3228            }
3229
3230            if (mDragMode == DRAG_MODE_CREATE_FOLDER || mDragMode == DRAG_MODE_ADD_TO_FOLDER ||
3231                    !nearestDropOccupied) {
3232                if (mDragTargetLayout != null) {
3233                    mDragTargetLayout.revertTempState();
3234                }
3235            }
3236        }
3237    }
3238
3239    private void manageFolderFeedback(ItemInfo info, CellLayout targetLayout,
3240            int[] targetCell, float distance, View dragOverView, boolean accessibleDrag) {
3241        boolean userFolderPending = willCreateUserFolder(info, targetLayout, targetCell, distance,
3242                false);
3243        if (mDragMode == DRAG_MODE_NONE && userFolderPending &&
3244                !mFolderCreationAlarm.alarmPending()) {
3245
3246            FolderCreationAlarmListener listener = new
3247                    FolderCreationAlarmListener(targetLayout, targetCell[0], targetCell[1]);
3248
3249            if (!accessibleDrag) {
3250                mFolderCreationAlarm.setOnAlarmListener(listener);
3251                mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT);
3252            } else {
3253                listener.onAlarm(mFolderCreationAlarm);
3254            }
3255            return;
3256        }
3257
3258        boolean willAddToFolder =
3259                willAddToExistingUserFolder(info, targetLayout, targetCell, distance);
3260
3261        if (willAddToFolder && mDragMode == DRAG_MODE_NONE) {
3262            mDragOverFolderIcon = ((FolderIcon) dragOverView);
3263            mDragOverFolderIcon.onDragEnter(info);
3264            if (targetLayout != null) {
3265                targetLayout.clearDragOutlines();
3266            }
3267            setDragMode(DRAG_MODE_ADD_TO_FOLDER);
3268            return;
3269        }
3270
3271        if (mDragMode == DRAG_MODE_ADD_TO_FOLDER && !willAddToFolder) {
3272            setDragMode(DRAG_MODE_NONE);
3273        }
3274        if (mDragMode == DRAG_MODE_CREATE_FOLDER && !userFolderPending) {
3275            setDragMode(DRAG_MODE_NONE);
3276        }
3277
3278        return;
3279    }
3280
3281    class FolderCreationAlarmListener implements OnAlarmListener {
3282        CellLayout layout;
3283        int cellX;
3284        int cellY;
3285
3286        public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) {
3287            this.layout = layout;
3288            this.cellX = cellX;
3289            this.cellY = cellY;
3290        }
3291
3292        public void onAlarm(Alarm alarm) {
3293            if (mDragFolderRingAnimator != null) {
3294                // This shouldn't happen ever, but just in case, make sure we clean up the mess.
3295                mDragFolderRingAnimator.animateToNaturalState();
3296            }
3297            mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null);
3298            mDragFolderRingAnimator.setCell(cellX, cellY);
3299            mDragFolderRingAnimator.setCellLayout(layout);
3300            mDragFolderRingAnimator.animateToAcceptState();
3301            layout.showFolderAccept(mDragFolderRingAnimator);
3302            layout.clearDragOutlines();
3303            setDragMode(DRAG_MODE_CREATE_FOLDER);
3304        }
3305    }
3306
3307    class ReorderAlarmListener implements OnAlarmListener {
3308        float[] dragViewCenter;
3309        int minSpanX, minSpanY, spanX, spanY;
3310        DragView dragView;
3311        View child;
3312
3313        public ReorderAlarmListener(float[] dragViewCenter, int minSpanX, int minSpanY, int spanX,
3314                int spanY, DragView dragView, View child) {
3315            this.dragViewCenter = dragViewCenter;
3316            this.minSpanX = minSpanX;
3317            this.minSpanY = minSpanY;
3318            this.spanX = spanX;
3319            this.spanY = spanY;
3320            this.child = child;
3321            this.dragView = dragView;
3322        }
3323
3324        public void onAlarm(Alarm alarm) {
3325            int[] resultSpan = new int[2];
3326            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
3327                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, mDragTargetLayout,
3328                    mTargetCell);
3329            mLastReorderX = mTargetCell[0];
3330            mLastReorderY = mTargetCell[1];
3331
3332            mTargetCell = mDragTargetLayout.performReorder((int) mDragViewVisualCenter[0],
3333                (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY,
3334                child, mTargetCell, resultSpan, CellLayout.MODE_DRAG_OVER);
3335
3336            if (mTargetCell[0] < 0 || mTargetCell[1] < 0) {
3337                mDragTargetLayout.revertTempState();
3338            } else {
3339                setDragMode(DRAG_MODE_REORDER);
3340            }
3341
3342            boolean resize = resultSpan[0] != spanX || resultSpan[1] != spanY;
3343            mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
3344                (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
3345                mTargetCell[0], mTargetCell[1], resultSpan[0], resultSpan[1], resize,
3346                dragView.getDragVisualizeOffset(), dragView.getDragRegion());
3347        }
3348    }
3349
3350    @Override
3351    public void getHitRectRelativeToDragLayer(Rect outRect) {
3352        // We want the workspace to have the whole area of the display (it will find the correct
3353        // cell layout to drop to in the existing drag/drop logic.
3354        mLauncher.getDragLayer().getDescendantRectRelativeToSelf(this, outRect);
3355    }
3356
3357    /**
3358     * Drop an item that didn't originate on one of the workspace screens.
3359     * It may have come from Launcher (e.g. from all apps or customize), or it may have
3360     * come from another app altogether.
3361     *
3362     * NOTE: This can also be called when we are outside of a drag event, when we want
3363     * to add an item to one of the workspace screens.
3364     */
3365    private void onDropExternal(final int[] touchXY, final ItemInfo dragInfo,
3366            final CellLayout cellLayout, boolean insertAtFirst, DragObject d) {
3367        final Runnable exitSpringLoadedRunnable = new Runnable() {
3368            @Override
3369            public void run() {
3370                mLauncher.exitSpringLoadedDragModeDelayed(true,
3371                        Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, null);
3372            }
3373        };
3374
3375        ItemInfo info = dragInfo;
3376        int spanX = info.spanX;
3377        int spanY = info.spanY;
3378        if (mDragInfo != null) {
3379            spanX = mDragInfo.spanX;
3380            spanY = mDragInfo.spanY;
3381        }
3382
3383        final long container = mLauncher.isHotseatLayout(cellLayout) ?
3384                LauncherSettings.Favorites.CONTAINER_HOTSEAT :
3385                    LauncherSettings.Favorites.CONTAINER_DESKTOP;
3386        final long screenId = getIdForScreen(cellLayout);
3387        if (!mLauncher.isHotseatLayout(cellLayout)
3388                && screenId != getScreenIdForPageIndex(mCurrentPage)
3389                && mState != State.SPRING_LOADED) {
3390            snapToScreenId(screenId, null);
3391        }
3392
3393        if (info instanceof PendingAddItemInfo) {
3394            final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo;
3395
3396            boolean findNearestVacantCell = true;
3397            if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
3398                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
3399                        cellLayout, mTargetCell);
3400                float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0],
3401                        mDragViewVisualCenter[1], mTargetCell);
3402                if (willCreateUserFolder(d.dragInfo, cellLayout, mTargetCell, distance, true)
3403                        || willAddToExistingUserFolder(
3404                                d.dragInfo, cellLayout, mTargetCell, distance)) {
3405                    findNearestVacantCell = false;
3406                }
3407            }
3408
3409            final ItemInfo item = d.dragInfo;
3410            boolean updateWidgetSize = false;
3411            if (findNearestVacantCell) {
3412                int minSpanX = item.spanX;
3413                int minSpanY = item.spanY;
3414                if (item.minSpanX > 0 && item.minSpanY > 0) {
3415                    minSpanX = item.minSpanX;
3416                    minSpanY = item.minSpanY;
3417                }
3418                int[] resultSpan = new int[2];
3419                mTargetCell = cellLayout.performReorder((int) mDragViewVisualCenter[0],
3420                        (int) mDragViewVisualCenter[1], minSpanX, minSpanY, info.spanX, info.spanY,
3421                        null, mTargetCell, resultSpan, CellLayout.MODE_ON_DROP_EXTERNAL);
3422
3423                if (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY) {
3424                    updateWidgetSize = true;
3425                }
3426                item.spanX = resultSpan[0];
3427                item.spanY = resultSpan[1];
3428            }
3429
3430            Runnable onAnimationCompleteRunnable = new Runnable() {
3431                @Override
3432                public void run() {
3433                    // Normally removeExtraEmptyScreen is called in Workspace#onDragEnd, but when
3434                    // adding an item that may not be dropped right away (due to a config activity)
3435                    // we defer the removal until the activity returns.
3436                    deferRemoveExtraEmptyScreen();
3437
3438                    // When dragging and dropping from customization tray, we deal with creating
3439                    // widgets/shortcuts/folders in a slightly different way
3440                    mLauncher.addPendingItem(pendingInfo, container, screenId, mTargetCell,
3441                            item.spanX, item.spanY);
3442                }
3443            };
3444            boolean isWidget = pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET
3445                    || pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
3446
3447            View finalView = isWidget ? ((PendingAddWidgetInfo) pendingInfo).boundWidget : null;
3448
3449            if (finalView instanceof AppWidgetHostView && updateWidgetSize) {
3450                AppWidgetHostView awhv = (AppWidgetHostView) finalView;
3451                AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, item.spanX,
3452                        item.spanY);
3453            }
3454
3455            int animationStyle = ANIMATE_INTO_POSITION_AND_DISAPPEAR;
3456            if (isWidget && ((PendingAddWidgetInfo) pendingInfo).info != null &&
3457                    ((PendingAddWidgetInfo) pendingInfo).info.configure != null) {
3458                animationStyle = ANIMATE_INTO_POSITION_AND_REMAIN;
3459            }
3460            animateWidgetDrop(info, cellLayout, d.dragView, onAnimationCompleteRunnable,
3461                    animationStyle, finalView, true);
3462        } else {
3463            // This is for other drag/drop cases, like dragging from All Apps
3464            View view = null;
3465
3466            switch (info.itemType) {
3467            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
3468            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3469                if (info.container == NO_ID && info instanceof AppInfo) {
3470                    // Came from all apps -- make a copy
3471                    info = ((AppInfo) info).makeShortcut();
3472                }
3473                view = mLauncher.createShortcut(cellLayout, (ShortcutInfo) info);
3474                break;
3475            case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
3476                view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout,
3477                        (FolderInfo) info, mIconCache);
3478                break;
3479            default:
3480                throw new IllegalStateException("Unknown item type: " + info.itemType);
3481            }
3482
3483            // First we find the cell nearest to point at which the item is
3484            // dropped, without any consideration to whether there is an item there.
3485            if (touchXY != null) {
3486                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
3487                        cellLayout, mTargetCell);
3488                float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0],
3489                        mDragViewVisualCenter[1], mTargetCell);
3490                d.postAnimationRunnable = exitSpringLoadedRunnable;
3491                if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, distance,
3492                        true, d.dragView, d.postAnimationRunnable)) {
3493                    return;
3494                }
3495                if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, distance, d,
3496                        true)) {
3497                    return;
3498                }
3499            }
3500
3501            if (touchXY != null) {
3502                // when dragging and dropping, just find the closest free spot
3503                mTargetCell = cellLayout.performReorder((int) mDragViewVisualCenter[0],
3504                        (int) mDragViewVisualCenter[1], 1, 1, 1, 1,
3505                        null, mTargetCell, null, CellLayout.MODE_ON_DROP_EXTERNAL);
3506            } else {
3507                cellLayout.findCellForSpan(mTargetCell, 1, 1);
3508            }
3509            // Add the item to DB before adding to screen ensures that the container and other
3510            // values of the info is properly updated.
3511            LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screenId,
3512                    mTargetCell[0], mTargetCell[1]);
3513
3514            addInScreen(view, container, screenId, mTargetCell[0], mTargetCell[1], info.spanX,
3515                    info.spanY, insertAtFirst);
3516            cellLayout.onDropChild(view);
3517            cellLayout.getShortcutsAndWidgets().measureChild(view);
3518
3519            if (d.dragView != null) {
3520                // We wrap the animation call in the temporary set and reset of the current
3521                // cellLayout to its final transform -- this means we animate the drag view to
3522                // the correct final location.
3523                setFinalTransitionTransform(cellLayout);
3524                mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view,
3525                        exitSpringLoadedRunnable, this);
3526                resetTransitionTransform(cellLayout);
3527            }
3528        }
3529    }
3530
3531    public Bitmap createWidgetBitmap(ItemInfo widgetInfo, View layout) {
3532        int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(widgetInfo, false);
3533        int visibility = layout.getVisibility();
3534        layout.setVisibility(VISIBLE);
3535
3536        int width = MeasureSpec.makeMeasureSpec(unScaledSize[0], MeasureSpec.EXACTLY);
3537        int height = MeasureSpec.makeMeasureSpec(unScaledSize[1], MeasureSpec.EXACTLY);
3538        Bitmap b = Bitmap.createBitmap(unScaledSize[0], unScaledSize[1],
3539                Bitmap.Config.ARGB_8888);
3540        mCanvas.setBitmap(b);
3541
3542        layout.measure(width, height);
3543        layout.layout(0, 0, unScaledSize[0], unScaledSize[1]);
3544        layout.draw(mCanvas);
3545        mCanvas.setBitmap(null);
3546        layout.setVisibility(visibility);
3547        return b;
3548    }
3549
3550    private void getFinalPositionForDropAnimation(int[] loc, float[] scaleXY,
3551            DragView dragView, CellLayout layout, ItemInfo info, int[] targetCell,
3552            boolean external, boolean scale) {
3553        // Now we animate the dragView, (ie. the widget or shortcut preview) into its final
3554        // location and size on the home screen.
3555        int spanX = info.spanX;
3556        int spanY = info.spanY;
3557
3558        Rect r = estimateItemPosition(layout, info, targetCell[0], targetCell[1], spanX, spanY);
3559        loc[0] = r.left;
3560        loc[1] = r.top;
3561
3562        setFinalTransitionTransform(layout);
3563        float cellLayoutScale =
3564                mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(layout, loc, true);
3565        resetTransitionTransform(layout);
3566
3567        float dragViewScaleX;
3568        float dragViewScaleY;
3569        if (scale) {
3570            dragViewScaleX = (1.0f * r.width()) / dragView.getMeasuredWidth();
3571            dragViewScaleY = (1.0f * r.height()) / dragView.getMeasuredHeight();
3572        } else {
3573            dragViewScaleX = 1f;
3574            dragViewScaleY = 1f;
3575        }
3576
3577        // The animation will scale the dragView about its center, so we need to center about
3578        // the final location.
3579        loc[0] -= (dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2;
3580        loc[1] -= (dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2;
3581
3582        scaleXY[0] = dragViewScaleX * cellLayoutScale;
3583        scaleXY[1] = dragViewScaleY * cellLayoutScale;
3584    }
3585
3586    public void animateWidgetDrop(ItemInfo info, CellLayout cellLayout, DragView dragView,
3587            final Runnable onCompleteRunnable, int animationType, final View finalView,
3588            boolean external) {
3589        Rect from = new Rect();
3590        mLauncher.getDragLayer().getViewRectRelativeToSelf(dragView, from);
3591
3592        int[] finalPos = new int[2];
3593        float scaleXY[] = new float[2];
3594        boolean scalePreview = !(info instanceof PendingAddShortcutInfo);
3595        getFinalPositionForDropAnimation(finalPos, scaleXY, dragView, cellLayout, info, mTargetCell,
3596                external, scalePreview);
3597
3598        Resources res = mLauncher.getResources();
3599        final int duration = res.getInteger(R.integer.config_dropAnimMaxDuration) - 200;
3600
3601        // In the case where we've prebound the widget, we remove it from the DragLayer
3602        if (finalView instanceof AppWidgetHostView && external) {
3603            mLauncher.getDragLayer().removeView(finalView);
3604        }
3605
3606        boolean isWidget = info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET ||
3607                info.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
3608        if ((animationType == ANIMATE_INTO_POSITION_AND_RESIZE || external) && finalView != null) {
3609            Bitmap crossFadeBitmap = createWidgetBitmap(info, finalView);
3610            dragView.setCrossFadeBitmap(crossFadeBitmap);
3611            dragView.crossFade((int) (duration * 0.8f));
3612        } else if (isWidget && external) {
3613            scaleXY[0] = scaleXY[1] = Math.min(scaleXY[0],  scaleXY[1]);
3614        }
3615
3616        DragLayer dragLayer = mLauncher.getDragLayer();
3617        if (animationType == CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION) {
3618            mLauncher.getDragLayer().animateViewIntoPosition(dragView, finalPos, 0f, 0.1f, 0.1f,
3619                    DragLayer.ANIMATION_END_DISAPPEAR, onCompleteRunnable, duration);
3620        } else {
3621            int endStyle;
3622            if (animationType == ANIMATE_INTO_POSITION_AND_REMAIN) {
3623                endStyle = DragLayer.ANIMATION_END_REMAIN_VISIBLE;
3624            } else {
3625                endStyle = DragLayer.ANIMATION_END_DISAPPEAR;;
3626            }
3627
3628            Runnable onComplete = new Runnable() {
3629                @Override
3630                public void run() {
3631                    if (finalView != null) {
3632                        finalView.setVisibility(VISIBLE);
3633                    }
3634                    if (onCompleteRunnable != null) {
3635                        onCompleteRunnable.run();
3636                    }
3637                }
3638            };
3639            dragLayer.animateViewIntoPosition(dragView, from.left, from.top, finalPos[0],
3640                    finalPos[1], 1, 1, 1, scaleXY[0], scaleXY[1], onComplete, endStyle,
3641                    duration, this);
3642        }
3643    }
3644
3645    public void setFinalTransitionTransform(CellLayout layout) {
3646        if (isSwitchingState()) {
3647            mCurrentScale = getScaleX();
3648            setScaleX(mStateTransitionAnimation.getFinalScale());
3649            setScaleY(mStateTransitionAnimation.getFinalScale());
3650        }
3651    }
3652    public void resetTransitionTransform(CellLayout layout) {
3653        if (isSwitchingState()) {
3654            setScaleX(mCurrentScale);
3655            setScaleY(mCurrentScale);
3656        }
3657    }
3658
3659    /**
3660     * Return the current {@link CellLayout}, correctly picking the destination
3661     * screen while a scroll is in progress.
3662     */
3663    public CellLayout getCurrentDropLayout() {
3664        return (CellLayout) getChildAt(getNextPage());
3665    }
3666
3667    /**
3668     * Return the current CellInfo describing our current drag; this method exists
3669     * so that Launcher can sync this object with the correct info when the activity is created/
3670     * destroyed
3671     *
3672     */
3673    public CellLayout.CellInfo getDragInfo() {
3674        return mDragInfo;
3675    }
3676
3677    public int getCurrentPageOffsetFromCustomContent() {
3678        return getNextPage() - numCustomPages();
3679    }
3680
3681    /**
3682     * Calculate the nearest cell where the given object would be dropped.
3683     *
3684     * pixelX and pixelY should be in the coordinate system of layout
3685     */
3686    @Thunk int[] findNearestArea(int pixelX, int pixelY,
3687            int spanX, int spanY, CellLayout layout, int[] recycle) {
3688        return layout.findNearestArea(
3689                pixelX, pixelY, spanX, spanY, recycle);
3690    }
3691
3692    void setup(DragController dragController) {
3693        mSpringLoadedDragController = new SpringLoadedDragController(mLauncher);
3694        mDragController = dragController;
3695
3696        // hardware layers on children are enabled on startup, but should be disabled until
3697        // needed
3698        updateChildrenLayersEnabled(false);
3699    }
3700
3701    /**
3702     * Called at the end of a drag which originated on the workspace.
3703     */
3704    public void onDropCompleted(final View target, final DragObject d,
3705            final boolean isFlingToDelete, final boolean success) {
3706        if (mDeferDropAfterUninstall) {
3707            mDeferredAction = new Runnable() {
3708                public void run() {
3709                    onDropCompleted(target, d, isFlingToDelete, success);
3710                    mDeferredAction = null;
3711                }
3712            };
3713            return;
3714        }
3715
3716        boolean beingCalledAfterUninstall = mDeferredAction != null;
3717
3718        if (success && !(beingCalledAfterUninstall && !mUninstallSuccessful)) {
3719            if (target != this && mDragInfo != null) {
3720                removeWorkspaceItem(mDragInfo.cell);
3721            }
3722        } else if (mDragInfo != null) {
3723            final CellLayout cellLayout = mLauncher.getCellLayout(
3724                    mDragInfo.container, mDragInfo.screenId);
3725            if (cellLayout != null) {
3726                cellLayout.onDropChild(mDragInfo.cell);
3727            } else if (ProviderConfig.IS_DOGFOOD_BUILD) {
3728                throw new RuntimeException("Invalid state: cellLayout == null in "
3729                        + "Workspace#onDropCompleted. Please file a bug. ");
3730            };
3731        }
3732        if ((d.cancelled || (beingCalledAfterUninstall && !mUninstallSuccessful))
3733                && mDragInfo.cell != null) {
3734            mDragInfo.cell.setVisibility(VISIBLE);
3735        }
3736        mDragOutline = null;
3737        mDragInfo = null;
3738    }
3739
3740    /**
3741     * For opposite operation. See {@link #addInScreen}.
3742     */
3743    public void removeWorkspaceItem(View v) {
3744        CellLayout parentCell = getParentCellLayoutForView(v);
3745        if (parentCell != null) {
3746            parentCell.removeView(v);
3747        } else if (ProviderConfig.IS_DOGFOOD_BUILD) {
3748            // When an app is uninstalled using the drop target, we wait until resume to remove
3749            // the icon. We also remove all the corresponding items from the workspace at
3750            // {@link Launcher#bindComponentsRemoved}. That call can come before or after
3751            // {@link Launcher#mOnResumeCallbacks} depending on how busy the worker thread is.
3752            Log.e(TAG, "mDragInfo.cell has null parent");
3753        }
3754        if (v instanceof DropTarget) {
3755            mDragController.removeDropTarget((DropTarget) v);
3756        }
3757    }
3758
3759    @Override
3760    public void deferCompleteDropAfterUninstallActivity() {
3761        mDeferDropAfterUninstall = true;
3762    }
3763
3764    /// maybe move this into a smaller part
3765    @Override
3766    public void onUninstallActivityReturned(boolean success) {
3767        mDeferDropAfterUninstall = false;
3768        mUninstallSuccessful = success;
3769        if (mDeferredAction != null) {
3770            mDeferredAction.run();
3771        }
3772    }
3773
3774    void saveWorkspaceToDb() {
3775        saveWorkspaceScreenToDb((CellLayout) mLauncher.getHotseat().getLayout());
3776        int count = getChildCount();
3777        for (int i = 0; i < count; i++) {
3778            CellLayout cl = (CellLayout) getChildAt(i);
3779            saveWorkspaceScreenToDb(cl);
3780        }
3781    }
3782
3783    void saveWorkspaceScreenToDb(CellLayout cl) {
3784        int count = cl.getShortcutsAndWidgets().getChildCount();
3785
3786        long screenId = getIdForScreen(cl);
3787        int container = Favorites.CONTAINER_DESKTOP;
3788
3789        Hotseat hotseat = mLauncher.getHotseat();
3790        if (mLauncher.isHotseatLayout(cl)) {
3791            screenId = -1;
3792            container = Favorites.CONTAINER_HOTSEAT;
3793        }
3794
3795        for (int i = 0; i < count; i++) {
3796            View v = cl.getShortcutsAndWidgets().getChildAt(i);
3797            ItemInfo info = (ItemInfo) v.getTag();
3798            // Null check required as the AllApps button doesn't have an item info
3799            if (info != null) {
3800                int cellX = info.cellX;
3801                int cellY = info.cellY;
3802                if (container == Favorites.CONTAINER_HOTSEAT) {
3803                    cellX = hotseat.getCellXFromOrder((int) info.screenId);
3804                    cellY = hotseat.getCellYFromOrder((int) info.screenId);
3805                }
3806                LauncherModel.addItemToDatabase(mLauncher, info, container, screenId, cellX, cellY);
3807            }
3808            if (v instanceof FolderIcon) {
3809                FolderIcon fi = (FolderIcon) v;
3810                fi.getFolder().addItemLocationsInDatabase();
3811            }
3812        }
3813    }
3814
3815    @Override
3816    public float getIntrinsicIconScaleFactor() {
3817        return 1f;
3818    }
3819
3820    @Override
3821    public boolean supportsFlingToDelete() {
3822        return true;
3823    }
3824
3825    @Override
3826    public boolean supportsAppInfoDropTarget() {
3827        return false;
3828    }
3829
3830    @Override
3831    public boolean supportsDeleteDropTarget() {
3832        return true;
3833    }
3834
3835    @Override
3836    public void onFlingToDelete(DragObject d, PointF vec) {
3837        // Do nothing
3838    }
3839
3840    @Override
3841    public void onFlingToDeleteCompleted() {
3842        // Do nothing
3843    }
3844
3845    public boolean isDropEnabled() {
3846        return true;
3847    }
3848
3849    @Override
3850    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
3851        // We don't dispatch restoreInstanceState to our children using this code path.
3852        // Some pages will be restored immediately as their items are bound immediately, and
3853        // others we will need to wait until after their items are bound.
3854        mSavedStates = container;
3855    }
3856
3857    public void restoreInstanceStateForChild(int child) {
3858        if (mSavedStates != null) {
3859            mRestoredPages.add(child);
3860            CellLayout cl = (CellLayout) getChildAt(child);
3861            if (cl != null) {
3862                cl.restoreInstanceState(mSavedStates);
3863            }
3864        }
3865    }
3866
3867    public void restoreInstanceStateForRemainingPages() {
3868        int count = getChildCount();
3869        for (int i = 0; i < count; i++) {
3870            if (!mRestoredPages.contains(i)) {
3871                restoreInstanceStateForChild(i);
3872            }
3873        }
3874        mRestoredPages.clear();
3875        mSavedStates = null;
3876    }
3877
3878    @Override
3879    public void scrollLeft() {
3880        if (!workspaceInModalState() && !mIsSwitchingState) {
3881            super.scrollLeft();
3882        }
3883        Folder openFolder = getOpenFolder();
3884        if (openFolder != null) {
3885            openFolder.completeDragExit();
3886        }
3887    }
3888
3889    @Override
3890    public void scrollRight() {
3891        if (!workspaceInModalState() && !mIsSwitchingState) {
3892            super.scrollRight();
3893        }
3894        Folder openFolder = getOpenFolder();
3895        if (openFolder != null) {
3896            openFolder.completeDragExit();
3897        }
3898    }
3899
3900    @Override
3901    public boolean onEnterScrollArea(int x, int y, int direction) {
3902        // Ignore the scroll area if we are dragging over the hot seat
3903        boolean isPortrait = !mLauncher.getDeviceProfile().isLandscape;
3904        if (mLauncher.getHotseat() != null && isPortrait) {
3905            Rect r = new Rect();
3906            mLauncher.getHotseat().getHitRect(r);
3907            if (r.contains(x, y)) {
3908                return false;
3909            }
3910        }
3911
3912        boolean result = false;
3913        if (!workspaceInModalState() && !mIsSwitchingState && getOpenFolder() == null) {
3914            mInScrollArea = true;
3915
3916            final int page = getNextPage() +
3917                       (direction == DragController.SCROLL_LEFT ? -1 : 1);
3918            // We always want to exit the current layout to ensure parity of enter / exit
3919            setCurrentDropLayout(null);
3920
3921            if (0 <= page && page < getChildCount()) {
3922                // Ensure that we are not dragging over to the custom content screen
3923                if (getScreenIdForPageIndex(page) == CUSTOM_CONTENT_SCREEN_ID) {
3924                    return false;
3925                }
3926
3927                CellLayout layout = (CellLayout) getChildAt(page);
3928                setCurrentDragOverlappingLayout(layout);
3929
3930                // Workspace is responsible for drawing the edge glow on adjacent pages,
3931                // so we need to redraw the workspace when this may have changed.
3932                invalidate();
3933                result = true;
3934            }
3935        }
3936        return result;
3937    }
3938
3939    @Override
3940    public boolean onExitScrollArea() {
3941        boolean result = false;
3942        if (mInScrollArea) {
3943            invalidate();
3944            CellLayout layout = getCurrentDropLayout();
3945            setCurrentDropLayout(layout);
3946            setCurrentDragOverlappingLayout(layout);
3947
3948            result = true;
3949            mInScrollArea = false;
3950        }
3951        return result;
3952    }
3953
3954    private void onResetScrollArea() {
3955        setCurrentDragOverlappingLayout(null);
3956        mInScrollArea = false;
3957    }
3958
3959    /**
3960     * Returns a specific CellLayout
3961     */
3962    CellLayout getParentCellLayoutForView(View v) {
3963        ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts();
3964        for (CellLayout layout : layouts) {
3965            if (layout.getShortcutsAndWidgets().indexOfChild(v) > -1) {
3966                return layout;
3967            }
3968        }
3969        return null;
3970    }
3971
3972    /**
3973     * Returns a list of all the CellLayouts in the workspace.
3974     */
3975    ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() {
3976        ArrayList<CellLayout> layouts = new ArrayList<CellLayout>();
3977        int screenCount = getChildCount();
3978        for (int screen = 0; screen < screenCount; screen++) {
3979            layouts.add(((CellLayout) getChildAt(screen)));
3980        }
3981        if (mLauncher.getHotseat() != null) {
3982            layouts.add(mLauncher.getHotseat().getLayout());
3983        }
3984        return layouts;
3985    }
3986
3987    /**
3988     * We should only use this to search for specific children.  Do not use this method to modify
3989     * ShortcutsAndWidgetsContainer directly. Includes ShortcutAndWidgetContainers from
3990     * the hotseat and workspace pages
3991     */
3992    ArrayList<ShortcutAndWidgetContainer> getAllShortcutAndWidgetContainers() {
3993        ArrayList<ShortcutAndWidgetContainer> childrenLayouts =
3994                new ArrayList<ShortcutAndWidgetContainer>();
3995        int screenCount = getChildCount();
3996        for (int screen = 0; screen < screenCount; screen++) {
3997            childrenLayouts.add(((CellLayout) getChildAt(screen)).getShortcutsAndWidgets());
3998        }
3999        if (mLauncher.getHotseat() != null) {
4000            childrenLayouts.add(mLauncher.getHotseat().getLayout().getShortcutsAndWidgets());
4001        }
4002        return childrenLayouts;
4003    }
4004
4005    public Folder getFolderForTag(final Object tag) {
4006        return (Folder) getFirstMatch(new ItemOperator() {
4007
4008            @Override
4009            public boolean evaluate(ItemInfo info, View v, View parent) {
4010                return (v instanceof Folder) && (((Folder) v).getInfo() == tag)
4011                        && ((Folder) v).getInfo().opened;
4012            }
4013        });
4014    }
4015
4016    public View getHomescreenIconByItemId(final long id) {
4017        return getFirstMatch(new ItemOperator() {
4018
4019            @Override
4020            public boolean evaluate(ItemInfo info, View v, View parent) {
4021                return info != null && info.id == id;
4022            }
4023        });
4024    }
4025
4026    public View getViewForTag(final Object tag) {
4027        return getFirstMatch(new ItemOperator() {
4028
4029            @Override
4030            public boolean evaluate(ItemInfo info, View v, View parent) {
4031                return info == tag;
4032            }
4033        });
4034    }
4035
4036    public LauncherAppWidgetHostView getWidgetForAppWidgetId(final int appWidgetId) {
4037        return (LauncherAppWidgetHostView) getFirstMatch(new ItemOperator() {
4038
4039            @Override
4040            public boolean evaluate(ItemInfo info, View v, View parent) {
4041                return (info instanceof LauncherAppWidgetInfo) &&
4042                        ((LauncherAppWidgetInfo) info).appWidgetId == appWidgetId;
4043            }
4044        });
4045    }
4046
4047    private View getFirstMatch(final ItemOperator operator) {
4048        final View[] value = new View[1];
4049        mapOverItems(MAP_NO_RECURSE, new ItemOperator() {
4050            @Override
4051            public boolean evaluate(ItemInfo info, View v, View parent) {
4052                if (operator.evaluate(info, v, parent)) {
4053                    value[0] = v;
4054                    return true;
4055                }
4056                return false;
4057            }
4058        });
4059        return value[0];
4060    }
4061
4062    void clearDropTargets() {
4063        mapOverItems(MAP_NO_RECURSE, new ItemOperator() {
4064            @Override
4065            public boolean evaluate(ItemInfo info, View v, View parent) {
4066                if (v instanceof DropTarget) {
4067                    mDragController.removeDropTarget((DropTarget) v);
4068                }
4069                // not done, process all the shortcuts
4070                return false;
4071            }
4072        });
4073    }
4074
4075    public void disableShortcutsByPackageName(final ArrayList<String> packages,
4076            final UserHandleCompat user, final int reason) {
4077        final HashSet<String> packageNames = new HashSet<String>();
4078        packageNames.addAll(packages);
4079
4080        mapOverItems(MAP_RECURSE, new ItemOperator() {
4081            @Override
4082            public boolean evaluate(ItemInfo info, View v, View parent) {
4083                if (info instanceof ShortcutInfo && v instanceof BubbleTextView) {
4084                    ShortcutInfo shortcutInfo = (ShortcutInfo) info;
4085                    ComponentName cn = shortcutInfo.getTargetComponent();
4086                    if (user.equals(shortcutInfo.user) && cn != null
4087                            && packageNames.contains(cn.getPackageName())) {
4088                        shortcutInfo.isDisabled |= reason;
4089                        BubbleTextView shortcut = (BubbleTextView) v;
4090                        shortcut.applyFromShortcutInfo(shortcutInfo, mIconCache);
4091
4092                        if (parent != null) {
4093                            parent.invalidate();
4094                        }
4095                    }
4096                }
4097                // process all the shortcuts
4098                return false;
4099            }
4100        });
4101    }
4102
4103    // Removes ALL items that match a given package name, this is usually called when a package
4104    // has been removed and we want to remove all components (widgets, shortcuts, apps) that
4105    // belong to that package.
4106    void removeItemsByPackageName(final ArrayList<String> packages, final UserHandleCompat user) {
4107        final HashSet<String> packageNames = new HashSet<String>();
4108        packageNames.addAll(packages);
4109
4110        // Filter out all the ItemInfos that this is going to affect
4111        final HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
4112        final HashSet<ComponentName> cns = new HashSet<ComponentName>();
4113        ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
4114        for (CellLayout layoutParent : cellLayouts) {
4115            ViewGroup layout = layoutParent.getShortcutsAndWidgets();
4116            int childCount = layout.getChildCount();
4117            for (int i = 0; i < childCount; ++i) {
4118                View view = layout.getChildAt(i);
4119                infos.add((ItemInfo) view.getTag());
4120            }
4121        }
4122        LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() {
4123            @Override
4124            public boolean filterItem(ItemInfo parent, ItemInfo info,
4125                                      ComponentName cn) {
4126                if (packageNames.contains(cn.getPackageName())
4127                        && info.user.equals(user)) {
4128                    cns.add(cn);
4129                    return true;
4130                }
4131                return false;
4132            }
4133        };
4134        LauncherModel.filterItemInfos(infos, filter);
4135
4136        // Remove the affected components
4137        removeItemsByComponentName(cns, user);
4138    }
4139
4140    /**
4141     * Removes items that match the item info specified. When applications are removed
4142     * as a part of an update, this is called to ensure that other widgets and application
4143     * shortcuts are not removed.
4144     */
4145    void removeItemsByComponentName(final HashSet<ComponentName> componentNames,
4146            final UserHandleCompat user) {
4147        ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
4148        for (final CellLayout layoutParent: cellLayouts) {
4149            final ViewGroup layout = layoutParent.getShortcutsAndWidgets();
4150
4151            final HashMap<ItemInfo, View> children = new HashMap<ItemInfo, View>();
4152            for (int j = 0; j < layout.getChildCount(); j++) {
4153                final View view = layout.getChildAt(j);
4154                children.put((ItemInfo) view.getTag(), view);
4155            }
4156
4157            final ArrayList<View> childrenToRemove = new ArrayList<View>();
4158            final HashMap<FolderInfo, ArrayList<ShortcutInfo>> folderAppsToRemove =
4159                    new HashMap<FolderInfo, ArrayList<ShortcutInfo>>();
4160            LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() {
4161                @Override
4162                public boolean filterItem(ItemInfo parent, ItemInfo info,
4163                                          ComponentName cn) {
4164                    if (parent instanceof FolderInfo) {
4165                        if (componentNames.contains(cn) && info.user.equals(user)) {
4166                            FolderInfo folder = (FolderInfo) parent;
4167                            ArrayList<ShortcutInfo> appsToRemove;
4168                            if (folderAppsToRemove.containsKey(folder)) {
4169                                appsToRemove = folderAppsToRemove.get(folder);
4170                            } else {
4171                                appsToRemove = new ArrayList<ShortcutInfo>();
4172                                folderAppsToRemove.put(folder, appsToRemove);
4173                            }
4174                            appsToRemove.add((ShortcutInfo) info);
4175                            return true;
4176                        }
4177                    } else {
4178                        if (componentNames.contains(cn) && info.user.equals(user)) {
4179                            childrenToRemove.add(children.get(info));
4180                            return true;
4181                        }
4182                    }
4183                    return false;
4184                }
4185            };
4186            LauncherModel.filterItemInfos(children.keySet(), filter);
4187
4188            // Remove all the apps from their folders
4189            for (FolderInfo folder : folderAppsToRemove.keySet()) {
4190                ArrayList<ShortcutInfo> appsToRemove = folderAppsToRemove.get(folder);
4191                for (ShortcutInfo info : appsToRemove) {
4192                    folder.remove(info);
4193                }
4194            }
4195
4196            // Remove all the other children
4197            for (View child : childrenToRemove) {
4198                // Note: We can not remove the view directly from CellLayoutChildren as this
4199                // does not re-mark the spaces as unoccupied.
4200                layoutParent.removeViewInLayout(child);
4201                if (child instanceof DropTarget) {
4202                    mDragController.removeDropTarget((DropTarget) child);
4203                }
4204            }
4205
4206            if (childrenToRemove.size() > 0) {
4207                layout.requestLayout();
4208                layout.invalidate();
4209            }
4210        }
4211
4212        // Strip all the empty screens
4213        stripEmptyScreens();
4214    }
4215
4216    interface ItemOperator {
4217        /**
4218         * Process the next itemInfo, possibly with side-effect on {@link ItemOperator#value}.
4219         *
4220         * @param info info for the shortcut
4221         * @param view view for the shortcut
4222         * @param parent containing folder, or null
4223         * @return true if done, false to continue the map
4224         */
4225        public boolean evaluate(ItemInfo info, View view, View parent);
4226    }
4227
4228    /**
4229     * Map the operator over the shortcuts and widgets, return the first-non-null value.
4230     *
4231     * @param recurse true: iterate over folder children. false: op get the folders themselves.
4232     * @param op the operator to map over the shortcuts
4233     */
4234    void mapOverItems(boolean recurse, ItemOperator op) {
4235        ArrayList<ShortcutAndWidgetContainer> containers = getAllShortcutAndWidgetContainers();
4236        final int containerCount = containers.size();
4237        for (int containerIdx = 0; containerIdx < containerCount; containerIdx++) {
4238            ShortcutAndWidgetContainer container = containers.get(containerIdx);
4239            // map over all the shortcuts on the workspace
4240            final int itemCount = container.getChildCount();
4241            for (int itemIdx = 0; itemIdx < itemCount; itemIdx++) {
4242                View item = container.getChildAt(itemIdx);
4243                ItemInfo info = (ItemInfo) item.getTag();
4244                if (recurse && info instanceof FolderInfo && item instanceof FolderIcon) {
4245                    FolderIcon folder = (FolderIcon) item;
4246                    ArrayList<View> folderChildren = folder.getFolder().getItemsInReadingOrder();
4247                    // map over all the children in the folder
4248                    final int childCount = folderChildren.size();
4249                    for (int childIdx = 0; childIdx < childCount; childIdx++) {
4250                        View child = folderChildren.get(childIdx);
4251                        info = (ItemInfo) child.getTag();
4252                        if (op.evaluate(info, child, folder)) {
4253                            return;
4254                        }
4255                    }
4256                } else {
4257                    if (op.evaluate(info, item, null)) {
4258                        return;
4259                    }
4260                }
4261            }
4262        }
4263    }
4264
4265    void updateShortcuts(ArrayList<ShortcutInfo> shortcuts) {
4266        final HashSet<ShortcutInfo> updates = new HashSet<ShortcutInfo>(shortcuts);
4267        mapOverItems(MAP_RECURSE, new ItemOperator() {
4268            @Override
4269            public boolean evaluate(ItemInfo info, View v, View parent) {
4270                if (info instanceof ShortcutInfo && v instanceof BubbleTextView &&
4271                        updates.contains(info)) {
4272                    ShortcutInfo si = (ShortcutInfo) info;
4273                    BubbleTextView shortcut = (BubbleTextView) v;
4274                    Drawable oldIcon = getTextViewIcon(shortcut);
4275                    boolean oldPromiseState = (oldIcon instanceof PreloadIconDrawable)
4276                            && ((PreloadIconDrawable) oldIcon).hasNotCompleted();
4277                    shortcut.applyFromShortcutInfo(si, mIconCache,
4278                            si.isPromise() != oldPromiseState);
4279
4280                    if (parent != null) {
4281                        parent.invalidate();
4282                    }
4283                }
4284                // process all the shortcuts
4285                return false;
4286            }
4287        });
4288    }
4289
4290    public void removeAbandonedPromise(String packageName, UserHandleCompat user) {
4291        ArrayList<String> packages = new ArrayList<String>(1);
4292        packages.add(packageName);
4293        LauncherModel.deletePackageFromDatabase(mLauncher, packageName, user);
4294        removeItemsByPackageName(packages, user);
4295    }
4296
4297    public void updateRestoreItems(final HashSet<ItemInfo> updates) {
4298        mapOverItems(MAP_RECURSE, new ItemOperator() {
4299            @Override
4300            public boolean evaluate(ItemInfo info, View v, View parent) {
4301                if (info instanceof ShortcutInfo && v instanceof BubbleTextView
4302                        && updates.contains(info)) {
4303                    ((BubbleTextView) v).applyState(false);
4304                } else if (v instanceof PendingAppWidgetHostView
4305                        && info instanceof LauncherAppWidgetInfo
4306                        && updates.contains(info)) {
4307                    ((PendingAppWidgetHostView) v).applyState();
4308                }
4309                // process all the shortcuts
4310                return false;
4311            }
4312        });
4313    }
4314
4315    void widgetsRestored(ArrayList<LauncherAppWidgetInfo> changedInfo) {
4316        if (!changedInfo.isEmpty()) {
4317            DeferredWidgetRefresh widgetRefresh = new DeferredWidgetRefresh(changedInfo,
4318                    mLauncher.getAppWidgetHost());
4319            if (LauncherModel.getProviderInfo(getContext(),
4320                    changedInfo.get(0).providerName,
4321                    changedInfo.get(0).user) != null) {
4322                // Re-inflate the widgets which have changed status
4323                widgetRefresh.run();
4324            } else {
4325                // widgetRefresh will automatically run when the packages are updated.
4326                // For now just update the progress bars
4327                for (LauncherAppWidgetInfo info : changedInfo) {
4328                    if (info.hostView instanceof PendingAppWidgetHostView) {
4329                        info.installProgress = 100;
4330                        ((PendingAppWidgetHostView) info.hostView).applyState();
4331                    }
4332                }
4333            }
4334        }
4335    }
4336
4337    private void moveToScreen(int page, boolean animate) {
4338        if (!workspaceInModalState()) {
4339            if (animate) {
4340                snapToPage(page);
4341            } else {
4342                setCurrentPage(page);
4343            }
4344        }
4345        View child = getChildAt(page);
4346        if (child != null) {
4347            child.requestFocus();
4348        }
4349    }
4350
4351    void moveToDefaultScreen(boolean animate) {
4352        moveToScreen(mDefaultPage, animate);
4353    }
4354
4355    void moveToCustomContentScreen(boolean animate) {
4356        if (hasCustomContent()) {
4357            int ccIndex = getPageIndexForScreenId(CUSTOM_CONTENT_SCREEN_ID);
4358            if (animate) {
4359                snapToPage(ccIndex);
4360            } else {
4361                setCurrentPage(ccIndex);
4362            }
4363            View child = getChildAt(ccIndex);
4364            if (child != null) {
4365                child.requestFocus();
4366            }
4367         }
4368        exitWidgetResizeMode();
4369    }
4370
4371    @Override
4372    protected PageIndicator.PageMarkerResources getPageIndicatorMarker(int pageIndex) {
4373        long screenId = getScreenIdForPageIndex(pageIndex);
4374        if (screenId == EXTRA_EMPTY_SCREEN_ID) {
4375            int count = mScreenOrder.size() - numCustomPages();
4376            if (count > 1) {
4377                return new PageIndicator.PageMarkerResources(R.drawable.ic_pageindicator_current,
4378                        R.drawable.ic_pageindicator_add);
4379            }
4380        }
4381
4382        return super.getPageIndicatorMarker(pageIndex);
4383    }
4384
4385    protected String getPageIndicatorDescription() {
4386        String settings = getResources().getString(R.string.settings_button_text);
4387        return getCurrentPageDescription() + ", " + settings;
4388    }
4389
4390    protected String getCurrentPageDescription() {
4391        if (hasCustomContent() && getNextPage() == 0) {
4392            return mCustomContentDescription;
4393        }
4394        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
4395        return getPageDescription(page);
4396    }
4397
4398    private String getPageDescription(int page) {
4399        int delta = numCustomPages();
4400        return getContext().getString(R.string.workspace_scroll_format,
4401                page + 1 - delta, getChildCount() - delta);
4402    }
4403
4404    public void getLocationInDragLayer(int[] loc) {
4405        mLauncher.getDragLayer().getLocationInDragLayer(this, loc);
4406    }
4407
4408    @Override
4409    public void fillInLaunchSourceData(Bundle sourceData) {
4410        sourceData.putString(Stats.SOURCE_EXTRA_CONTAINER, Stats.CONTAINER_HOMESCREEN);
4411        sourceData.putInt(Stats.SOURCE_EXTRA_CONTAINER_PAGE, getCurrentPage());
4412    }
4413
4414    /**
4415     * Used as a workaround to ensure that the AppWidgetService receives the
4416     * PACKAGE_ADDED broadcast before updating widgets.
4417     */
4418    private class DeferredWidgetRefresh implements Runnable {
4419        private final ArrayList<LauncherAppWidgetInfo> mInfos;
4420        private final LauncherAppWidgetHost mHost;
4421        private final Handler mHandler;
4422
4423        private boolean mRefreshPending;
4424
4425        public DeferredWidgetRefresh(ArrayList<LauncherAppWidgetInfo> infos,
4426                LauncherAppWidgetHost host) {
4427            mInfos = infos;
4428            mHost = host;
4429            mHandler = new Handler();
4430            mRefreshPending = true;
4431
4432            mHost.addProviderChangeListener(this);
4433            // Force refresh after 10 seconds, if we don't get the provider changed event.
4434            // This could happen when the provider is no longer available in the app.
4435            mHandler.postDelayed(this, 10000);
4436        }
4437
4438        @Override
4439        public void run() {
4440            mHost.removeProviderChangeListener(this);
4441            mHandler.removeCallbacks(this);
4442
4443            if (!mRefreshPending) {
4444                return;
4445            }
4446
4447            mRefreshPending = false;
4448
4449            for (LauncherAppWidgetInfo info : mInfos) {
4450                if (info.hostView instanceof PendingAppWidgetHostView) {
4451                    PendingAppWidgetHostView view = (PendingAppWidgetHostView) info.hostView;
4452                    mLauncher.removeAppWidget(info);
4453
4454                    CellLayout cl = (CellLayout) view.getParent().getParent();
4455                    // Remove the current widget
4456                    cl.removeView(view);
4457                    mLauncher.bindAppWidget(info);
4458                }
4459            }
4460        }
4461    }
4462}
4463