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