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