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