Workspace.java revision 803a4bec0fe4f291b5e131f0a4fcb6ca8ecd2ec3
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    static final boolean MAP_NO_RECURSE = false;
102    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 getFreeScrollPageRange(int[] range) {
2090        getOverviewModePages(range);
2091    }
2092
2093    private void getOverviewModePages(int[] range) {
2094        int start = numCustomPages();
2095        int end = getChildCount() - 1;
2096
2097        range[0] = Math.max(0, Math.min(start, getChildCount() - 1));
2098        range[1] = Math.max(0,  end);
2099    }
2100
2101    protected void onStartReordering() {
2102        super.onStartReordering();
2103        showOutlines();
2104        // Reordering handles its own animations, disable the automatic ones.
2105        disableLayoutTransitions();
2106    }
2107
2108    protected void onEndReordering() {
2109        super.onEndReordering();
2110
2111        if (mLauncher.isWorkspaceLoading()) {
2112            // Invalid and dangerous operation if workspace is loading
2113            return;
2114        }
2115
2116        hideOutlines();
2117        mScreenOrder.clear();
2118        int count = getChildCount();
2119        for (int i = 0; i < count; i++) {
2120            CellLayout cl = ((CellLayout) getChildAt(i));
2121            mScreenOrder.add(getIdForScreen(cl));
2122        }
2123
2124        mLauncher.getModel().updateWorkspaceScreenOrder(mLauncher, mScreenOrder);
2125
2126        // Re-enable auto layout transitions for page deletion.
2127        enableLayoutTransitions();
2128    }
2129
2130    public boolean isInOverviewMode() {
2131        return mState == State.OVERVIEW;
2132    }
2133
2134    public boolean enterOverviewMode() {
2135        if (mTouchState != TOUCH_STATE_REST) {
2136            return false;
2137        }
2138        enableOverviewMode(true, -1, true);
2139        return true;
2140    }
2141
2142    public void exitOverviewMode(boolean animated) {
2143        exitOverviewMode(-1, animated);
2144    }
2145
2146    public void exitOverviewMode(int snapPage, boolean animated) {
2147        enableOverviewMode(false, snapPage, animated);
2148    }
2149
2150    private void enableOverviewMode(boolean enable, int snapPage, boolean animated) {
2151        State finalState = Workspace.State.OVERVIEW;
2152        if (!enable) {
2153            finalState = Workspace.State.NORMAL;
2154        }
2155
2156        Animator workspaceAnim = getChangeStateAnimation(finalState, animated, 0, snapPage);
2157        if (workspaceAnim != null) {
2158            onTransitionPrepare();
2159            workspaceAnim.addListener(new AnimatorListenerAdapter() {
2160                @Override
2161                public void onAnimationEnd(Animator arg0) {
2162                    onTransitionEnd();
2163                }
2164            });
2165            workspaceAnim.start();
2166        }
2167    }
2168
2169    int getOverviewModeTranslationY() {
2170        LauncherAppState app = LauncherAppState.getInstance();
2171        DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
2172        Rect overviewBar = grid.getOverviewModeButtonBarRect();
2173
2174        int availableHeight = getViewportHeight();
2175        int scaledHeight = (int) (mOverviewModeShrinkFactor * getNormalChildHeight());
2176        int offsetFromTopEdge = (availableHeight - scaledHeight) / 2;
2177        int offsetToCenterInOverview = (availableHeight - mInsets.top - overviewBar.height()
2178                - scaledHeight) / 2;
2179
2180        return -offsetFromTopEdge + mInsets.top + offsetToCenterInOverview;
2181    }
2182
2183    boolean shouldVoiceButtonProxyBeVisible() {
2184        if (isOnOrMovingToCustomContent()) {
2185            return false;
2186        }
2187        if (mState != State.NORMAL) {
2188            return false;
2189        }
2190        return true;
2191    }
2192
2193    public void updateInteractionForState() {
2194        if (mState != State.NORMAL) {
2195            mLauncher.onInteractionBegin();
2196        } else {
2197            mLauncher.onInteractionEnd();
2198        }
2199    }
2200
2201    private void setState(State state) {
2202        mState = state;
2203        updateInteractionForState();
2204        updateAccessibilityFlags();
2205    }
2206
2207    State getState() {
2208        return mState;
2209    }
2210
2211    private void updateAccessibilityFlags() {
2212        int accessible = mState == State.NORMAL ?
2213                ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES :
2214                ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
2215        setImportantForAccessibility(accessible);
2216    }
2217
2218    Animator getChangeStateAnimation(final State state, boolean animated, int delay, int snapPage) {
2219        if (mState == state) {
2220            return null;
2221        }
2222
2223        // Initialize animation arrays for the first time if necessary
2224        initAnimationArrays();
2225
2226        AnimatorSet anim = animated ? LauncherAnimUtils.createAnimatorSet() : null;
2227
2228        final State oldState = mState;
2229        final boolean oldStateIsNormal = (oldState == State.NORMAL);
2230        final boolean oldStateIsSpringLoaded = (oldState == State.SPRING_LOADED);
2231        final boolean oldStateIsSmall = (oldState == State.SMALL);
2232        final boolean oldStateIsOverview = (oldState == State.OVERVIEW);
2233        setState(state);
2234        final boolean stateIsNormal = (state == State.NORMAL);
2235        final boolean stateIsSpringLoaded = (state == State.SPRING_LOADED);
2236        final boolean stateIsSmall = (state == State.SMALL);
2237        final boolean stateIsOverview = (state == State.OVERVIEW);
2238        float finalBackgroundAlpha = (stateIsSpringLoaded || stateIsOverview) ? 1.0f : 0f;
2239        float finalHotseatAndPageIndicatorAlpha = (stateIsOverview || stateIsSmall) ? 0f : 1f;
2240        float finalOverviewPanelAlpha = stateIsOverview ? 1f : 0f;
2241        float finalSearchBarAlpha = !stateIsNormal ? 0f : 1f;
2242        float finalWorkspaceTranslationY = stateIsOverview ? getOverviewModeTranslationY() : 0;
2243
2244        boolean workspaceToAllApps = (oldStateIsNormal && stateIsSmall);
2245        boolean allAppsToWorkspace = (oldStateIsSmall && stateIsNormal);
2246        boolean workspaceToOverview = (oldStateIsNormal && stateIsOverview);
2247        boolean overviewToWorkspace = (oldStateIsOverview && stateIsNormal);
2248
2249        mNewScale = 1.0f;
2250
2251        if (oldStateIsOverview) {
2252            disableFreeScroll();
2253        } else if (stateIsOverview) {
2254            enableFreeScroll();
2255        }
2256
2257        if (state != State.NORMAL) {
2258            if (stateIsSpringLoaded) {
2259                mNewScale = mSpringLoadedShrinkFactor;
2260            } else if (stateIsOverview) {
2261                mNewScale = mOverviewModeShrinkFactor;
2262            } else if (stateIsSmall){
2263                mNewScale = mOverviewModeShrinkFactor - 0.3f;
2264            }
2265            if (workspaceToAllApps) {
2266                updateChildrenLayersEnabled(false);
2267            }
2268        }
2269
2270        final int duration;
2271        if (workspaceToAllApps) {
2272            duration = getResources().getInteger(R.integer.config_workspaceUnshrinkTime);
2273        } else if (workspaceToOverview || overviewToWorkspace) {
2274            duration = getResources().getInteger(R.integer.config_overviewTransitionTime);
2275        } else {
2276            duration = getResources().getInteger(R.integer.config_appsCustomizeWorkspaceShrinkTime);
2277        }
2278
2279        if (snapPage == -1) {
2280            snapPage = getPageNearestToCenterOfScreen();
2281        }
2282        snapToPage(snapPage, duration, mZoomInInterpolator);
2283
2284        for (int i = 0; i < getChildCount(); i++) {
2285            final CellLayout cl = (CellLayout) getChildAt(i);
2286            boolean isCurrentPage = (i == snapPage);
2287            float initialAlpha = cl.getShortcutsAndWidgets().getAlpha();
2288            float finalAlpha;
2289            if (stateIsSmall) {
2290                finalAlpha = 0f;
2291            } else if (stateIsNormal && mWorkspaceFadeInAdjacentScreens) {
2292                finalAlpha = (i == snapPage || i < numCustomPages()) ? 1f : 0f;
2293            } else {
2294                finalAlpha = 1f;
2295            }
2296
2297            // If we are animating to/from the small state, then hide the side pages and fade the
2298            // current page in
2299            if (!mIsSwitchingState) {
2300                if (workspaceToAllApps || allAppsToWorkspace) {
2301                    if (allAppsToWorkspace && isCurrentPage) {
2302                        initialAlpha = 0f;
2303                    } else if (!isCurrentPage) {
2304                        initialAlpha = finalAlpha = 0f;
2305                    }
2306                    cl.setShortcutAndWidgetAlpha(initialAlpha);
2307                }
2308            }
2309
2310            mOldAlphas[i] = initialAlpha;
2311            mNewAlphas[i] = finalAlpha;
2312            if (animated) {
2313                mOldBackgroundAlphas[i] = cl.getBackgroundAlpha();
2314                mNewBackgroundAlphas[i] = finalBackgroundAlpha;
2315            } else {
2316                cl.setBackgroundAlpha(finalBackgroundAlpha);
2317                cl.setShortcutAndWidgetAlpha(finalAlpha);
2318            }
2319        }
2320
2321        final View searchBar = mLauncher.getQsbBar();
2322        final View overviewPanel = mLauncher.getOverviewPanel();
2323        final View hotseat = mLauncher.getHotseat();
2324        final View pageIndicator = getPageIndicator();
2325        if (animated) {
2326            anim.setDuration(duration);
2327            LauncherViewPropertyAnimator scale = new LauncherViewPropertyAnimator(this);
2328            scale.scaleX(mNewScale)
2329                .scaleY(mNewScale)
2330                .translationY(finalWorkspaceTranslationY)
2331                .setInterpolator(mZoomInInterpolator);
2332            anim.play(scale);
2333            for (int index = 0; index < getChildCount(); index++) {
2334                final int i = index;
2335                final CellLayout cl = (CellLayout) getChildAt(i);
2336                float currentAlpha = cl.getShortcutsAndWidgets().getAlpha();
2337                if (mOldAlphas[i] == 0 && mNewAlphas[i] == 0) {
2338                    cl.setBackgroundAlpha(mNewBackgroundAlphas[i]);
2339                    cl.setShortcutAndWidgetAlpha(mNewAlphas[i]);
2340                } else {
2341                    if (mOldAlphas[i] != mNewAlphas[i] || currentAlpha != mNewAlphas[i]) {
2342                        LauncherViewPropertyAnimator alphaAnim =
2343                            new LauncherViewPropertyAnimator(cl.getShortcutsAndWidgets());
2344                        alphaAnim.alpha(mNewAlphas[i])
2345                            .setInterpolator(mZoomInInterpolator);
2346                        anim.play(alphaAnim);
2347                    }
2348                    if (mOldBackgroundAlphas[i] != 0 ||
2349                        mNewBackgroundAlphas[i] != 0) {
2350                        ValueAnimator bgAnim =
2351                                LauncherAnimUtils.ofFloat(cl, 0f, 1f);
2352                        bgAnim.setInterpolator(mZoomInInterpolator);
2353                        bgAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
2354                                public void onAnimationUpdate(float a, float b) {
2355                                    cl.setBackgroundAlpha(
2356                                            a * mOldBackgroundAlphas[i] +
2357                                            b * mNewBackgroundAlphas[i]);
2358                                }
2359                            });
2360                        anim.play(bgAnim);
2361                    }
2362                }
2363            }
2364            Animator pageIndicatorAlpha = null;
2365            if (pageIndicator != null) {
2366                pageIndicatorAlpha = new LauncherViewPropertyAnimator(pageIndicator)
2367                    .alpha(finalHotseatAndPageIndicatorAlpha).withLayer();
2368                pageIndicatorAlpha.addListener(new AlphaUpdateListener(pageIndicator));
2369            } else {
2370                // create a dummy animation so we don't need to do null checks later
2371                pageIndicatorAlpha = ValueAnimator.ofFloat(0, 0);
2372            }
2373
2374            Animator hotseatAlpha = new LauncherViewPropertyAnimator(hotseat)
2375                .alpha(finalHotseatAndPageIndicatorAlpha).withLayer();
2376            hotseatAlpha.addListener(new AlphaUpdateListener(hotseat));
2377
2378            Animator searchBarAlpha = new LauncherViewPropertyAnimator(searchBar)
2379                .alpha(finalSearchBarAlpha).withLayer();
2380            searchBarAlpha.addListener(new AlphaUpdateListener(searchBar));
2381
2382            Animator overviewPanelAlpha = new LauncherViewPropertyAnimator(overviewPanel)
2383                .alpha(finalOverviewPanelAlpha).withLayer();
2384            overviewPanelAlpha.addListener(new AlphaUpdateListener(overviewPanel));
2385
2386            if (workspaceToOverview) {
2387                pageIndicatorAlpha.setInterpolator(new DecelerateInterpolator(2));
2388                hotseatAlpha.setInterpolator(new DecelerateInterpolator(2));
2389                overviewPanelAlpha.setInterpolator(null);
2390            } else if (overviewToWorkspace) {
2391                pageIndicatorAlpha.setInterpolator(null);
2392                hotseatAlpha.setInterpolator(null);
2393                overviewPanelAlpha.setInterpolator(new DecelerateInterpolator(2));
2394            }
2395            searchBarAlpha.setInterpolator(null);
2396
2397            anim.play(overviewPanelAlpha);
2398            anim.play(hotseatAlpha);
2399            anim.play(searchBarAlpha);
2400            anim.play(pageIndicatorAlpha);
2401            anim.setStartDelay(delay);
2402        } else {
2403            overviewPanel.setAlpha(finalOverviewPanelAlpha);
2404            AlphaUpdateListener.updateVisibility(overviewPanel);
2405            hotseat.setAlpha(finalHotseatAndPageIndicatorAlpha);
2406            AlphaUpdateListener.updateVisibility(hotseat);
2407            if (pageIndicator != null) {
2408                pageIndicator.setAlpha(finalHotseatAndPageIndicatorAlpha);
2409                AlphaUpdateListener.updateVisibility(pageIndicator);
2410            }
2411            searchBar.setAlpha(finalSearchBarAlpha);
2412            AlphaUpdateListener.updateVisibility(searchBar);
2413            updateCustomContentVisibility();
2414            setScaleX(mNewScale);
2415            setScaleY(mNewScale);
2416            setTranslationY(finalWorkspaceTranslationY);
2417        }
2418        mLauncher.updateVoiceButtonProxyVisible(false);
2419
2420        if (stateIsSpringLoaded) {
2421            // Right now we're covered by Apps Customize
2422            // Show the background gradient immediately, so the gradient will
2423            // be showing once AppsCustomize disappears
2424            animateBackgroundGradient(getResources().getInteger(
2425                    R.integer.config_appsCustomizeSpringLoadedBgAlpha) / 100f, false);
2426        } else if (stateIsOverview) {
2427            animateBackgroundGradient(getResources().getInteger(
2428                    R.integer.config_appsCustomizeSpringLoadedBgAlpha) / 100f, true);
2429        } else {
2430            // Fade the background gradient away
2431            animateBackgroundGradient(0f, animated);
2432        }
2433        return anim;
2434    }
2435
2436    static class AlphaUpdateListener implements AnimatorUpdateListener, AnimatorListener {
2437        View view;
2438        public AlphaUpdateListener(View v) {
2439            view = v;
2440        }
2441
2442        @Override
2443        public void onAnimationUpdate(ValueAnimator arg0) {
2444            updateVisibility(view);
2445        }
2446
2447        public static void updateVisibility(View view) {
2448            // We want to avoid the extra layout pass by setting the views to GONE unless
2449            // accessibility is on, in which case not setting them to GONE causes a glitch.
2450            int invisibleState = sAccessibilityEnabled ? GONE : INVISIBLE;
2451            if (view.getAlpha() < ALPHA_CUTOFF_THRESHOLD && view.getVisibility() != invisibleState) {
2452                view.setVisibility(invisibleState);
2453            } else if (view.getAlpha() > ALPHA_CUTOFF_THRESHOLD
2454                    && view.getVisibility() != VISIBLE) {
2455                view.setVisibility(VISIBLE);
2456            }
2457        }
2458
2459        @Override
2460        public void onAnimationCancel(Animator arg0) {
2461        }
2462
2463        @Override
2464        public void onAnimationEnd(Animator arg0) {
2465            updateVisibility(view);
2466        }
2467
2468        @Override
2469        public void onAnimationRepeat(Animator arg0) {
2470        }
2471
2472        @Override
2473        public void onAnimationStart(Animator arg0) {
2474            // We want the views to be visible for animation, so fade-in/out is visible
2475            view.setVisibility(VISIBLE);
2476        }
2477    }
2478
2479    @Override
2480    public void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace) {
2481        onTransitionPrepare();
2482    }
2483
2484    @Override
2485    public void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace) {
2486    }
2487
2488    @Override
2489    public void onLauncherTransitionStep(Launcher l, float t) {
2490        mTransitionProgress = t;
2491    }
2492
2493    @Override
2494    public void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace) {
2495        onTransitionEnd();
2496    }
2497
2498    private void onTransitionPrepare() {
2499        mIsSwitchingState = true;
2500
2501        // Invalidate here to ensure that the pages are rendered during the state change transition.
2502        invalidate();
2503
2504        updateChildrenLayersEnabled(false);
2505        hideCustomContentIfNecessary();
2506    }
2507
2508    void updateCustomContentVisibility() {
2509        int visibility = mState == Workspace.State.NORMAL ? VISIBLE : INVISIBLE;
2510        if (hasCustomContent()) {
2511            mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID).setVisibility(visibility);
2512        }
2513    }
2514
2515    void showCustomContentIfNecessary() {
2516        boolean show  = mState == Workspace.State.NORMAL;
2517        if (show && hasCustomContent()) {
2518            mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID).setVisibility(VISIBLE);
2519        }
2520    }
2521
2522    void hideCustomContentIfNecessary() {
2523        boolean hide  = mState != Workspace.State.NORMAL;
2524        if (hide && hasCustomContent()) {
2525            disableLayoutTransitions();
2526            mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID).setVisibility(INVISIBLE);
2527            enableLayoutTransitions();
2528        }
2529    }
2530
2531    private void onTransitionEnd() {
2532        mIsSwitchingState = false;
2533        updateChildrenLayersEnabled(false);
2534        // The code in getChangeStateAnimation to determine initialAlpha and finalAlpha will ensure
2535        // ensure that only the current page is visible during (and subsequently, after) the
2536        // transition animation.  If fade adjacent pages is disabled, then re-enable the page
2537        // visibility after the transition animation.
2538        if (!mWorkspaceFadeInAdjacentScreens) {
2539            for (int i = 0; i < getChildCount(); i++) {
2540                final CellLayout cl = (CellLayout) getChildAt(i);
2541                cl.setShortcutAndWidgetAlpha(1f);
2542            }
2543        } else {
2544            for (int i = 0; i < numCustomPages(); i++) {
2545                final CellLayout cl = (CellLayout) getChildAt(i);
2546                cl.setShortcutAndWidgetAlpha(1f);
2547            }
2548        }
2549        showCustomContentIfNecessary();
2550    }
2551
2552    @Override
2553    public View getContent() {
2554        return this;
2555    }
2556
2557    /**
2558     * Draw the View v into the given Canvas.
2559     *
2560     * @param v the view to draw
2561     * @param destCanvas the canvas to draw on
2562     * @param padding the horizontal and vertical padding to use when drawing
2563     */
2564    private void drawDragView(View v, Canvas destCanvas, int padding, boolean pruneToDrawable) {
2565        final Rect clipRect = mTempRect;
2566        v.getDrawingRect(clipRect);
2567
2568        boolean textVisible = false;
2569
2570        destCanvas.save();
2571        if (v instanceof TextView && pruneToDrawable) {
2572            Drawable d = ((TextView) v).getCompoundDrawables()[1];
2573            Rect bounds = getDrawableBounds(d);
2574            clipRect.set(0, 0, bounds.width() + padding, bounds.height() + padding);
2575            destCanvas.translate(padding / 2, padding / 2);
2576            d.draw(destCanvas);
2577        } else {
2578            if (v instanceof FolderIcon) {
2579                // For FolderIcons the text can bleed into the icon area, and so we need to
2580                // hide the text completely (which can't be achieved by clipping).
2581                if (((FolderIcon) v).getTextVisible()) {
2582                    ((FolderIcon) v).setTextVisible(false);
2583                    textVisible = true;
2584                }
2585            } else if (v instanceof BubbleTextView) {
2586                final BubbleTextView tv = (BubbleTextView) v;
2587                clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V +
2588                        tv.getLayout().getLineTop(0);
2589            } else if (v instanceof TextView) {
2590                final TextView tv = (TextView) v;
2591                clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() +
2592                        tv.getLayout().getLineTop(0);
2593            }
2594            destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2);
2595            destCanvas.clipRect(clipRect, Op.REPLACE);
2596            v.draw(destCanvas);
2597
2598            // Restore text visibility of FolderIcon if necessary
2599            if (textVisible) {
2600                ((FolderIcon) v).setTextVisible(true);
2601            }
2602        }
2603        destCanvas.restore();
2604    }
2605
2606    /**
2607     * Returns a new bitmap to show when the given View is being dragged around.
2608     * Responsibility for the bitmap is transferred to the caller.
2609     */
2610    public Bitmap createDragBitmap(View v, Canvas canvas, int padding) {
2611        Bitmap b;
2612
2613        if (v instanceof TextView) {
2614            Drawable d = ((TextView) v).getCompoundDrawables()[1];
2615            Rect bounds = getDrawableBounds(d);
2616            b = Bitmap.createBitmap(bounds.width() + padding,
2617                    bounds.height() + padding, Bitmap.Config.ARGB_8888);
2618        } else {
2619            b = Bitmap.createBitmap(
2620                    v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
2621        }
2622
2623        canvas.setBitmap(b);
2624        drawDragView(v, canvas, padding, true);
2625        canvas.setBitmap(null);
2626
2627        return b;
2628    }
2629
2630    /**
2631     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
2632     * Responsibility for the bitmap is transferred to the caller.
2633     */
2634    private Bitmap createDragOutline(View v, Canvas canvas, int padding) {
2635        final int outlineColor = getResources().getColor(R.color.outline_color);
2636        final Bitmap b = Bitmap.createBitmap(
2637                v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
2638
2639        canvas.setBitmap(b);
2640        drawDragView(v, canvas, padding, true);
2641        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
2642        canvas.setBitmap(null);
2643        return b;
2644    }
2645
2646    /**
2647     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
2648     * Responsibility for the bitmap is transferred to the caller.
2649     */
2650    private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h,
2651            boolean clipAlpha) {
2652        final int outlineColor = getResources().getColor(R.color.outline_color);
2653        final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
2654        canvas.setBitmap(b);
2655
2656        Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight());
2657        float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(),
2658                (h - padding) / (float) orig.getHeight());
2659        int scaledWidth = (int) (scaleFactor * orig.getWidth());
2660        int scaledHeight = (int) (scaleFactor * orig.getHeight());
2661        Rect dst = new Rect(0, 0, scaledWidth, scaledHeight);
2662
2663        // center the image
2664        dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2);
2665
2666        canvas.drawBitmap(orig, src, dst, null);
2667        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor,
2668                clipAlpha);
2669        canvas.setBitmap(null);
2670
2671        return b;
2672    }
2673
2674    void startDrag(CellLayout.CellInfo cellInfo) {
2675        View child = cellInfo.cell;
2676
2677        // Make sure the drag was started by a long press as opposed to a long click.
2678        if (!child.isInTouchMode()) {
2679            return;
2680        }
2681
2682        mDragInfo = cellInfo;
2683        child.setVisibility(INVISIBLE);
2684        CellLayout layout = (CellLayout) child.getParent().getParent();
2685        layout.prepareChildForDrag(child);
2686
2687        child.clearFocus();
2688        child.setPressed(false);
2689
2690        final Canvas canvas = new Canvas();
2691
2692        // The outline is used to visualize where the item will land if dropped
2693        mDragOutline = createDragOutline(child, canvas, DRAG_BITMAP_PADDING);
2694        beginDragShared(child, this);
2695    }
2696
2697    public void beginDragShared(View child, DragSource source) {
2698        mLauncher.onDragStarted(child);
2699        // The drag bitmap follows the touch point around on the screen
2700        final Bitmap b = createDragBitmap(child, new Canvas(), DRAG_BITMAP_PADDING);
2701
2702        final int bmpWidth = b.getWidth();
2703        final int bmpHeight = b.getHeight();
2704
2705        float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY);
2706        int dragLayerX = Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2);
2707        int dragLayerY = Math.round(mTempXY[1] - (bmpHeight - scale * bmpHeight) / 2
2708                        - DRAG_BITMAP_PADDING / 2);
2709
2710        LauncherAppState app = LauncherAppState.getInstance();
2711        DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
2712        Point dragVisualizeOffset = null;
2713        Rect dragRect = null;
2714        if (child instanceof BubbleTextView || child instanceof PagedViewIcon) {
2715            int iconSize = grid.iconSizePx;
2716            int top = child.getPaddingTop();
2717            int left = (bmpWidth - iconSize) / 2;
2718            int right = left + iconSize;
2719            int bottom = top + iconSize;
2720            dragLayerY += top;
2721            // Note: The drag region is used to calculate drag layer offsets, but the
2722            // dragVisualizeOffset in addition to the dragRect (the size) to position the outline.
2723            dragVisualizeOffset = new Point(-DRAG_BITMAP_PADDING / 2, DRAG_BITMAP_PADDING / 2);
2724            dragRect = new Rect(left, top, right, bottom);
2725        } else if (child instanceof FolderIcon) {
2726            int previewSize = grid.folderIconSizePx;
2727            dragRect = new Rect(0, child.getPaddingTop(), child.getWidth(), previewSize);
2728        }
2729
2730        // Clear the pressed state if necessary
2731        if (child instanceof BubbleTextView) {
2732            BubbleTextView icon = (BubbleTextView) child;
2733            icon.clearPressedOrFocusedBackground();
2734        } else if (child instanceof FolderIcon) {
2735            // The folder cling isn't flexible enough to be shown in non-default workspace positions
2736            // Also if they are dragging it a folder, we assume they don't need to see the cling.
2737            mLauncher.markFolderClingDismissedIfNecessary();
2738        }
2739
2740        if (child.getTag() == null || !(child.getTag() instanceof ItemInfo)) {
2741            String msg = "Drag started with a view that has no tag set. This "
2742                    + "will cause a crash (issue 11627249) down the line. "
2743                    + "View: " + child + "  tag: " + child.getTag();
2744            throw new IllegalStateException(msg);
2745        }
2746
2747        DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(),
2748                DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect, scale);
2749        dv.setIntrinsicIconScaleFactor(source.getIntrinsicIconScaleFactor());
2750
2751        if (child.getParent() instanceof ShortcutAndWidgetContainer) {
2752            mDragSourceInternal = (ShortcutAndWidgetContainer) child.getParent();
2753        }
2754
2755        b.recycle();
2756    }
2757
2758    public void beginExternalDragShared(View child, DragSource source) {
2759        LauncherAppState app = LauncherAppState.getInstance();
2760        DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
2761        int iconSize = grid.iconSizePx;
2762
2763        // Notify launcher of drag start
2764        mLauncher.onDragStarted(child);
2765
2766        // Compose a new drag bitmap that is of the icon size
2767        final Bitmap tmpB = createDragBitmap(child, new Canvas(), DRAG_BITMAP_PADDING);
2768        Bitmap b = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888);
2769        Paint p = new Paint();
2770        p.setFilterBitmap(true);
2771        Canvas c = new Canvas(b);
2772        c.drawBitmap(tmpB, new Rect(0, 0, tmpB.getWidth(), tmpB.getHeight()),
2773                new Rect(0, 0, iconSize, iconSize), p);
2774        c.setBitmap(null);
2775
2776        // Find the child's location on the screen
2777        int bmpWidth = tmpB.getWidth();
2778        float iconScale = (float) bmpWidth / iconSize;
2779        float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY) * iconScale;
2780        int dragLayerX = Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2);
2781        int dragLayerY = Math.round(mTempXY[1]);
2782
2783        // Note: The drag region is used to calculate drag layer offsets, but the
2784        // dragVisualizeOffset in addition to the dragRect (the size) to position the outline.
2785        Point dragVisualizeOffset = new Point(-DRAG_BITMAP_PADDING / 2, DRAG_BITMAP_PADDING / 2);
2786        Rect dragRect = new Rect(0, 0, iconSize, iconSize);
2787
2788        if (child.getTag() == null || !(child.getTag() instanceof ItemInfo)) {
2789            String msg = "Drag started with a view that has no tag set. This "
2790                    + "will cause a crash (issue 11627249) down the line. "
2791                    + "View: " + child + "  tag: " + child.getTag();
2792            throw new IllegalStateException(msg);
2793        }
2794
2795        // Start the drag
2796        DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(),
2797                DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect, scale);
2798        dv.setIntrinsicIconScaleFactor(source.getIntrinsicIconScaleFactor());
2799
2800        // Recycle temporary bitmaps
2801        tmpB.recycle();
2802    }
2803
2804    void addApplicationShortcut(ShortcutInfo info, CellLayout target, long container, long screenId,
2805            int cellX, int cellY, boolean insertAtFirst, int intersectX, int intersectY) {
2806        View view = mLauncher.createShortcut(R.layout.application, target, (ShortcutInfo) info);
2807
2808        final int[] cellXY = new int[2];
2809        target.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY);
2810        addInScreen(view, container, screenId, cellXY[0], cellXY[1], 1, 1, insertAtFirst);
2811
2812        LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screenId, cellXY[0],
2813                cellXY[1]);
2814    }
2815
2816    public boolean transitionStateShouldAllowDrop() {
2817        return ((!isSwitchingState() || mTransitionProgress > 0.5f) && mState != State.SMALL);
2818    }
2819
2820    /**
2821     * {@inheritDoc}
2822     */
2823    public boolean acceptDrop(DragObject d) {
2824        // If it's an external drop (e.g. from All Apps), check if it should be accepted
2825        CellLayout dropTargetLayout = mDropToLayout;
2826        if (d.dragSource != this) {
2827            // Don't accept the drop if we're not over a screen at time of drop
2828            if (dropTargetLayout == null) {
2829                return false;
2830            }
2831            if (!transitionStateShouldAllowDrop()) return false;
2832
2833            mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
2834                    d.dragView, mDragViewVisualCenter);
2835
2836            // We want the point to be mapped to the dragTarget.
2837            if (mLauncher.isHotseatLayout(dropTargetLayout)) {
2838                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
2839            } else {
2840                mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter, null);
2841            }
2842
2843            int spanX = 1;
2844            int spanY = 1;
2845            if (mDragInfo != null) {
2846                final CellLayout.CellInfo dragCellInfo = mDragInfo;
2847                spanX = dragCellInfo.spanX;
2848                spanY = dragCellInfo.spanY;
2849            } else {
2850                final ItemInfo dragInfo = (ItemInfo) d.dragInfo;
2851                spanX = dragInfo.spanX;
2852                spanY = dragInfo.spanY;
2853            }
2854
2855            int minSpanX = spanX;
2856            int minSpanY = spanY;
2857            if (d.dragInfo instanceof PendingAddWidgetInfo) {
2858                minSpanX = ((PendingAddWidgetInfo) d.dragInfo).minSpanX;
2859                minSpanY = ((PendingAddWidgetInfo) d.dragInfo).minSpanY;
2860            }
2861
2862            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2863                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, dropTargetLayout,
2864                    mTargetCell);
2865            float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0],
2866                    mDragViewVisualCenter[1], mTargetCell);
2867            if (mCreateUserFolderOnDrop && willCreateUserFolder((ItemInfo) d.dragInfo,
2868                    dropTargetLayout, mTargetCell, distance, true)) {
2869                return true;
2870            }
2871
2872            if (mAddToExistingFolderOnDrop && willAddToExistingUserFolder((ItemInfo) d.dragInfo,
2873                    dropTargetLayout, mTargetCell, distance)) {
2874                return true;
2875            }
2876
2877            int[] resultSpan = new int[2];
2878            mTargetCell = dropTargetLayout.performReorder((int) mDragViewVisualCenter[0],
2879                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY,
2880                    null, mTargetCell, resultSpan, CellLayout.MODE_ACCEPT_DROP);
2881            boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0;
2882
2883            // Don't accept the drop if there's no room for the item
2884            if (!foundCell) {
2885                // Don't show the message if we are dropping on the AllApps button and the hotseat
2886                // is full
2887                boolean isHotseat = mLauncher.isHotseatLayout(dropTargetLayout);
2888                if (mTargetCell != null && isHotseat) {
2889                    Hotseat hotseat = mLauncher.getHotseat();
2890                    if (hotseat.isAllAppsButtonRank(
2891                            hotseat.getOrderInHotseat(mTargetCell[0], mTargetCell[1]))) {
2892                        return false;
2893                    }
2894                }
2895
2896                mLauncher.showOutOfSpaceMessage(isHotseat);
2897                return false;
2898            }
2899        }
2900
2901        long screenId = getIdForScreen(dropTargetLayout);
2902        if (screenId == EXTRA_EMPTY_SCREEN_ID) {
2903            commitExtraEmptyScreen();
2904        }
2905
2906        return true;
2907    }
2908
2909    boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell, float
2910            distance, boolean considerTimeout) {
2911        if (distance > mMaxDistanceForFolderCreation) return false;
2912        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2913
2914        if (dropOverView != null) {
2915            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams();
2916            if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.tmpCellY)) {
2917                return false;
2918            }
2919        }
2920
2921        boolean hasntMoved = false;
2922        if (mDragInfo != null) {
2923            hasntMoved = dropOverView == mDragInfo.cell;
2924        }
2925
2926        if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) {
2927            return false;
2928        }
2929
2930        boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo);
2931        boolean willBecomeShortcut =
2932                (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
2933                info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT);
2934
2935        return (aboveShortcut && willBecomeShortcut);
2936    }
2937
2938    boolean willAddToExistingUserFolder(Object dragInfo, CellLayout target, int[] targetCell,
2939            float distance) {
2940        if (distance > mMaxDistanceForFolderCreation) return false;
2941        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2942
2943        if (dropOverView != null) {
2944            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams();
2945            if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.tmpCellY)) {
2946                return false;
2947            }
2948        }
2949
2950        if (dropOverView instanceof FolderIcon) {
2951            FolderIcon fi = (FolderIcon) dropOverView;
2952            if (fi.acceptDrop(dragInfo)) {
2953                return true;
2954            }
2955        }
2956        return false;
2957    }
2958
2959    boolean createUserFolderIfNecessary(View newView, long container, CellLayout target,
2960            int[] targetCell, float distance, boolean external, DragView dragView,
2961            Runnable postAnimationRunnable) {
2962        if (distance > mMaxDistanceForFolderCreation) return false;
2963        View v = target.getChildAt(targetCell[0], targetCell[1]);
2964
2965        boolean hasntMoved = false;
2966        if (mDragInfo != null) {
2967            CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell);
2968            hasntMoved = (mDragInfo.cellX == targetCell[0] &&
2969                    mDragInfo.cellY == targetCell[1]) && (cellParent == target);
2970        }
2971
2972        if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false;
2973        mCreateUserFolderOnDrop = false;
2974        final long screenId = (targetCell == null) ? mDragInfo.screenId : getIdForScreen(target);
2975
2976        boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo);
2977        boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo);
2978
2979        if (aboveShortcut && willBecomeShortcut) {
2980            ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag();
2981            ShortcutInfo destInfo = (ShortcutInfo) v.getTag();
2982            // if the drag started here, we need to remove it from the workspace
2983            if (!external) {
2984                getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2985            }
2986
2987            Rect folderLocation = new Rect();
2988            float scale = mLauncher.getDragLayer().getDescendantRectRelativeToSelf(v, folderLocation);
2989            target.removeView(v);
2990
2991            FolderIcon fi =
2992                mLauncher.addFolder(target, container, screenId, targetCell[0], targetCell[1]);
2993            destInfo.cellX = -1;
2994            destInfo.cellY = -1;
2995            sourceInfo.cellX = -1;
2996            sourceInfo.cellY = -1;
2997
2998            // If the dragView is null, we can't animate
2999            boolean animate = dragView != null;
3000            if (animate) {
3001                fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale,
3002                        postAnimationRunnable);
3003            } else {
3004                fi.addItem(destInfo);
3005                fi.addItem(sourceInfo);
3006            }
3007            return true;
3008        }
3009        return false;
3010    }
3011
3012    boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell,
3013            float distance, DragObject d, boolean external) {
3014        if (distance > mMaxDistanceForFolderCreation) return false;
3015
3016        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
3017        if (!mAddToExistingFolderOnDrop) return false;
3018        mAddToExistingFolderOnDrop = false;
3019
3020        if (dropOverView instanceof FolderIcon) {
3021            FolderIcon fi = (FolderIcon) dropOverView;
3022            if (fi.acceptDrop(d.dragInfo)) {
3023                fi.onDrop(d);
3024
3025                // if the drag started here, we need to remove it from the workspace
3026                if (!external) {
3027                    getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
3028                }
3029                return true;
3030            }
3031        }
3032        return false;
3033    }
3034
3035    public void onDrop(final DragObject d) {
3036        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView,
3037                mDragViewVisualCenter);
3038
3039        CellLayout dropTargetLayout = mDropToLayout;
3040
3041        // We want the point to be mapped to the dragTarget.
3042        if (dropTargetLayout != null) {
3043            if (mLauncher.isHotseatLayout(dropTargetLayout)) {
3044                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
3045            } else {
3046                mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter, null);
3047            }
3048        }
3049
3050        int snapScreen = -1;
3051        boolean resizeOnDrop = false;
3052        if (d.dragSource != this) {
3053            final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0],
3054                    (int) mDragViewVisualCenter[1] };
3055            onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d);
3056        } else if (mDragInfo != null) {
3057            final View cell = mDragInfo.cell;
3058
3059            Runnable resizeRunnable = null;
3060            if (dropTargetLayout != null && !d.cancelled) {
3061                // Move internally
3062                boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout);
3063                boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout);
3064                long container = hasMovedIntoHotseat ?
3065                        LauncherSettings.Favorites.CONTAINER_HOTSEAT :
3066                        LauncherSettings.Favorites.CONTAINER_DESKTOP;
3067                long screenId = (mTargetCell[0] < 0) ?
3068                        mDragInfo.screenId : getIdForScreen(dropTargetLayout);
3069                int spanX = mDragInfo != null ? mDragInfo.spanX : 1;
3070                int spanY = mDragInfo != null ? mDragInfo.spanY : 1;
3071                // First we find the cell nearest to point at which the item is
3072                // dropped, without any consideration to whether there is an item there.
3073
3074                mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int)
3075                        mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell);
3076                float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0],
3077                        mDragViewVisualCenter[1], mTargetCell);
3078
3079                // If the item being dropped is a shortcut and the nearest drop
3080                // cell also contains a shortcut, then create a folder with the two shortcuts.
3081                if (!mInScrollArea && createUserFolderIfNecessary(cell, container,
3082                        dropTargetLayout, mTargetCell, distance, false, d.dragView, null)) {
3083                    // The folder cling isn't flexible enough to be shown in non-default workspace
3084                    // positions. Also if they are creating a folder, we assume they don't need to
3085                    // see the cling.
3086                    mLauncher.markFolderClingDismissedIfNecessary();
3087                    return;
3088                }
3089
3090                if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell,
3091                        distance, d, false)) {
3092                    return;
3093                }
3094
3095                // Aside from the special case where we're dropping a shortcut onto a shortcut,
3096                // we need to find the nearest cell location that is vacant
3097                ItemInfo item = (ItemInfo) d.dragInfo;
3098                int minSpanX = item.spanX;
3099                int minSpanY = item.spanY;
3100                if (item.minSpanX > 0 && item.minSpanY > 0) {
3101                    minSpanX = item.minSpanX;
3102                    minSpanY = item.minSpanY;
3103                }
3104
3105                int[] resultSpan = new int[2];
3106                mTargetCell = dropTargetLayout.performReorder((int) mDragViewVisualCenter[0],
3107                        (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, cell,
3108                        mTargetCell, resultSpan, CellLayout.MODE_ON_DROP);
3109
3110                boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0;
3111
3112                // if the widget resizes on drop
3113                if (foundCell && (cell instanceof AppWidgetHostView) &&
3114                        (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY)) {
3115                    resizeOnDrop = true;
3116                    item.spanX = resultSpan[0];
3117                    item.spanY = resultSpan[1];
3118                    AppWidgetHostView awhv = (AppWidgetHostView) cell;
3119                    AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, resultSpan[0],
3120                            resultSpan[1]);
3121                }
3122
3123                if (getScreenIdForPageIndex(mCurrentPage) != screenId && !hasMovedIntoHotseat) {
3124                    snapScreen = getPageIndexForScreenId(screenId);
3125                    snapToPage(snapScreen);
3126                }
3127
3128                if (foundCell) {
3129                    final ItemInfo info = (ItemInfo) cell.getTag();
3130                    if (hasMovedLayouts) {
3131                        // Reparent the view
3132                        getParentCellLayoutForView(cell).removeView(cell);
3133                        addInScreen(cell, container, screenId, mTargetCell[0], mTargetCell[1],
3134                                info.spanX, info.spanY);
3135                    }
3136
3137                    // update the item's position after drop
3138                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
3139                    lp.cellX = lp.tmpCellX = mTargetCell[0];
3140                    lp.cellY = lp.tmpCellY = mTargetCell[1];
3141                    lp.cellHSpan = item.spanX;
3142                    lp.cellVSpan = item.spanY;
3143                    lp.isLockedToGrid = true;
3144
3145                    if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
3146                            cell instanceof LauncherAppWidgetHostView) {
3147                        final CellLayout cellLayout = dropTargetLayout;
3148                        // We post this call so that the widget has a chance to be placed
3149                        // in its final location
3150
3151                        final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell;
3152                        AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo();
3153                        if (pinfo != null &&
3154                                pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) {
3155                            final Runnable addResizeFrame = new Runnable() {
3156                                public void run() {
3157                                    DragLayer dragLayer = mLauncher.getDragLayer();
3158                                    dragLayer.addResizeFrame(info, hostView, cellLayout);
3159                                }
3160                            };
3161                            resizeRunnable = (new Runnable() {
3162                                public void run() {
3163                                    if (!isPageMoving()) {
3164                                        addResizeFrame.run();
3165                                    } else {
3166                                        mDelayedResizeRunnable = addResizeFrame;
3167                                    }
3168                                }
3169                            });
3170                        }
3171                    }
3172
3173                    LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId, lp.cellX,
3174                            lp.cellY, item.spanX, item.spanY);
3175                } else {
3176                    // If we can't find a drop location, we return the item to its original position
3177                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
3178                    mTargetCell[0] = lp.cellX;
3179                    mTargetCell[1] = lp.cellY;
3180                    CellLayout layout = (CellLayout) cell.getParent().getParent();
3181                    layout.markCellsAsOccupiedForView(cell);
3182                }
3183            }
3184
3185            final CellLayout parent = (CellLayout) cell.getParent().getParent();
3186            final Runnable finalResizeRunnable = resizeRunnable;
3187            // Prepare it to be animated into its new position
3188            // This must be called after the view has been re-parented
3189            final Runnable onCompleteRunnable = new Runnable() {
3190                @Override
3191                public void run() {
3192                    mAnimatingViewIntoPlace = false;
3193                    updateChildrenLayersEnabled(false);
3194                    if (finalResizeRunnable != null) {
3195                        finalResizeRunnable.run();
3196                    }
3197                }
3198            };
3199            mAnimatingViewIntoPlace = true;
3200            if (d.dragView.hasDrawn()) {
3201                final ItemInfo info = (ItemInfo) cell.getTag();
3202                if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET) {
3203                    int animationType = resizeOnDrop ? ANIMATE_INTO_POSITION_AND_RESIZE :
3204                            ANIMATE_INTO_POSITION_AND_DISAPPEAR;
3205                    animateWidgetDrop(info, parent, d.dragView,
3206                            onCompleteRunnable, animationType, cell, false);
3207                } else {
3208                    int duration = snapScreen < 0 ? -1 : ADJACENT_SCREEN_DROP_DURATION;
3209                    mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration,
3210                            onCompleteRunnable, this);
3211                }
3212            } else {
3213                d.deferDragViewCleanupPostAnimation = false;
3214                cell.setVisibility(VISIBLE);
3215            }
3216            parent.onDropChild(cell);
3217        }
3218    }
3219
3220    public void setFinalScrollForPageChange(int pageIndex) {
3221        CellLayout cl = (CellLayout) getChildAt(pageIndex);
3222        if (cl != null) {
3223            mSavedScrollX = getScrollX();
3224            mSavedTranslationX = cl.getTranslationX();
3225            mSavedRotationY = cl.getRotationY();
3226            final int newX = getScrollForPage(pageIndex);
3227            setScrollX(newX);
3228            cl.setTranslationX(0f);
3229            cl.setRotationY(0f);
3230        }
3231    }
3232
3233    public void resetFinalScrollForPageChange(int pageIndex) {
3234        if (pageIndex >= 0) {
3235            CellLayout cl = (CellLayout) getChildAt(pageIndex);
3236            setScrollX(mSavedScrollX);
3237            cl.setTranslationX(mSavedTranslationX);
3238            cl.setRotationY(mSavedRotationY);
3239        }
3240    }
3241
3242    public void getViewLocationRelativeToSelf(View v, int[] location) {
3243        getLocationInWindow(location);
3244        int x = location[0];
3245        int y = location[1];
3246
3247        v.getLocationInWindow(location);
3248        int vX = location[0];
3249        int vY = location[1];
3250
3251        location[0] = vX - x;
3252        location[1] = vY - y;
3253    }
3254
3255    public void onDragEnter(DragObject d) {
3256        mDragEnforcer.onDragEnter();
3257        mCreateUserFolderOnDrop = false;
3258        mAddToExistingFolderOnDrop = false;
3259
3260        mDropToLayout = null;
3261        CellLayout layout = getCurrentDropLayout();
3262        setCurrentDropLayout(layout);
3263        setCurrentDragOverlappingLayout(layout);
3264
3265        // Because we don't have space in the Phone UI (the CellLayouts run to the edge) we
3266        // don't need to show the outlines
3267        if (LauncherAppState.getInstance().isScreenLarge()) {
3268            showOutlines();
3269        }
3270    }
3271
3272    /** Return a rect that has the cellWidth/cellHeight (left, top), and
3273     * widthGap/heightGap (right, bottom) */
3274    static Rect getCellLayoutMetrics(Launcher launcher, int orientation) {
3275        LauncherAppState app = LauncherAppState.getInstance();
3276        DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
3277
3278        Resources res = launcher.getResources();
3279        Display display = launcher.getWindowManager().getDefaultDisplay();
3280        Point smallestSize = new Point();
3281        Point largestSize = new Point();
3282        display.getCurrentSizeRange(smallestSize, largestSize);
3283        int countX = (int) grid.numColumns;
3284        int countY = (int) grid.numRows;
3285        if (orientation == CellLayout.LANDSCAPE) {
3286            if (mLandscapeCellLayoutMetrics == null) {
3287                Rect padding = grid.getWorkspacePadding(CellLayout.LANDSCAPE);
3288                int width = largestSize.x - padding.left - padding.right;
3289                int height = smallestSize.y - padding.top - padding.bottom;
3290                mLandscapeCellLayoutMetrics = new Rect();
3291                mLandscapeCellLayoutMetrics.set(
3292                        grid.calculateCellWidth(width, countX),
3293                        grid.calculateCellHeight(height, countY), 0, 0);
3294            }
3295            return mLandscapeCellLayoutMetrics;
3296        } else if (orientation == CellLayout.PORTRAIT) {
3297            if (mPortraitCellLayoutMetrics == null) {
3298                Rect padding = grid.getWorkspacePadding(CellLayout.PORTRAIT);
3299                int width = smallestSize.x - padding.left - padding.right;
3300                int height = largestSize.y - padding.top - padding.bottom;
3301                mPortraitCellLayoutMetrics = new Rect();
3302                mPortraitCellLayoutMetrics.set(
3303                        grid.calculateCellWidth(width, countX),
3304                        grid.calculateCellHeight(height, countY), 0, 0);
3305            }
3306            return mPortraitCellLayoutMetrics;
3307        }
3308        return null;
3309    }
3310
3311    public void onDragExit(DragObject d) {
3312        mDragEnforcer.onDragExit();
3313
3314        // Here we store the final page that will be dropped to, if the workspace in fact
3315        // receives the drop
3316        if (mInScrollArea) {
3317            if (isPageMoving()) {
3318                // If the user drops while the page is scrolling, we should use that page as the
3319                // destination instead of the page that is being hovered over.
3320                mDropToLayout = (CellLayout) getPageAt(getNextPage());
3321            } else {
3322                mDropToLayout = mDragOverlappingLayout;
3323            }
3324        } else {
3325            mDropToLayout = mDragTargetLayout;
3326        }
3327
3328        if (mDragMode == DRAG_MODE_CREATE_FOLDER) {
3329            mCreateUserFolderOnDrop = true;
3330        } else if (mDragMode == DRAG_MODE_ADD_TO_FOLDER) {
3331            mAddToExistingFolderOnDrop = true;
3332        }
3333
3334        // Reset the scroll area and previous drag target
3335        onResetScrollArea();
3336        setCurrentDropLayout(null);
3337        setCurrentDragOverlappingLayout(null);
3338
3339        mSpringLoadedDragController.cancel();
3340
3341        if (!mIsPageMoving) {
3342            hideOutlines();
3343        }
3344    }
3345
3346    void setCurrentDropLayout(CellLayout layout) {
3347        if (mDragTargetLayout != null) {
3348            mDragTargetLayout.revertTempState();
3349            mDragTargetLayout.onDragExit();
3350        }
3351        mDragTargetLayout = layout;
3352        if (mDragTargetLayout != null) {
3353            mDragTargetLayout.onDragEnter();
3354        }
3355        cleanupReorder(true);
3356        cleanupFolderCreation();
3357        setCurrentDropOverCell(-1, -1);
3358    }
3359
3360    void setCurrentDragOverlappingLayout(CellLayout layout) {
3361        if (mDragOverlappingLayout != null) {
3362            mDragOverlappingLayout.setIsDragOverlapping(false);
3363        }
3364        mDragOverlappingLayout = layout;
3365        if (mDragOverlappingLayout != null) {
3366            mDragOverlappingLayout.setIsDragOverlapping(true);
3367        }
3368        invalidate();
3369    }
3370
3371    void setCurrentDropOverCell(int x, int y) {
3372        if (x != mDragOverX || y != mDragOverY) {
3373            mDragOverX = x;
3374            mDragOverY = y;
3375            setDragMode(DRAG_MODE_NONE);
3376        }
3377    }
3378
3379    void setDragMode(int dragMode) {
3380        if (dragMode != mDragMode) {
3381            if (dragMode == DRAG_MODE_NONE) {
3382                cleanupAddToFolder();
3383                // We don't want to cancel the re-order alarm every time the target cell changes
3384                // as this feels to slow / unresponsive.
3385                cleanupReorder(false);
3386                cleanupFolderCreation();
3387            } else if (dragMode == DRAG_MODE_ADD_TO_FOLDER) {
3388                cleanupReorder(true);
3389                cleanupFolderCreation();
3390            } else if (dragMode == DRAG_MODE_CREATE_FOLDER) {
3391                cleanupAddToFolder();
3392                cleanupReorder(true);
3393            } else if (dragMode == DRAG_MODE_REORDER) {
3394                cleanupAddToFolder();
3395                cleanupFolderCreation();
3396            }
3397            mDragMode = dragMode;
3398        }
3399    }
3400
3401    private void cleanupFolderCreation() {
3402        if (mDragFolderRingAnimator != null) {
3403            mDragFolderRingAnimator.animateToNaturalState();
3404            mDragFolderRingAnimator = null;
3405        }
3406        mFolderCreationAlarm.setOnAlarmListener(null);
3407        mFolderCreationAlarm.cancelAlarm();
3408    }
3409
3410    private void cleanupAddToFolder() {
3411        if (mDragOverFolderIcon != null) {
3412            mDragOverFolderIcon.onDragExit(null);
3413            mDragOverFolderIcon = null;
3414        }
3415    }
3416
3417    private void cleanupReorder(boolean cancelAlarm) {
3418        // Any pending reorders are canceled
3419        if (cancelAlarm) {
3420            mReorderAlarm.cancelAlarm();
3421        }
3422        mLastReorderX = -1;
3423        mLastReorderY = -1;
3424    }
3425
3426   /*
3427    *
3428    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
3429    * coordinate space. The argument xy is modified with the return result.
3430    *
3431    * if cachedInverseMatrix is not null, this method will just use that matrix instead of
3432    * computing it itself; we use this to avoid redundant matrix inversions in
3433    * findMatchingPageForDragOver
3434    *
3435    */
3436   void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) {
3437       xy[0] = xy[0] - v.getLeft();
3438       xy[1] = xy[1] - v.getTop();
3439   }
3440
3441   boolean isPointInSelfOverHotseat(int x, int y, Rect r) {
3442       if (r == null) {
3443           r = new Rect();
3444       }
3445       mTempPt[0] = x;
3446       mTempPt[1] = y;
3447       mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempPt, true);
3448
3449       LauncherAppState app = LauncherAppState.getInstance();
3450       DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
3451       r = grid.getHotseatRect();
3452       if (r.contains(mTempPt[0], mTempPt[1])) {
3453           return true;
3454       }
3455       return false;
3456   }
3457
3458   void mapPointFromSelfToHotseatLayout(Hotseat hotseat, float[] xy) {
3459       mTempPt[0] = (int) xy[0];
3460       mTempPt[1] = (int) xy[1];
3461       mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempPt, true);
3462       mLauncher.getDragLayer().mapCoordInSelfToDescendent(hotseat.getLayout(), mTempPt);
3463
3464       xy[0] = mTempPt[0];
3465       xy[1] = mTempPt[1];
3466   }
3467
3468   /*
3469    *
3470    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
3471    * the parent View's coordinate space. The argument xy is modified with the return result.
3472    *
3473    */
3474   void mapPointFromChildToSelf(View v, float[] xy) {
3475       xy[0] += v.getLeft();
3476       xy[1] += v.getTop();
3477   }
3478
3479   static private float squaredDistance(float[] point1, float[] point2) {
3480        float distanceX = point1[0] - point2[0];
3481        float distanceY = point2[1] - point2[1];
3482        return distanceX * distanceX + distanceY * distanceY;
3483   }
3484
3485    /*
3486     *
3487     * This method returns the CellLayout that is currently being dragged to. In order to drag
3488     * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
3489     * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
3490     *
3491     * Return null if no CellLayout is currently being dragged over
3492     *
3493     */
3494    private CellLayout findMatchingPageForDragOver(
3495            DragView dragView, float originX, float originY, boolean exact) {
3496        // We loop through all the screens (ie CellLayouts) and see which ones overlap
3497        // with the item being dragged and then choose the one that's closest to the touch point
3498        final int screenCount = getChildCount();
3499        CellLayout bestMatchingScreen = null;
3500        float smallestDistSoFar = Float.MAX_VALUE;
3501
3502        for (int i = 0; i < screenCount; i++) {
3503            // The custom content screen is not a valid drag over option
3504            if (mScreenOrder.get(i) == CUSTOM_CONTENT_SCREEN_ID) {
3505                continue;
3506            }
3507
3508            CellLayout cl = (CellLayout) getChildAt(i);
3509
3510            final float[] touchXy = {originX, originY};
3511            // Transform the touch coordinates to the CellLayout's local coordinates
3512            // If the touch point is within the bounds of the cell layout, we can return immediately
3513            cl.getMatrix().invert(mTempInverseMatrix);
3514            mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix);
3515
3516            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
3517                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
3518                return cl;
3519            }
3520
3521            if (!exact) {
3522                // Get the center of the cell layout in screen coordinates
3523                final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
3524                cellLayoutCenter[0] = cl.getWidth()/2;
3525                cellLayoutCenter[1] = cl.getHeight()/2;
3526                mapPointFromChildToSelf(cl, cellLayoutCenter);
3527
3528                touchXy[0] = originX;
3529                touchXy[1] = originY;
3530
3531                // Calculate the distance between the center of the CellLayout
3532                // and the touch point
3533                float dist = squaredDistance(touchXy, cellLayoutCenter);
3534
3535                if (dist < smallestDistSoFar) {
3536                    smallestDistSoFar = dist;
3537                    bestMatchingScreen = cl;
3538                }
3539            }
3540        }
3541        return bestMatchingScreen;
3542    }
3543
3544    // This is used to compute the visual center of the dragView. This point is then
3545    // used to visualize drop locations and determine where to drop an item. The idea is that
3546    // the visual center represents the user's interpretation of where the item is, and hence
3547    // is the appropriate point to use when determining drop location.
3548    private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset,
3549            DragView dragView, float[] recycle) {
3550        float res[];
3551        if (recycle == null) {
3552            res = new float[2];
3553        } else {
3554            res = recycle;
3555        }
3556
3557        // First off, the drag view has been shifted in a way that is not represented in the
3558        // x and y values or the x/yOffsets. Here we account for that shift.
3559        x += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX);
3560        y += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
3561
3562        // These represent the visual top and left of drag view if a dragRect was provided.
3563        // If a dragRect was not provided, then they correspond to the actual view left and
3564        // top, as the dragRect is in that case taken to be the entire dragView.
3565        // R.dimen.dragViewOffsetY.
3566        int left = x - xOffset;
3567        int top = y - yOffset;
3568
3569        // In order to find the visual center, we shift by half the dragRect
3570        res[0] = left + dragView.getDragRegion().width() / 2;
3571        res[1] = top + dragView.getDragRegion().height() / 2;
3572
3573        return res;
3574    }
3575
3576    private boolean isDragWidget(DragObject d) {
3577        return (d.dragInfo instanceof LauncherAppWidgetInfo ||
3578                d.dragInfo instanceof PendingAddWidgetInfo);
3579    }
3580    private boolean isExternalDragWidget(DragObject d) {
3581        return d.dragSource != this && isDragWidget(d);
3582    }
3583
3584    public void onDragOver(DragObject d) {
3585        // Skip drag over events while we are dragging over side pages
3586        if (mInScrollArea || mIsSwitchingState || mState == State.SMALL) return;
3587
3588        Rect r = new Rect();
3589        CellLayout layout = null;
3590        ItemInfo item = (ItemInfo) d.dragInfo;
3591
3592        // Ensure that we have proper spans for the item that we are dropping
3593        if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found");
3594        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
3595            d.dragView, mDragViewVisualCenter);
3596
3597        final View child = (mDragInfo == null) ? null : mDragInfo.cell;
3598        // Identify whether we have dragged over a side page
3599        if (isSmall()) {
3600            if (mLauncher.getHotseat() != null && !isExternalDragWidget(d)) {
3601                if (isPointInSelfOverHotseat(d.x, d.y, r)) {
3602                    layout = mLauncher.getHotseat().getLayout();
3603                }
3604            }
3605            if (layout == null) {
3606                layout = findMatchingPageForDragOver(d.dragView, d.x, d.y, false);
3607            }
3608            if (layout != mDragTargetLayout) {
3609                setCurrentDropLayout(layout);
3610                setCurrentDragOverlappingLayout(layout);
3611
3612                boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED);
3613                if (isInSpringLoadedMode) {
3614                    if (mLauncher.isHotseatLayout(layout)) {
3615                        mSpringLoadedDragController.cancel();
3616                    } else {
3617                        mSpringLoadedDragController.setAlarm(mDragTargetLayout);
3618                    }
3619                }
3620            }
3621        } else {
3622            // Test to see if we are over the hotseat otherwise just use the current page
3623            if (mLauncher.getHotseat() != null && !isDragWidget(d)) {
3624                if (isPointInSelfOverHotseat(d.x, d.y, r)) {
3625                    layout = mLauncher.getHotseat().getLayout();
3626                }
3627            }
3628            if (layout == null) {
3629                layout = getCurrentDropLayout();
3630            }
3631            if (layout != mDragTargetLayout) {
3632                setCurrentDropLayout(layout);
3633                setCurrentDragOverlappingLayout(layout);
3634            }
3635        }
3636
3637        // Handle the drag over
3638        if (mDragTargetLayout != null) {
3639            // We want the point to be mapped to the dragTarget.
3640            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
3641                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
3642            } else {
3643                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
3644            }
3645
3646            ItemInfo info = (ItemInfo) d.dragInfo;
3647
3648            int minSpanX = item.spanX;
3649            int minSpanY = item.spanY;
3650            if (item.minSpanX > 0 && item.minSpanY > 0) {
3651                minSpanX = item.minSpanX;
3652                minSpanY = item.minSpanY;
3653            }
3654
3655            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
3656                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY,
3657                    mDragTargetLayout, mTargetCell);
3658            int reorderX = mTargetCell[0];
3659            int reorderY = mTargetCell[1];
3660
3661            setCurrentDropOverCell(mTargetCell[0], mTargetCell[1]);
3662
3663            float targetCellDistance = mDragTargetLayout.getDistanceFromCell(
3664                    mDragViewVisualCenter[0], mDragViewVisualCenter[1], mTargetCell);
3665
3666            final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0],
3667                    mTargetCell[1]);
3668
3669            manageFolderFeedback(info, mDragTargetLayout, mTargetCell,
3670                    targetCellDistance, dragOverView);
3671
3672            boolean nearestDropOccupied = mDragTargetLayout.isNearestDropLocationOccupied((int)
3673                    mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], item.spanX,
3674                    item.spanY, child, mTargetCell);
3675
3676            if (!nearestDropOccupied) {
3677                mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
3678                        (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
3679                        mTargetCell[0], mTargetCell[1], item.spanX, item.spanY, false,
3680                        d.dragView.getDragVisualizeOffset(), d.dragView.getDragRegion());
3681            } else if ((mDragMode == DRAG_MODE_NONE || mDragMode == DRAG_MODE_REORDER)
3682                    && !mReorderAlarm.alarmPending() && (mLastReorderX != reorderX ||
3683                    mLastReorderY != reorderY)) {
3684
3685                int[] resultSpan = new int[2];
3686                mDragTargetLayout.performReorder((int) mDragViewVisualCenter[0],
3687                        (int) mDragViewVisualCenter[1], minSpanX, minSpanY, item.spanX, item.spanY,
3688                        child, mTargetCell, resultSpan, CellLayout.MODE_SHOW_REORDER_HINT);
3689
3690                // Otherwise, if we aren't adding to or creating a folder and there's no pending
3691                // reorder, then we schedule a reorder
3692                ReorderAlarmListener listener = new ReorderAlarmListener(mDragViewVisualCenter,
3693                        minSpanX, minSpanY, item.spanX, item.spanY, d.dragView, child);
3694                mReorderAlarm.setOnAlarmListener(listener);
3695                mReorderAlarm.setAlarm(REORDER_TIMEOUT);
3696            }
3697
3698            if (mDragMode == DRAG_MODE_CREATE_FOLDER || mDragMode == DRAG_MODE_ADD_TO_FOLDER ||
3699                    !nearestDropOccupied) {
3700                if (mDragTargetLayout != null) {
3701                    mDragTargetLayout.revertTempState();
3702                }
3703            }
3704        }
3705    }
3706
3707    private void manageFolderFeedback(ItemInfo info, CellLayout targetLayout,
3708            int[] targetCell, float distance, View dragOverView) {
3709        boolean userFolderPending = willCreateUserFolder(info, targetLayout, targetCell, distance,
3710                false);
3711
3712        if (mDragMode == DRAG_MODE_NONE && userFolderPending &&
3713                !mFolderCreationAlarm.alarmPending()) {
3714            mFolderCreationAlarm.setOnAlarmListener(new
3715                    FolderCreationAlarmListener(targetLayout, targetCell[0], targetCell[1]));
3716            mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT);
3717            return;
3718        }
3719
3720        boolean willAddToFolder =
3721                willAddToExistingUserFolder(info, targetLayout, targetCell, distance);
3722
3723        if (willAddToFolder && mDragMode == DRAG_MODE_NONE) {
3724            mDragOverFolderIcon = ((FolderIcon) dragOverView);
3725            mDragOverFolderIcon.onDragEnter(info);
3726            if (targetLayout != null) {
3727                targetLayout.clearDragOutlines();
3728            }
3729            setDragMode(DRAG_MODE_ADD_TO_FOLDER);
3730            return;
3731        }
3732
3733        if (mDragMode == DRAG_MODE_ADD_TO_FOLDER && !willAddToFolder) {
3734            setDragMode(DRAG_MODE_NONE);
3735        }
3736        if (mDragMode == DRAG_MODE_CREATE_FOLDER && !userFolderPending) {
3737            setDragMode(DRAG_MODE_NONE);
3738        }
3739
3740        return;
3741    }
3742
3743    class FolderCreationAlarmListener implements OnAlarmListener {
3744        CellLayout layout;
3745        int cellX;
3746        int cellY;
3747
3748        public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) {
3749            this.layout = layout;
3750            this.cellX = cellX;
3751            this.cellY = cellY;
3752        }
3753
3754        public void onAlarm(Alarm alarm) {
3755            if (mDragFolderRingAnimator != null) {
3756                // This shouldn't happen ever, but just in case, make sure we clean up the mess.
3757                mDragFolderRingAnimator.animateToNaturalState();
3758            }
3759            mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null);
3760            mDragFolderRingAnimator.setCell(cellX, cellY);
3761            mDragFolderRingAnimator.setCellLayout(layout);
3762            mDragFolderRingAnimator.animateToAcceptState();
3763            layout.showFolderAccept(mDragFolderRingAnimator);
3764            layout.clearDragOutlines();
3765            setDragMode(DRAG_MODE_CREATE_FOLDER);
3766        }
3767    }
3768
3769    class ReorderAlarmListener implements OnAlarmListener {
3770        float[] dragViewCenter;
3771        int minSpanX, minSpanY, spanX, spanY;
3772        DragView dragView;
3773        View child;
3774
3775        public ReorderAlarmListener(float[] dragViewCenter, int minSpanX, int minSpanY, int spanX,
3776                int spanY, DragView dragView, View child) {
3777            this.dragViewCenter = dragViewCenter;
3778            this.minSpanX = minSpanX;
3779            this.minSpanY = minSpanY;
3780            this.spanX = spanX;
3781            this.spanY = spanY;
3782            this.child = child;
3783            this.dragView = dragView;
3784        }
3785
3786        public void onAlarm(Alarm alarm) {
3787            int[] resultSpan = new int[2];
3788            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
3789                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, mDragTargetLayout,
3790                    mTargetCell);
3791            mLastReorderX = mTargetCell[0];
3792            mLastReorderY = mTargetCell[1];
3793
3794            mTargetCell = mDragTargetLayout.performReorder((int) mDragViewVisualCenter[0],
3795                (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY,
3796                child, mTargetCell, resultSpan, CellLayout.MODE_DRAG_OVER);
3797
3798            if (mTargetCell[0] < 0 || mTargetCell[1] < 0) {
3799                mDragTargetLayout.revertTempState();
3800            } else {
3801                setDragMode(DRAG_MODE_REORDER);
3802            }
3803
3804            boolean resize = resultSpan[0] != spanX || resultSpan[1] != spanY;
3805            mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
3806                (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
3807                mTargetCell[0], mTargetCell[1], resultSpan[0], resultSpan[1], resize,
3808                dragView.getDragVisualizeOffset(), dragView.getDragRegion());
3809        }
3810    }
3811
3812    @Override
3813    public void getHitRectRelativeToDragLayer(Rect outRect) {
3814        // We want the workspace to have the whole area of the display (it will find the correct
3815        // cell layout to drop to in the existing drag/drop logic.
3816        mLauncher.getDragLayer().getDescendantRectRelativeToSelf(this, outRect);
3817    }
3818
3819    /**
3820     * Add the item specified by dragInfo to the given layout.
3821     * @return true if successful
3822     */
3823    public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) {
3824        if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) {
3825            onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false);
3826            return true;
3827        }
3828        mLauncher.showOutOfSpaceMessage(mLauncher.isHotseatLayout(layout));
3829        return false;
3830    }
3831
3832    private void onDropExternal(int[] touchXY, Object dragInfo,
3833            CellLayout cellLayout, boolean insertAtFirst) {
3834        onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null);
3835    }
3836
3837    /**
3838     * Drop an item that didn't originate on one of the workspace screens.
3839     * It may have come from Launcher (e.g. from all apps or customize), or it may have
3840     * come from another app altogether.
3841     *
3842     * NOTE: This can also be called when we are outside of a drag event, when we want
3843     * to add an item to one of the workspace screens.
3844     */
3845    private void onDropExternal(final int[] touchXY, final Object dragInfo,
3846            final CellLayout cellLayout, boolean insertAtFirst, DragObject d) {
3847        final Runnable exitSpringLoadedRunnable = new Runnable() {
3848            @Override
3849            public void run() {
3850                mLauncher.exitSpringLoadedDragModeDelayed(true,
3851                        Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, null);
3852            }
3853        };
3854
3855        ItemInfo info = (ItemInfo) dragInfo;
3856        int spanX = info.spanX;
3857        int spanY = info.spanY;
3858        if (mDragInfo != null) {
3859            spanX = mDragInfo.spanX;
3860            spanY = mDragInfo.spanY;
3861        }
3862
3863        final long container = mLauncher.isHotseatLayout(cellLayout) ?
3864                LauncherSettings.Favorites.CONTAINER_HOTSEAT :
3865                    LauncherSettings.Favorites.CONTAINER_DESKTOP;
3866        final long screenId = getIdForScreen(cellLayout);
3867        if (!mLauncher.isHotseatLayout(cellLayout)
3868                && screenId != getScreenIdForPageIndex(mCurrentPage)
3869                && mState != State.SPRING_LOADED) {
3870            snapToScreenId(screenId, null);
3871        }
3872
3873        if (info instanceof PendingAddItemInfo) {
3874            final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo;
3875
3876            boolean findNearestVacantCell = true;
3877            if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
3878                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
3879                        cellLayout, mTargetCell);
3880                float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0],
3881                        mDragViewVisualCenter[1], mTargetCell);
3882                if (willCreateUserFolder((ItemInfo) d.dragInfo, cellLayout, mTargetCell,
3883                        distance, true) || willAddToExistingUserFolder((ItemInfo) d.dragInfo,
3884                                cellLayout, mTargetCell, distance)) {
3885                    findNearestVacantCell = false;
3886                }
3887            }
3888
3889            final ItemInfo item = (ItemInfo) d.dragInfo;
3890            boolean updateWidgetSize = false;
3891            if (findNearestVacantCell) {
3892                int minSpanX = item.spanX;
3893                int minSpanY = item.spanY;
3894                if (item.minSpanX > 0 && item.minSpanY > 0) {
3895                    minSpanX = item.minSpanX;
3896                    minSpanY = item.minSpanY;
3897                }
3898                int[] resultSpan = new int[2];
3899                mTargetCell = cellLayout.performReorder((int) mDragViewVisualCenter[0],
3900                        (int) mDragViewVisualCenter[1], minSpanX, minSpanY, info.spanX, info.spanY,
3901                        null, mTargetCell, resultSpan, CellLayout.MODE_ON_DROP_EXTERNAL);
3902
3903                if (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY) {
3904                    updateWidgetSize = true;
3905                }
3906                item.spanX = resultSpan[0];
3907                item.spanY = resultSpan[1];
3908            }
3909
3910            Runnable onAnimationCompleteRunnable = new Runnable() {
3911                @Override
3912                public void run() {
3913                    // Normally removeExtraEmptyScreen is called in Workspace#onDragEnd, but when
3914                    // adding an item that may not be dropped right away (due to a config activity)
3915                    // we defer the removal until the activity returns.
3916                    deferRemoveExtraEmptyScreen();
3917
3918                    // When dragging and dropping from customization tray, we deal with creating
3919                    // widgets/shortcuts/folders in a slightly different way
3920                    switch (pendingInfo.itemType) {
3921                    case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
3922                        int span[] = new int[2];
3923                        span[0] = item.spanX;
3924                        span[1] = item.spanY;
3925                        mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) pendingInfo,
3926                                container, screenId, mTargetCell, span, null);
3927                        break;
3928                    case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3929                        mLauncher.processShortcutFromDrop(pendingInfo.componentName,
3930                                container, screenId, mTargetCell, null);
3931                        break;
3932                    default:
3933                        throw new IllegalStateException("Unknown item type: " +
3934                                pendingInfo.itemType);
3935                    }
3936                }
3937            };
3938            View finalView = pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET
3939                    ? ((PendingAddWidgetInfo) pendingInfo).boundWidget : null;
3940
3941            if (finalView instanceof AppWidgetHostView && updateWidgetSize) {
3942                AppWidgetHostView awhv = (AppWidgetHostView) finalView;
3943                AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, item.spanX,
3944                        item.spanY);
3945            }
3946
3947            int animationStyle = ANIMATE_INTO_POSITION_AND_DISAPPEAR;
3948            if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
3949                    ((PendingAddWidgetInfo) pendingInfo).info.configure != null) {
3950                animationStyle = ANIMATE_INTO_POSITION_AND_REMAIN;
3951            }
3952            animateWidgetDrop(info, cellLayout, d.dragView, onAnimationCompleteRunnable,
3953                    animationStyle, finalView, true);
3954        } else {
3955            // This is for other drag/drop cases, like dragging from All Apps
3956            View view = null;
3957
3958            switch (info.itemType) {
3959            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
3960            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3961                if (info.container == NO_ID && info instanceof AppInfo) {
3962                    // Came from all apps -- make a copy
3963                    info = new ShortcutInfo((AppInfo) info);
3964                }
3965                view = mLauncher.createShortcut(R.layout.application, cellLayout,
3966                        (ShortcutInfo) info);
3967                break;
3968            case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
3969                view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout,
3970                        (FolderInfo) info, mIconCache);
3971                break;
3972            default:
3973                throw new IllegalStateException("Unknown item type: " + info.itemType);
3974            }
3975
3976            // First we find the cell nearest to point at which the item is
3977            // dropped, without any consideration to whether there is an item there.
3978            if (touchXY != null) {
3979                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
3980                        cellLayout, mTargetCell);
3981                float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0],
3982                        mDragViewVisualCenter[1], mTargetCell);
3983                d.postAnimationRunnable = exitSpringLoadedRunnable;
3984                if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, distance,
3985                        true, d.dragView, d.postAnimationRunnable)) {
3986                    // The folder cling isn't flexible enough to be shown in non-default workspace
3987                    // positions. Also if they are creating a folder, we assume they don't need to
3988                    // see the cling.
3989                    mLauncher.markFolderClingDismissedIfNecessary();
3990                    return;
3991                }
3992                if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, distance, d,
3993                        true)) {
3994                    return;
3995                }
3996            }
3997
3998            if (touchXY != null) {
3999                // when dragging and dropping, just find the closest free spot
4000                mTargetCell = cellLayout.performReorder((int) mDragViewVisualCenter[0],
4001                        (int) mDragViewVisualCenter[1], 1, 1, 1, 1,
4002                        null, mTargetCell, null, CellLayout.MODE_ON_DROP_EXTERNAL);
4003            } else {
4004                cellLayout.findCellForSpan(mTargetCell, 1, 1);
4005            }
4006            addInScreen(view, container, screenId, mTargetCell[0], mTargetCell[1], info.spanX,
4007                    info.spanY, insertAtFirst);
4008            cellLayout.onDropChild(view);
4009            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
4010            cellLayout.getShortcutsAndWidgets().measureChild(view);
4011
4012            LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screenId,
4013                    lp.cellX, lp.cellY);
4014
4015            if (d.dragView != null) {
4016                // We wrap the animation call in the temporary set and reset of the current
4017                // cellLayout to its final transform -- this means we animate the drag view to
4018                // the correct final location.
4019                setFinalTransitionTransform(cellLayout);
4020                mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view,
4021                        exitSpringLoadedRunnable, this);
4022                resetTransitionTransform(cellLayout);
4023            }
4024        }
4025    }
4026
4027    public Bitmap createWidgetBitmap(ItemInfo widgetInfo, View layout) {
4028        int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(widgetInfo.spanX,
4029                widgetInfo.spanY, widgetInfo, false);
4030        int visibility = layout.getVisibility();
4031        layout.setVisibility(VISIBLE);
4032
4033        int width = MeasureSpec.makeMeasureSpec(unScaledSize[0], MeasureSpec.EXACTLY);
4034        int height = MeasureSpec.makeMeasureSpec(unScaledSize[1], MeasureSpec.EXACTLY);
4035        Bitmap b = Bitmap.createBitmap(unScaledSize[0], unScaledSize[1],
4036                Bitmap.Config.ARGB_8888);
4037        Canvas c = new Canvas(b);
4038
4039        layout.measure(width, height);
4040        layout.layout(0, 0, unScaledSize[0], unScaledSize[1]);
4041        layout.draw(c);
4042        c.setBitmap(null);
4043        layout.setVisibility(visibility);
4044        return b;
4045    }
4046
4047    private void getFinalPositionForDropAnimation(int[] loc, float[] scaleXY,
4048            DragView dragView, CellLayout layout, ItemInfo info, int[] targetCell,
4049            boolean external, boolean scale) {
4050        // Now we animate the dragView, (ie. the widget or shortcut preview) into its final
4051        // location and size on the home screen.
4052        int spanX = info.spanX;
4053        int spanY = info.spanY;
4054
4055        Rect r = estimateItemPosition(layout, info, targetCell[0], targetCell[1], spanX, spanY);
4056        loc[0] = r.left;
4057        loc[1] = r.top;
4058
4059        setFinalTransitionTransform(layout);
4060        float cellLayoutScale =
4061                mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(layout, loc, true);
4062        resetTransitionTransform(layout);
4063
4064        float dragViewScaleX;
4065        float dragViewScaleY;
4066        if (scale) {
4067            dragViewScaleX = (1.0f * r.width()) / dragView.getMeasuredWidth();
4068            dragViewScaleY = (1.0f * r.height()) / dragView.getMeasuredHeight();
4069        } else {
4070            dragViewScaleX = 1f;
4071            dragViewScaleY = 1f;
4072        }
4073
4074        // The animation will scale the dragView about its center, so we need to center about
4075        // the final location.
4076        loc[0] -= (dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2;
4077        loc[1] -= (dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2;
4078
4079        scaleXY[0] = dragViewScaleX * cellLayoutScale;
4080        scaleXY[1] = dragViewScaleY * cellLayoutScale;
4081    }
4082
4083    public void animateWidgetDrop(ItemInfo info, CellLayout cellLayout, DragView dragView,
4084            final Runnable onCompleteRunnable, int animationType, final View finalView,
4085            boolean external) {
4086        Rect from = new Rect();
4087        mLauncher.getDragLayer().getViewRectRelativeToSelf(dragView, from);
4088
4089        int[] finalPos = new int[2];
4090        float scaleXY[] = new float[2];
4091        boolean scalePreview = !(info instanceof PendingAddShortcutInfo);
4092        getFinalPositionForDropAnimation(finalPos, scaleXY, dragView, cellLayout, info, mTargetCell,
4093                external, scalePreview);
4094
4095        Resources res = mLauncher.getResources();
4096        final int duration = res.getInteger(R.integer.config_dropAnimMaxDuration) - 200;
4097
4098        // In the case where we've prebound the widget, we remove it from the DragLayer
4099        if (finalView instanceof AppWidgetHostView && external) {
4100            Log.d(TAG, "6557954 Animate widget drop, final view is appWidgetHostView");
4101            mLauncher.getDragLayer().removeView(finalView);
4102        }
4103        if ((animationType == ANIMATE_INTO_POSITION_AND_RESIZE || external) && finalView != null) {
4104            Bitmap crossFadeBitmap = createWidgetBitmap(info, finalView);
4105            dragView.setCrossFadeBitmap(crossFadeBitmap);
4106            dragView.crossFade((int) (duration * 0.8f));
4107        } else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET && external) {
4108            scaleXY[0] = scaleXY[1] = Math.min(scaleXY[0],  scaleXY[1]);
4109        }
4110
4111        DragLayer dragLayer = mLauncher.getDragLayer();
4112        if (animationType == CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION) {
4113            mLauncher.getDragLayer().animateViewIntoPosition(dragView, finalPos, 0f, 0.1f, 0.1f,
4114                    DragLayer.ANIMATION_END_DISAPPEAR, onCompleteRunnable, duration);
4115        } else {
4116            int endStyle;
4117            if (animationType == ANIMATE_INTO_POSITION_AND_REMAIN) {
4118                endStyle = DragLayer.ANIMATION_END_REMAIN_VISIBLE;
4119            } else {
4120                endStyle = DragLayer.ANIMATION_END_DISAPPEAR;;
4121            }
4122
4123            Runnable onComplete = new Runnable() {
4124                @Override
4125                public void run() {
4126                    if (finalView != null) {
4127                        finalView.setVisibility(VISIBLE);
4128                    }
4129                    if (onCompleteRunnable != null) {
4130                        onCompleteRunnable.run();
4131                    }
4132                }
4133            };
4134            dragLayer.animateViewIntoPosition(dragView, from.left, from.top, finalPos[0],
4135                    finalPos[1], 1, 1, 1, scaleXY[0], scaleXY[1], onComplete, endStyle,
4136                    duration, this);
4137        }
4138    }
4139
4140    public void setFinalTransitionTransform(CellLayout layout) {
4141        if (isSwitchingState()) {
4142            mCurrentScale = getScaleX();
4143            setScaleX(mNewScale);
4144            setScaleY(mNewScale);
4145        }
4146    }
4147    public void resetTransitionTransform(CellLayout layout) {
4148        if (isSwitchingState()) {
4149            setScaleX(mCurrentScale);
4150            setScaleY(mCurrentScale);
4151        }
4152    }
4153
4154    /**
4155     * Return the current {@link CellLayout}, correctly picking the destination
4156     * screen while a scroll is in progress.
4157     */
4158    public CellLayout getCurrentDropLayout() {
4159        return (CellLayout) getChildAt(getNextPage());
4160    }
4161
4162    /**
4163     * Return the current CellInfo describing our current drag; this method exists
4164     * so that Launcher can sync this object with the correct info when the activity is created/
4165     * destroyed
4166     *
4167     */
4168    public CellLayout.CellInfo getDragInfo() {
4169        return mDragInfo;
4170    }
4171
4172    public int getCurrentPageOffsetFromCustomContent() {
4173        return getNextPage() - numCustomPages();
4174    }
4175
4176    /**
4177     * Calculate the nearest cell where the given object would be dropped.
4178     *
4179     * pixelX and pixelY should be in the coordinate system of layout
4180     */
4181    private int[] findNearestArea(int pixelX, int pixelY,
4182            int spanX, int spanY, CellLayout layout, int[] recycle) {
4183        return layout.findNearestArea(
4184                pixelX, pixelY, spanX, spanY, recycle);
4185    }
4186
4187    void setup(DragController dragController) {
4188        mSpringLoadedDragController = new SpringLoadedDragController(mLauncher);
4189        mDragController = dragController;
4190
4191        // hardware layers on children are enabled on startup, but should be disabled until
4192        // needed
4193        updateChildrenLayersEnabled(false);
4194    }
4195
4196    /**
4197     * Called at the end of a drag which originated on the workspace.
4198     */
4199    public void onDropCompleted(final View target, final DragObject d,
4200            final boolean isFlingToDelete, final boolean success) {
4201        if (mDeferDropAfterUninstall) {
4202            mDeferredAction = new Runnable() {
4203                public void run() {
4204                    onDropCompleted(target, d, isFlingToDelete, success);
4205                    mDeferredAction = null;
4206                }
4207            };
4208            return;
4209        }
4210
4211        boolean beingCalledAfterUninstall = mDeferredAction != null;
4212
4213        if (success && !(beingCalledAfterUninstall && !mUninstallSuccessful)) {
4214            if (target != this && mDragInfo != null) {
4215                CellLayout parentCell = getParentCellLayoutForView(mDragInfo.cell);
4216                if (parentCell != null) {
4217                    parentCell.removeView(mDragInfo.cell);
4218                }
4219                if (mDragInfo.cell instanceof DropTarget) {
4220                    mDragController.removeDropTarget((DropTarget) mDragInfo.cell);
4221                }
4222            }
4223        } else if (mDragInfo != null) {
4224            CellLayout cellLayout;
4225            if (mLauncher.isHotseatLayout(target)) {
4226                cellLayout = mLauncher.getHotseat().getLayout();
4227            } else {
4228                cellLayout = getScreenWithId(mDragInfo.screenId);
4229            }
4230            if (cellLayout == null && LauncherAppState.isDogfoodBuild()) {
4231                throw new RuntimeException("Invalid state: cellLayout == null in "
4232                        + "Workspace#onDropCompleted. Please file a bug. ");
4233            }
4234            if (cellLayout != null) {
4235                cellLayout.onDropChild(mDragInfo.cell);
4236            }
4237        }
4238        if ((d.cancelled || (beingCalledAfterUninstall && !mUninstallSuccessful))
4239                && mDragInfo.cell != null) {
4240            mDragInfo.cell.setVisibility(VISIBLE);
4241        }
4242        mDragOutline = null;
4243        mDragInfo = null;
4244    }
4245
4246    public void deferCompleteDropAfterUninstallActivity() {
4247        mDeferDropAfterUninstall = true;
4248    }
4249
4250    /// maybe move this into a smaller part
4251    public void onUninstallActivityReturned(boolean success) {
4252        mDeferDropAfterUninstall = false;
4253        mUninstallSuccessful = success;
4254        if (mDeferredAction != null) {
4255            mDeferredAction.run();
4256        }
4257    }
4258
4259    void updateItemLocationsInDatabase(CellLayout cl) {
4260        int count = cl.getShortcutsAndWidgets().getChildCount();
4261
4262        long screenId = getIdForScreen(cl);
4263        int container = Favorites.CONTAINER_DESKTOP;
4264
4265        if (mLauncher.isHotseatLayout(cl)) {
4266            screenId = -1;
4267            container = Favorites.CONTAINER_HOTSEAT;
4268        }
4269
4270        for (int i = 0; i < count; i++) {
4271            View v = cl.getShortcutsAndWidgets().getChildAt(i);
4272            ItemInfo info = (ItemInfo) v.getTag();
4273            // Null check required as the AllApps button doesn't have an item info
4274            if (info != null && info.requiresDbUpdate) {
4275                info.requiresDbUpdate = false;
4276                LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId, info.cellX,
4277                        info.cellY, info.spanX, info.spanY);
4278            }
4279        }
4280    }
4281
4282    ArrayList<ComponentName> getUniqueComponents(boolean stripDuplicates, ArrayList<ComponentName> duplicates) {
4283        ArrayList<ComponentName> uniqueIntents = new ArrayList<ComponentName>();
4284        getUniqueIntents((CellLayout) mLauncher.getHotseat().getLayout(), uniqueIntents, duplicates, false);
4285        int count = getChildCount();
4286        for (int i = 0; i < count; i++) {
4287            CellLayout cl = (CellLayout) getChildAt(i);
4288            getUniqueIntents(cl, uniqueIntents, duplicates, false);
4289        }
4290        return uniqueIntents;
4291    }
4292
4293    void getUniqueIntents(CellLayout cl, ArrayList<ComponentName> uniqueIntents,
4294            ArrayList<ComponentName> duplicates, boolean stripDuplicates) {
4295        int count = cl.getShortcutsAndWidgets().getChildCount();
4296
4297        ArrayList<View> children = new ArrayList<View>();
4298        for (int i = 0; i < count; i++) {
4299            View v = cl.getShortcutsAndWidgets().getChildAt(i);
4300            children.add(v);
4301        }
4302
4303        for (int i = 0; i < count; i++) {
4304            View v = children.get(i);
4305            ItemInfo info = (ItemInfo) v.getTag();
4306            // Null check required as the AllApps button doesn't have an item info
4307            if (info instanceof ShortcutInfo) {
4308                ShortcutInfo si = (ShortcutInfo) info;
4309                ComponentName cn = si.intent.getComponent();
4310
4311                Uri dataUri = si.intent.getData();
4312                // If dataUri is not null / empty or if this component isn't one that would
4313                // have previously showed up in the AllApps list, then this is a widget-type
4314                // shortcut, so ignore it.
4315                if (dataUri != null && !dataUri.equals(Uri.EMPTY)) {
4316                    continue;
4317                }
4318
4319                if (!uniqueIntents.contains(cn)) {
4320                    uniqueIntents.add(cn);
4321                } else {
4322                    if (stripDuplicates) {
4323                        cl.removeViewInLayout(v);
4324                        LauncherModel.deleteItemFromDatabase(mLauncher, si);
4325                    }
4326                    if (duplicates != null) {
4327                        duplicates.add(cn);
4328                    }
4329                }
4330            }
4331            if (v instanceof FolderIcon) {
4332                FolderIcon fi = (FolderIcon) v;
4333                ArrayList<View> items = fi.getFolder().getItemsInReadingOrder();
4334                for (int j = 0; j < items.size(); j++) {
4335                    if (items.get(j).getTag() instanceof ShortcutInfo) {
4336                        ShortcutInfo si = (ShortcutInfo) items.get(j).getTag();
4337                        ComponentName cn = si.intent.getComponent();
4338
4339                        Uri dataUri = si.intent.getData();
4340                        // If dataUri is not null / empty or if this component isn't one that would
4341                        // have previously showed up in the AllApps list, then this is a widget-type
4342                        // shortcut, so ignore it.
4343                        if (dataUri != null && !dataUri.equals(Uri.EMPTY)) {
4344                            continue;
4345                        }
4346
4347                        if (!uniqueIntents.contains(cn)) {
4348                            uniqueIntents.add(cn);
4349                        }  else {
4350                            if (stripDuplicates) {
4351                                fi.getFolderInfo().remove(si);
4352                                LauncherModel.deleteItemFromDatabase(mLauncher, si);
4353                            }
4354                            if (duplicates != null) {
4355                                duplicates.add(cn);
4356                            }
4357                        }
4358                    }
4359                }
4360            }
4361        }
4362    }
4363
4364    void saveWorkspaceToDb() {
4365        saveWorkspaceScreenToDb((CellLayout) mLauncher.getHotseat().getLayout());
4366        int count = getChildCount();
4367        for (int i = 0; i < count; i++) {
4368            CellLayout cl = (CellLayout) getChildAt(i);
4369            saveWorkspaceScreenToDb(cl);
4370        }
4371    }
4372
4373    void saveWorkspaceScreenToDb(CellLayout cl) {
4374        int count = cl.getShortcutsAndWidgets().getChildCount();
4375
4376        long screenId = getIdForScreen(cl);
4377        int container = Favorites.CONTAINER_DESKTOP;
4378
4379        Hotseat hotseat = mLauncher.getHotseat();
4380        if (mLauncher.isHotseatLayout(cl)) {
4381            screenId = -1;
4382            container = Favorites.CONTAINER_HOTSEAT;
4383        }
4384
4385        for (int i = 0; i < count; i++) {
4386            View v = cl.getShortcutsAndWidgets().getChildAt(i);
4387            ItemInfo info = (ItemInfo) v.getTag();
4388            // Null check required as the AllApps button doesn't have an item info
4389            if (info != null) {
4390                int cellX = info.cellX;
4391                int cellY = info.cellY;
4392                if (container == Favorites.CONTAINER_HOTSEAT) {
4393                    cellX = hotseat.getCellXFromOrder((int) info.screenId);
4394                    cellY = hotseat.getCellYFromOrder((int) info.screenId);
4395                }
4396                LauncherModel.addItemToDatabase(mLauncher, info, container, screenId, cellX,
4397                        cellY, false);
4398            }
4399            if (v instanceof FolderIcon) {
4400                FolderIcon fi = (FolderIcon) v;
4401                fi.getFolder().addItemLocationsInDatabase();
4402            }
4403        }
4404    }
4405
4406    @Override
4407    public float getIntrinsicIconScaleFactor() {
4408        return 1f;
4409    }
4410
4411    @Override
4412    public boolean supportsFlingToDelete() {
4413        return true;
4414    }
4415
4416    @Override
4417    public boolean supportsAppInfoDropTarget() {
4418        return false;
4419    }
4420
4421    @Override
4422    public boolean supportsDeleteDropTarget() {
4423        return true;
4424    }
4425
4426    @Override
4427    public void onFlingToDelete(DragObject d, int x, int y, PointF vec) {
4428        // Do nothing
4429    }
4430
4431    @Override
4432    public void onFlingToDeleteCompleted() {
4433        // Do nothing
4434    }
4435
4436    public boolean isDropEnabled() {
4437        return true;
4438    }
4439
4440    @Override
4441    protected void onRestoreInstanceState(Parcelable state) {
4442        super.onRestoreInstanceState(state);
4443        Launcher.setScreen(mCurrentPage);
4444    }
4445
4446    @Override
4447    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
4448        // We don't dispatch restoreInstanceState to our children using this code path.
4449        // Some pages will be restored immediately as their items are bound immediately, and
4450        // others we will need to wait until after their items are bound.
4451        mSavedStates = container;
4452    }
4453
4454    public void restoreInstanceStateForChild(int child) {
4455        if (mSavedStates != null) {
4456            mRestoredPages.add(child);
4457            CellLayout cl = (CellLayout) getChildAt(child);
4458            if (cl != null) {
4459                cl.restoreInstanceState(mSavedStates);
4460            }
4461        }
4462    }
4463
4464    public void restoreInstanceStateForRemainingPages() {
4465        int count = getChildCount();
4466        for (int i = 0; i < count; i++) {
4467            if (!mRestoredPages.contains(i)) {
4468                restoreInstanceStateForChild(i);
4469            }
4470        }
4471        mRestoredPages.clear();
4472        mSavedStates = null;
4473    }
4474
4475    @Override
4476    public void scrollLeft() {
4477        if (!isSmall() && !mIsSwitchingState) {
4478            super.scrollLeft();
4479        }
4480        Folder openFolder = getOpenFolder();
4481        if (openFolder != null) {
4482            openFolder.completeDragExit();
4483        }
4484    }
4485
4486    @Override
4487    public void scrollRight() {
4488        if (!isSmall() && !mIsSwitchingState) {
4489            super.scrollRight();
4490        }
4491        Folder openFolder = getOpenFolder();
4492        if (openFolder != null) {
4493            openFolder.completeDragExit();
4494        }
4495    }
4496
4497    @Override
4498    public boolean onEnterScrollArea(int x, int y, int direction) {
4499        // Ignore the scroll area if we are dragging over the hot seat
4500        boolean isPortrait = !LauncherAppState.isScreenLandscape(getContext());
4501        if (mLauncher.getHotseat() != null && isPortrait) {
4502            Rect r = new Rect();
4503            mLauncher.getHotseat().getHitRect(r);
4504            if (r.contains(x, y)) {
4505                return false;
4506            }
4507        }
4508
4509        boolean result = false;
4510        if (!isSmall() && !mIsSwitchingState && getOpenFolder() == null) {
4511            mInScrollArea = true;
4512
4513            final int page = getNextPage() +
4514                       (direction == DragController.SCROLL_LEFT ? -1 : 1);
4515            // We always want to exit the current layout to ensure parity of enter / exit
4516            setCurrentDropLayout(null);
4517
4518            if (0 <= page && page < getChildCount()) {
4519                // Ensure that we are not dragging over to the custom content screen
4520                if (getScreenIdForPageIndex(page) == CUSTOM_CONTENT_SCREEN_ID) {
4521                    return false;
4522                }
4523
4524                CellLayout layout = (CellLayout) getChildAt(page);
4525                setCurrentDragOverlappingLayout(layout);
4526
4527                // Workspace is responsible for drawing the edge glow on adjacent pages,
4528                // so we need to redraw the workspace when this may have changed.
4529                invalidate();
4530                result = true;
4531            }
4532        }
4533        return result;
4534    }
4535
4536    @Override
4537    public boolean onExitScrollArea() {
4538        boolean result = false;
4539        if (mInScrollArea) {
4540            invalidate();
4541            CellLayout layout = getCurrentDropLayout();
4542            setCurrentDropLayout(layout);
4543            setCurrentDragOverlappingLayout(layout);
4544
4545            result = true;
4546            mInScrollArea = false;
4547        }
4548        return result;
4549    }
4550
4551    private void onResetScrollArea() {
4552        setCurrentDragOverlappingLayout(null);
4553        mInScrollArea = false;
4554    }
4555
4556    /**
4557     * Returns a specific CellLayout
4558     */
4559    CellLayout getParentCellLayoutForView(View v) {
4560        ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts();
4561        for (CellLayout layout : layouts) {
4562            if (layout.getShortcutsAndWidgets().indexOfChild(v) > -1) {
4563                return layout;
4564            }
4565        }
4566        return null;
4567    }
4568
4569    /**
4570     * Returns a list of all the CellLayouts in the workspace.
4571     */
4572    ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() {
4573        ArrayList<CellLayout> layouts = new ArrayList<CellLayout>();
4574        int screenCount = getChildCount();
4575        for (int screen = 0; screen < screenCount; screen++) {
4576            layouts.add(((CellLayout) getChildAt(screen)));
4577        }
4578        if (mLauncher.getHotseat() != null) {
4579            layouts.add(mLauncher.getHotseat().getLayout());
4580        }
4581        return layouts;
4582    }
4583
4584    /**
4585     * We should only use this to search for specific children.  Do not use this method to modify
4586     * ShortcutsAndWidgetsContainer directly. Includes ShortcutAndWidgetContainers from
4587     * the hotseat and workspace pages
4588     */
4589    ArrayList<ShortcutAndWidgetContainer> getAllShortcutAndWidgetContainers() {
4590        ArrayList<ShortcutAndWidgetContainer> childrenLayouts =
4591                new ArrayList<ShortcutAndWidgetContainer>();
4592        int screenCount = getChildCount();
4593        for (int screen = 0; screen < screenCount; screen++) {
4594            childrenLayouts.add(((CellLayout) getChildAt(screen)).getShortcutsAndWidgets());
4595        }
4596        if (mLauncher.getHotseat() != null) {
4597            childrenLayouts.add(mLauncher.getHotseat().getLayout().getShortcutsAndWidgets());
4598        }
4599        return childrenLayouts;
4600    }
4601
4602    public Folder getFolderForTag(final Object tag) {
4603        final Folder[] value = new Folder[1];
4604        mapOverShortcuts(MAP_NO_RECURSE, new ShortcutOperator() {
4605            @Override
4606            public boolean evaluate(ItemInfo info, View v, View parent) {
4607                if (v instanceof Folder) {
4608                    Folder f = (Folder) v;
4609                    if (f.getInfo() == tag && f.getInfo().opened) {
4610                        value[0] = f;
4611                        return true;
4612                    }
4613                }
4614                return false;
4615            }
4616        });
4617        return value[0];
4618    }
4619
4620    public View getViewForTag(final Object tag) {
4621        final View[] value = new View[1];
4622        mapOverShortcuts(MAP_NO_RECURSE, new ShortcutOperator() {
4623            @Override
4624            public boolean evaluate(ItemInfo info, View v, View parent) {
4625                if (v.getTag() == tag) {
4626                    value[0] = v;
4627                    return true;
4628                }
4629                return false;
4630            }
4631        });
4632        return value[0];
4633    }
4634
4635    void clearDropTargets() {
4636        mapOverShortcuts(MAP_NO_RECURSE, new ShortcutOperator() {
4637            @Override
4638            public boolean evaluate(ItemInfo info, View v, View parent) {
4639                if (v instanceof DropTarget) {
4640                    mDragController.removeDropTarget((DropTarget) v);
4641                }
4642                // not done, process all the shortcuts
4643                return false;
4644            }
4645        });
4646    }
4647
4648    // Removes ALL items that match a given package name, this is usually called when a package
4649    // has been removed and we want to remove all components (widgets, shortcuts, apps) that
4650    // belong to that package.
4651    void removeItemsByPackageName(final ArrayList<String> packages, final UserHandleCompat user) {
4652        final HashSet<String> packageNames = new HashSet<String>();
4653        packageNames.addAll(packages);
4654
4655        // Filter out all the ItemInfos that this is going to affect
4656        final HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
4657        final HashSet<ComponentName> cns = new HashSet<ComponentName>();
4658        ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
4659        for (CellLayout layoutParent : cellLayouts) {
4660            ViewGroup layout = layoutParent.getShortcutsAndWidgets();
4661            int childCount = layout.getChildCount();
4662            for (int i = 0; i < childCount; ++i) {
4663                View view = layout.getChildAt(i);
4664                infos.add((ItemInfo) view.getTag());
4665            }
4666        }
4667        LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() {
4668            @Override
4669            public boolean filterItem(ItemInfo parent, ItemInfo info,
4670                                      ComponentName cn) {
4671                if (packageNames.contains(cn.getPackageName())
4672                        && info.user.equals(user)) {
4673                    cns.add(cn);
4674                    return true;
4675                }
4676                return false;
4677            }
4678        };
4679        LauncherModel.filterItemInfos(infos, filter);
4680
4681        // Remove the affected components
4682        removeItemsByComponentName(cns, user);
4683    }
4684
4685    // Removes items that match the application info specified, when applications are removed
4686    // as a part of an update, this is called to ensure that other widgets and application
4687    // shortcuts are not removed.
4688    void removeItemsByApplicationInfo(final ArrayList<AppInfo> appInfos, UserHandleCompat user) {
4689        // Just create a hash table of all the specific components that this will affect
4690        HashSet<ComponentName> cns = new HashSet<ComponentName>();
4691        for (AppInfo info : appInfos) {
4692            cns.add(info.componentName);
4693        }
4694
4695        // Remove all the things
4696        removeItemsByComponentName(cns, user);
4697    }
4698
4699    void removeItemsByComponentName(final HashSet<ComponentName> componentNames,
4700            final UserHandleCompat user) {
4701        ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
4702        for (final CellLayout layoutParent: cellLayouts) {
4703            final ViewGroup layout = layoutParent.getShortcutsAndWidgets();
4704
4705            final HashMap<ItemInfo, View> children = new HashMap<ItemInfo, View>();
4706            for (int j = 0; j < layout.getChildCount(); j++) {
4707                final View view = layout.getChildAt(j);
4708                children.put((ItemInfo) view.getTag(), view);
4709            }
4710
4711            final ArrayList<View> childrenToRemove = new ArrayList<View>();
4712            final HashMap<FolderInfo, ArrayList<ShortcutInfo>> folderAppsToRemove =
4713                    new HashMap<FolderInfo, ArrayList<ShortcutInfo>>();
4714            LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() {
4715                @Override
4716                public boolean filterItem(ItemInfo parent, ItemInfo info,
4717                                          ComponentName cn) {
4718                    if (parent instanceof FolderInfo) {
4719                        if (componentNames.contains(cn) && info.user.equals(user)) {
4720                            FolderInfo folder = (FolderInfo) parent;
4721                            ArrayList<ShortcutInfo> appsToRemove;
4722                            if (folderAppsToRemove.containsKey(folder)) {
4723                                appsToRemove = folderAppsToRemove.get(folder);
4724                            } else {
4725                                appsToRemove = new ArrayList<ShortcutInfo>();
4726                                folderAppsToRemove.put(folder, appsToRemove);
4727                            }
4728                            appsToRemove.add((ShortcutInfo) info);
4729                            return true;
4730                        }
4731                    } else {
4732                        if (componentNames.contains(cn) && info.user.equals(user)) {
4733                            childrenToRemove.add(children.get(info));
4734                            return true;
4735                        }
4736                    }
4737                    return false;
4738                }
4739            };
4740            LauncherModel.filterItemInfos(children.keySet(), filter);
4741
4742            // Remove all the apps from their folders
4743            for (FolderInfo folder : folderAppsToRemove.keySet()) {
4744                ArrayList<ShortcutInfo> appsToRemove = folderAppsToRemove.get(folder);
4745                for (ShortcutInfo info : appsToRemove) {
4746                    folder.remove(info);
4747                }
4748            }
4749
4750            // Remove all the other children
4751            for (View child : childrenToRemove) {
4752                // Note: We can not remove the view directly from CellLayoutChildren as this
4753                // does not re-mark the spaces as unoccupied.
4754                layoutParent.removeViewInLayout(child);
4755                if (child instanceof DropTarget) {
4756                    mDragController.removeDropTarget((DropTarget) child);
4757                }
4758            }
4759
4760            if (childrenToRemove.size() > 0) {
4761                layout.requestLayout();
4762                layout.invalidate();
4763            }
4764        }
4765
4766        // Strip all the empty screens
4767        stripEmptyScreens();
4768    }
4769
4770    private void updateShortcut(HashMap<ComponentName, AppInfo> appsMap, ItemInfo info,
4771                                View child) {
4772        ComponentName cn = info.getIntent().getComponent();
4773        if (info.getRestoredIntent() != null) {
4774            cn = info.getRestoredIntent().getComponent();
4775        }
4776        if (cn != null) {
4777            AppInfo appInfo = appsMap.get(cn);
4778            if ((appInfo != null) && LauncherModel.isShortcutInfoUpdateable(info)) {
4779                ShortcutInfo shortcutInfo = (ShortcutInfo) info;
4780                BubbleTextView shortcut = (BubbleTextView) child;
4781                shortcutInfo.restore();
4782                shortcutInfo.updateIcon(mIconCache);
4783                shortcutInfo.title = appInfo.title.toString();
4784                shortcut.applyFromShortcutInfo(shortcutInfo, mIconCache);
4785            }
4786        }
4787    }
4788
4789    interface ShortcutOperator {
4790        /**
4791         * Process the next shortcut, possibly with side-effect on {@link ShortcutOperator#value}.
4792         *
4793         * @param info info for the shortcut
4794         * @param view view for the shortcut
4795         * @param parent containing folder, or null
4796         * @return true if done, false to continue the map
4797         */
4798        public boolean evaluate(ItemInfo info, View view, View parent);
4799    }
4800
4801    /**
4802     * Map the operator over the shortcuts, return the first-non-null value.
4803     *
4804     * @param recurse true: iterate over folder children. false: op get the folders themselves.
4805     * @param op the operator to map over the shortcuts
4806     */
4807    void mapOverShortcuts(boolean recurse, ShortcutOperator op) {
4808        ArrayList<ShortcutAndWidgetContainer> containers = getAllShortcutAndWidgetContainers();
4809        final int containerCount = containers.size();
4810        for (int containerIdx = 0; containerIdx < containerCount; containerIdx++) {
4811            ShortcutAndWidgetContainer container = containers.get(containerIdx);
4812            // map over all the shortcuts on the workspace
4813            final int itemCount = container.getChildCount();
4814            for (int itemIdx = 0; itemIdx < itemCount; itemIdx++) {
4815                View item = container.getChildAt(itemIdx);
4816                ItemInfo info = (ItemInfo) item.getTag();
4817                if (recurse && info instanceof FolderInfo && item instanceof FolderIcon) {
4818                    FolderIcon folder = (FolderIcon) item;
4819                    ArrayList<View> folderChildren = folder.getFolder().getItemsInReadingOrder();
4820                    // map over all the children in the folder
4821                    final int childCount = folderChildren.size();
4822                    for (int childIdx = 0; childIdx < childCount; childIdx++) {
4823                        View child = folderChildren.get(childIdx);
4824                        info = (ItemInfo) child.getTag();
4825                        if (op.evaluate(info, child, folder)) {
4826                            return;
4827                        }
4828                    }
4829                } else {
4830                    if (op.evaluate(info, item, null)) {
4831                        return;
4832                    }
4833                }
4834            }
4835        }
4836    }
4837
4838    void updateShortcuts(ArrayList<AppInfo> apps) {
4839        // Create a map of the apps to test against
4840        final HashMap<ComponentName, AppInfo> appsMap = new HashMap<ComponentName, AppInfo>();
4841        for (AppInfo ai : apps) {
4842            appsMap.put(ai.componentName, ai);
4843        }
4844
4845        mapOverShortcuts(MAP_RECURSE, new ShortcutOperator() {
4846            @Override
4847            public boolean evaluate(ItemInfo info, View v, View parent) {
4848                if (info instanceof ShortcutInfo) {
4849                    updateShortcut(appsMap, info, v);
4850                    if (parent != null) {
4851                        parent.invalidate();
4852                    }
4853                }
4854                // process all the shortcuts
4855                return false;
4856            }
4857        });
4858    }
4859
4860    public void removeAbandonedPromise(BubbleTextView abandonedIcon, UserHandleCompat user) {
4861        if (abandonedIcon.getTag() != null && abandonedIcon.getTag() instanceof ShortcutInfo) {
4862            final ShortcutInfo shortcut = (ShortcutInfo) abandonedIcon.getTag();
4863            if (shortcut.isAbandoned()) {
4864                HashSet<ComponentName> cns = new HashSet<ComponentName>(1);
4865                cns.add(shortcut.getRestoredIntent().getComponent());
4866                LauncherModel.deleteItemFromDatabase(mLauncher, shortcut);
4867                removeItemsByComponentName(cns, user);
4868            }
4869        }
4870    }
4871
4872    public void updatePackageState(final String pkgName, final int state) {
4873        mapOverShortcuts(MAP_RECURSE, new ShortcutOperator() {
4874            @Override
4875            public boolean evaluate(ItemInfo info, View v, View parent) {
4876                if (info instanceof ShortcutInfo
4877                        && ((ShortcutInfo) info).isPromiseFor(pkgName)
4878                        && v instanceof BubbleTextView) {
4879                    ((ShortcutInfo) info).setState(state);
4880                    ((BubbleTextView)v).applyState();
4881                }
4882                // process all the shortcuts
4883                return false;
4884            }
4885        });
4886    }
4887
4888    private void moveToScreen(int page, boolean animate) {
4889        if (!isSmall()) {
4890            if (animate) {
4891                snapToPage(page);
4892            } else {
4893                setCurrentPage(page);
4894            }
4895        }
4896        View child = getChildAt(page);
4897        if (child != null) {
4898            child.requestFocus();
4899        }
4900    }
4901
4902    void moveToDefaultScreen(boolean animate) {
4903        moveToScreen(mDefaultPage, animate);
4904    }
4905
4906    void moveToCustomContentScreen(boolean animate) {
4907        if (hasCustomContent()) {
4908            int ccIndex = getPageIndexForScreenId(CUSTOM_CONTENT_SCREEN_ID);
4909            if (animate) {
4910                snapToPage(ccIndex);
4911            } else {
4912                setCurrentPage(ccIndex);
4913            }
4914            View child = getChildAt(ccIndex);
4915            if (child != null) {
4916                child.requestFocus();
4917            }
4918         }
4919        exitWidgetResizeMode();
4920    }
4921
4922    @Override
4923    protected PageIndicator.PageMarkerResources getPageIndicatorMarker(int pageIndex) {
4924        long screenId = getScreenIdForPageIndex(pageIndex);
4925        if (screenId == EXTRA_EMPTY_SCREEN_ID) {
4926            int count = mScreenOrder.size() - numCustomPages();
4927            if (count > 1) {
4928                return new PageIndicator.PageMarkerResources(R.drawable.ic_pageindicator_current,
4929                        R.drawable.ic_pageindicator_add);
4930            }
4931        }
4932
4933        return super.getPageIndicatorMarker(pageIndex);
4934    }
4935
4936    @Override
4937    public void syncPages() {
4938    }
4939
4940    @Override
4941    public void syncPageItems(int page, boolean immediate) {
4942    }
4943
4944    protected String getPageIndicatorDescription() {
4945        String settings = getResources().getString(R.string.settings_button_text);
4946        return getCurrentPageDescription() + ", " + settings;
4947    }
4948
4949    protected String getCurrentPageDescription() {
4950        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
4951        int delta = numCustomPages();
4952        if (hasCustomContent() && getNextPage() == 0) {
4953            return mCustomContentDescription;
4954        }
4955        return String.format(getContext().getString(R.string.workspace_scroll_format),
4956                page + 1 - delta, getChildCount() - delta);
4957    }
4958
4959    public void getLocationInDragLayer(int[] loc) {
4960        mLauncher.getDragLayer().getLocationInDragLayer(this, loc);
4961    }
4962}
4963