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