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