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