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