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