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