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