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