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