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