Workspace.java revision 43bf11d9c95f76c2dfeb625b23cb458df81252b3
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.popup.PopupContainerWithArrow;
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        final State fromState = mState;
2046
2047        // Update the current state
2048        mState = toState;
2049
2050        // Create the animation to the new state
2051        AnimatorSet workspaceAnim =  mStateTransitionAnimation.getAnimationToState(fromState,
2052                toState, animated, layerViews);
2053
2054        boolean shouldNotifyWidgetChange = !fromState.shouldUpdateWidget
2055                && toState.shouldUpdateWidget;
2056
2057        updateAccessibilityFlags();
2058
2059        if (shouldNotifyWidgetChange) {
2060            mLauncher.notifyWidgetProvidersChanged();
2061        }
2062
2063        if (mOnStateChangeListener != null) {
2064            mOnStateChangeListener.prepareStateChange(toState, animated ? workspaceAnim : null);
2065        }
2066
2067        onPrepareStateTransition(mState.hasMultipleVisiblePages);
2068
2069        StateTransitionListener listener = new StateTransitionListener();
2070        if (animated) {
2071            ValueAnimator stepAnimator = ValueAnimator.ofFloat(0, 1);
2072            stepAnimator.addUpdateListener(listener);
2073
2074            workspaceAnim.play(stepAnimator);
2075            workspaceAnim.addListener(listener);
2076        } else {
2077            listener.onAnimationStart(null);
2078            listener.onAnimationEnd(null);
2079        }
2080
2081        return workspaceAnim;
2082    }
2083
2084    public State getState() {
2085        return mState;
2086    }
2087
2088    public void updateAccessibilityFlags() {
2089        // TODO: Update the accessibility flags appropriately when dragging.
2090        if (!mLauncher.getAccessibilityDelegate().isInAccessibleDrag()) {
2091            int total = getPageCount();
2092            for (int i = numCustomPages(); i < total; i++) {
2093                updateAccessibilityFlags((CellLayout) getPageAt(i), i);
2094            }
2095            setImportantForAccessibility((mState == State.NORMAL || mState == State.OVERVIEW)
2096                    ? IMPORTANT_FOR_ACCESSIBILITY_AUTO
2097                    : IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
2098        }
2099    }
2100
2101    private void updateAccessibilityFlags(CellLayout page, int pageNo) {
2102        if (mState == State.OVERVIEW) {
2103            page.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
2104            page.getShortcutsAndWidgets().setImportantForAccessibility(
2105                    IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
2106            page.setContentDescription(getPageDescription(pageNo));
2107
2108            // No custom action for the first page.
2109            if (!FeatureFlags.QSB_ON_FIRST_SCREEN || pageNo > 0) {
2110                if (mPagesAccessibilityDelegate == null) {
2111                    mPagesAccessibilityDelegate = new OverviewScreenAccessibilityDelegate(this);
2112                }
2113                page.setAccessibilityDelegate(mPagesAccessibilityDelegate);
2114            }
2115        } else {
2116            int accessible = mState == State.NORMAL ?
2117                    IMPORTANT_FOR_ACCESSIBILITY_AUTO :
2118                        IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
2119            page.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
2120            page.getShortcutsAndWidgets().setImportantForAccessibility(accessible);
2121            page.setContentDescription(null);
2122            page.setAccessibilityDelegate(null);
2123        }
2124    }
2125
2126    public void onPrepareStateTransition(boolean multiplePagesVisible) {
2127        mIsSwitchingState = true;
2128        mTransitionProgress = 0;
2129
2130        if (multiplePagesVisible) {
2131            mForceDrawAdjacentPages = true;
2132        }
2133        invalidate(); // This will call dispatchDraw(), which calls getVisiblePages().
2134
2135        updateChildrenLayersEnabled(false);
2136        hideCustomContentIfNecessary();
2137    }
2138
2139    public void onEndStateTransition() {
2140        mIsSwitchingState = false;
2141        updateChildrenLayersEnabled(false);
2142        showCustomContentIfNecessary();
2143        mForceDrawAdjacentPages = false;
2144        mTransitionProgress = 1;
2145    }
2146
2147    void updateCustomContentVisibility() {
2148        int visibility = mState == Workspace.State.NORMAL ? VISIBLE : INVISIBLE;
2149        setCustomContentVisibility(visibility);
2150    }
2151
2152    void setCustomContentVisibility(int visibility) {
2153        if (hasCustomContent()) {
2154            mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID).setVisibility(visibility);
2155        }
2156    }
2157
2158    void showCustomContentIfNecessary() {
2159        boolean show  = mState == Workspace.State.NORMAL;
2160        if (show && hasCustomContent()) {
2161            mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID).setVisibility(VISIBLE);
2162        }
2163    }
2164
2165    void hideCustomContentIfNecessary() {
2166        boolean hide  = mState != Workspace.State.NORMAL;
2167        if (hide && hasCustomContent()) {
2168            disableLayoutTransitions();
2169            mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID).setVisibility(INVISIBLE);
2170            enableLayoutTransitions();
2171        }
2172    }
2173
2174    /**
2175     * Returns the drawable for the given text view.
2176     */
2177    public static Drawable getTextViewIcon(TextView tv) {
2178        final Drawable[] drawables = tv.getCompoundDrawables();
2179        for (int i = 0; i < drawables.length; i++) {
2180            if (drawables[i] != null) {
2181                return drawables[i];
2182            }
2183        }
2184        return null;
2185    }
2186
2187    public void startDrag(CellLayout.CellInfo cellInfo, DragOptions options) {
2188        View child = cellInfo.cell;
2189
2190        // Make sure the drag was started by a long press as opposed to a long click.
2191        if (!child.isInTouchMode()) {
2192            return;
2193        }
2194
2195        mDragInfo = cellInfo;
2196        child.setVisibility(INVISIBLE);
2197
2198        if (options.isAccessibleDrag) {
2199            mDragController.addDragListener(new AccessibleDragListenerAdapter(
2200                    this, CellLayout.WORKSPACE_ACCESSIBILITY_DRAG) {
2201                @Override
2202                protected void enableAccessibleDrag(boolean enable) {
2203                    super.enableAccessibleDrag(enable);
2204                    setEnableForLayout(mLauncher.getHotseat().getLayout(),enable);
2205
2206                    // We need to allow our individual children to become click handlers in this
2207                    // case, so temporarily unset the click handlers.
2208                    setOnClickListener(enable ? null : mLauncher);
2209                }
2210            });
2211        }
2212
2213        beginDragShared(child, this, options);
2214    }
2215
2216    public void beginDragShared(View child, DragSource source, DragOptions options) {
2217        Object dragObject = child.getTag();
2218        if (!(dragObject instanceof ItemInfo)) {
2219            String msg = "Drag started with a view that has no tag set. This "
2220                    + "will cause a crash (issue 11627249) down the line. "
2221                    + "View: " + child + "  tag: " + child.getTag();
2222            throw new IllegalStateException(msg);
2223        }
2224        beginDragShared(child, source, (ItemInfo) dragObject,
2225                new DragPreviewProvider(child), options);
2226    }
2227
2228
2229    public DragView beginDragShared(View child, DragSource source, ItemInfo dragObject,
2230            DragPreviewProvider previewProvider, DragOptions dragOptions) {
2231        child.clearFocus();
2232        child.setPressed(false);
2233        mOutlineProvider = previewProvider;
2234
2235        // The drag bitmap follows the touch point around on the screen
2236        final Bitmap b = previewProvider.createDragBitmap(mCanvas);
2237        int halfPadding = previewProvider.previewPadding / 2;
2238
2239        float scale = previewProvider.getScaleAndPosition(b, mTempXY);
2240        int dragLayerX = mTempXY[0];
2241        int dragLayerY = mTempXY[1];
2242
2243        DeviceProfile grid = mLauncher.getDeviceProfile();
2244        Point dragVisualizeOffset = null;
2245        Rect dragRect = null;
2246        if (child instanceof BubbleTextView) {
2247            int iconSize = grid.iconSizePx;
2248            int top = child.getPaddingTop();
2249            int left = (b.getWidth() - iconSize) / 2;
2250            int right = left + iconSize;
2251            int bottom = top + iconSize;
2252            dragLayerY += top;
2253            // Note: The drag region is used to calculate drag layer offsets, but the
2254            // dragVisualizeOffset in addition to the dragRect (the size) to position the outline.
2255            dragVisualizeOffset = new Point(- halfPadding, halfPadding);
2256            dragRect = new Rect(left, top, right, bottom);
2257        } else if (child instanceof FolderIcon) {
2258            int previewSize = grid.folderIconSizePx;
2259            dragVisualizeOffset = new Point(- halfPadding, halfPadding - child.getPaddingTop());
2260            dragRect = new Rect(0, child.getPaddingTop(), child.getWidth(), previewSize);
2261        }
2262
2263        // Clear the pressed state if necessary
2264        if (child instanceof BubbleTextView) {
2265            BubbleTextView icon = (BubbleTextView) child;
2266            icon.clearPressedBackground();
2267        }
2268
2269        if (child.getParent() instanceof ShortcutAndWidgetContainer) {
2270            mDragSourceInternal = (ShortcutAndWidgetContainer) child.getParent();
2271        }
2272
2273        if (child instanceof BubbleTextView) {
2274            PopupContainerWithArrow popupContainer = PopupContainerWithArrow
2275                    .showForIcon((BubbleTextView) child);
2276            if (popupContainer != null) {
2277                dragOptions.preDragCondition = popupContainer.createPreDragCondition();
2278
2279                mLauncher.getUserEventDispatcher().resetElapsedContainerMillis();
2280            }
2281        }
2282
2283        DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source,
2284                dragObject, dragVisualizeOffset, dragRect, scale, dragOptions);
2285        dv.setIntrinsicIconScaleFactor(source.getIntrinsicIconScaleFactor());
2286        b.recycle();
2287        return dv;
2288    }
2289
2290    private boolean transitionStateShouldAllowDrop() {
2291        return ((!isSwitchingState() || mTransitionProgress > ALLOW_DROP_TRANSITION_PROGRESS) &&
2292                (mState == State.NORMAL || mState == State.SPRING_LOADED));
2293    }
2294
2295    /**
2296     * {@inheritDoc}
2297     */
2298    public boolean acceptDrop(DragObject d) {
2299        // If it's an external drop (e.g. from All Apps), check if it should be accepted
2300        CellLayout dropTargetLayout = mDropToLayout;
2301        if (d.dragSource != this) {
2302            // Don't accept the drop if we're not over a screen at time of drop
2303            if (dropTargetLayout == null) {
2304                return false;
2305            }
2306            if (!transitionStateShouldAllowDrop()) return false;
2307
2308            mDragViewVisualCenter = d.getVisualCenter(mDragViewVisualCenter);
2309
2310            // We want the point to be mapped to the dragTarget.
2311            if (mLauncher.isHotseatLayout(dropTargetLayout)) {
2312                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
2313            } else {
2314                mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter);
2315            }
2316
2317            int spanX = 1;
2318            int spanY = 1;
2319            if (mDragInfo != null) {
2320                final CellLayout.CellInfo dragCellInfo = mDragInfo;
2321                spanX = dragCellInfo.spanX;
2322                spanY = dragCellInfo.spanY;
2323            } else {
2324                spanX = d.dragInfo.spanX;
2325                spanY = d.dragInfo.spanY;
2326            }
2327
2328            int minSpanX = spanX;
2329            int minSpanY = spanY;
2330            if (d.dragInfo instanceof PendingAddWidgetInfo) {
2331                minSpanX = ((PendingAddWidgetInfo) d.dragInfo).minSpanX;
2332                minSpanY = ((PendingAddWidgetInfo) d.dragInfo).minSpanY;
2333            }
2334
2335            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2336                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, dropTargetLayout,
2337                    mTargetCell);
2338            float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0],
2339                    mDragViewVisualCenter[1], mTargetCell);
2340            if (mCreateUserFolderOnDrop && willCreateUserFolder(d.dragInfo,
2341                    dropTargetLayout, mTargetCell, distance, true)) {
2342                return true;
2343            }
2344
2345            if (mAddToExistingFolderOnDrop && willAddToExistingUserFolder(d.dragInfo,
2346                    dropTargetLayout, mTargetCell, distance)) {
2347                return true;
2348            }
2349
2350            int[] resultSpan = new int[2];
2351            mTargetCell = dropTargetLayout.performReorder((int) mDragViewVisualCenter[0],
2352                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY,
2353                    null, mTargetCell, resultSpan, CellLayout.MODE_ACCEPT_DROP);
2354            boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0;
2355
2356            // Don't accept the drop if there's no room for the item
2357            if (!foundCell) {
2358                onNoCellFound(dropTargetLayout);
2359                return false;
2360            }
2361        }
2362
2363        long screenId = getIdForScreen(dropTargetLayout);
2364        if (screenId == EXTRA_EMPTY_SCREEN_ID) {
2365            commitExtraEmptyScreen();
2366        }
2367
2368        return true;
2369    }
2370
2371    boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell,
2372            float distance, boolean considerTimeout) {
2373        if (distance > mMaxDistanceForFolderCreation) return false;
2374        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2375        return willCreateUserFolder(info, dropOverView, considerTimeout);
2376    }
2377
2378    boolean willCreateUserFolder(ItemInfo info, View dropOverView, boolean considerTimeout) {
2379        if (dropOverView != null) {
2380            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams();
2381            if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.cellY)) {
2382                return false;
2383            }
2384        }
2385
2386        boolean hasntMoved = false;
2387        if (mDragInfo != null) {
2388            hasntMoved = dropOverView == mDragInfo.cell;
2389        }
2390
2391        if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) {
2392            return false;
2393        }
2394
2395        boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo);
2396        boolean willBecomeShortcut =
2397                (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
2398                        info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT ||
2399                        info.itemType == LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT);
2400
2401        return (aboveShortcut && willBecomeShortcut);
2402    }
2403
2404    boolean willAddToExistingUserFolder(ItemInfo dragInfo, CellLayout target, int[] targetCell,
2405            float distance) {
2406        if (distance > mMaxDistanceForFolderCreation) return false;
2407        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2408        return willAddToExistingUserFolder(dragInfo, dropOverView);
2409
2410    }
2411    boolean willAddToExistingUserFolder(ItemInfo dragInfo, View dropOverView) {
2412        if (dropOverView != null) {
2413            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams();
2414            if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.cellY)) {
2415                return false;
2416            }
2417        }
2418
2419        if (dropOverView instanceof FolderIcon) {
2420            FolderIcon fi = (FolderIcon) dropOverView;
2421            if (fi.acceptDrop(dragInfo)) {
2422                return true;
2423            }
2424        }
2425        return false;
2426    }
2427
2428    boolean createUserFolderIfNecessary(View newView, long container, CellLayout target,
2429            int[] targetCell, float distance, boolean external, DragView dragView,
2430            Runnable postAnimationRunnable) {
2431        if (distance > mMaxDistanceForFolderCreation) return false;
2432        View v = target.getChildAt(targetCell[0], targetCell[1]);
2433
2434        boolean hasntMoved = false;
2435        if (mDragInfo != null) {
2436            CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell);
2437            hasntMoved = (mDragInfo.cellX == targetCell[0] &&
2438                    mDragInfo.cellY == targetCell[1]) && (cellParent == target);
2439        }
2440
2441        if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false;
2442        mCreateUserFolderOnDrop = false;
2443        final long screenId = getIdForScreen(target);
2444
2445        boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo);
2446        boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo);
2447
2448        if (aboveShortcut && willBecomeShortcut) {
2449            ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag();
2450            ShortcutInfo destInfo = (ShortcutInfo) v.getTag();
2451            // if the drag started here, we need to remove it from the workspace
2452            if (!external) {
2453                getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2454            }
2455
2456            Rect folderLocation = new Rect();
2457            float scale = mLauncher.getDragLayer().getDescendantRectRelativeToSelf(v, folderLocation);
2458            target.removeView(v);
2459
2460            FolderIcon fi =
2461                mLauncher.addFolder(target, container, screenId, targetCell[0], targetCell[1]);
2462            destInfo.cellX = -1;
2463            destInfo.cellY = -1;
2464            sourceInfo.cellX = -1;
2465            sourceInfo.cellY = -1;
2466
2467            // If the dragView is null, we can't animate
2468            boolean animate = dragView != null;
2469            if (animate) {
2470                // In order to keep everything continuous, we hand off the currently rendered
2471                // folder background to the newly created icon. This preserves animation state.
2472                fi.setFolderBackground(mFolderCreateBg);
2473                mFolderCreateBg = new FolderIcon.PreviewBackground();
2474                fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale,
2475                        postAnimationRunnable);
2476            } else {
2477                fi.prepareCreate(v);
2478                fi.addItem(destInfo);
2479                fi.addItem(sourceInfo);
2480            }
2481            return true;
2482        }
2483        return false;
2484    }
2485
2486    boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell,
2487            float distance, DragObject d, boolean external) {
2488        if (distance > mMaxDistanceForFolderCreation) return false;
2489
2490        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2491        if (!mAddToExistingFolderOnDrop) return false;
2492        mAddToExistingFolderOnDrop = false;
2493
2494        if (dropOverView instanceof FolderIcon) {
2495            FolderIcon fi = (FolderIcon) dropOverView;
2496            if (fi.acceptDrop(d.dragInfo)) {
2497                fi.onDrop(d);
2498
2499                // if the drag started here, we need to remove it from the workspace
2500                if (!external) {
2501                    getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2502                }
2503                return true;
2504            }
2505        }
2506        return false;
2507    }
2508
2509    @Override
2510    public void prepareAccessibilityDrop() { }
2511
2512    public void onDrop(final DragObject d) {
2513        mDragViewVisualCenter = d.getVisualCenter(mDragViewVisualCenter);
2514        CellLayout dropTargetLayout = mDropToLayout;
2515
2516        // We want the point to be mapped to the dragTarget.
2517        if (dropTargetLayout != null) {
2518            if (mLauncher.isHotseatLayout(dropTargetLayout)) {
2519                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
2520            } else {
2521                mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter);
2522            }
2523        }
2524
2525        int snapScreen = -1;
2526        boolean resizeOnDrop = false;
2527        if (d.dragSource != this) {
2528            final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0],
2529                    (int) mDragViewVisualCenter[1] };
2530            onDropExternal(touchXY, dropTargetLayout, d);
2531        } else if (mDragInfo != null) {
2532            final View cell = mDragInfo.cell;
2533            boolean droppedOnOriginalCellDuringTransition = false;
2534
2535            if (dropTargetLayout != null && !d.cancelled) {
2536                // Move internally
2537                boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout);
2538                boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout);
2539                long container = hasMovedIntoHotseat ?
2540                        LauncherSettings.Favorites.CONTAINER_HOTSEAT :
2541                        LauncherSettings.Favorites.CONTAINER_DESKTOP;
2542                long screenId = (mTargetCell[0] < 0) ?
2543                        mDragInfo.screenId : getIdForScreen(dropTargetLayout);
2544                int spanX = mDragInfo != null ? mDragInfo.spanX : 1;
2545                int spanY = mDragInfo != null ? mDragInfo.spanY : 1;
2546                // First we find the cell nearest to point at which the item is
2547                // dropped, without any consideration to whether there is an item there.
2548
2549                mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int)
2550                        mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell);
2551                float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0],
2552                        mDragViewVisualCenter[1], mTargetCell);
2553
2554                // If the item being dropped is a shortcut and the nearest drop
2555                // cell also contains a shortcut, then create a folder with the two shortcuts.
2556                if (createUserFolderIfNecessary(cell, container,
2557                        dropTargetLayout, mTargetCell, distance, false, d.dragView, null)) {
2558                    return;
2559                }
2560
2561                if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell,
2562                        distance, d, false)) {
2563                    return;
2564                }
2565
2566                // Aside from the special case where we're dropping a shortcut onto a shortcut,
2567                // we need to find the nearest cell location that is vacant
2568                ItemInfo item = d.dragInfo;
2569                int minSpanX = item.spanX;
2570                int minSpanY = item.spanY;
2571                if (item.minSpanX > 0 && item.minSpanY > 0) {
2572                    minSpanX = item.minSpanX;
2573                    minSpanY = item.minSpanY;
2574                }
2575
2576                droppedOnOriginalCellDuringTransition = mIsSwitchingState
2577                        && item.screenId == screenId && item.container == container
2578                        && item.cellX == mTargetCell[0] && item.cellY == mTargetCell[1];
2579
2580                // When quickly moving an item, a user may accidentally rearrange their
2581                // workspace. So instead we move the icon back safely to its original position.
2582                boolean returnToOriginalCellToPreventShuffling = !isFinishedSwitchingState()
2583                        && !droppedOnOriginalCellDuringTransition && !dropTargetLayout
2584                        .isRegionVacant(mTargetCell[0], mTargetCell[1], spanX, spanY);
2585                int[] resultSpan = new int[2];
2586                if (returnToOriginalCellToPreventShuffling) {
2587                    mTargetCell[0] = mTargetCell[1] = -1;
2588                } else {
2589                    mTargetCell = dropTargetLayout.performReorder((int) mDragViewVisualCenter[0],
2590                            (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, cell,
2591                            mTargetCell, resultSpan, CellLayout.MODE_ON_DROP);
2592                }
2593
2594                boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0;
2595
2596                // if the widget resizes on drop
2597                if (foundCell && (cell instanceof AppWidgetHostView) &&
2598                        (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY)) {
2599                    resizeOnDrop = true;
2600                    item.spanX = resultSpan[0];
2601                    item.spanY = resultSpan[1];
2602                    AppWidgetHostView awhv = (AppWidgetHostView) cell;
2603                    AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, resultSpan[0],
2604                            resultSpan[1]);
2605                }
2606
2607                if (foundCell) {
2608                    if (getScreenIdForPageIndex(mCurrentPage) != screenId && !hasMovedIntoHotseat) {
2609                        snapScreen = getPageIndexForScreenId(screenId);
2610                        snapToPage(snapScreen);
2611                    }
2612
2613                    final ItemInfo info = (ItemInfo) cell.getTag();
2614                    if (hasMovedLayouts) {
2615                        // Reparent the view
2616                        CellLayout parentCell = getParentCellLayoutForView(cell);
2617                        if (parentCell != null) {
2618                            parentCell.removeView(cell);
2619                        } else if (ProviderConfig.IS_DOGFOOD_BUILD) {
2620                            throw new NullPointerException("mDragInfo.cell has null parent");
2621                        }
2622                        addInScreen(cell, container, screenId, mTargetCell[0], mTargetCell[1],
2623                                info.spanX, info.spanY);
2624                    }
2625
2626                    // update the item's position after drop
2627                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
2628                    lp.cellX = lp.tmpCellX = mTargetCell[0];
2629                    lp.cellY = lp.tmpCellY = mTargetCell[1];
2630                    lp.cellHSpan = item.spanX;
2631                    lp.cellVSpan = item.spanY;
2632                    lp.isLockedToGrid = true;
2633
2634                    if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
2635                            cell instanceof LauncherAppWidgetHostView) {
2636                        final CellLayout cellLayout = dropTargetLayout;
2637                        // We post this call so that the widget has a chance to be placed
2638                        // in its final location
2639
2640                        final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell;
2641                        AppWidgetProviderInfo pInfo = hostView.getAppWidgetInfo();
2642                        if (pInfo != null && pInfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE
2643                                && !d.accessibleDrag) {
2644                            mDelayedResizeRunnable = new Runnable() {
2645                                public void run() {
2646                                    if (!isPageInTransition()) {
2647                                        DragLayer dragLayer = mLauncher.getDragLayer();
2648                                        dragLayer.addResizeFrame(hostView, cellLayout);
2649                                    }
2650                                }
2651                            };
2652                        }
2653                    }
2654
2655                    mLauncher.getModelWriter().modifyItemInDatabase(info, container, screenId,
2656                            lp.cellX, lp.cellY, item.spanX, item.spanY);
2657                } else {
2658                    if (!returnToOriginalCellToPreventShuffling) {
2659                        onNoCellFound(dropTargetLayout);
2660                    }
2661
2662                    // If we can't find a drop location, we return the item to its original position
2663                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
2664                    mTargetCell[0] = lp.cellX;
2665                    mTargetCell[1] = lp.cellY;
2666                    CellLayout layout = (CellLayout) cell.getParent().getParent();
2667                    layout.markCellsAsOccupiedForView(cell);
2668                }
2669            }
2670
2671            final CellLayout parent = (CellLayout) cell.getParent().getParent();
2672            // Prepare it to be animated into its new position
2673            // This must be called after the view has been re-parented
2674            final Runnable onCompleteRunnable = new Runnable() {
2675                @Override
2676                public void run() {
2677                    mAnimatingViewIntoPlace = false;
2678                    updateChildrenLayersEnabled(false);
2679                }
2680            };
2681            mAnimatingViewIntoPlace = true;
2682            if (d.dragView.hasDrawn()) {
2683                if (droppedOnOriginalCellDuringTransition) {
2684                    // Animate the item to its original position, while simultaneously exiting
2685                    // spring-loaded mode so the page meets the icon where it was picked up.
2686                    mLauncher.getDragController().animateDragViewToOriginalPosition(
2687                            mDelayedResizeRunnable, cell,
2688                            mStateTransitionAnimation.mSpringLoadedTransitionTime);
2689                    mLauncher.exitSpringLoadedDragMode();
2690                    mLauncher.getDropTargetBar().onDragEnd();
2691                    parent.onDropChild(cell);
2692                    return;
2693                }
2694                final ItemInfo info = (ItemInfo) cell.getTag();
2695                boolean isWidget = info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET
2696                        || info.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
2697                if (isWidget) {
2698                    int animationType = resizeOnDrop ? ANIMATE_INTO_POSITION_AND_RESIZE :
2699                            ANIMATE_INTO_POSITION_AND_DISAPPEAR;
2700                    animateWidgetDrop(info, parent, d.dragView,
2701                            onCompleteRunnable, animationType, cell, false);
2702                } else {
2703                    int duration = snapScreen < 0 ? -1 : ADJACENT_SCREEN_DROP_DURATION;
2704                    mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration,
2705                            onCompleteRunnable, this);
2706                }
2707            } else {
2708                d.deferDragViewCleanupPostAnimation = false;
2709                cell.setVisibility(VISIBLE);
2710            }
2711            parent.onDropChild(cell);
2712        }
2713        if (d.stateAnnouncer != null) {
2714            d.stateAnnouncer.completeAction(R.string.item_moved);
2715        }
2716    }
2717
2718    public void onNoCellFound(View dropTargetLayout) {
2719        if (mLauncher.isHotseatLayout(dropTargetLayout)) {
2720            Hotseat hotseat = mLauncher.getHotseat();
2721            boolean droppedOnAllAppsIcon = !FeatureFlags.NO_ALL_APPS_ICON
2722                    && mTargetCell != null && !mLauncher.getDeviceProfile().inv.isAllAppsButtonRank(
2723                    hotseat.getOrderInHotseat(mTargetCell[0], mTargetCell[1]));
2724            if (!droppedOnAllAppsIcon) {
2725                // Only show message when hotseat is full and drop target was not AllApps button
2726                showOutOfSpaceMessage(true);
2727            }
2728        } else {
2729            showOutOfSpaceMessage(false);
2730        }
2731    }
2732
2733    private void showOutOfSpaceMessage(boolean isHotseatLayout) {
2734        int strId = (isHotseatLayout ? R.string.hotseat_out_of_space : R.string.out_of_space);
2735        Toast.makeText(mLauncher, mLauncher.getString(strId), Toast.LENGTH_SHORT).show();
2736    }
2737
2738    /**
2739     * Computes the area relative to dragLayer which is used to display a page.
2740     */
2741    public void getPageAreaRelativeToDragLayer(Rect outArea) {
2742        CellLayout child = (CellLayout) getChildAt(getNextPage());
2743        if (child == null) {
2744            return;
2745        }
2746        ShortcutAndWidgetContainer boundingLayout = child.getShortcutsAndWidgets();
2747
2748        // Use the absolute left instead of the child left, as we want the visible area
2749        // irrespective of the visible child. Since the view can only scroll horizontally, the
2750        // top position is not affected.
2751        mTempXY[0] = getViewportOffsetX() + getPaddingLeft() + boundingLayout.getLeft();
2752        mTempXY[1] = child.getTop() + boundingLayout.getTop();
2753
2754        float scale = mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempXY);
2755        outArea.set(mTempXY[0], mTempXY[1],
2756                (int) (mTempXY[0] + scale * boundingLayout.getMeasuredWidth()),
2757                (int) (mTempXY[1] + scale * boundingLayout.getMeasuredHeight()));
2758    }
2759
2760    @Override
2761    public void onDragEnter(DragObject d) {
2762        if (ENFORCE_DRAG_EVENT_ORDER) {
2763            enforceDragParity("onDragEnter", 1, 1);
2764        }
2765
2766        mCreateUserFolderOnDrop = false;
2767        mAddToExistingFolderOnDrop = false;
2768
2769        mDropToLayout = null;
2770        mDragViewVisualCenter = d.getVisualCenter(mDragViewVisualCenter);
2771        setDropLayoutForDragObject(d, mDragViewVisualCenter[0], mDragViewVisualCenter[1]);
2772    }
2773
2774    @Override
2775    public void onDragExit(DragObject d) {
2776        if (ENFORCE_DRAG_EVENT_ORDER) {
2777            enforceDragParity("onDragExit", -1, 0);
2778        }
2779
2780        // Here we store the final page that will be dropped to, if the workspace in fact
2781        // receives the drop
2782        mDropToLayout = mDragTargetLayout;
2783        if (mDragMode == DRAG_MODE_CREATE_FOLDER) {
2784            mCreateUserFolderOnDrop = true;
2785        } else if (mDragMode == DRAG_MODE_ADD_TO_FOLDER) {
2786            mAddToExistingFolderOnDrop = true;
2787        }
2788
2789        // Reset the previous drag target
2790        setCurrentDropLayout(null);
2791        setCurrentDragOverlappingLayout(null);
2792
2793        mSpringLoadedDragController.cancel();
2794    }
2795
2796    private void enforceDragParity(String event, int update, int expectedValue) {
2797        enforceDragParity(this, event, update, expectedValue);
2798        for (int i = 0; i < getChildCount(); i++) {
2799            enforceDragParity(getChildAt(i), event, update, expectedValue);
2800        }
2801    }
2802
2803    private void enforceDragParity(View v, String event, int update, int expectedValue) {
2804        Object tag = v.getTag(R.id.drag_event_parity);
2805        int value = tag == null ? 0 : (Integer) tag;
2806        value += update;
2807        v.setTag(R.id.drag_event_parity, value);
2808
2809        if (value != expectedValue) {
2810            Log.e(TAG, event + ": Drag contract violated: " + value);
2811        }
2812    }
2813
2814    void setCurrentDropLayout(CellLayout layout) {
2815        if (mDragTargetLayout != null) {
2816            mDragTargetLayout.revertTempState();
2817            mDragTargetLayout.onDragExit();
2818        }
2819        mDragTargetLayout = layout;
2820        if (mDragTargetLayout != null) {
2821            mDragTargetLayout.onDragEnter();
2822        }
2823        cleanupReorder(true);
2824        cleanupFolderCreation();
2825        setCurrentDropOverCell(-1, -1);
2826    }
2827
2828    void setCurrentDragOverlappingLayout(CellLayout layout) {
2829        if (mDragOverlappingLayout != null) {
2830            mDragOverlappingLayout.setIsDragOverlapping(false);
2831        }
2832        mDragOverlappingLayout = layout;
2833        if (mDragOverlappingLayout != null) {
2834            mDragOverlappingLayout.setIsDragOverlapping(true);
2835        }
2836        // Invalidating the scrim will also force this CellLayout
2837        // to be invalidated so that it is highlighted if necessary.
2838        mLauncher.getDragLayer().invalidateScrim();
2839    }
2840
2841    public CellLayout getCurrentDragOverlappingLayout() {
2842        return mDragOverlappingLayout;
2843    }
2844
2845    void setCurrentDropOverCell(int x, int y) {
2846        if (x != mDragOverX || y != mDragOverY) {
2847            mDragOverX = x;
2848            mDragOverY = y;
2849            setDragMode(DRAG_MODE_NONE);
2850        }
2851    }
2852
2853    void setDragMode(int dragMode) {
2854        if (dragMode != mDragMode) {
2855            if (dragMode == DRAG_MODE_NONE) {
2856                cleanupAddToFolder();
2857                // We don't want to cancel the re-order alarm every time the target cell changes
2858                // as this feels to slow / unresponsive.
2859                cleanupReorder(false);
2860                cleanupFolderCreation();
2861            } else if (dragMode == DRAG_MODE_ADD_TO_FOLDER) {
2862                cleanupReorder(true);
2863                cleanupFolderCreation();
2864            } else if (dragMode == DRAG_MODE_CREATE_FOLDER) {
2865                cleanupAddToFolder();
2866                cleanupReorder(true);
2867            } else if (dragMode == DRAG_MODE_REORDER) {
2868                cleanupAddToFolder();
2869                cleanupFolderCreation();
2870            }
2871            mDragMode = dragMode;
2872        }
2873    }
2874
2875    private void cleanupFolderCreation() {
2876        if (mFolderCreateBg != null) {
2877            mFolderCreateBg.animateToRest();
2878        }
2879        mFolderCreationAlarm.setOnAlarmListener(null);
2880        mFolderCreationAlarm.cancelAlarm();
2881    }
2882
2883    private void cleanupAddToFolder() {
2884        if (mDragOverFolderIcon != null) {
2885            mDragOverFolderIcon.onDragExit();
2886            mDragOverFolderIcon = null;
2887        }
2888    }
2889
2890    private void cleanupReorder(boolean cancelAlarm) {
2891        // Any pending reorders are canceled
2892        if (cancelAlarm) {
2893            mReorderAlarm.cancelAlarm();
2894        }
2895        mLastReorderX = -1;
2896        mLastReorderY = -1;
2897    }
2898
2899   /*
2900    *
2901    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2902    * coordinate space. The argument xy is modified with the return result.
2903    */
2904   void mapPointFromSelfToChild(View v, float[] xy) {
2905       xy[0] = xy[0] - v.getLeft();
2906       xy[1] = xy[1] - v.getTop();
2907   }
2908
2909   boolean isPointInSelfOverHotseat(int x, int y) {
2910       mTempXY[0] = x;
2911       mTempXY[1] = y;
2912       mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempXY, true);
2913       View hotseat = mLauncher.getHotseat();
2914       return mTempXY[0] >= hotseat.getLeft() &&
2915               mTempXY[0] <= hotseat.getRight() &&
2916               mTempXY[1] >= hotseat.getTop() &&
2917               mTempXY[1] <= hotseat.getBottom();
2918   }
2919
2920   void mapPointFromSelfToHotseatLayout(Hotseat hotseat, float[] xy) {
2921       mTempXY[0] = (int) xy[0];
2922       mTempXY[1] = (int) xy[1];
2923       mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempXY, true);
2924       mLauncher.getDragLayer().mapCoordInSelfToDescendant(hotseat.getLayout(), mTempXY);
2925
2926       xy[0] = mTempXY[0];
2927       xy[1] = mTempXY[1];
2928   }
2929
2930   /*
2931    *
2932    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
2933    * the parent View's coordinate space. The argument xy is modified with the return result.
2934    *
2935    */
2936   void mapPointFromChildToSelf(View v, float[] xy) {
2937       xy[0] += v.getLeft();
2938       xy[1] += v.getTop();
2939   }
2940
2941    private boolean isDragWidget(DragObject d) {
2942        return (d.dragInfo instanceof LauncherAppWidgetInfo ||
2943                d.dragInfo instanceof PendingAddWidgetInfo);
2944    }
2945
2946    public void onDragOver(DragObject d) {
2947        // Skip drag over events while we are dragging over side pages
2948        if (!transitionStateShouldAllowDrop()) return;
2949
2950        ItemInfo item = d.dragInfo;
2951        if (item == null) {
2952            if (ProviderConfig.IS_DOGFOOD_BUILD) {
2953                throw new NullPointerException("DragObject has null info");
2954            }
2955            return;
2956        }
2957
2958        // Ensure that we have proper spans for the item that we are dropping
2959        if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found");
2960        mDragViewVisualCenter = d.getVisualCenter(mDragViewVisualCenter);
2961
2962        final View child = (mDragInfo == null) ? null : mDragInfo.cell;
2963        if (setDropLayoutForDragObject(d, mDragViewVisualCenter[0], mDragViewVisualCenter[1])) {
2964            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
2965                mSpringLoadedDragController.cancel();
2966            } else {
2967                mSpringLoadedDragController.setAlarm(mDragTargetLayout);
2968            }
2969        }
2970
2971        // Handle the drag over
2972        if (mDragTargetLayout != null) {
2973            // We want the point to be mapped to the dragTarget.
2974            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
2975                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
2976            } else {
2977                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter);
2978            }
2979
2980            int minSpanX = item.spanX;
2981            int minSpanY = item.spanY;
2982            if (item.minSpanX > 0 && item.minSpanY > 0) {
2983                minSpanX = item.minSpanX;
2984                minSpanY = item.minSpanY;
2985            }
2986
2987            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2988                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY,
2989                    mDragTargetLayout, mTargetCell);
2990            int reorderX = mTargetCell[0];
2991            int reorderY = mTargetCell[1];
2992
2993            setCurrentDropOverCell(mTargetCell[0], mTargetCell[1]);
2994
2995            float targetCellDistance = mDragTargetLayout.getDistanceFromCell(
2996                    mDragViewVisualCenter[0], mDragViewVisualCenter[1], mTargetCell);
2997
2998            manageFolderFeedback(mDragTargetLayout, mTargetCell, targetCellDistance, d);
2999
3000            boolean nearestDropOccupied = mDragTargetLayout.isNearestDropLocationOccupied((int)
3001                    mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], item.spanX,
3002                    item.spanY, child, mTargetCell);
3003
3004            if (!nearestDropOccupied) {
3005                mDragTargetLayout.visualizeDropLocation(child, mOutlineProvider,
3006                        mTargetCell[0], mTargetCell[1], item.spanX, item.spanY, false, d);
3007            } else if ((mDragMode == DRAG_MODE_NONE || mDragMode == DRAG_MODE_REORDER)
3008                    && !mReorderAlarm.alarmPending() && (mLastReorderX != reorderX ||
3009                    mLastReorderY != reorderY)) {
3010
3011                int[] resultSpan = new int[2];
3012                mDragTargetLayout.performReorder((int) mDragViewVisualCenter[0],
3013                        (int) mDragViewVisualCenter[1], minSpanX, minSpanY, item.spanX, item.spanY,
3014                        child, mTargetCell, resultSpan, CellLayout.MODE_SHOW_REORDER_HINT);
3015
3016                // Otherwise, if we aren't adding to or creating a folder and there's no pending
3017                // reorder, then we schedule a reorder
3018                ReorderAlarmListener listener = new ReorderAlarmListener(mDragViewVisualCenter,
3019                        minSpanX, minSpanY, item.spanX, item.spanY, d, child);
3020                mReorderAlarm.setOnAlarmListener(listener);
3021                mReorderAlarm.setAlarm(REORDER_TIMEOUT);
3022            }
3023
3024            if (mDragMode == DRAG_MODE_CREATE_FOLDER || mDragMode == DRAG_MODE_ADD_TO_FOLDER ||
3025                    !nearestDropOccupied) {
3026                if (mDragTargetLayout != null) {
3027                    mDragTargetLayout.revertTempState();
3028                }
3029            }
3030        }
3031    }
3032
3033    /**
3034     * Updates {@link #mDragTargetLayout} and {@link #mDragOverlappingLayout}
3035     * based on the DragObject's position.
3036     *
3037     * The layout will be:
3038     * - The Hotseat if the drag object is over it
3039     * - A side page if we are in spring-loaded mode and the drag object is over it
3040     * - The current page otherwise
3041     *
3042     * @return whether the layout is different from the current {@link #mDragTargetLayout}.
3043     */
3044    private boolean setDropLayoutForDragObject(DragObject d, float centerX, float centerY) {
3045        CellLayout layout = null;
3046        // Test to see if we are over the hotseat first
3047        if (mLauncher.getHotseat() != null && !isDragWidget(d)) {
3048            if (isPointInSelfOverHotseat(d.x, d.y)) {
3049                layout = mLauncher.getHotseat().getLayout();
3050            }
3051        }
3052
3053        int nextPage = getNextPage();
3054        if (layout == null && !isPageInTransition()) {
3055            // Check if the item is dragged over left page
3056            mTempTouchCoordinates[0] = Math.min(centerX, d.x);
3057            mTempTouchCoordinates[1] = d.y;
3058            layout = verifyInsidePage(nextPage + (mIsRtl ? 1 : -1), mTempTouchCoordinates);
3059        }
3060
3061        if (layout == null && !isPageInTransition()) {
3062            // Check if the item is dragged over right page
3063            mTempTouchCoordinates[0] = Math.max(centerX, d.x);
3064            mTempTouchCoordinates[1] = d.y;
3065            layout = verifyInsidePage(nextPage + (mIsRtl ? -1 : 1), mTempTouchCoordinates);
3066        }
3067
3068        // Always pick the current page.
3069        if (layout == null && nextPage >= numCustomPages() && nextPage < getPageCount()) {
3070            layout = (CellLayout) getChildAt(nextPage);
3071        }
3072        if (layout != mDragTargetLayout) {
3073            setCurrentDropLayout(layout);
3074            setCurrentDragOverlappingLayout(layout);
3075            return true;
3076        }
3077        return false;
3078    }
3079
3080    /**
3081     * Returns the child CellLayout if the point is inside the page coordinates, null otherwise.
3082     */
3083    private CellLayout verifyInsidePage(int pageNo, float[] touchXy)  {
3084        if (pageNo >= numCustomPages() && pageNo < getPageCount()) {
3085            CellLayout cl = (CellLayout) getChildAt(pageNo);
3086            mapPointFromSelfToChild(cl, touchXy);
3087            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
3088                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
3089                // This point is inside the cell layout
3090                return cl;
3091            }
3092        }
3093        return null;
3094    }
3095
3096    private void manageFolderFeedback(CellLayout targetLayout,
3097            int[] targetCell, float distance, DragObject dragObject) {
3098        if (distance > mMaxDistanceForFolderCreation) return;
3099
3100        final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0], mTargetCell[1]);
3101        ItemInfo info = dragObject.dragInfo;
3102        boolean userFolderPending = willCreateUserFolder(info, dragOverView, false);
3103        if (mDragMode == DRAG_MODE_NONE && userFolderPending &&
3104                !mFolderCreationAlarm.alarmPending()) {
3105
3106            FolderCreationAlarmListener listener = new
3107                    FolderCreationAlarmListener(targetLayout, targetCell[0], targetCell[1]);
3108
3109            if (!dragObject.accessibleDrag) {
3110                mFolderCreationAlarm.setOnAlarmListener(listener);
3111                mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT);
3112            } else {
3113                listener.onAlarm(mFolderCreationAlarm);
3114            }
3115
3116            if (dragObject.stateAnnouncer != null) {
3117                dragObject.stateAnnouncer.announce(WorkspaceAccessibilityHelper
3118                        .getDescriptionForDropOver(dragOverView, getContext()));
3119            }
3120            return;
3121        }
3122
3123        boolean willAddToFolder = willAddToExistingUserFolder(info, dragOverView);
3124        if (willAddToFolder && mDragMode == DRAG_MODE_NONE) {
3125            mDragOverFolderIcon = ((FolderIcon) dragOverView);
3126            mDragOverFolderIcon.onDragEnter(info);
3127            if (targetLayout != null) {
3128                targetLayout.clearDragOutlines();
3129            }
3130            setDragMode(DRAG_MODE_ADD_TO_FOLDER);
3131
3132            if (dragObject.stateAnnouncer != null) {
3133                dragObject.stateAnnouncer.announce(WorkspaceAccessibilityHelper
3134                        .getDescriptionForDropOver(dragOverView, getContext()));
3135            }
3136            return;
3137        }
3138
3139        if (mDragMode == DRAG_MODE_ADD_TO_FOLDER && !willAddToFolder) {
3140            setDragMode(DRAG_MODE_NONE);
3141        }
3142        if (mDragMode == DRAG_MODE_CREATE_FOLDER && !userFolderPending) {
3143            setDragMode(DRAG_MODE_NONE);
3144        }
3145    }
3146
3147    class FolderCreationAlarmListener implements OnAlarmListener {
3148        CellLayout layout;
3149        int cellX;
3150        int cellY;
3151
3152        FolderIcon.PreviewBackground bg = new FolderIcon.PreviewBackground();
3153
3154        public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) {
3155            this.layout = layout;
3156            this.cellX = cellX;
3157            this.cellY = cellY;
3158
3159            DeviceProfile grid = mLauncher.getDeviceProfile();
3160            BubbleTextView cell = (BubbleTextView) layout.getChildAt(cellX, cellY);
3161
3162            bg.setup(getResources().getDisplayMetrics(), grid, null,
3163                    cell.getMeasuredWidth(), cell.getPaddingTop());
3164
3165            // The full preview background should appear behind the icon
3166            bg.isClipping = false;
3167        }
3168
3169        public void onAlarm(Alarm alarm) {
3170            mFolderCreateBg = bg;
3171            mFolderCreateBg.animateToAccept(layout, cellX, cellY);
3172            layout.clearDragOutlines();
3173            setDragMode(DRAG_MODE_CREATE_FOLDER);
3174        }
3175    }
3176
3177    class ReorderAlarmListener implements OnAlarmListener {
3178        float[] dragViewCenter;
3179        int minSpanX, minSpanY, spanX, spanY;
3180        DragObject dragObject;
3181        View child;
3182
3183        public ReorderAlarmListener(float[] dragViewCenter, int minSpanX, int minSpanY, int spanX,
3184                int spanY, DragObject dragObject, View child) {
3185            this.dragViewCenter = dragViewCenter;
3186            this.minSpanX = minSpanX;
3187            this.minSpanY = minSpanY;
3188            this.spanX = spanX;
3189            this.spanY = spanY;
3190            this.child = child;
3191            this.dragObject = dragObject;
3192        }
3193
3194        public void onAlarm(Alarm alarm) {
3195            int[] resultSpan = new int[2];
3196            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
3197                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, mDragTargetLayout,
3198                    mTargetCell);
3199            mLastReorderX = mTargetCell[0];
3200            mLastReorderY = mTargetCell[1];
3201
3202            mTargetCell = mDragTargetLayout.performReorder((int) mDragViewVisualCenter[0],
3203                (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY,
3204                child, mTargetCell, resultSpan, CellLayout.MODE_DRAG_OVER);
3205
3206            if (mTargetCell[0] < 0 || mTargetCell[1] < 0) {
3207                mDragTargetLayout.revertTempState();
3208            } else {
3209                setDragMode(DRAG_MODE_REORDER);
3210            }
3211
3212            boolean resize = resultSpan[0] != spanX || resultSpan[1] != spanY;
3213            mDragTargetLayout.visualizeDropLocation(child, mOutlineProvider,
3214                mTargetCell[0], mTargetCell[1], resultSpan[0], resultSpan[1], resize, dragObject);
3215        }
3216    }
3217
3218    @Override
3219    public void getHitRectRelativeToDragLayer(Rect outRect) {
3220        // We want the workspace to have the whole area of the display (it will find the correct
3221        // cell layout to drop to in the existing drag/drop logic.
3222        mLauncher.getDragLayer().getDescendantRectRelativeToSelf(this, outRect);
3223    }
3224
3225    /**
3226     * Drop an item that didn't originate on one of the workspace screens.
3227     * It may have come from Launcher (e.g. from all apps or customize), or it may have
3228     * come from another app altogether.
3229     *
3230     * NOTE: This can also be called when we are outside of a drag event, when we want
3231     * to add an item to one of the workspace screens.
3232     */
3233    private void onDropExternal(final int[] touchXY, final CellLayout cellLayout, DragObject d) {
3234        final Runnable exitSpringLoadedRunnable = new Runnable() {
3235            @Override
3236            public void run() {
3237                mLauncher.exitSpringLoadedDragModeDelayed(true,
3238                        Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, null);
3239            }
3240        };
3241
3242        if (d.dragInfo instanceof PendingAddShortcutInfo) {
3243            ShortcutInfo si = ((PendingAddShortcutInfo) d.dragInfo)
3244                    .activityInfo.createShortcutInfo();
3245            if (si != null) {
3246                d.dragInfo = si;
3247            }
3248        }
3249
3250        ItemInfo info = d.dragInfo;
3251        int spanX = info.spanX;
3252        int spanY = info.spanY;
3253        if (mDragInfo != null) {
3254            spanX = mDragInfo.spanX;
3255            spanY = mDragInfo.spanY;
3256        }
3257
3258        final long container = mLauncher.isHotseatLayout(cellLayout) ?
3259                LauncherSettings.Favorites.CONTAINER_HOTSEAT :
3260                    LauncherSettings.Favorites.CONTAINER_DESKTOP;
3261        final long screenId = getIdForScreen(cellLayout);
3262        if (!mLauncher.isHotseatLayout(cellLayout)
3263                && screenId != getScreenIdForPageIndex(mCurrentPage)
3264                && mState != State.SPRING_LOADED) {
3265            snapToScreenId(screenId, null);
3266        }
3267
3268        if (info instanceof PendingAddItemInfo) {
3269            final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) info;
3270
3271            boolean findNearestVacantCell = true;
3272            if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
3273                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
3274                        cellLayout, mTargetCell);
3275                float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0],
3276                        mDragViewVisualCenter[1], mTargetCell);
3277                if (willCreateUserFolder(d.dragInfo, cellLayout, mTargetCell, distance, true)
3278                        || willAddToExistingUserFolder(
3279                                d.dragInfo, cellLayout, mTargetCell, distance)) {
3280                    findNearestVacantCell = false;
3281                }
3282            }
3283
3284            final ItemInfo item = d.dragInfo;
3285            boolean updateWidgetSize = false;
3286            if (findNearestVacantCell) {
3287                int minSpanX = item.spanX;
3288                int minSpanY = item.spanY;
3289                if (item.minSpanX > 0 && item.minSpanY > 0) {
3290                    minSpanX = item.minSpanX;
3291                    minSpanY = item.minSpanY;
3292                }
3293                int[] resultSpan = new int[2];
3294                mTargetCell = cellLayout.performReorder((int) mDragViewVisualCenter[0],
3295                        (int) mDragViewVisualCenter[1], minSpanX, minSpanY, info.spanX, info.spanY,
3296                        null, mTargetCell, resultSpan, CellLayout.MODE_ON_DROP_EXTERNAL);
3297
3298                if (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY) {
3299                    updateWidgetSize = true;
3300                }
3301                item.spanX = resultSpan[0];
3302                item.spanY = resultSpan[1];
3303            }
3304
3305            Runnable onAnimationCompleteRunnable = new Runnable() {
3306                @Override
3307                public void run() {
3308                    // Normally removeExtraEmptyScreen is called in Workspace#onDragEnd, but when
3309                    // adding an item that may not be dropped right away (due to a config activity)
3310                    // we defer the removal until the activity returns.
3311                    deferRemoveExtraEmptyScreen();
3312
3313                    // When dragging and dropping from customization tray, we deal with creating
3314                    // widgets/shortcuts/folders in a slightly different way
3315                    mLauncher.addPendingItem(pendingInfo, container, screenId, mTargetCell,
3316                            item.spanX, item.spanY);
3317                }
3318            };
3319            boolean isWidget = pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET
3320                    || pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
3321
3322            AppWidgetHostView finalView = isWidget ?
3323                    ((PendingAddWidgetInfo) pendingInfo).boundWidget : null;
3324
3325            if (finalView != null && updateWidgetSize) {
3326                AppWidgetResizeFrame.updateWidgetSizeRanges(finalView, mLauncher, item.spanX,
3327                        item.spanY);
3328            }
3329
3330            int animationStyle = ANIMATE_INTO_POSITION_AND_DISAPPEAR;
3331            if (isWidget && ((PendingAddWidgetInfo) pendingInfo).info != null &&
3332                    ((PendingAddWidgetInfo) pendingInfo).getHandler().needsConfigure()) {
3333                animationStyle = ANIMATE_INTO_POSITION_AND_REMAIN;
3334            }
3335            animateWidgetDrop(info, cellLayout, d.dragView, onAnimationCompleteRunnable,
3336                    animationStyle, finalView, true);
3337        } else {
3338            // This is for other drag/drop cases, like dragging from All Apps
3339            View view = null;
3340
3341            switch (info.itemType) {
3342            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
3343            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3344            case LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT:
3345                if (info.container == NO_ID && info instanceof AppInfo) {
3346                    // Came from all apps -- make a copy
3347                    info = ((AppInfo) info).makeShortcut();
3348                    d.dragInfo = info;
3349                }
3350                view = mLauncher.createShortcut(cellLayout, (ShortcutInfo) info);
3351                break;
3352            case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
3353                view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout,
3354                        (FolderInfo) info);
3355                break;
3356            default:
3357                throw new IllegalStateException("Unknown item type: " + info.itemType);
3358            }
3359
3360            // First we find the cell nearest to point at which the item is
3361            // dropped, without any consideration to whether there is an item there.
3362            if (touchXY != null) {
3363                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
3364                        cellLayout, mTargetCell);
3365                float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0],
3366                        mDragViewVisualCenter[1], mTargetCell);
3367                d.postAnimationRunnable = exitSpringLoadedRunnable;
3368                if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, distance,
3369                        true, d.dragView, d.postAnimationRunnable)) {
3370                    return;
3371                }
3372                if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, distance, d,
3373                        true)) {
3374                    return;
3375                }
3376            }
3377
3378            if (touchXY != null) {
3379                // when dragging and dropping, just find the closest free spot
3380                mTargetCell = cellLayout.performReorder((int) mDragViewVisualCenter[0],
3381                        (int) mDragViewVisualCenter[1], 1, 1, 1, 1,
3382                        null, mTargetCell, null, CellLayout.MODE_ON_DROP_EXTERNAL);
3383            } else {
3384                cellLayout.findCellForSpan(mTargetCell, 1, 1);
3385            }
3386            // Add the item to DB before adding to screen ensures that the container and other
3387            // values of the info is properly updated.
3388            mLauncher.getModelWriter().addOrMoveItemInDatabase(info, container, screenId,
3389                    mTargetCell[0], mTargetCell[1]);
3390
3391            addInScreen(view, container, screenId, mTargetCell[0], mTargetCell[1],
3392                    info.spanX, info.spanY);
3393            cellLayout.onDropChild(view);
3394            cellLayout.getShortcutsAndWidgets().measureChild(view);
3395
3396            if (d.dragView != null) {
3397                // We wrap the animation call in the temporary set and reset of the current
3398                // cellLayout to its final transform -- this means we animate the drag view to
3399                // the correct final location.
3400                setFinalTransitionTransform(cellLayout);
3401                mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view,
3402                        exitSpringLoadedRunnable, this);
3403                resetTransitionTransform(cellLayout);
3404            }
3405        }
3406    }
3407
3408    public Bitmap createWidgetBitmap(ItemInfo widgetInfo, View layout) {
3409        int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(widgetInfo, false, true);
3410        int visibility = layout.getVisibility();
3411        layout.setVisibility(VISIBLE);
3412
3413        int width = MeasureSpec.makeMeasureSpec(unScaledSize[0], MeasureSpec.EXACTLY);
3414        int height = MeasureSpec.makeMeasureSpec(unScaledSize[1], MeasureSpec.EXACTLY);
3415        Bitmap b = Bitmap.createBitmap(unScaledSize[0], unScaledSize[1],
3416                Bitmap.Config.ARGB_8888);
3417        mCanvas.setBitmap(b);
3418
3419        layout.measure(width, height);
3420        layout.layout(0, 0, unScaledSize[0], unScaledSize[1]);
3421        layout.draw(mCanvas);
3422        mCanvas.setBitmap(null);
3423        layout.setVisibility(visibility);
3424        return b;
3425    }
3426
3427    private void getFinalPositionForDropAnimation(int[] loc, float[] scaleXY,
3428            DragView dragView, CellLayout layout, ItemInfo info, int[] targetCell, boolean scale) {
3429        // Now we animate the dragView, (ie. the widget or shortcut preview) into its final
3430        // location and size on the home screen.
3431        int spanX = info.spanX;
3432        int spanY = info.spanY;
3433
3434        Rect r = estimateItemPosition(layout, targetCell[0], targetCell[1], spanX, spanY);
3435        if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET) {
3436            DeviceProfile profile = mLauncher.getDeviceProfile();
3437            Utilities.shrinkRect(r, profile.appWidgetScale.x, profile.appWidgetScale.y);
3438        }
3439        loc[0] = r.left;
3440        loc[1] = r.top;
3441
3442        setFinalTransitionTransform(layout);
3443        float cellLayoutScale =
3444                mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(layout, loc, true);
3445        resetTransitionTransform(layout);
3446
3447        if (scale) {
3448            float dragViewScaleX = (1.0f * r.width()) / dragView.getMeasuredWidth();
3449            float dragViewScaleY = (1.0f * r.height()) / dragView.getMeasuredHeight();
3450
3451            // The animation will scale the dragView about its center, so we need to center about
3452            // the final location.
3453            loc[0] -= (dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2
3454                    - Math.ceil(layout.getUnusedHorizontalSpace() / 2f);
3455            loc[1] -= (dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2;
3456            scaleXY[0] = dragViewScaleX * cellLayoutScale;
3457            scaleXY[1] = dragViewScaleY * cellLayoutScale;
3458        } else {
3459            // Since we are not cross-fading the dragView, align the drag view to the
3460            // final cell position.
3461            float dragScale = dragView.getInitialScale() * cellLayoutScale;
3462            loc[0] += (dragScale - 1) * dragView.getWidth() / 2;
3463            loc[1] += (dragScale - 1) * dragView.getHeight() / 2;
3464            scaleXY[0] = scaleXY[1] = dragScale;
3465
3466            // If a dragRegion was provided, offset the final position accordingly.
3467            Rect dragRegion = dragView.getDragRegion();
3468            if (dragRegion != null) {
3469                loc[0] += cellLayoutScale * dragRegion.left;
3470                loc[1] += cellLayoutScale * dragRegion.top;
3471            }
3472        }
3473    }
3474
3475    public void animateWidgetDrop(ItemInfo info, CellLayout cellLayout, final DragView dragView,
3476            final Runnable onCompleteRunnable, int animationType, final View finalView,
3477            boolean external) {
3478        Rect from = new Rect();
3479        mLauncher.getDragLayer().getViewRectRelativeToSelf(dragView, from);
3480
3481        int[] finalPos = new int[2];
3482        float scaleXY[] = new float[2];
3483        boolean scalePreview = !(info instanceof PendingAddShortcutInfo);
3484        getFinalPositionForDropAnimation(finalPos, scaleXY, dragView, cellLayout, info, mTargetCell,
3485                scalePreview);
3486
3487        Resources res = mLauncher.getResources();
3488        final int duration = res.getInteger(R.integer.config_dropAnimMaxDuration) - 200;
3489
3490        boolean isWidget = info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET ||
3491                info.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
3492        if ((animationType == ANIMATE_INTO_POSITION_AND_RESIZE || external) && finalView != null) {
3493            Bitmap crossFadeBitmap = createWidgetBitmap(info, finalView);
3494            dragView.setCrossFadeBitmap(crossFadeBitmap);
3495            dragView.crossFade((int) (duration * 0.8f));
3496        } else if (isWidget && external) {
3497            scaleXY[0] = scaleXY[1] = Math.min(scaleXY[0],  scaleXY[1]);
3498        }
3499
3500        DragLayer dragLayer = mLauncher.getDragLayer();
3501        if (animationType == CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION) {
3502            mLauncher.getDragLayer().animateViewIntoPosition(dragView, finalPos, 0f, 0.1f, 0.1f,
3503                    DragLayer.ANIMATION_END_DISAPPEAR, onCompleteRunnable, duration);
3504        } else {
3505            int endStyle;
3506            if (animationType == ANIMATE_INTO_POSITION_AND_REMAIN) {
3507                endStyle = DragLayer.ANIMATION_END_REMAIN_VISIBLE;
3508            } else {
3509                endStyle = DragLayer.ANIMATION_END_DISAPPEAR;
3510            }
3511
3512            Runnable onComplete = new Runnable() {
3513                @Override
3514                public void run() {
3515                    if (finalView != null) {
3516                        finalView.setVisibility(VISIBLE);
3517                    }
3518                    if (onCompleteRunnable != null) {
3519                        onCompleteRunnable.run();
3520                    }
3521                }
3522            };
3523            dragLayer.animateViewIntoPosition(dragView, from.left, from.top, finalPos[0],
3524                    finalPos[1], 1, 1, 1, scaleXY[0], scaleXY[1], onComplete, endStyle,
3525                    duration, this);
3526        }
3527    }
3528
3529    public void setFinalTransitionTransform(CellLayout layout) {
3530        if (isSwitchingState()) {
3531            mCurrentScale = getScaleX();
3532            setScaleX(mStateTransitionAnimation.getFinalScale());
3533            setScaleY(mStateTransitionAnimation.getFinalScale());
3534        }
3535    }
3536    public void resetTransitionTransform(CellLayout layout) {
3537        if (isSwitchingState()) {
3538            setScaleX(mCurrentScale);
3539            setScaleY(mCurrentScale);
3540        }
3541    }
3542
3543    public WorkspaceStateTransitionAnimation getStateTransitionAnimation() {
3544        return mStateTransitionAnimation;
3545    }
3546
3547    /**
3548     * Return the current CellInfo describing our current drag; this method exists
3549     * so that Launcher can sync this object with the correct info when the activity is created/
3550     * destroyed
3551     *
3552     */
3553    public CellLayout.CellInfo getDragInfo() {
3554        return mDragInfo;
3555    }
3556
3557    public int getCurrentPageOffsetFromCustomContent() {
3558        return getNextPage() - numCustomPages();
3559    }
3560
3561    /**
3562     * Calculate the nearest cell where the given object would be dropped.
3563     *
3564     * pixelX and pixelY should be in the coordinate system of layout
3565     */
3566    @Thunk int[] findNearestArea(int pixelX, int pixelY,
3567            int spanX, int spanY, CellLayout layout, int[] recycle) {
3568        return layout.findNearestArea(
3569                pixelX, pixelY, spanX, spanY, recycle);
3570    }
3571
3572    void setup(DragController dragController) {
3573        mSpringLoadedDragController = new SpringLoadedDragController(mLauncher);
3574        mDragController = dragController;
3575
3576        // hardware layers on children are enabled on startup, but should be disabled until
3577        // needed
3578        updateChildrenLayersEnabled(false);
3579    }
3580
3581    /**
3582     * Called at the end of a drag which originated on the workspace.
3583     */
3584    public void onDropCompleted(final View target, final DragObject d,
3585            final boolean isFlingToDelete, final boolean success) {
3586        if (mDeferDropAfterUninstall) {
3587            final CellLayout.CellInfo dragInfo = mDragInfo;
3588            mDeferredAction = new Runnable() {
3589                public void run() {
3590                    mDragInfo = dragInfo; // Restore the drag info that was cleared in onDragEnd()
3591                    onDropCompleted(target, d, isFlingToDelete, success);
3592                    mDeferredAction = null;
3593                }
3594            };
3595            return;
3596        }
3597
3598        boolean beingCalledAfterUninstall = mDeferredAction != null;
3599
3600        if (success && !(beingCalledAfterUninstall && !mUninstallSuccessful)) {
3601            if (target != this && mDragInfo != null) {
3602                removeWorkspaceItem(mDragInfo.cell);
3603            }
3604        } else if (mDragInfo != null) {
3605            final CellLayout cellLayout = mLauncher.getCellLayout(
3606                    mDragInfo.container, mDragInfo.screenId);
3607            if (cellLayout != null) {
3608                cellLayout.onDropChild(mDragInfo.cell);
3609            } else if (ProviderConfig.IS_DOGFOOD_BUILD) {
3610                throw new RuntimeException("Invalid state: cellLayout == null in "
3611                        + "Workspace#onDropCompleted. Please file a bug. ");
3612            };
3613        }
3614        if ((d.cancelled || (beingCalledAfterUninstall && !mUninstallSuccessful))
3615                && mDragInfo.cell != null) {
3616            mDragInfo.cell.setVisibility(VISIBLE);
3617        }
3618        mDragInfo = null;
3619
3620        if (!isFlingToDelete) {
3621            // Fling to delete already exits spring loaded mode after the animation finishes.
3622            mLauncher.exitSpringLoadedDragModeDelayed(success,
3623                    Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, mDelayedResizeRunnable);
3624            mDelayedResizeRunnable = null;
3625        }
3626    }
3627
3628    /**
3629     * For opposite operation. See {@link #addInScreen}.
3630     */
3631    public void removeWorkspaceItem(View v) {
3632        CellLayout parentCell = getParentCellLayoutForView(v);
3633        if (parentCell != null) {
3634            parentCell.removeView(v);
3635        } else if (ProviderConfig.IS_DOGFOOD_BUILD) {
3636            // When an app is uninstalled using the drop target, we wait until resume to remove
3637            // the icon. We also remove all the corresponding items from the workspace at
3638            // {@link Launcher#bindComponentsRemoved}. That call can come before or after
3639            // {@link Launcher#mOnResumeCallbacks} depending on how busy the worker thread is.
3640            Log.e(TAG, "mDragInfo.cell has null parent");
3641        }
3642        if (v instanceof DropTarget) {
3643            mDragController.removeDropTarget((DropTarget) v);
3644        }
3645    }
3646
3647    /**
3648     * Removes all folder listeners
3649     */
3650    public void removeFolderListeners() {
3651        mapOverItems(false, new ItemOperator() {
3652            @Override
3653            public boolean evaluate(ItemInfo info, View view) {
3654                if (view instanceof FolderIcon) {
3655                    ((FolderIcon) view).removeListeners();
3656                }
3657                return false;
3658            }
3659        });
3660    }
3661
3662    @Override
3663    public void deferCompleteDropAfterUninstallActivity() {
3664        mDeferDropAfterUninstall = true;
3665    }
3666
3667    /// maybe move this into a smaller part
3668    @Override
3669    public void onDragObjectRemoved(boolean success) {
3670        mDeferDropAfterUninstall = false;
3671        mUninstallSuccessful = success;
3672        if (mDeferredAction != null) {
3673            mDeferredAction.run();
3674        }
3675    }
3676
3677    @Override
3678    public float getIntrinsicIconScaleFactor() {
3679        return 1f;
3680    }
3681
3682    @Override
3683    public boolean supportsAppInfoDropTarget() {
3684        return true;
3685    }
3686
3687    @Override
3688    public boolean supportsDeleteDropTarget() {
3689        return true;
3690    }
3691
3692    public boolean isDropEnabled() {
3693        return true;
3694    }
3695
3696    @Override
3697    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
3698        // We don't dispatch restoreInstanceState to our children using this code path.
3699        // Some pages will be restored immediately as their items are bound immediately, and
3700        // others we will need to wait until after their items are bound.
3701        mSavedStates = container;
3702    }
3703
3704    public void restoreInstanceStateForChild(int child) {
3705        if (mSavedStates != null) {
3706            mRestoredPages.add(child);
3707            CellLayout cl = (CellLayout) getChildAt(child);
3708            if (cl != null) {
3709                cl.restoreInstanceState(mSavedStates);
3710            }
3711        }
3712    }
3713
3714    public void restoreInstanceStateForRemainingPages() {
3715        int count = getChildCount();
3716        for (int i = 0; i < count; i++) {
3717            if (!mRestoredPages.contains(i)) {
3718                restoreInstanceStateForChild(i);
3719            }
3720        }
3721        mRestoredPages.clear();
3722        mSavedStates = null;
3723    }
3724
3725    @Override
3726    public void scrollLeft() {
3727        if (!workspaceInModalState() && !mIsSwitchingState) {
3728            super.scrollLeft();
3729        }
3730        Folder openFolder = Folder.getOpen(mLauncher);
3731        if (openFolder != null) {
3732            openFolder.completeDragExit();
3733        }
3734    }
3735
3736    @Override
3737    public void scrollRight() {
3738        if (!workspaceInModalState() && !mIsSwitchingState) {
3739            super.scrollRight();
3740        }
3741        Folder openFolder = Folder.getOpen(mLauncher);
3742        if (openFolder != null) {
3743            openFolder.completeDragExit();
3744        }
3745    }
3746
3747    /**
3748     * Returns a specific CellLayout
3749     */
3750    CellLayout getParentCellLayoutForView(View v) {
3751        ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts();
3752        for (CellLayout layout : layouts) {
3753            if (layout.getShortcutsAndWidgets().indexOfChild(v) > -1) {
3754                return layout;
3755            }
3756        }
3757        return null;
3758    }
3759
3760    /**
3761     * Returns a list of all the CellLayouts in the workspace.
3762     */
3763    ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() {
3764        ArrayList<CellLayout> layouts = new ArrayList<CellLayout>();
3765        int screenCount = getChildCount();
3766        for (int screen = 0; screen < screenCount; screen++) {
3767            layouts.add(((CellLayout) getChildAt(screen)));
3768        }
3769        if (mLauncher.getHotseat() != null) {
3770            layouts.add(mLauncher.getHotseat().getLayout());
3771        }
3772        return layouts;
3773    }
3774
3775    /**
3776     * We should only use this to search for specific children.  Do not use this method to modify
3777     * ShortcutsAndWidgetsContainer directly. Includes ShortcutAndWidgetContainers from
3778     * the hotseat and workspace pages
3779     */
3780    ArrayList<ShortcutAndWidgetContainer> getAllShortcutAndWidgetContainers() {
3781        ArrayList<ShortcutAndWidgetContainer> childrenLayouts = new ArrayList<>();
3782        int screenCount = getChildCount();
3783        for (int screen = 0; screen < screenCount; screen++) {
3784            childrenLayouts.add(((CellLayout) getChildAt(screen)).getShortcutsAndWidgets());
3785        }
3786        if (mLauncher.getHotseat() != null) {
3787            childrenLayouts.add(mLauncher.getHotseat().getLayout().getShortcutsAndWidgets());
3788        }
3789        return childrenLayouts;
3790    }
3791
3792    public View getHomescreenIconByItemId(final long id) {
3793        return getFirstMatch(new ItemOperator() {
3794
3795            @Override
3796            public boolean evaluate(ItemInfo info, View v) {
3797                return info != null && info.id == id;
3798            }
3799        });
3800    }
3801
3802    public View getViewForTag(final Object tag) {
3803        return getFirstMatch(new ItemOperator() {
3804
3805            @Override
3806            public boolean evaluate(ItemInfo info, View v) {
3807                return info == tag;
3808            }
3809        });
3810    }
3811
3812    public LauncherAppWidgetHostView getWidgetForAppWidgetId(final int appWidgetId) {
3813        return (LauncherAppWidgetHostView) getFirstMatch(new ItemOperator() {
3814
3815            @Override
3816            public boolean evaluate(ItemInfo info, View v) {
3817                return (info instanceof LauncherAppWidgetInfo) &&
3818                        ((LauncherAppWidgetInfo) info).appWidgetId == appWidgetId;
3819            }
3820        });
3821    }
3822
3823    public View getFirstMatch(final ItemOperator operator) {
3824        final View[] value = new View[1];
3825        mapOverItems(MAP_NO_RECURSE, new ItemOperator() {
3826            @Override
3827            public boolean evaluate(ItemInfo info, View v) {
3828                if (operator.evaluate(info, v)) {
3829                    value[0] = v;
3830                    return true;
3831                }
3832                return false;
3833            }
3834        });
3835        return value[0];
3836    }
3837
3838    void clearDropTargets() {
3839        mapOverItems(MAP_NO_RECURSE, new ItemOperator() {
3840            @Override
3841            public boolean evaluate(ItemInfo info, View v) {
3842                if (v instanceof DropTarget) {
3843                    mDragController.removeDropTarget((DropTarget) v);
3844                }
3845                // not done, process all the shortcuts
3846                return false;
3847            }
3848        });
3849    }
3850
3851    /**
3852     * Removes items that match the {@param matcher}. When applications are removed
3853     * as a part of an update, this is called to ensure that other widgets and application
3854     * shortcuts are not removed.
3855     */
3856    public void removeItemsByMatcher(final ItemInfoMatcher matcher) {
3857        ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
3858        for (final CellLayout layoutParent: cellLayouts) {
3859            final ViewGroup layout = layoutParent.getShortcutsAndWidgets();
3860
3861            LongArrayMap<View> idToViewMap = new LongArrayMap<>();
3862            ArrayList<ItemInfo> items = new ArrayList<>();
3863            for (int j = 0; j < layout.getChildCount(); j++) {
3864                final View view = layout.getChildAt(j);
3865                if (view.getTag() instanceof ItemInfo) {
3866                    ItemInfo item = (ItemInfo) view.getTag();
3867                    items.add(item);
3868                    idToViewMap.put(item.id, view);
3869                }
3870            }
3871
3872            for (ItemInfo itemToRemove : matcher.filterItemInfos(items)) {
3873                View child = idToViewMap.get(itemToRemove.id);
3874
3875                if (child != null) {
3876                    // Note: We can not remove the view directly from CellLayoutChildren as this
3877                    // does not re-mark the spaces as unoccupied.
3878                    layoutParent.removeViewInLayout(child);
3879                    if (child instanceof DropTarget) {
3880                        mDragController.removeDropTarget((DropTarget) child);
3881                    }
3882                } else if (itemToRemove.container >= 0) {
3883                    // The item may belong to a folder.
3884                    View parent = idToViewMap.get(itemToRemove.container);
3885                    if (parent != null) {
3886                        ((FolderInfo) parent.getTag()).remove((ShortcutInfo) itemToRemove, false);
3887                    }
3888                }
3889            }
3890        }
3891
3892        // Strip all the empty screens
3893        stripEmptyScreens();
3894    }
3895
3896    public interface ItemOperator {
3897        /**
3898         * Process the next itemInfo, possibly with side-effect on the next item.
3899         *
3900         * @param info info for the shortcut
3901         * @param view view for the shortcut
3902         * @return true if done, false to continue the map
3903         */
3904        public boolean evaluate(ItemInfo info, View view);
3905    }
3906
3907    /**
3908     * Map the operator over the shortcuts and widgets, return the first-non-null value.
3909     *
3910     * @param recurse true: iterate over folder children. false: op get the folders themselves.
3911     * @param op the operator to map over the shortcuts
3912     */
3913    void mapOverItems(boolean recurse, ItemOperator op) {
3914        ArrayList<ShortcutAndWidgetContainer> containers = getAllShortcutAndWidgetContainers();
3915        final int containerCount = containers.size();
3916        for (int containerIdx = 0; containerIdx < containerCount; containerIdx++) {
3917            ShortcutAndWidgetContainer container = containers.get(containerIdx);
3918            // map over all the shortcuts on the workspace
3919            final int itemCount = container.getChildCount();
3920            for (int itemIdx = 0; itemIdx < itemCount; itemIdx++) {
3921                View item = container.getChildAt(itemIdx);
3922                ItemInfo info = (ItemInfo) item.getTag();
3923                if (recurse && info instanceof FolderInfo && item instanceof FolderIcon) {
3924                    FolderIcon folder = (FolderIcon) item;
3925                    ArrayList<View> folderChildren = folder.getFolder().getItemsInReadingOrder();
3926                    // map over all the children in the folder
3927                    final int childCount = folderChildren.size();
3928                    for (int childIdx = 0; childIdx < childCount; childIdx++) {
3929                        View child = folderChildren.get(childIdx);
3930                        info = (ItemInfo) child.getTag();
3931                        if (op.evaluate(info, child)) {
3932                            return;
3933                        }
3934                    }
3935                } else {
3936                    if (op.evaluate(info, item)) {
3937                        return;
3938                    }
3939                }
3940            }
3941        }
3942    }
3943
3944    void updateShortcuts(ArrayList<ShortcutInfo> shortcuts) {
3945        int total  = shortcuts.size();
3946        final HashSet<ShortcutInfo> updates = new HashSet<ShortcutInfo>(total);
3947        final HashSet<Long> folderIds = new HashSet<>();
3948
3949        for (int i = 0; i < total; i++) {
3950            ShortcutInfo s = shortcuts.get(i);
3951            updates.add(s);
3952            folderIds.add(s.container);
3953        }
3954
3955        mapOverItems(MAP_RECURSE, new ItemOperator() {
3956            @Override
3957            public boolean evaluate(ItemInfo info, View v) {
3958                if (info instanceof ShortcutInfo && v instanceof BubbleTextView &&
3959                        updates.contains(info)) {
3960                    ShortcutInfo si = (ShortcutInfo) info;
3961                    BubbleTextView shortcut = (BubbleTextView) v;
3962                    Drawable oldIcon = getTextViewIcon(shortcut);
3963                    boolean oldPromiseState = (oldIcon instanceof PreloadIconDrawable)
3964                            && ((PreloadIconDrawable) oldIcon).hasNotCompleted();
3965                    shortcut.applyFromShortcutInfo(si, si.isPromise() != oldPromiseState);
3966                }
3967                // process all the shortcuts
3968                return false;
3969            }
3970        });
3971
3972        // Update folder icons
3973        mapOverItems(MAP_NO_RECURSE, new ItemOperator() {
3974            @Override
3975            public boolean evaluate(ItemInfo info, View v) {
3976                if (info instanceof FolderInfo && folderIds.contains(info.id)) {
3977                    ((FolderInfo) info).itemsChanged(false);
3978                }
3979                // process all the shortcuts
3980                return false;
3981            }
3982        });
3983    }
3984
3985    public void updateIconBadges(final Set<PackageUserKey> updatedBadges) {
3986        final PackageUserKey packageUserKey = new PackageUserKey(null, null);
3987        mapOverItems(MAP_RECURSE, new ItemOperator() {
3988            @Override
3989            public boolean evaluate(ItemInfo info, View v) {
3990                if (info instanceof ShortcutInfo && v instanceof BubbleTextView) {
3991                    packageUserKey.updateFromItemInfo(info);
3992                    if (updatedBadges.contains(packageUserKey)) {
3993                        ((BubbleTextView) v).applyBadgeState(info);
3994                    }
3995                }
3996                // process all the shortcuts
3997                return false;
3998            }
3999        });
4000    }
4001
4002    public void removeAbandonedPromise(String packageName, UserHandle user) {
4003        HashSet<String> packages = new HashSet<>(1);
4004        packages.add(packageName);
4005        ItemInfoMatcher matcher = ItemInfoMatcher.ofPackages(packages, user);
4006        mLauncher.getModelWriter().deleteItemsFromDatabase(matcher);
4007        removeItemsByMatcher(matcher);
4008    }
4009
4010    public void updateRestoreItems(final HashSet<ItemInfo> updates) {
4011        mapOverItems(MAP_RECURSE, new ItemOperator() {
4012            @Override
4013            public boolean evaluate(ItemInfo info, View v) {
4014                if (info instanceof ShortcutInfo && v instanceof BubbleTextView
4015                        && updates.contains(info)) {
4016                    ((BubbleTextView) v).applyPromiseState(false /* promiseStateChanged */);
4017                } else if (v instanceof PendingAppWidgetHostView
4018                        && info instanceof LauncherAppWidgetInfo
4019                        && updates.contains(info)) {
4020                    ((PendingAppWidgetHostView) v).applyState();
4021                }
4022                // process all the shortcuts
4023                return false;
4024            }
4025        });
4026    }
4027
4028    public void widgetsRestored(final ArrayList<LauncherAppWidgetInfo> changedInfo) {
4029        if (!changedInfo.isEmpty()) {
4030            DeferredWidgetRefresh widgetRefresh = new DeferredWidgetRefresh(changedInfo,
4031                    mLauncher.getAppWidgetHost());
4032
4033            LauncherAppWidgetInfo item = changedInfo.get(0);
4034            final AppWidgetProviderInfo widgetInfo;
4035            if (item.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_ID_NOT_VALID)) {
4036                widgetInfo = AppWidgetManagerCompat
4037                        .getInstance(mLauncher).findProvider(item.providerName, item.user);
4038            } else {
4039                widgetInfo = AppWidgetManagerCompat.getInstance(mLauncher)
4040                        .getAppWidgetInfo(item.appWidgetId);
4041            }
4042
4043            if (widgetInfo != null) {
4044                // Re-inflate the widgets which have changed status
4045                widgetRefresh.run();
4046            } else {
4047                // widgetRefresh will automatically run when the packages are updated.
4048                // For now just update the progress bars
4049                mapOverItems(MAP_NO_RECURSE, new ItemOperator() {
4050                    @Override
4051                    public boolean evaluate(ItemInfo info, View view) {
4052                        if (view instanceof PendingAppWidgetHostView
4053                                && changedInfo.contains(info)) {
4054                            ((LauncherAppWidgetInfo) info).installProgress = 100;
4055                            ((PendingAppWidgetHostView) view).applyState();
4056                        }
4057                        // process all the shortcuts
4058                        return false;
4059                    }
4060                });
4061            }
4062        }
4063    }
4064
4065    private void moveToScreen(int page, boolean animate) {
4066        if (!workspaceInModalState()) {
4067            if (animate) {
4068                snapToPage(page);
4069            } else {
4070                setCurrentPage(page);
4071            }
4072        }
4073        View child = getChildAt(page);
4074        if (child != null) {
4075            child.requestFocus();
4076        }
4077    }
4078
4079    void moveToDefaultScreen(boolean animate) {
4080        moveToScreen(getDefaultPage(), animate);
4081    }
4082
4083    void moveToCustomContentScreen(boolean animate) {
4084        if (hasCustomContent()) {
4085            int ccIndex = getPageIndexForScreenId(CUSTOM_CONTENT_SCREEN_ID);
4086            if (animate) {
4087                snapToPage(ccIndex);
4088            } else {
4089                setCurrentPage(ccIndex);
4090            }
4091            View child = getChildAt(ccIndex);
4092            if (child != null) {
4093                child.requestFocus();
4094            }
4095         }
4096        exitWidgetResizeMode();
4097    }
4098
4099    @Override
4100    protected String getPageIndicatorDescription() {
4101        return getResources().getString(R.string.all_apps_button_label);
4102    }
4103
4104    @Override
4105    protected String getCurrentPageDescription() {
4106        if (hasCustomContent() && getNextPage() == 0) {
4107            return mCustomContentDescription;
4108        }
4109        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
4110        return getPageDescription(page);
4111    }
4112
4113    private String getPageDescription(int page) {
4114        int delta = numCustomPages();
4115        int nScreens = getChildCount() - delta;
4116        int extraScreenId = mScreenOrder.indexOf(EXTRA_EMPTY_SCREEN_ID);
4117        if (extraScreenId >= 0 && nScreens > 1) {
4118            if (page == extraScreenId) {
4119                return getContext().getString(R.string.workspace_new_page);
4120            }
4121            nScreens--;
4122        }
4123        if (nScreens == 0) {
4124            // When the workspace is not loaded, we do not know how many screen will be bound.
4125            return getContext().getString(R.string.all_apps_home_button_label);
4126        }
4127        return getContext().getString(R.string.workspace_scroll_format,
4128                page + 1 - delta, nScreens);
4129    }
4130
4131    @Override
4132    public void fillInLogContainerData(View v, ItemInfo info, Target target, Target targetParent) {
4133        target.gridX = info.cellX;
4134        target.gridY = info.cellY;
4135        target.pageIndex = getCurrentPage();
4136        targetParent.containerType = ContainerType.WORKSPACE;
4137        if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
4138            target.rank = info.rank;
4139            targetParent.containerType = ContainerType.HOTSEAT;
4140        } else if (info.container >= 0) {
4141            targetParent.containerType = ContainerType.FOLDER;
4142        }
4143    }
4144
4145    @Override
4146    public boolean enableFreeScroll() {
4147        if (getState() == State.OVERVIEW) {
4148            return super.enableFreeScroll();
4149        } else {
4150            Log.w(TAG, "enableFreeScroll called but not in overview: state=" + getState());
4151            return false;
4152        }
4153    }
4154
4155    /**
4156     * Used as a workaround to ensure that the AppWidgetService receives the
4157     * PACKAGE_ADDED broadcast before updating widgets.
4158     */
4159    private class DeferredWidgetRefresh implements Runnable {
4160        private final ArrayList<LauncherAppWidgetInfo> mInfos;
4161        private final LauncherAppWidgetHost mHost;
4162        private final Handler mHandler;
4163
4164        private boolean mRefreshPending;
4165
4166        public DeferredWidgetRefresh(ArrayList<LauncherAppWidgetInfo> infos,
4167                LauncherAppWidgetHost host) {
4168            mInfos = infos;
4169            mHost = host;
4170            mHandler = new Handler();
4171            mRefreshPending = true;
4172
4173            mHost.addProviderChangeListener(this);
4174            // Force refresh after 10 seconds, if we don't get the provider changed event.
4175            // This could happen when the provider is no longer available in the app.
4176            mHandler.postDelayed(this, 10000);
4177        }
4178
4179        @Override
4180        public void run() {
4181            mHost.removeProviderChangeListener(this);
4182            mHandler.removeCallbacks(this);
4183
4184            if (!mRefreshPending) {
4185                return;
4186            }
4187
4188            mRefreshPending = false;
4189
4190            mapOverItems(MAP_NO_RECURSE, new ItemOperator() {
4191                @Override
4192                public boolean evaluate(ItemInfo info, View view) {
4193                    if (view instanceof PendingAppWidgetHostView && mInfos.contains(info)) {
4194                        mLauncher.removeItem(view, info, false /* deleteFromDb */);
4195                        mLauncher.bindAppWidget((LauncherAppWidgetInfo) info);
4196                    }
4197                    // process all the shortcuts
4198                    return false;
4199                }
4200            });
4201        }
4202    }
4203
4204    public interface OnStateChangeListener {
4205
4206        /**
4207         * Called when the workspace state is changing.
4208         * @param toState final state
4209         * @param targetAnim animation which will be played during the transition or null.
4210         */
4211        void prepareStateChange(State toState, AnimatorSet targetAnim);
4212    }
4213
4214    public static final boolean isQsbContainerPage(int pageNo) {
4215        return pageNo == 0;
4216    }
4217
4218    private class StateTransitionListener extends AnimatorListenerAdapter
4219            implements AnimatorUpdateListener {
4220        @Override
4221        public void onAnimationUpdate(ValueAnimator anim) {
4222            mTransitionProgress = anim.getAnimatedFraction();
4223        }
4224
4225        @Override
4226        public void onAnimationStart(Animator animation) {
4227            if (mState == State.SPRING_LOADED) {
4228                // Show the page indicator at the same time as the rest of the transition.
4229                showPageIndicatorAtCurrentScroll();
4230            }
4231            mTransitionProgress = 0;
4232        }
4233
4234        @Override
4235        public void onAnimationEnd(Animator animation) {
4236            onEndStateTransition();
4237        }
4238    }
4239}
4240