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