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