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