Workspace.java revision a64718061a46e3982e35547e675244642bb82860
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.launcher2;
18
19import android.animation.Animator;
20import android.animation.AnimatorListenerAdapter;
21import android.animation.AnimatorSet;
22import android.animation.ObjectAnimator;
23import android.animation.TimeInterpolator;
24import android.animation.ValueAnimator;
25import android.animation.Animator.AnimatorListener;
26import android.animation.ValueAnimator.AnimatorUpdateListener;
27import android.app.AlertDialog;
28import android.app.WallpaperManager;
29import android.appwidget.AppWidgetManager;
30import android.appwidget.AppWidgetProviderInfo;
31import android.content.ClipData;
32import android.content.ClipDescription;
33import android.content.ComponentName;
34import android.content.Context;
35import android.content.Intent;
36import android.content.res.Resources;
37import android.content.res.TypedArray;
38import android.graphics.Bitmap;
39import android.graphics.Camera;
40import android.graphics.Canvas;
41import android.graphics.Matrix;
42import android.graphics.Paint;
43import android.graphics.PorterDuff;
44import android.graphics.Rect;
45import android.graphics.RectF;
46import android.graphics.Region.Op;
47import android.graphics.drawable.Drawable;
48import android.os.IBinder;
49import android.os.Parcelable;
50import android.util.AttributeSet;
51import android.util.DisplayMetrics;
52import android.util.Log;
53import android.util.Pair;
54import android.view.Display;
55import android.view.DragEvent;
56import android.view.MotionEvent;
57import android.view.View;
58import android.view.ViewGroup;
59import android.view.animation.DecelerateInterpolator;
60import android.widget.ImageView;
61import android.widget.TextView;
62import android.widget.Toast;
63
64import com.android.launcher.R;
65import com.android.launcher2.FolderIcon.FolderRingAnimator;
66import com.android.launcher2.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
67
68import java.util.ArrayList;
69import java.util.HashSet;
70import java.util.List;
71
72/**
73 * The workspace is a wide area with a wallpaper and a finite number of pages.
74 * Each page contains a number of icons, folders or widgets the user can
75 * interact with. A workspace is meant to be used with a fixed width only.
76 */
77public class Workspace extends SmoothPagedView
78        implements DropTarget, DragSource, DragScroller, View.OnTouchListener,
79        DragController.DragListener {
80    @SuppressWarnings({"UnusedDeclaration"})
81    private static final String TAG = "Launcher.Workspace";
82
83    // Y rotation to apply to the workspace screens
84    private static final float WORKSPACE_ROTATION = 12.5f;
85    private static final float WORKSPACE_OVERSCROLL_ROTATION = 24f;
86    private static float CAMERA_DISTANCE = 6500;
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    private static final int BACKGROUND_FADE_OUT_DURATION = 350;
93    private static final int ADJACENT_SCREEN_DROP_DURATION = 300;
94
95    // These animators are used to fade the children's outlines
96    private ObjectAnimator mChildrenOutlineFadeInAnimation;
97    private ObjectAnimator mChildrenOutlineFadeOutAnimation;
98    private float mChildrenOutlineAlpha = 0;
99
100    // These properties refer to the background protection gradient used for AllApps and Customize
101    private ValueAnimator mBackgroundFadeInAnimation;
102    private ValueAnimator mBackgroundFadeOutAnimation;
103    private Drawable mBackground;
104    boolean mDrawBackground = true;
105    private float mBackgroundAlpha = 0;
106    private float mOverScrollMaxBackgroundAlpha = 0.0f;
107    private int mOverScrollPageIndex = -1;
108    private AnimatorSet mDividerAnimator;
109
110    private float mWallpaperScrollRatio = 1.0f;
111
112    private final WallpaperManager mWallpaperManager;
113    private IBinder mWindowToken;
114    private static final float WALLPAPER_SCREENS_SPAN = 1.5f;
115
116    private int mDefaultPage;
117
118    /**
119     * CellInfo for the cell that is currently being dragged
120     */
121    private CellLayout.CellInfo mDragInfo;
122
123    /**
124     * Target drop area calculated during last acceptDrop call.
125     */
126    private int[] mTargetCell = new int[2];
127
128    /**
129     * The CellLayout that is currently being dragged over
130     */
131    private CellLayout mDragTargetLayout = null;
132
133    private Launcher mLauncher;
134    private IconCache mIconCache;
135    private DragController mDragController;
136
137    // These are temporary variables to prevent having to allocate a new object just to
138    // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
139    private int[] mTempCell = new int[2];
140    private int[] mTempEstimate = new int[2];
141    private float[] mDragViewVisualCenter = new float[2];
142    private float[] mTempDragCoordinates = new float[2];
143    private float[] mTempCellLayoutCenterCoordinates = new float[2];
144    private float[] mTempDragBottomRightCoordinates = new float[2];
145    private Matrix mTempInverseMatrix = new Matrix();
146
147    private SpringLoadedDragController mSpringLoadedDragController;
148    private float mSpringLoadedShrinkFactor;
149
150    private static final int DEFAULT_CELL_COUNT_X = 4;
151    private static final int DEFAULT_CELL_COUNT_Y = 4;
152
153    // State variable that indicates whether the pages are small (ie when you're
154    // in all apps or customize mode)
155
156    enum State { NORMAL, SPRING_LOADED, SMALL };
157    private State mState = State.NORMAL;
158    private boolean mIsSwitchingState = false;
159    private boolean mSwitchStateAfterFirstLayout = false;
160    private State mStateAfterFirstLayout;
161
162    private AnimatorSet mAnimator;
163    private AnimatorListener mChangeStateAnimationListener;
164
165    boolean mAnimatingViewIntoPlace = false;
166    boolean mIsDragOccuring = false;
167    boolean mChildrenLayersEnabled = true;
168
169    /** Is the user is dragging an item near the edge of a page? */
170    private boolean mInScrollArea = false;
171
172    private final HolographicOutlineHelper mOutlineHelper = new HolographicOutlineHelper();
173    private Bitmap mDragOutline = null;
174    private final Rect mTempRect = new Rect();
175    private final int[] mTempXY = new int[2];
176    private int mDragViewMultiplyColor;
177
178    // Paint used to draw external drop outline
179    private final Paint mExternalDragOutlinePaint = new Paint();
180
181    // Camera and Matrix used to determine the final position of a neighboring CellLayout
182    private final Matrix mMatrix = new Matrix();
183    private final Camera mCamera = new Camera();
184    private final float mTempFloat2[] = new float[2];
185
186    enum WallpaperVerticalOffset { TOP, MIDDLE, BOTTOM };
187    int mWallpaperWidth;
188    int mWallpaperHeight;
189    WallpaperOffsetInterpolator mWallpaperOffset;
190    boolean mUpdateWallpaperOffsetImmediately = false;
191    private Runnable mDelayedResizeRunnable;
192    private int mDisplayWidth;
193    private int mDisplayHeight;
194    private boolean mIsStaticWallpaper;
195    private int mWallpaperTravelWidth;
196
197    // Variables relating to the creation of user folders by hovering shortcuts over shortcuts
198    private static final int FOLDER_CREATION_TIMEOUT = 250;
199    private final Alarm mFolderCreationAlarm = new Alarm();
200    private FolderRingAnimator mDragFolderRingAnimator = null;
201    private View mLastDragOverView = null;
202    private boolean mCreateUserFolderOnDrop = false;
203
204    // Variables relating to touch disambiguation (scrolling workspace vs. scrolling a widget)
205    private float mXDown;
206    private float mYDown;
207    final static float START_DAMPING_TOUCH_SLOP_ANGLE = (float) Math.PI / 6;
208    final static float MAX_SWIPE_ANGLE = (float) Math.PI / 3;
209    final static float TOUCH_SLOP_DAMPING_FACTOR = 4;
210
211    // These variables are used for storing the initial and final values during workspace animations
212    private int mSavedScrollX;
213    private float mSavedRotationY;
214    private float mSavedTranslationX;
215    private float mCurrentScaleX;
216    private float mCurrentScaleY;
217    private float mCurrentRotationY;
218    private float mCurrentTranslationX;
219    private float mCurrentTranslationY;
220    private float[] mOldTranslationXs;
221    private float[] mOldTranslationYs;
222    private float[] mOldScaleXs;
223    private float[] mOldScaleYs;
224    private float[] mOldBackgroundAlphas;
225    private float[] mOldBackgroundAlphaMultipliers;
226    private float[] mOldAlphas;
227    private float[] mOldRotationYs;
228    private float[] mNewTranslationXs;
229    private float[] mNewTranslationYs;
230    private float[] mNewScaleXs;
231    private float[] mNewScaleYs;
232    private float[] mNewBackgroundAlphas;
233    private float[] mNewBackgroundAlphaMultipliers;
234    private float[] mNewAlphas;
235    private float[] mNewRotationYs;
236    private float mTransitionProgress;
237
238    /**
239     * Used to inflate the Workspace from XML.
240     *
241     * @param context The application's context.
242     * @param attrs The attributes set containing the Workspace's customization values.
243     */
244    public Workspace(Context context, AttributeSet attrs) {
245        this(context, attrs, 0);
246    }
247
248    /**
249     * Used to inflate the Workspace from XML.
250     *
251     * @param context The application's context.
252     * @param attrs The attributes set containing the Workspace's customization values.
253     * @param defStyle Unused.
254     */
255    public Workspace(Context context, AttributeSet attrs, int defStyle) {
256        super(context, attrs, defStyle);
257        mContentIsRefreshable = false;
258
259        // With workspace, data is available straight from the get-go
260        setDataIsReady();
261
262        mFadeInAdjacentScreens =
263            getResources().getBoolean(R.bool.config_workspaceFadeAdjacentScreens);
264        mWallpaperManager = WallpaperManager.getInstance(context);
265
266        int cellCountX = DEFAULT_CELL_COUNT_X;
267        int cellCountY = DEFAULT_CELL_COUNT_Y;
268
269        TypedArray a = context.obtainStyledAttributes(attrs,
270                R.styleable.Workspace, defStyle, 0);
271
272        final Resources res = context.getResources();
273        if (LauncherApplication.isScreenLarge()) {
274            // Determine number of rows/columns dynamically
275            // TODO: This code currently fails on tablets with an aspect ratio < 1.3.
276            // Around that ratio we should make cells the same size in portrait and
277            // landscape
278            TypedArray actionBarSizeTypedArray =
279                context.obtainStyledAttributes(new int[] { android.R.attr.actionBarSize });
280            final float actionBarHeight = actionBarSizeTypedArray.getDimension(0, 0f);
281            final float systemBarHeight = res.getDimension(R.dimen.status_bar_height);
282            final float smallestScreenDim = res.getConfiguration().smallestScreenWidthDp;
283
284            cellCountX = 1;
285            while (CellLayout.widthInPortrait(res, cellCountX + 1) <= smallestScreenDim) {
286                cellCountX++;
287            }
288
289            cellCountY = 1;
290            while (actionBarHeight + CellLayout.heightInLandscape(res, cellCountY + 1)
291                <= smallestScreenDim - systemBarHeight) {
292                cellCountY++;
293            }
294        }
295
296        mSpringLoadedShrinkFactor =
297            res.getInteger(R.integer.config_workspaceSpringLoadShrinkPercentage) / 100.0f;
298        mDragViewMultiplyColor = res.getColor(R.color.drag_view_multiply_color);
299
300        // if the value is manually specified, use that instead
301        cellCountX = a.getInt(R.styleable.Workspace_cellCountX, cellCountX);
302        cellCountY = a.getInt(R.styleable.Workspace_cellCountY, cellCountY);
303        mDefaultPage = a.getInt(R.styleable.Workspace_defaultScreen, 1);
304        a.recycle();
305
306        LauncherModel.updateWorkspaceLayoutCells(cellCountX, cellCountY);
307        setHapticFeedbackEnabled(false);
308
309        mLauncher = (Launcher) context;
310        initWorkspace();
311
312        // Disable multitouch across the workspace/all apps/customize tray
313        setMotionEventSplittingEnabled(true);
314    }
315
316    public void onDragStart(DragSource source, Object info, int dragAction) {
317        mIsDragOccuring = true;
318        updateChildrenLayersEnabled();
319        mLauncher.lockScreenOrientationOnLargeUI();
320    }
321
322    public void onDragEnd() {
323        mIsDragOccuring = false;
324        updateChildrenLayersEnabled();
325        mLauncher.unlockScreenOrientationOnLargeUI();
326    }
327
328    /**
329     * Initializes various states for this workspace.
330     */
331    protected void initWorkspace() {
332        Context context = getContext();
333        mCurrentPage = mDefaultPage;
334        Launcher.setScreen(mCurrentPage);
335        LauncherApplication app = (LauncherApplication)context.getApplicationContext();
336        mIconCache = app.getIconCache();
337        mExternalDragOutlinePaint.setAntiAlias(true);
338        setWillNotDraw(false);
339        setChildrenDrawnWithCacheEnabled(true);
340
341        try {
342            final Resources res = getResources();
343            mBackground = res.getDrawable(R.drawable.apps_customize_bg);
344        } catch (Resources.NotFoundException e) {
345            // In this case, we will skip drawing background protection
346        }
347
348        mChangeStateAnimationListener = new AnimatorListenerAdapter() {
349            @Override
350            public void onAnimationStart(Animator animation) {
351                mIsSwitchingState = true;
352            }
353
354            @Override
355            public void onAnimationEnd(Animator animation) {
356                mIsSwitchingState = false;
357                mWallpaperOffset.setOverrideHorizontalCatchupConstant(false);
358                mAnimator = null;
359                updateChildrenLayersEnabled();
360            }
361        };
362
363        mSnapVelocity = 600;
364        mWallpaperOffset = new WallpaperOffsetInterpolator();
365        Display display = mLauncher.getWindowManager().getDefaultDisplay();
366        mDisplayWidth = display.getWidth();
367        mDisplayHeight = display.getHeight();
368        mWallpaperTravelWidth = (int) (mDisplayWidth *
369                wallpaperTravelToScreenWidthRatio(mDisplayWidth, mDisplayHeight));
370    }
371
372    @Override
373    protected int getScrollMode() {
374        return SmoothPagedView.X_LARGE_MODE;
375    }
376
377    @Override
378    protected void onViewAdded(View child) {
379        super.onViewAdded(child);
380        if (!(child instanceof CellLayout)) {
381            throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
382        }
383        CellLayout cl = ((CellLayout) child);
384        cl.setOnInterceptTouchListener(this);
385        cl.setClickable(true);
386        cl.enableHardwareLayers();
387    }
388
389    /**
390     * @return The open folder on the current screen, or null if there is none
391     */
392    Folder getOpenFolder() {
393        DragLayer dragLayer = mLauncher.getDragLayer();
394        int count = dragLayer.getChildCount();
395        for (int i = 0; i < count; i++) {
396            View child = dragLayer.getChildAt(i);
397            if (child instanceof Folder) {
398                Folder folder = (Folder) child;
399                if (folder.getInfo().opened)
400                    return folder;
401            }
402        }
403        return null;
404    }
405
406    boolean isTouchActive() {
407        return mTouchState != TOUCH_STATE_REST;
408    }
409
410    /**
411     * Adds the specified child in the specified screen. The position and dimension of
412     * the child are defined by x, y, spanX and spanY.
413     *
414     * @param child The child to add in one of the workspace's screens.
415     * @param screen The screen in which to add the child.
416     * @param x The X position of the child in the screen's grid.
417     * @param y The Y position of the child in the screen's grid.
418     * @param spanX The number of cells spanned horizontally by the child.
419     * @param spanY The number of cells spanned vertically by the child.
420     */
421    void addInScreen(View child, long container, int screen, int x, int y, int spanX, int spanY) {
422        addInScreen(child, container, screen, x, y, spanX, spanY, false);
423    }
424
425    /**
426     * Adds the specified child in the specified screen. The position and dimension of
427     * the child are defined by x, y, spanX and spanY.
428     *
429     * @param child The child to add in one of the workspace's screens.
430     * @param screen The screen in which to add the child.
431     * @param x The X position of the child in the screen's grid.
432     * @param y The Y position of the child in the screen's grid.
433     * @param spanX The number of cells spanned horizontally by the child.
434     * @param spanY The number of cells spanned vertically by the child.
435     * @param insert When true, the child is inserted at the beginning of the children list.
436     */
437    void addInScreen(View child, long container, int screen, int x, int y, int spanX, int spanY,
438            boolean insert) {
439        if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
440            if (screen < 0 || screen >= getChildCount()) {
441                Log.e(TAG, "The screen must be >= 0 and < " + getChildCount()
442                    + " (was " + screen + "); skipping child");
443                return;
444            }
445        }
446
447        final CellLayout layout;
448        if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
449            layout = mLauncher.getHotseat().getLayout();
450            child.setOnKeyListener(null);
451
452            // Hide folder title in the hotseat
453            if (child instanceof FolderIcon) {
454                ((FolderIcon) child).setTextVisible(false);
455            }
456
457            if (screen < 0) {
458                screen = mLauncher.getHotseat().getOrderInHotseat(x, y);
459            } else {
460                // Note: We do this to ensure that the hotseat is always laid out in the orientation
461                // of the hotseat in order regardless of which orientation they were added
462                x = mLauncher.getHotseat().getCellXFromOrder(screen);
463                y = mLauncher.getHotseat().getCellYFromOrder(screen);
464            }
465        } else {
466            // Show folder title if not in the hotseat
467            if (child instanceof FolderIcon) {
468                ((FolderIcon) child).setTextVisible(true);
469            }
470
471            layout = (CellLayout) getChildAt(screen);
472            child.setOnKeyListener(new BubbleTextViewKeyEventListener());
473        }
474
475        CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
476        if (lp == null) {
477            lp = new CellLayout.LayoutParams(x, y, spanX, spanY);
478        } else {
479            lp.cellX = x;
480            lp.cellY = y;
481            lp.cellHSpan = spanX;
482            lp.cellVSpan = spanY;
483        }
484
485        if (spanX < 0 && spanY < 0) {
486            lp.isLockedToGrid = false;
487        }
488
489        // Get the canonical child id to uniquely represent this view in this screen
490        int childId = LauncherModel.getCellLayoutChildId(container, screen, x, y, spanX, spanY);
491        boolean markCellsAsOccupied = !(child instanceof Folder);
492        if (!layout.addViewToCellLayout(child, insert ? 0 : -1, childId, lp, markCellsAsOccupied)) {
493            // TODO: This branch occurs when the workspace is adding views
494            // outside of the defined grid
495            // maybe we should be deleting these items from the LauncherModel?
496            Log.w(TAG, "Failed to add to item at (" + lp.cellX + "," + lp.cellY + ") to CellLayout");
497        }
498
499        if (!(child instanceof Folder)) {
500            child.setHapticFeedbackEnabled(false);
501            child.setOnLongClickListener(mLongClickListener);
502        }
503        if (child instanceof DropTarget) {
504            mDragController.addDropTarget((DropTarget) child);
505        }
506    }
507
508    /**
509     * Check if the point (x, y) hits a given page.
510     */
511    private boolean hitsPage(int index, float x, float y) {
512        final View page = getChildAt(index);
513        if (page != null) {
514            float[] localXY = { x, y };
515            mapPointFromSelfToChild(page, localXY);
516            return (localXY[0] >= 0 && localXY[0] < page.getWidth()
517                    && localXY[1] >= 0 && localXY[1] < page.getHeight());
518        }
519        return false;
520    }
521
522    @Override
523    protected boolean hitsPreviousPage(float x, float y) {
524        // mNextPage is set to INVALID_PAGE whenever we are stationary.
525        // Calculating "next page" this way ensures that you scroll to whatever page you tap on
526        final int current = (mNextPage == INVALID_PAGE) ? mCurrentPage : mNextPage;
527
528        // Only allow tap to next page on large devices, where there's significant margin outside
529        // the active workspace
530        return LauncherApplication.isScreenLarge() && hitsPage(current - 1, x, y);
531    }
532
533    @Override
534    protected boolean hitsNextPage(float x, float y) {
535        // mNextPage is set to INVALID_PAGE whenever we are stationary.
536        // Calculating "next page" this way ensures that you scroll to whatever page you tap on
537        final int current = (mNextPage == INVALID_PAGE) ? mCurrentPage : mNextPage;
538
539        // Only allow tap to next page on large devices, where there's significant margin outside
540        // the active workspace
541        return LauncherApplication.isScreenLarge() && hitsPage(current + 1, x, y);
542    }
543
544    /**
545     * Called directly from a CellLayout (not by the framework), after we've been added as a
546     * listener via setOnInterceptTouchEventListener(). This allows us to tell the CellLayout
547     * that it should intercept touch events, which is not something that is normally supported.
548     */
549    @Override
550    public boolean onTouch(View v, MotionEvent event) {
551        return (isSmall() || mIsSwitchingState);
552    }
553
554    public boolean isSwitchingState() {
555        return mIsSwitchingState;
556    }
557
558    protected void onWindowVisibilityChanged (int visibility) {
559        mLauncher.onWindowVisibilityChanged(visibility);
560    }
561
562    @Override
563    public boolean dispatchUnhandledMove(View focused, int direction) {
564        if (isSmall() || mIsSwitchingState) {
565            // when the home screens are shrunken, shouldn't allow side-scrolling
566            return false;
567        }
568        return super.dispatchUnhandledMove(focused, direction);
569    }
570
571    @Override
572    public boolean onInterceptTouchEvent(MotionEvent ev) {
573        switch (ev.getAction() & MotionEvent.ACTION_MASK) {
574        case MotionEvent.ACTION_DOWN:
575            mXDown = ev.getX();
576            mYDown = ev.getY();
577            break;
578        case MotionEvent.ACTION_POINTER_UP:
579        case MotionEvent.ACTION_UP:
580            if (mTouchState == TOUCH_STATE_REST) {
581                final CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage);
582                if (!currentPage.lastDownOnOccupiedCell()) {
583                    onWallpaperTap(ev);
584                }
585            }
586        }
587        return super.onInterceptTouchEvent(ev);
588    }
589
590    @Override
591    protected void determineScrollingStart(MotionEvent ev) {
592        if (!isSmall() && !mIsSwitchingState) {
593            float deltaX = Math.abs(ev.getX() - mXDown);
594            float deltaY = Math.abs(ev.getY() - mYDown);
595
596            if (Float.compare(deltaX, 0f) == 0) return;
597
598            float slope = deltaY / deltaX;
599            float theta = (float) Math.atan(slope);
600
601            if (deltaX > mTouchSlop || deltaY > mTouchSlop) {
602                cancelCurrentPageLongPress();
603            }
604
605            if (theta > MAX_SWIPE_ANGLE) {
606                // Above MAX_SWIPE_ANGLE, we don't want to ever start scrolling the workspace
607                return;
608            } else if (theta > START_DAMPING_TOUCH_SLOP_ANGLE) {
609                // Above START_DAMPING_TOUCH_SLOP_ANGLE and below MAX_SWIPE_ANGLE, we want to
610                // increase the touch slop to make it harder to begin scrolling the workspace. This
611                // results in vertically scrolling widgets to more easily. The higher the angle, the
612                // more we increase touch slop.
613                theta -= START_DAMPING_TOUCH_SLOP_ANGLE;
614                float extraRatio = (float)
615                        Math.sqrt((theta / (MAX_SWIPE_ANGLE - START_DAMPING_TOUCH_SLOP_ANGLE)));
616                super.determineScrollingStart(ev, 1 + TOUCH_SLOP_DAMPING_FACTOR * extraRatio);
617            } else {
618                // Below START_DAMPING_TOUCH_SLOP_ANGLE, we don't do anything special
619                super.determineScrollingStart(ev);
620            }
621        }
622    }
623
624    @Override
625    protected boolean isScrollingIndicatorEnabled() {
626        return mState != State.SPRING_LOADED;
627    }
628
629    protected void onPageBeginMoving() {
630        super.onPageBeginMoving();
631        mIsStaticWallpaper = mWallpaperManager.getWallpaperInfo() == null;
632
633        if (isHardwareAccelerated()) {
634            updateChildrenLayersEnabled();
635        } else {
636            if (mNextPage != INVALID_PAGE) {
637                // we're snapping to a particular screen
638                enableChildrenCache(mCurrentPage, mNextPage);
639            } else {
640                // this is when user is actively dragging a particular screen, they might
641                // swipe it either left or right (but we won't advance by more than one screen)
642                enableChildrenCache(mCurrentPage - 1, mCurrentPage + 1);
643            }
644        }
645
646        // Only show page outlines as we pan if we are on large screen
647        if (LauncherApplication.isScreenLarge()) {
648            showOutlines();
649        }
650    }
651
652    protected void onPageEndMoving() {
653        super.onPageEndMoving();
654
655        if (isHardwareAccelerated()) {
656            updateChildrenLayersEnabled();
657        } else {
658            clearChildrenCache();
659        }
660
661        // Hide the outlines, as long as we're not dragging
662        if (!mDragController.dragging()) {
663            // Only hide page outlines as we pan if we are on large screen
664            if (LauncherApplication.isScreenLarge()) {
665                hideOutlines();
666            }
667        }
668        mOverScrollMaxBackgroundAlpha = 0.0f;
669        mOverScrollPageIndex = -1;
670
671        if (mDelayedResizeRunnable != null) {
672            mDelayedResizeRunnable.run();
673            mDelayedResizeRunnable = null;
674        }
675    }
676
677    @Override
678    protected void notifyPageSwitchListener() {
679        super.notifyPageSwitchListener();
680        Launcher.setScreen(mCurrentPage);
681    };
682
683    // As a ratio of screen height, the total distance we want the parallax effect to span
684    // vertically
685    private float wallpaperTravelToScreenHeightRatio(int width, int height) {
686        return 1.1f;
687    }
688
689    // As a ratio of screen height, the total distance we want the parallax effect to span
690    // horizontally
691    private float wallpaperTravelToScreenWidthRatio(int width, int height) {
692        float aspectRatio = width / (float) height;
693
694        // At an aspect ratio of 16/10, the wallpaper parallax effect should span 1.5 * screen width
695        // At an aspect ratio of 10/16, the wallpaper parallax effect should span 1.2 * screen width
696        // We will use these two data points to extrapolate how much the wallpaper parallax effect
697        // to span (ie travel) at any aspect ratio:
698
699        final float ASPECT_RATIO_LANDSCAPE = 16/10f;
700        final float ASPECT_RATIO_PORTRAIT = 10/16f;
701        final float WALLPAPER_WIDTH_TO_SCREEN_RATIO_LANDSCAPE = 1.5f;
702        final float WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT = 1.2f;
703
704        // To find out the desired width at different aspect ratios, we use the following two
705        // formulas, where the coefficient on x is the aspect ratio (width/height):
706        //   (16/10)x + y = 1.5
707        //   (10/16)x + y = 1.2
708        // We solve for x and y and end up with a final formula:
709        final float x =
710            (WALLPAPER_WIDTH_TO_SCREEN_RATIO_LANDSCAPE - WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT) /
711            (ASPECT_RATIO_LANDSCAPE - ASPECT_RATIO_PORTRAIT);
712        final float y = WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT - x * ASPECT_RATIO_PORTRAIT;
713        return x * aspectRatio + y;
714    }
715
716    // The range of scroll values for Workspace
717    private int getScrollRange() {
718        return getChildOffset(getChildCount() - 1) - getChildOffset(0);
719    }
720
721    protected void setWallpaperDimension() {
722        DisplayMetrics displayMetrics = new DisplayMetrics();
723        mLauncher.getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics);
724        final int maxDim = Math.max(displayMetrics.widthPixels, displayMetrics.heightPixels);
725        final int minDim = Math.min(displayMetrics.widthPixels, displayMetrics.heightPixels);
726
727        // We need to ensure that there is enough extra space in the wallpaper for the intended
728        // parallax effects
729        if (LauncherApplication.isScreenLarge()) {
730            mWallpaperWidth = (int) (maxDim * wallpaperTravelToScreenWidthRatio(maxDim, minDim));
731            mWallpaperHeight = (int)(maxDim * wallpaperTravelToScreenHeightRatio(maxDim, minDim));
732        } else {
733            mWallpaperWidth = (int) (minDim * WALLPAPER_SCREENS_SPAN);
734            mWallpaperHeight = maxDim;
735        }
736        new Thread("setWallpaperDimension") {
737            public void run() {
738                mWallpaperManager.suggestDesiredDimensions(mWallpaperWidth, mWallpaperHeight);
739            }
740        }.start();
741    }
742
743    public void setVerticalWallpaperOffset(float offset) {
744        mWallpaperOffset.setFinalY(offset);
745    }
746    public float getVerticalWallpaperOffset() {
747        return mWallpaperOffset.getCurrY();
748    }
749    public void setHorizontalWallpaperOffset(float offset) {
750        mWallpaperOffset.setFinalX(offset);
751    }
752    public float getHorizontalWallpaperOffset() {
753        return mWallpaperOffset.getCurrX();
754    }
755
756    private float wallpaperOffsetForCurrentScroll() {
757        final boolean overScrollWallpaper = LauncherApplication.isScreenLarge();
758        final boolean isStaticWallpaper = mIsStaticWallpaper;
759        // The wallpaper travel width is how far, from left to right, the wallpaper will move
760        // at this orientation (for example, in portrait mode we don't move all the way to the
761        // edges of the wallpaper, or otherwise the parallax effect would be too strong)
762        int wallpaperTravelWidth = mWallpaperTravelWidth;
763        if (!overScrollWallpaper || !isStaticWallpaper) {
764            wallpaperTravelWidth = mWallpaperWidth;
765        }
766
767        // Set wallpaper offset steps (1 / (number of screens - 1))
768        // We have 3 vertical offset states (centered, and then top/bottom aligned
769        // for all apps/customize)
770        if (LauncherApplication.isScreenLarge()) {
771            mWallpaperManager.setWallpaperOffsetSteps(1.0f / (getChildCount() - 1), 1.0f / (3 - 1));
772        } else {
773            mWallpaperManager.setWallpaperOffsetSteps(1.0f / (getChildCount() - 1), 1.0f);
774        }
775
776        // For the purposes of computing the scrollRange and overScrollOffset, we ignore
777        // assume that mLayoutScale is 1. This means that when we're in spring-loaded mode,
778        // there's no discrepancy between the wallpaper offset for a given page.
779        float layoutScale = mLayoutScale;
780        mLayoutScale = 1f;
781        int scrollRange = getScrollRange();
782        float scrollProgressOffset = 0;
783
784        // Account for over scroll: you only see the absolute edge of the wallpaper if
785        // you over scroll as far as you can in landscape mode. Only do this for static wallpapers
786        // because live wallpapers (and probably 3rd party wallpaper providers) rely on the offset
787        // being even intervals from 0 to 1 (eg [0, 0.25, 0.5, 0.75, 1])
788        if (isStaticWallpaper && overScrollWallpaper) {
789            int overScrollOffset = (int) (maxOverScroll() * mDisplayWidth);
790            scrollProgressOffset += overScrollOffset / (float) getScrollRange();
791            scrollRange += 2 * overScrollOffset;
792        }
793
794        // Again, we adjust the wallpaper offset to be consistent between values of mLayoutScale
795
796        float adjustedScrollX = overScrollWallpaper ?
797                mScrollX : Math.max(0, Math.min(mScrollX, mMaxScrollX));
798        adjustedScrollX *= mWallpaperScrollRatio;
799        mLayoutScale = layoutScale;
800
801        float scrollProgress =
802            adjustedScrollX / (float) scrollRange + scrollProgressOffset;
803        float offsetInDips = wallpaperTravelWidth * scrollProgress +
804            (mWallpaperWidth - wallpaperTravelWidth) / 2; // center it
805        float offset = offsetInDips / (float) mWallpaperWidth;
806        return offset;
807    }
808    private void syncWallpaperOffsetWithScroll() {
809        final boolean enableWallpaperEffects = isHardwareAccelerated();
810        if (enableWallpaperEffects) {
811            mWallpaperOffset.setFinalX(wallpaperOffsetForCurrentScroll());
812        }
813    }
814
815    public void updateWallpaperOffsetImmediately() {
816        mUpdateWallpaperOffsetImmediately = true;
817    }
818
819    private void updateWallpaperOffsets() {
820        boolean updateNow = false;
821        boolean keepUpdating = true;
822        if (mUpdateWallpaperOffsetImmediately) {
823            updateNow = true;
824            keepUpdating = false;
825            mWallpaperOffset.jumpToFinal();
826            mUpdateWallpaperOffsetImmediately = false;
827        } else {
828            updateNow = keepUpdating = mWallpaperOffset.computeScrollOffset();
829        }
830        if (updateNow) {
831            if (mWindowToken != null) {
832                mWallpaperManager.setWallpaperOffsets(mWindowToken,
833                        mWallpaperOffset.getCurrX(), mWallpaperOffset.getCurrY());
834            }
835        }
836        if (keepUpdating) {
837            fastInvalidate();
838        }
839    }
840
841    @Override
842    protected void updateCurrentPageScroll() {
843        super.updateCurrentPageScroll();
844        computeWallpaperScrollRatio(mCurrentPage);
845    }
846
847    @Override
848    protected void snapToPage(int whichPage) {
849        super.snapToPage(whichPage);
850        computeWallpaperScrollRatio(whichPage);
851    }
852
853    private void computeWallpaperScrollRatio(int page) {
854        // Here, we determine what the desired scroll would be with and without a layout scale,
855        // and compute a ratio between the two. This allows us to adjust the wallpaper offset
856        // as though there is no layout scale.
857        float layoutScale = mLayoutScale;
858        int scaled = getChildOffset(page) - getRelativeChildOffset(page);
859        mLayoutScale = 1.0f;
860        float unscaled = getChildOffset(page) - getRelativeChildOffset(page);
861        mLayoutScale = layoutScale;
862        if (scaled > 0) {
863            mWallpaperScrollRatio = (1.0f * unscaled) / scaled;
864        } else {
865            mWallpaperScrollRatio = 1f;
866        }
867    }
868
869    class WallpaperOffsetInterpolator {
870        float mFinalHorizontalWallpaperOffset = 0.0f;
871        float mFinalVerticalWallpaperOffset = 0.5f;
872        float mHorizontalWallpaperOffset = 0.0f;
873        float mVerticalWallpaperOffset = 0.5f;
874        long mLastWallpaperOffsetUpdateTime;
875        boolean mIsMovingFast;
876        boolean mOverrideHorizontalCatchupConstant;
877        float mHorizontalCatchupConstant = 0.35f;
878        float mVerticalCatchupConstant = 0.35f;
879
880        public WallpaperOffsetInterpolator() {
881            mVerticalWallpaperOffset = LauncherApplication.isScreenLarge() ? 0.5f : 0f;
882            mFinalVerticalWallpaperOffset = LauncherApplication.isScreenLarge() ? 0.5f : 0f;
883        }
884
885        public void setOverrideHorizontalCatchupConstant(boolean override) {
886            mOverrideHorizontalCatchupConstant = override;
887        }
888
889        public void setHorizontalCatchupConstant(float f) {
890            mHorizontalCatchupConstant = f;
891        }
892
893        public void setVerticalCatchupConstant(float f) {
894            mVerticalCatchupConstant = f;
895        }
896
897        public boolean computeScrollOffset() {
898            if (Float.compare(mHorizontalWallpaperOffset, mFinalHorizontalWallpaperOffset) == 0 &&
899                    Float.compare(mVerticalWallpaperOffset, mFinalVerticalWallpaperOffset) == 0) {
900                mIsMovingFast = false;
901                return false;
902            }
903            boolean isLandscape = mDisplayWidth > mDisplayHeight;
904
905            long currentTime = System.currentTimeMillis();
906            long timeSinceLastUpdate = currentTime - mLastWallpaperOffsetUpdateTime;
907            timeSinceLastUpdate = Math.min((long) (1000/30f), timeSinceLastUpdate);
908            timeSinceLastUpdate = Math.max(1L, timeSinceLastUpdate);
909
910            float xdiff = Math.abs(mFinalHorizontalWallpaperOffset - mHorizontalWallpaperOffset);
911            if (!mIsMovingFast && xdiff > 0.07) {
912                mIsMovingFast = true;
913            }
914
915            float fractionToCatchUpIn1MsHorizontal;
916            if (mOverrideHorizontalCatchupConstant) {
917                fractionToCatchUpIn1MsHorizontal = mHorizontalCatchupConstant;
918            } else if (mIsMovingFast) {
919                fractionToCatchUpIn1MsHorizontal = isLandscape ? 0.5f : 0.75f;
920            } else {
921                // slow
922                fractionToCatchUpIn1MsHorizontal = isLandscape ? 0.27f : 0.5f;
923            }
924            float fractionToCatchUpIn1MsVertical = mVerticalCatchupConstant;
925
926            fractionToCatchUpIn1MsHorizontal /= 33f;
927            fractionToCatchUpIn1MsVertical /= 33f;
928
929            final float UPDATE_THRESHOLD = 0.00001f;
930            float hOffsetDelta = mFinalHorizontalWallpaperOffset - mHorizontalWallpaperOffset;
931            float vOffsetDelta = mFinalVerticalWallpaperOffset - mVerticalWallpaperOffset;
932            boolean jumpToFinalValue = Math.abs(hOffsetDelta) < UPDATE_THRESHOLD &&
933                Math.abs(vOffsetDelta) < UPDATE_THRESHOLD;
934
935            // Don't have any lag between workspace and wallpaper on non-large devices
936            if (!LauncherApplication.isScreenLarge() || jumpToFinalValue) {
937                mHorizontalWallpaperOffset = mFinalHorizontalWallpaperOffset;
938                mVerticalWallpaperOffset = mFinalVerticalWallpaperOffset;
939            } else {
940                float percentToCatchUpVertical =
941                    Math.min(1.0f, timeSinceLastUpdate * fractionToCatchUpIn1MsVertical);
942                float percentToCatchUpHorizontal =
943                    Math.min(1.0f, timeSinceLastUpdate * fractionToCatchUpIn1MsHorizontal);
944                mHorizontalWallpaperOffset += percentToCatchUpHorizontal * hOffsetDelta;
945                mVerticalWallpaperOffset += percentToCatchUpVertical * vOffsetDelta;
946            }
947
948            mLastWallpaperOffsetUpdateTime = System.currentTimeMillis();
949            return true;
950        }
951
952        public float getCurrX() {
953            return mHorizontalWallpaperOffset;
954        }
955
956        public float getFinalX() {
957            return mFinalHorizontalWallpaperOffset;
958        }
959
960        public float getCurrY() {
961            return mVerticalWallpaperOffset;
962        }
963
964        public float getFinalY() {
965            return mFinalVerticalWallpaperOffset;
966        }
967
968        public void setFinalX(float x) {
969            mFinalHorizontalWallpaperOffset = Math.max(0f, Math.min(x, 1.0f));
970        }
971
972        public void setFinalY(float y) {
973            mFinalVerticalWallpaperOffset = Math.max(0f, Math.min(y, 1.0f));
974        }
975
976        public void jumpToFinal() {
977            mHorizontalWallpaperOffset = mFinalHorizontalWallpaperOffset;
978            mVerticalWallpaperOffset = mFinalVerticalWallpaperOffset;
979        }
980    }
981
982    @Override
983    public void computeScroll() {
984        super.computeScroll();
985        syncWallpaperOffsetWithScroll();
986    }
987
988    void showOutlines() {
989        if (!isSmall() && !mIsSwitchingState) {
990            if (mChildrenOutlineFadeOutAnimation != null) mChildrenOutlineFadeOutAnimation.cancel();
991            if (mChildrenOutlineFadeInAnimation != null) mChildrenOutlineFadeInAnimation.cancel();
992            mChildrenOutlineFadeInAnimation = ObjectAnimator.ofFloat(this, "childrenOutlineAlpha", 1.0f);
993            mChildrenOutlineFadeInAnimation.setDuration(CHILDREN_OUTLINE_FADE_IN_DURATION);
994            mChildrenOutlineFadeInAnimation.start();
995        }
996    }
997
998    void hideOutlines() {
999        if (!isSmall() && !mIsSwitchingState) {
1000            if (mChildrenOutlineFadeInAnimation != null) mChildrenOutlineFadeInAnimation.cancel();
1001            if (mChildrenOutlineFadeOutAnimation != null) mChildrenOutlineFadeOutAnimation.cancel();
1002            mChildrenOutlineFadeOutAnimation = ObjectAnimator.ofFloat(this, "childrenOutlineAlpha", 0.0f);
1003            mChildrenOutlineFadeOutAnimation.setDuration(CHILDREN_OUTLINE_FADE_OUT_DURATION);
1004            mChildrenOutlineFadeOutAnimation.setStartDelay(CHILDREN_OUTLINE_FADE_OUT_DELAY);
1005            mChildrenOutlineFadeOutAnimation.start();
1006        }
1007    }
1008
1009    public void showOutlinesTemporarily() {
1010        if (!mIsPageMoving && !isTouchActive()) {
1011            snapToPage(mCurrentPage);
1012        }
1013    }
1014
1015    public void setChildrenOutlineAlpha(float alpha) {
1016        mChildrenOutlineAlpha = alpha;
1017        for (int i = 0; i < getChildCount(); i++) {
1018            CellLayout cl = (CellLayout) getChildAt(i);
1019            cl.setBackgroundAlpha(alpha);
1020        }
1021    }
1022
1023    public float getChildrenOutlineAlpha() {
1024        return mChildrenOutlineAlpha;
1025    }
1026
1027    void disableBackground() {
1028        mDrawBackground = false;
1029    }
1030    void enableBackground() {
1031        mDrawBackground = true;
1032    }
1033
1034    private void animateBackgroundGradient(float finalAlpha, boolean animated) {
1035        if (mBackground == null) return;
1036        if (mBackgroundFadeInAnimation != null) {
1037            mBackgroundFadeInAnimation.cancel();
1038            mBackgroundFadeInAnimation = null;
1039        }
1040        if (mBackgroundFadeOutAnimation != null) {
1041            mBackgroundFadeOutAnimation.cancel();
1042            mBackgroundFadeOutAnimation = null;
1043        }
1044        float startAlpha = getBackgroundAlpha();
1045        if (finalAlpha != startAlpha) {
1046            if (animated) {
1047                mBackgroundFadeOutAnimation = ValueAnimator.ofFloat(startAlpha, finalAlpha);
1048                mBackgroundFadeOutAnimation.addUpdateListener(new AnimatorUpdateListener() {
1049                    public void onAnimationUpdate(ValueAnimator animation) {
1050                        setBackgroundAlpha(((Float) animation.getAnimatedValue()).floatValue());
1051                    }
1052                });
1053                mBackgroundFadeOutAnimation.setInterpolator(new DecelerateInterpolator(1.5f));
1054                mBackgroundFadeOutAnimation.setDuration(BACKGROUND_FADE_OUT_DURATION);
1055                mBackgroundFadeOutAnimation.start();
1056            } else {
1057                setBackgroundAlpha(finalAlpha);
1058            }
1059        }
1060    }
1061
1062    public void setBackgroundAlpha(float alpha) {
1063        if (alpha != mBackgroundAlpha) {
1064            mBackgroundAlpha = alpha;
1065            invalidate();
1066        }
1067    }
1068
1069    public float getBackgroundAlpha() {
1070        return mBackgroundAlpha;
1071    }
1072
1073    /**
1074     * Due to 3D transformations, if two CellLayouts are theoretically touching each other,
1075     * on the xy plane, when one is rotated along the y-axis, the gap between them is perceived
1076     * as being larger. This method computes what offset the rotated view should be translated
1077     * in order to minimize this perceived gap.
1078     * @param degrees Angle of the view
1079     * @param width Width of the view
1080     * @param height Height of the view
1081     * @return Offset to be used in a View.setTranslationX() call
1082     */
1083    private float getOffsetXForRotation(float degrees, int width, int height) {
1084        mMatrix.reset();
1085        mCamera.save();
1086        mCamera.rotateY(Math.abs(degrees));
1087        mCamera.getMatrix(mMatrix);
1088        mCamera.restore();
1089
1090        mMatrix.preTranslate(-width * 0.5f, -height * 0.5f);
1091        mMatrix.postTranslate(width * 0.5f, height * 0.5f);
1092        mTempFloat2[0] = width;
1093        mTempFloat2[1] = height;
1094        mMatrix.mapPoints(mTempFloat2);
1095        return (width - mTempFloat2[0]) * (degrees > 0.0f ? 1.0f : -1.0f);
1096    }
1097
1098    float backgroundAlphaInterpolator(float r) {
1099        float pivotA = 0.1f;
1100        float pivotB = 0.4f;
1101        if (r < pivotA) {
1102            return 0;
1103        } else if (r > pivotB) {
1104            return 1.0f;
1105        } else {
1106            return (r - pivotA)/(pivotB - pivotA);
1107        }
1108    }
1109
1110    float overScrollBackgroundAlphaInterpolator(float r) {
1111        float threshold = 0.08f;
1112
1113        if (r > mOverScrollMaxBackgroundAlpha) {
1114            mOverScrollMaxBackgroundAlpha = r;
1115        } else if (r < mOverScrollMaxBackgroundAlpha) {
1116            r = mOverScrollMaxBackgroundAlpha;
1117        }
1118
1119        return Math.min(r / threshold, 1.0f);
1120    }
1121
1122    private void screenScrolledLargeUI(int screenCenter) {
1123        for (int i = 0; i < getChildCount(); i++) {
1124            CellLayout cl = (CellLayout) getChildAt(i);
1125            if (cl != null) {
1126                float scrollProgress = getScrollProgress(screenCenter, cl, i);
1127                float rotation = WORKSPACE_ROTATION * scrollProgress;
1128                float translationX = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight());
1129
1130                // If the current page (i) is being over scrolled, we use a different
1131                // set of rules for setting the background alpha multiplier.
1132                if (!isSmall()) {
1133                    if ((mScrollX < 0 && i == 0) || (mScrollX > mMaxScrollX &&
1134                            i == getChildCount() -1 )) {
1135                        cl.setBackgroundAlphaMultiplier(
1136                                overScrollBackgroundAlphaInterpolator(Math.abs(scrollProgress)));
1137                        mOverScrollPageIndex = i;
1138                    } else if (mOverScrollPageIndex != i) {
1139                        cl.setBackgroundAlphaMultiplier(
1140                                backgroundAlphaInterpolator(Math.abs(scrollProgress)));
1141                    }
1142                }
1143                cl.setTranslationX(translationX);
1144                cl.setRotationY(rotation);
1145            }
1146        }
1147    }
1148
1149    private void resetCellLayoutTransforms(CellLayout cl, boolean left) {
1150        cl.setTranslationX(0);
1151        cl.setRotationY(0);
1152        cl.setOverScrollAmount(0, left);
1153        cl.setPivotX(cl.getMeasuredWidth() / 2);
1154        cl.setPivotY(cl.getMeasuredHeight() / 2);
1155    }
1156
1157    private void screenScrolledStandardUI(int screenCenter) {
1158        if (mScrollX < 0 || mScrollX > mMaxScrollX) {
1159            int index = mScrollX < 0 ? 0 : getChildCount() - 1;
1160            CellLayout cl = (CellLayout) getChildAt(index);
1161            float scrollProgress = getScrollProgress(screenCenter, cl, index);
1162            cl.setOverScrollAmount(Math.abs(scrollProgress), index == 0);
1163            float translationX = index == 0 ? mScrollX : - (mMaxScrollX - mScrollX);
1164            float rotation = - WORKSPACE_OVERSCROLL_ROTATION * scrollProgress;
1165            cl.setCameraDistance(mDensity * CAMERA_DISTANCE);
1166            cl.setPivotX(cl.getMeasuredWidth() * (index == 0 ? 0.75f : 0.25f));
1167            cl.setTranslationX(translationX);
1168            cl.setRotationY(rotation);
1169        } else {
1170            // We don't want to mess with the translations during transitions
1171            if (!isSwitchingState()) {
1172                resetCellLayoutTransforms((CellLayout) getChildAt(0), true);
1173                resetCellLayoutTransforms((CellLayout) getChildAt(getChildCount() - 1), false);
1174            }
1175        }
1176    }
1177
1178    @Override
1179    protected void screenScrolled(int screenCenter) {
1180        super.screenScrolled(screenCenter);
1181        if (LauncherApplication.isScreenLarge()) {
1182            screenScrolledLargeUI(screenCenter);
1183        } else {
1184            screenScrolledStandardUI(screenCenter);
1185        }
1186    }
1187
1188    @Override
1189    protected void overScroll(float amount) {
1190        if (LauncherApplication.isScreenLarge()) {
1191            dampedOverScroll(amount);
1192        } else {
1193            acceleratedOverScroll(amount);
1194        }
1195    }
1196
1197    protected void onAttachedToWindow() {
1198        super.onAttachedToWindow();
1199        mWindowToken = getWindowToken();
1200        computeScroll();
1201        mDragController.setWindowToken(mWindowToken);
1202    }
1203
1204    protected void onDetachedFromWindow() {
1205        mWindowToken = null;
1206    }
1207
1208    @Override
1209    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
1210        if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
1211            mUpdateWallpaperOffsetImmediately = true;
1212        }
1213        super.onLayout(changed, left, top, right, bottom);
1214
1215        // if shrinkToBottom() is called on initialization, it has to be deferred
1216        // until after the first call to onLayout so that it has the correct width
1217        if (mSwitchStateAfterFirstLayout) {
1218            mSwitchStateAfterFirstLayout = false;
1219            // shrink can trigger a synchronous onLayout call, so we
1220            // post this to avoid a stack overflow / tangled onLayout calls
1221            post(new Runnable() {
1222                public void run() {
1223                    changeState(mStateAfterFirstLayout, false);
1224                }
1225            });
1226        }
1227    }
1228
1229    @Override
1230    protected void onDraw(Canvas canvas) {
1231        updateWallpaperOffsets();
1232
1233        // Draw the background gradient if necessary
1234        if (mBackground != null && mBackgroundAlpha > 0.0f && mDrawBackground) {
1235            int alpha = (int) (mBackgroundAlpha * 255);
1236            mBackground.setAlpha(alpha);
1237            mBackground.setBounds(mScrollX, 0, mScrollX + getMeasuredWidth(),
1238                    getMeasuredHeight());
1239            mBackground.draw(canvas);
1240        }
1241
1242        super.onDraw(canvas);
1243    }
1244
1245    @Override
1246    protected void dispatchDraw(Canvas canvas) {
1247        super.dispatchDraw(canvas);
1248
1249        if (mInScrollArea && !LauncherApplication.isScreenLarge()) {
1250            final int width = getWidth();
1251            final int height = getHeight();
1252            final int pageHeight = getChildAt(0).getHeight();
1253
1254            // Set the height of the outline to be the height of the page
1255            final int offset = (height - pageHeight - mPaddingTop - mPaddingBottom) / 2;
1256            final int paddingTop = mPaddingTop + offset;
1257            final int paddingBottom = mPaddingBottom + offset;
1258
1259            final CellLayout leftPage = (CellLayout) getChildAt(mCurrentPage - 1);
1260            final CellLayout rightPage = (CellLayout) getChildAt(mCurrentPage + 1);
1261
1262            if (leftPage != null && leftPage.getIsDragOverlapping()) {
1263                final Drawable d = getResources().getDrawable(R.drawable.page_hover_left_holo);
1264                d.setBounds(mScrollX, paddingTop, mScrollX + d.getIntrinsicWidth(),
1265                        height - paddingBottom);
1266                d.draw(canvas);
1267            } else if (rightPage != null && rightPage.getIsDragOverlapping()) {
1268                final Drawable d = getResources().getDrawable(R.drawable.page_hover_right_holo);
1269                d.setBounds(mScrollX + width - d.getIntrinsicWidth(), paddingTop, mScrollX + width,
1270                        height - paddingBottom);
1271                d.draw(canvas);
1272            }
1273        }
1274    }
1275
1276    @Override
1277    protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
1278        if (!mLauncher.isAllAppsVisible()) {
1279            final Folder openFolder = getOpenFolder();
1280            if (openFolder != null) {
1281                return openFolder.requestFocus(direction, previouslyFocusedRect);
1282            } else {
1283                return super.onRequestFocusInDescendants(direction, previouslyFocusedRect);
1284            }
1285        }
1286        return false;
1287    }
1288
1289    @Override
1290    public int getDescendantFocusability() {
1291        if (isSmall()) {
1292            return ViewGroup.FOCUS_BLOCK_DESCENDANTS;
1293        }
1294        return super.getDescendantFocusability();
1295    }
1296
1297    @Override
1298    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
1299        if (!mLauncher.isAllAppsVisible()) {
1300            final Folder openFolder = getOpenFolder();
1301            if (openFolder != null) {
1302                openFolder.addFocusables(views, direction);
1303            } else {
1304                super.addFocusables(views, direction, focusableMode);
1305            }
1306        }
1307    }
1308
1309    public boolean isSmall() {
1310        return mState == State.SMALL || mState == State.SPRING_LOADED;
1311    }
1312
1313    void enableChildrenCache(int fromPage, int toPage) {
1314        if (fromPage > toPage) {
1315            final int temp = fromPage;
1316            fromPage = toPage;
1317            toPage = temp;
1318        }
1319
1320        final int screenCount = getChildCount();
1321
1322        fromPage = Math.max(fromPage, 0);
1323        toPage = Math.min(toPage, screenCount - 1);
1324
1325        for (int i = fromPage; i <= toPage; i++) {
1326            final CellLayout layout = (CellLayout) getChildAt(i);
1327            layout.setChildrenDrawnWithCacheEnabled(true);
1328            layout.setChildrenDrawingCacheEnabled(true);
1329        }
1330    }
1331
1332    void clearChildrenCache() {
1333        final int screenCount = getChildCount();
1334        for (int i = 0; i < screenCount; i++) {
1335            final CellLayout layout = (CellLayout) getChildAt(i);
1336            layout.setChildrenDrawnWithCacheEnabled(false);
1337            // In software mode, we don't want the items to continue to be drawn into bitmaps
1338            if (!isHardwareAccelerated()) {
1339                layout.setChildrenDrawingCacheEnabled(false);
1340            }
1341        }
1342    }
1343
1344    private void updateChildrenLayersEnabled() {
1345        boolean small = isSmall() || mIsSwitchingState;
1346        boolean dragging = mAnimatingViewIntoPlace || mIsDragOccuring;
1347        boolean enableChildrenLayers = small || dragging || isPageMoving();
1348
1349        if (enableChildrenLayers != mChildrenLayersEnabled) {
1350            mChildrenLayersEnabled = enableChildrenLayers;
1351            for (int i = 0; i < getPageCount(); i++) {
1352                ((ViewGroup)getChildAt(i)).setChildrenLayersEnabled(enableChildrenLayers);
1353            }
1354        }
1355    }
1356
1357    protected void onWallpaperTap(MotionEvent ev) {
1358        final int[] position = mTempCell;
1359        getLocationOnScreen(position);
1360
1361        int pointerIndex = ev.getActionIndex();
1362        position[0] += (int) ev.getX(pointerIndex);
1363        position[1] += (int) ev.getY(pointerIndex);
1364
1365        mWallpaperManager.sendWallpaperCommand(getWindowToken(),
1366                ev.getAction() == MotionEvent.ACTION_UP
1367                        ? WallpaperManager.COMMAND_TAP : WallpaperManager.COMMAND_SECONDARY_TAP,
1368                position[0], position[1], 0, null);
1369    }
1370
1371    @Override
1372    protected void updateAdjacentPagesAlpha() {
1373        if (!isSmall()) {
1374            super.updateAdjacentPagesAlpha();
1375        }
1376    }
1377
1378    /*
1379     * This interpolator emulates the rate at which the perceived scale of an object changes
1380     * as its distance from a camera increases. When this interpolator is applied to a scale
1381     * animation on a view, it evokes the sense that the object is shrinking due to moving away
1382     * from the camera.
1383     */
1384    static class ZInterpolator implements TimeInterpolator {
1385        private float focalLength;
1386
1387        public ZInterpolator(float foc) {
1388            focalLength = foc;
1389        }
1390
1391        public float getInterpolation(float input) {
1392            return (1.0f - focalLength / (focalLength + input)) /
1393                (1.0f - focalLength / (focalLength + 1.0f));
1394        }
1395    }
1396
1397    /*
1398     * The exact reverse of ZInterpolator.
1399     */
1400    static class InverseZInterpolator implements TimeInterpolator {
1401        private ZInterpolator zInterpolator;
1402        public InverseZInterpolator(float foc) {
1403            zInterpolator = new ZInterpolator(foc);
1404        }
1405        public float getInterpolation(float input) {
1406            return 1 - zInterpolator.getInterpolation(1 - input);
1407        }
1408    }
1409
1410    /*
1411     * ZInterpolator compounded with an ease-out.
1412     */
1413    static class ZoomOutInterpolator implements TimeInterpolator {
1414        private final ZInterpolator zInterpolator = new ZInterpolator(0.2f);
1415        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(1.8f);
1416
1417        public float getInterpolation(float input) {
1418            return decelerate.getInterpolation(zInterpolator.getInterpolation(input));
1419        }
1420    }
1421
1422    /*
1423     * InvereZInterpolator compounded with an ease-out.
1424     */
1425    static class ZoomInInterpolator implements TimeInterpolator {
1426        private final InverseZInterpolator inverseZInterpolator = new InverseZInterpolator(0.35f);
1427        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(3.0f);
1428
1429        public float getInterpolation(float input) {
1430            return decelerate.getInterpolation(inverseZInterpolator.getInterpolation(input));
1431        }
1432    }
1433
1434    private final ZoomInInterpolator mZoomInInterpolator = new ZoomInInterpolator();
1435
1436    /*
1437    *
1438    * We call these methods (onDragStartedWithItemSpans/onDragStartedWithSize) whenever we
1439    * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace
1440    *
1441    * These methods mark the appropriate pages as accepting drops (which alters their visual
1442    * appearance).
1443    *
1444    */
1445    public void onDragStartedWithItem(View v) {
1446        final Canvas canvas = new Canvas();
1447
1448        // We need to add extra padding to the bitmap to make room for the glow effect
1449        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1450
1451        // The outline is used to visualize where the item will land if dropped
1452        mDragOutline = createDragOutline(v, canvas, bitmapPadding);
1453    }
1454
1455    public void onDragStartedWithItemSpans(int spanX, int spanY, Bitmap b) {
1456        final Canvas canvas = new Canvas();
1457
1458        // We need to add extra padding to the bitmap to make room for the glow effect
1459        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1460
1461        CellLayout cl = (CellLayout) getChildAt(0);
1462
1463        int[] size = cl.cellSpansToSize(spanX, spanY);
1464
1465        // The outline is used to visualize where the item will land if dropped
1466        mDragOutline = createDragOutline(b, canvas, bitmapPadding, size[0], size[1]);
1467    }
1468
1469    // we call this method whenever a drag and drop in Launcher finishes, even if Workspace was
1470    // never dragged over
1471    public void onDragStopped(boolean success) {
1472        // In the success case, DragController has already called onDragExit()
1473        if (!success) {
1474            doDragExit(null);
1475        }
1476    }
1477
1478    public void exitWidgetResizeMode() {
1479        DragLayer dragLayer = mLauncher.getDragLayer();
1480        dragLayer.clearAllResizeFrames();
1481    }
1482
1483    private void initAnimationArrays() {
1484        final int childCount = getChildCount();
1485        if (mOldTranslationXs != null) return;
1486        mOldTranslationXs = new float[childCount];
1487        mOldTranslationYs = new float[childCount];
1488        mOldScaleXs = new float[childCount];
1489        mOldScaleYs = new float[childCount];
1490        mOldBackgroundAlphas = new float[childCount];
1491        mOldBackgroundAlphaMultipliers = new float[childCount];
1492        mOldAlphas = new float[childCount];
1493        mOldRotationYs = new float[childCount];
1494        mNewTranslationXs = new float[childCount];
1495        mNewTranslationYs = new float[childCount];
1496        mNewScaleXs = new float[childCount];
1497        mNewScaleYs = new float[childCount];
1498        mNewBackgroundAlphas = new float[childCount];
1499        mNewBackgroundAlphaMultipliers = new float[childCount];
1500        mNewAlphas = new float[childCount];
1501        mNewRotationYs = new float[childCount];
1502    }
1503
1504    public void changeState(State shrinkState) {
1505        changeState(shrinkState, true);
1506    }
1507
1508    void changeState(final State state, boolean animated) {
1509        changeState(state, animated, 0);
1510    }
1511
1512    void changeState(final State state, boolean animated, int delay) {
1513        if (mFirstLayout) {
1514            // (mFirstLayout == "first layout has not happened yet")
1515            // cancel any pending shrinks that were set earlier
1516            mSwitchStateAfterFirstLayout = false;
1517            mStateAfterFirstLayout = state;
1518            return;
1519        }
1520
1521        if (mAnimator != null) {
1522            mAnimator.cancel();
1523        }
1524
1525        // Stop any scrolling, move to the current page right away
1526        setCurrentPage((mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage);
1527
1528        float finalScaleFactor = 1.0f;
1529        float finalBackgroundAlpha = (state == State.SPRING_LOADED) ? 1.0f : 0f;
1530        boolean normalState = false;
1531        State oldState = mState;
1532        mState = state;
1533        boolean zoomIn = true;
1534
1535        if (state != State.NORMAL) {
1536            finalScaleFactor = mSpringLoadedShrinkFactor - (state == State.SMALL ? 0.1f : 0);
1537            if (oldState == State.NORMAL && state == State.SMALL) {
1538                zoomIn = false;
1539                if (animated) {
1540                    hideScrollingIndicator(true);
1541                }
1542                setLayoutScale(finalScaleFactor);
1543                updateChildrenLayersEnabled();
1544            } else {
1545                finalBackgroundAlpha = 1.0f;
1546                setLayoutScale(finalScaleFactor);
1547            }
1548        } else {
1549            setLayoutScale(1.0f);
1550            normalState = true;
1551        }
1552
1553        float translationX = 0;
1554        float translationY = 0;
1555
1556        mAnimator = new AnimatorSet();
1557
1558        final int screenCount = getChildCount();
1559        initAnimationArrays();
1560
1561        final int duration = zoomIn ?
1562                getResources().getInteger(R.integer.config_workspaceUnshrinkTime) :
1563                getResources().getInteger(R.integer.config_appsCustomizeWorkspaceShrinkTime);
1564        for (int i = 0; i < screenCount; i++) {
1565            final CellLayout cl = (CellLayout)getChildAt(i);
1566            float finalAlphaValue = 0f;
1567            float rotation = 0f;
1568
1569            // Set the final alpha depending on whether we are fading side pages.  On phone ui,
1570            // we don't do any of the rotation, or the fading alpha in portrait.  See the
1571            // ctor and screenScrolled().
1572            if (mFadeInAdjacentScreens && normalState) {
1573                finalAlphaValue = (i == mCurrentPage) ? 1f : 0f;
1574            } else {
1575                finalAlphaValue = 1f;
1576            }
1577
1578            if (LauncherApplication.isScreenLarge()) {
1579                if (i < mCurrentPage) {
1580                    rotation = WORKSPACE_ROTATION;
1581                } else if (i > mCurrentPage) {
1582                    rotation = -WORKSPACE_ROTATION;
1583                }
1584            }
1585
1586            float finalAlphaMultiplierValue = 1f;
1587            // If the screen is not xlarge, then don't rotate the CellLayouts
1588            // NOTE: If we don't update the side pages alpha, then we should not hide the side
1589            //       pages. see unshrink().
1590            if (LauncherApplication.isScreenLarge()) {
1591                translationX = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight());
1592            }
1593
1594            mOldAlphas[i] = cl.getAlpha();
1595            mNewAlphas[i] = finalAlphaValue;
1596            if (animated) {
1597                mOldTranslationXs[i] = cl.getTranslationX();
1598                mOldTranslationYs[i] = cl.getTranslationY();
1599                mOldScaleXs[i] = cl.getScaleX();
1600                mOldScaleYs[i] = cl.getScaleY();
1601                mOldBackgroundAlphas[i] = cl.getBackgroundAlpha();
1602                mOldBackgroundAlphaMultipliers[i] = cl.getBackgroundAlphaMultiplier();
1603                mOldRotationYs[i] = cl.getRotationY();
1604
1605                mNewTranslationXs[i] = translationX;
1606                mNewTranslationYs[i] = translationY;
1607                mNewScaleXs[i] = finalScaleFactor;
1608                mNewScaleYs[i] = finalScaleFactor;
1609                mNewBackgroundAlphas[i] = finalBackgroundAlpha;
1610                mNewBackgroundAlphaMultipliers[i] = finalAlphaMultiplierValue;
1611                mNewRotationYs[i] = rotation;
1612            } else {
1613                cl.setTranslationX(translationX);
1614                cl.setTranslationY(translationY);
1615                cl.setScaleX(finalScaleFactor);
1616                cl.setScaleY(finalScaleFactor);
1617                cl.setBackgroundAlpha(0.0f);
1618                cl.setBackgroundAlphaMultiplier(finalAlphaMultiplierValue);
1619                cl.setAlpha(finalAlphaValue);
1620                cl.setRotationY(rotation);
1621                mChangeStateAnimationListener.onAnimationEnd(null);
1622            }
1623        }
1624
1625        if (animated) {
1626            ValueAnimator animWithInterpolator =
1627                ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
1628
1629            if (zoomIn) {
1630                animWithInterpolator.setInterpolator(mZoomInInterpolator);
1631            }
1632
1633            animWithInterpolator.addUpdateListener(new LauncherAnimatorUpdateListener() {
1634                public void onAnimationUpdate(float a, float b) {
1635                    mTransitionProgress = b;
1636                    if (b == 0f) {
1637                        // an optimization, but not required
1638                        return;
1639                    }
1640                    invalidate();
1641                    for (int i = 0; i < screenCount; i++) {
1642                        final CellLayout cl = (CellLayout) getChildAt(i);
1643                        cl.fastInvalidate();
1644                        cl.setFastTranslationX(a * mOldTranslationXs[i] + b * mNewTranslationXs[i]);
1645                        cl.setFastTranslationY(a * mOldTranslationYs[i] + b * mNewTranslationYs[i]);
1646                        cl.setFastScaleX(a * mOldScaleXs[i] + b * mNewScaleXs[i]);
1647                        cl.setFastScaleY(a * mOldScaleYs[i] + b * mNewScaleYs[i]);
1648                        cl.setFastBackgroundAlpha(
1649                                a * mOldBackgroundAlphas[i] + b * mNewBackgroundAlphas[i]);
1650                        cl.setBackgroundAlphaMultiplier(a * mOldBackgroundAlphaMultipliers[i] +
1651                                b * mNewBackgroundAlphaMultipliers[i]);
1652                        cl.setFastAlpha(a * mOldAlphas[i] + b * mNewAlphas[i]);
1653                    }
1654                }
1655            });
1656
1657            ValueAnimator rotationAnim =
1658                ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
1659            rotationAnim.setInterpolator(new DecelerateInterpolator(2.0f));
1660            rotationAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
1661                public void onAnimationUpdate(float a, float b) {
1662                    if (b == 0f) {
1663                        // an optimization, but not required
1664                        return;
1665                    }
1666                    for (int i = 0; i < screenCount; i++) {
1667                        final CellLayout cl = (CellLayout) getChildAt(i);
1668                        cl.setFastRotationY(a * mOldRotationYs[i] + b * mNewRotationYs[i]);
1669                    }
1670                }
1671            });
1672
1673            mAnimator.playTogether(animWithInterpolator, rotationAnim);
1674            mAnimator.setStartDelay(delay);
1675            // If we call this when we're not animated, onAnimationEnd is never called on
1676            // the listener; make sure we only use the listener when we're actually animating
1677            mAnimator.addListener(mChangeStateAnimationListener);
1678            mAnimator.start();
1679        }
1680
1681        if (state == State.SPRING_LOADED) {
1682            // Right now we're covered by Apps Customize
1683            // Show the background gradient immediately, so the gradient will
1684            // be showing once AppsCustomize disappears
1685            animateBackgroundGradient(getResources().getInteger(
1686                    R.integer.config_appsCustomizeSpringLoadedBgAlpha) / 100f, false);
1687        } else {
1688            // Fade the background gradient away
1689            animateBackgroundGradient(0f, true);
1690        }
1691    }
1692
1693    /**
1694     * Draw the View v into the given Canvas.
1695     *
1696     * @param v the view to draw
1697     * @param destCanvas the canvas to draw on
1698     * @param padding the horizontal and vertical padding to use when drawing
1699     */
1700    private void drawDragView(View v, Canvas destCanvas, int padding, boolean pruneToDrawable) {
1701        final Rect clipRect = mTempRect;
1702        v.getDrawingRect(clipRect);
1703
1704        boolean textVisible = false;
1705
1706        destCanvas.save();
1707        if (v instanceof TextView && pruneToDrawable) {
1708            Drawable d = ((TextView) v).getCompoundDrawables()[1];
1709            clipRect.set(0, 0, d.getIntrinsicWidth() + padding, d.getIntrinsicHeight() + padding);
1710            destCanvas.translate(padding / 2, padding / 2);
1711            d.draw(destCanvas);
1712        } else {
1713            if (v instanceof FolderIcon) {
1714                // For FolderIcons the text can bleed into the icon area, and so we need to
1715                // hide the text completely (which can't be achieved by clipping).
1716                if (((FolderIcon) v).getTextVisible()) {
1717                    ((FolderIcon) v).setTextVisible(false);
1718                    textVisible = true;
1719                }
1720            } else if (v instanceof BubbleTextView) {
1721                final BubbleTextView tv = (BubbleTextView) v;
1722                clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V +
1723                        tv.getLayout().getLineTop(0);
1724            } else if (v instanceof TextView) {
1725                final TextView tv = (TextView) v;
1726                clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() +
1727                        tv.getLayout().getLineTop(0);
1728            }
1729            destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2);
1730            destCanvas.clipRect(clipRect, Op.REPLACE);
1731            v.draw(destCanvas);
1732
1733            // Restore text visibility of FolderIcon if necessary
1734            if (textVisible) {
1735                ((FolderIcon) v).setTextVisible(true);
1736            }
1737        }
1738        destCanvas.restore();
1739    }
1740
1741    /**
1742     * Returns a new bitmap to show when the given View is being dragged around.
1743     * Responsibility for the bitmap is transferred to the caller.
1744     */
1745    public Bitmap createDragBitmap(View v, Canvas canvas, int padding) {
1746        final int outlineColor = getResources().getColor(android.R.color.holo_blue_light);
1747        Bitmap b;
1748
1749        if (v instanceof TextView) {
1750            Drawable d = ((TextView) v).getCompoundDrawables()[1];
1751            b = Bitmap.createBitmap(d.getIntrinsicWidth() + padding,
1752                    d.getIntrinsicHeight() + padding, Bitmap.Config.ARGB_8888);
1753        } else {
1754            b = Bitmap.createBitmap(
1755                    v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
1756        }
1757
1758        canvas.setBitmap(b);
1759        drawDragView(v, canvas, padding, true);
1760        mOutlineHelper.applyOuterBlur(b, canvas, outlineColor);
1761        canvas.drawColor(mDragViewMultiplyColor, PorterDuff.Mode.MULTIPLY);
1762        canvas.setBitmap(null);
1763
1764        return b;
1765    }
1766
1767    /**
1768     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
1769     * Responsibility for the bitmap is transferred to the caller.
1770     */
1771    private Bitmap createDragOutline(View v, Canvas canvas, int padding) {
1772        final int outlineColor = getResources().getColor(android.R.color.holo_blue_light);
1773        final Bitmap b = Bitmap.createBitmap(
1774                v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
1775
1776        canvas.setBitmap(b);
1777        drawDragView(v, canvas, padding, false);
1778        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1779        canvas.setBitmap(null);
1780        return b;
1781    }
1782
1783    /**
1784     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
1785     * Responsibility for the bitmap is transferred to the caller.
1786     */
1787    private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h) {
1788        final int outlineColor = getResources().getColor(android.R.color.holo_blue_light);
1789        final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
1790        canvas.setBitmap(b);
1791
1792        Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight());
1793        float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(),
1794                (h - padding) / (float) orig.getHeight());
1795        int scaledWidth = (int) (scaleFactor * orig.getWidth());
1796        int scaledHeight = (int) (scaleFactor * orig.getHeight());
1797        Rect dst = new Rect(0, 0, scaledWidth, scaledHeight);
1798
1799        // center the image
1800        dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2);
1801
1802        Paint p = new Paint();
1803        p.setFilterBitmap(true);
1804        canvas.drawBitmap(orig, src, dst, p);
1805        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1806        canvas.setBitmap(null);
1807
1808        return b;
1809    }
1810
1811    /**
1812     * Creates a drag outline to represent a drop (that we don't have the actual information for
1813     * yet).  May be changed in the future to alter the drop outline slightly depending on the
1814     * clip description mime data.
1815     */
1816    private Bitmap createExternalDragOutline(Canvas canvas, int padding) {
1817        Resources r = getResources();
1818        final int outlineColor = r.getColor(android.R.color.holo_blue_light);
1819        final int iconWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width);
1820        final int iconHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height);
1821        final int rectRadius = r.getDimensionPixelSize(R.dimen.external_drop_icon_rect_radius);
1822        final int inset = (int) (Math.min(iconWidth, iconHeight) * 0.2f);
1823        final Bitmap b = Bitmap.createBitmap(
1824                iconWidth + padding, iconHeight + padding, Bitmap.Config.ARGB_8888);
1825
1826        canvas.setBitmap(b);
1827        canvas.drawRoundRect(new RectF(inset, inset, iconWidth - inset, iconHeight - inset),
1828                rectRadius, rectRadius, mExternalDragOutlinePaint);
1829        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1830        canvas.setBitmap(null);
1831        return b;
1832    }
1833
1834    void startDrag(CellLayout.CellInfo cellInfo) {
1835        View child = cellInfo.cell;
1836
1837        // Make sure the drag was started by a long press as opposed to a long click.
1838        if (!child.isInTouchMode()) {
1839            return;
1840        }
1841
1842        mDragInfo = cellInfo;
1843        child.setVisibility(GONE);
1844
1845        child.clearFocus();
1846        child.setPressed(false);
1847
1848        final Canvas canvas = new Canvas();
1849
1850        // We need to add extra padding to the bitmap to make room for the glow effect
1851        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1852
1853        // The outline is used to visualize where the item will land if dropped
1854        mDragOutline = createDragOutline(child, canvas, bitmapPadding);
1855        beginDragShared(child, this);
1856    }
1857
1858    public void beginDragShared(View child, DragSource source) {
1859        // We need to add extra padding to the bitmap to make room for the glow effect
1860        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1861
1862        // The drag bitmap follows the touch point around on the screen
1863        final Bitmap b = createDragBitmap(child, new Canvas(), bitmapPadding);
1864
1865        final int bmpWidth = b.getWidth();
1866
1867        mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY);
1868        final int dragLayerX = (int) mTempXY[0] + (child.getWidth() - bmpWidth) / 2;
1869        int dragLayerY = mTempXY[1] - bitmapPadding / 2;
1870
1871        Rect dragRect = null;
1872        if (child instanceof BubbleTextView) {
1873            int iconSize = getResources().getDimensionPixelSize(R.dimen.app_icon_size);
1874            int top = child.getPaddingTop();
1875            int left = (bmpWidth - iconSize) / 2;
1876            int right = left + iconSize;
1877            int bottom = top + iconSize;
1878            dragLayerY += top;
1879            dragRect = new Rect(left, top, right, bottom);
1880        } else if (child instanceof FolderIcon) {
1881            int previewSize = getResources().getDimensionPixelSize(R.dimen.folder_preview_size);
1882            dragRect = new Rect(0, 0, child.getWidth(), previewSize);
1883        }
1884
1885        mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(),
1886                DragController.DRAG_ACTION_MOVE, dragRect);
1887        b.recycle();
1888    }
1889
1890    void addApplicationShortcut(ShortcutInfo info, CellLayout target, long container, int screen,
1891            int cellX, int cellY, boolean insertAtFirst, int intersectX, int intersectY) {
1892        View view = mLauncher.createShortcut(R.layout.application, target, (ShortcutInfo) info);
1893
1894        final int[] cellXY = new int[2];
1895        target.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY);
1896        addInScreen(view, container, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst);
1897        LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen, cellXY[0],
1898                cellXY[1]);
1899    }
1900
1901    public boolean transitionStateShouldAllowDrop() {
1902        return (!isSwitchingState() || mTransitionProgress > 0.5f);
1903    }
1904
1905    /**
1906     * {@inheritDoc}
1907     */
1908    public boolean acceptDrop(DragObject d) {
1909        // If it's an external drop (e.g. from All Apps), check if it should be accepted
1910        if (d.dragSource != this) {
1911            // Don't accept the drop if we're not over a screen at time of drop
1912            if (mDragTargetLayout == null) {
1913                return false;
1914            }
1915            if (!transitionStateShouldAllowDrop()) return false;
1916
1917            mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
1918                    d.dragView, mDragViewVisualCenter);
1919
1920            // We want the point to be mapped to the dragTarget.
1921            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
1922                mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter);
1923            } else {
1924                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
1925            }
1926
1927            int spanX = 1;
1928            int spanY = 1;
1929            View ignoreView = null;
1930            if (mDragInfo != null) {
1931                final CellLayout.CellInfo dragCellInfo = mDragInfo;
1932                spanX = dragCellInfo.spanX;
1933                spanY = dragCellInfo.spanY;
1934                ignoreView = dragCellInfo.cell;
1935            } else {
1936                final ItemInfo dragInfo = (ItemInfo) d.dragInfo;
1937                spanX = dragInfo.spanX;
1938                spanY = dragInfo.spanY;
1939            }
1940
1941            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
1942                    (int) mDragViewVisualCenter[1], spanX, spanY, mDragTargetLayout, mTargetCell);
1943            if (willCreateUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, mTargetCell, true)) {
1944                return true;
1945            }
1946            if (willAddToExistingUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout,
1947                    mTargetCell)) {
1948                return true;
1949            }
1950
1951
1952            // Don't accept the drop if there's no room for the item
1953            if (!mDragTargetLayout.findCellForSpanIgnoring(null, spanX, spanY, ignoreView)) {
1954                mLauncher.showOutOfSpaceMessage();
1955                return false;
1956            }
1957        }
1958        return true;
1959    }
1960
1961    boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell,
1962            boolean considerTimeout) {
1963        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
1964
1965        boolean hasntMoved = false;
1966        if (mDragInfo != null) {
1967            CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell);
1968            hasntMoved = (mDragInfo.cellX == targetCell[0] &&
1969                    mDragInfo.cellY == targetCell[1]) && (cellParent == target);
1970        }
1971
1972        if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) {
1973            return false;
1974        }
1975
1976        boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo);
1977        boolean willBecomeShortcut =
1978                (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
1979                info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT);
1980
1981        return (aboveShortcut && willBecomeShortcut);
1982    }
1983
1984    boolean willAddToExistingUserFolder(Object dragInfo, CellLayout target, int[] targetCell) {
1985        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
1986        if (dropOverView instanceof FolderIcon) {
1987            FolderIcon fi = (FolderIcon) dropOverView;
1988            if (fi.acceptDrop(dragInfo)) {
1989                return true;
1990            }
1991        }
1992        return false;
1993    }
1994
1995    boolean createUserFolderIfNecessary(View newView, long container, CellLayout target,
1996            int[] targetCell, boolean external, DragView dragView, Runnable postAnimationRunnable) {
1997        View v = target.getChildAt(targetCell[0], targetCell[1]);
1998        boolean hasntMoved = false;
1999        if (mDragInfo != null) {
2000            CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell);
2001            hasntMoved = (mDragInfo.cellX == targetCell[0] &&
2002                    mDragInfo.cellY == targetCell[1]) && (cellParent == target);
2003        }
2004
2005        if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false;
2006        mCreateUserFolderOnDrop = false;
2007        final int screen = (targetCell == null) ? mDragInfo.screen : indexOfChild(target);
2008
2009        boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo);
2010        boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo);
2011
2012        if (aboveShortcut && willBecomeShortcut) {
2013            ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag();
2014            ShortcutInfo destInfo = (ShortcutInfo) v.getTag();
2015            // if the drag started here, we need to remove it from the workspace
2016            if (!external) {
2017                getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2018            }
2019
2020            Rect folderLocation = new Rect();
2021            float scale = mLauncher.getDragLayer().getDescendantRectRelativeToSelf(v, folderLocation);
2022            target.removeView(v);
2023
2024            FolderIcon fi =
2025                mLauncher.addFolder(target, container, screen, targetCell[0], targetCell[1]);
2026            destInfo.cellX = -1;
2027            destInfo.cellY = -1;
2028            sourceInfo.cellX = -1;
2029            sourceInfo.cellY = -1;
2030
2031            // If the dragView is null, we can't animate
2032            boolean animate = dragView != null;
2033            if (animate) {
2034                fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale,
2035                        postAnimationRunnable);
2036            } else {
2037                fi.addItem(destInfo);
2038                fi.addItem(sourceInfo);
2039            }
2040            return true;
2041        }
2042        return false;
2043    }
2044
2045    boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell,
2046            DragObject d, boolean external) {
2047        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2048        if (dropOverView instanceof FolderIcon) {
2049            FolderIcon fi = (FolderIcon) dropOverView;
2050            if (fi.acceptDrop(d.dragInfo)) {
2051                fi.onDrop(d);
2052
2053                // if the drag started here, we need to remove it from the workspace
2054                if (!external) {
2055                    getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2056                }
2057                return true;
2058            }
2059        }
2060        return false;
2061    }
2062
2063    public void onDrop(DragObject d) {
2064        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView,
2065                mDragViewVisualCenter);
2066
2067        // We want the point to be mapped to the dragTarget.
2068        if (mDragTargetLayout != null) {
2069            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
2070                mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter);
2071            } else {
2072                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
2073            }
2074        }
2075
2076        CellLayout dropTargetLayout = mDragTargetLayout;
2077
2078        int snapScreen = -1;
2079        if (d.dragSource != this) {
2080            final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0],
2081                    (int) mDragViewVisualCenter[1] };
2082            onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d);
2083        } else if (mDragInfo != null) {
2084            final View cell = mDragInfo.cell;
2085
2086            if (dropTargetLayout != null) {
2087                // Move internally
2088                boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout);
2089                boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout);
2090                long container = hasMovedIntoHotseat ?
2091                        LauncherSettings.Favorites.CONTAINER_HOTSEAT :
2092                        LauncherSettings.Favorites.CONTAINER_DESKTOP;
2093                int screen = (mTargetCell[0] < 0) ?
2094                        mDragInfo.screen : indexOfChild(dropTargetLayout);
2095                int spanX = mDragInfo != null ? mDragInfo.spanX : 1;
2096                int spanY = mDragInfo != null ? mDragInfo.spanY : 1;
2097                // First we find the cell nearest to point at which the item is
2098                // dropped, without any consideration to whether there is an item there.
2099                mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int)
2100                        mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell);
2101                // If the item being dropped is a shortcut and the nearest drop
2102                // cell also contains a shortcut, then create a folder with the two shortcuts.
2103                if (!mInScrollArea && createUserFolderIfNecessary(cell, container,
2104                        dropTargetLayout, mTargetCell, false, d.dragView, null)) {
2105                    return;
2106                }
2107
2108                if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell, d, false)) {
2109                    return;
2110                }
2111
2112                // Aside from the special case where we're dropping a shortcut onto a shortcut,
2113                // we need to find the nearest cell location that is vacant
2114                mTargetCell = findNearestVacantArea((int) mDragViewVisualCenter[0],
2115                        (int) mDragViewVisualCenter[1], mDragInfo.spanX, mDragInfo.spanY, cell,
2116                        dropTargetLayout, mTargetCell);
2117
2118                if (mCurrentPage != screen && !hasMovedIntoHotseat) {
2119                    snapScreen = screen;
2120                    snapToPage(screen);
2121                }
2122
2123                if (mTargetCell[0] >= 0 && mTargetCell[1] >= 0) {
2124                    if (hasMovedLayouts) {
2125                        // Reparent the view
2126                        getParentCellLayoutForView(cell).removeView(cell);
2127                        addInScreen(cell, container, screen, mTargetCell[0], mTargetCell[1],
2128                                mDragInfo.spanX, mDragInfo.spanY);
2129                    }
2130
2131                    // update the item's position after drop
2132                    final ItemInfo info = (ItemInfo) cell.getTag();
2133                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
2134                    dropTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1]);
2135                    lp.cellX = mTargetCell[0];
2136                    lp.cellY = mTargetCell[1];
2137                    cell.setId(LauncherModel.getCellLayoutChildId(container, mDragInfo.screen,
2138                            mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY));
2139
2140                    if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
2141                            cell instanceof LauncherAppWidgetHostView) {
2142                        final CellLayout cellLayout = dropTargetLayout;
2143                        // We post this call so that the widget has a chance to be placed
2144                        // in its final location
2145
2146                        final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell;
2147                        AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo();
2148                        if (pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) {
2149                            final Runnable resizeRunnable = new Runnable() {
2150                                public void run() {
2151                                    DragLayer dragLayer = mLauncher.getDragLayer();
2152                                    dragLayer.addResizeFrame(info, hostView, cellLayout);
2153                                }
2154                            };
2155                            post(new Runnable() {
2156                                public void run() {
2157                                    if (!isPageMoving()) {
2158                                        resizeRunnable.run();
2159                                    } else {
2160                                        mDelayedResizeRunnable = resizeRunnable;
2161                                    }
2162                                }
2163                            });
2164                        }
2165                    }
2166
2167                    LauncherModel.moveItemInDatabase(mLauncher, info, container, screen, lp.cellX,
2168                            lp.cellY);
2169                }
2170            }
2171
2172            final CellLayout parent = (CellLayout) cell.getParent().getParent();
2173
2174            // Prepare it to be animated into its new position
2175            // This must be called after the view has been re-parented
2176            final Runnable disableHardwareLayersRunnable = new Runnable() {
2177                @Override
2178                public void run() {
2179                    mAnimatingViewIntoPlace = false;
2180                    updateChildrenLayersEnabled();
2181                }
2182            };
2183            mAnimatingViewIntoPlace = true;
2184            if (d.dragView.hasDrawn()) {
2185                int duration = snapScreen < 0 ? -1 : ADJACENT_SCREEN_DROP_DURATION;
2186                setFinalScrollForPageChange(snapScreen);
2187                mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration,
2188                        disableHardwareLayersRunnable);
2189                resetFinalScrollForPageChange(snapScreen);
2190            } else {
2191                cell.setVisibility(VISIBLE);
2192            }
2193            parent.onDropChild(cell);
2194        }
2195    }
2196
2197    public void setFinalScrollForPageChange(int screen) {
2198        if (screen >= 0) {
2199            mSavedScrollX = getScrollX();
2200            CellLayout cl = (CellLayout) getChildAt(screen);
2201            mSavedTranslationX = cl.getTranslationX();
2202            mSavedRotationY = cl.getRotationY();
2203            final int newX = getChildOffset(screen) - getRelativeChildOffset(screen);
2204            setScrollX(newX);
2205            cl.setTranslationX(0f);
2206            cl.setRotationY(0f);
2207        }
2208    }
2209
2210    public void resetFinalScrollForPageChange(int screen) {
2211        if (screen >= 0) {
2212            CellLayout cl = (CellLayout) getChildAt(screen);
2213            setScrollX(mSavedScrollX);
2214            cl.setTranslationX(mSavedTranslationX);
2215            cl.setRotationY(mSavedRotationY);
2216        }
2217    }
2218
2219    public void getViewLocationRelativeToSelf(View v, int[] location) {
2220        getLocationInWindow(location);
2221        int x = location[0];
2222        int y = location[1];
2223
2224        v.getLocationInWindow(location);
2225        int vX = location[0];
2226        int vY = location[1];
2227
2228        location[0] = vX - x;
2229        location[1] = vY - y;
2230    }
2231
2232    public void onDragEnter(DragObject d) {
2233        if (mDragTargetLayout != null) {
2234            mDragTargetLayout.setIsDragOverlapping(false);
2235            mDragTargetLayout.onDragExit();
2236        }
2237        mDragTargetLayout = getCurrentDropLayout();
2238        mDragTargetLayout.setIsDragOverlapping(true);
2239        mDragTargetLayout.onDragEnter();
2240
2241        // Because we don't have space in the Phone UI (the CellLayouts run to the edge) we
2242        // don't need to show the outlines
2243        if (LauncherApplication.isScreenLarge()) {
2244            showOutlines();
2245        }
2246    }
2247
2248    private void doDragExit(DragObject d) {
2249        // Clean up folders
2250        cleanupFolderCreation(d);
2251
2252        // Reset the scroll area and previous drag target
2253        onResetScrollArea();
2254
2255        if (mDragTargetLayout != null) {
2256            mDragTargetLayout.setIsDragOverlapping(false);
2257            mDragTargetLayout.onDragExit();
2258        }
2259        mLastDragOverView = null;
2260
2261        if (!mIsPageMoving) {
2262            hideOutlines();
2263        }
2264    }
2265
2266    public void onDragExit(DragObject d) {
2267        doDragExit(d);
2268    }
2269
2270    public DropTarget getDropTargetDelegate(DragObject d) {
2271        return null;
2272    }
2273
2274    /**
2275     * Tests to see if the drop will be accepted by Launcher, and if so, includes additional data
2276     * in the returned structure related to the widgets that match the drop (or a null list if it is
2277     * a shortcut drop).  If the drop is not accepted then a null structure is returned.
2278     */
2279    private Pair<Integer, List<WidgetMimeTypeHandlerData>> validateDrag(DragEvent event) {
2280        final LauncherModel model = mLauncher.getModel();
2281        final ClipDescription desc = event.getClipDescription();
2282        final int mimeTypeCount = desc.getMimeTypeCount();
2283        for (int i = 0; i < mimeTypeCount; ++i) {
2284            final String mimeType = desc.getMimeType(i);
2285            if (mimeType.equals(InstallShortcutReceiver.SHORTCUT_MIMETYPE)) {
2286                return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, null);
2287            } else {
2288                final List<WidgetMimeTypeHandlerData> widgets =
2289                    model.resolveWidgetsForMimeType(mContext, mimeType);
2290                if (widgets.size() > 0) {
2291                    return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, widgets);
2292                }
2293            }
2294        }
2295        return null;
2296    }
2297
2298    /**
2299     * Global drag and drop handler
2300     */
2301    @Override
2302    public boolean onDragEvent(DragEvent event) {
2303        final ClipDescription desc = event.getClipDescription();
2304        final CellLayout layout = (CellLayout) getChildAt(mCurrentPage);
2305        final int[] pos = new int[2];
2306        layout.getLocationOnScreen(pos);
2307        // We need to offset the drag coordinates to layout coordinate space
2308        final int x = (int) event.getX() - pos[0];
2309        final int y = (int) event.getY() - pos[1];
2310
2311        switch (event.getAction()) {
2312        case DragEvent.ACTION_DRAG_STARTED: {
2313            // Validate this drag
2314            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
2315            if (test != null) {
2316                boolean isShortcut = (test.second == null);
2317                if (isShortcut) {
2318                    // Check if we have enough space on this screen to add a new shortcut
2319                    if (!layout.findCellForSpan(pos, 1, 1)) {
2320                        mLauncher.showOutOfSpaceMessage();
2321                        return false;
2322                    }
2323                }
2324            } else {
2325                // Show error message if we couldn't accept any of the items
2326                Toast.makeText(mContext, mContext.getString(R.string.external_drop_widget_error),
2327                        Toast.LENGTH_SHORT).show();
2328                return false;
2329            }
2330
2331            // Create the drag outline
2332            // We need to add extra padding to the bitmap to make room for the glow effect
2333            final Canvas canvas = new Canvas();
2334            final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
2335            mDragOutline = createExternalDragOutline(canvas, bitmapPadding);
2336
2337            // Show the current page outlines to indicate that we can accept this drop
2338            showOutlines();
2339            layout.setIsDragOccuring(true);
2340            layout.onDragEnter();
2341            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
2342
2343            return true;
2344        }
2345        case DragEvent.ACTION_DRAG_LOCATION:
2346            // Visualize the drop location
2347            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
2348            return true;
2349        case DragEvent.ACTION_DROP: {
2350            // Try and add any shortcuts
2351            final LauncherModel model = mLauncher.getModel();
2352            final ClipData data = event.getClipData();
2353
2354            // We assume that the mime types are ordered in descending importance of
2355            // representation. So we enumerate the list of mime types and alert the
2356            // user if any widgets can handle the drop.  Only the most preferred
2357            // representation will be handled.
2358            pos[0] = x;
2359            pos[1] = y;
2360            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
2361            if (test != null) {
2362                final int index = test.first;
2363                final List<WidgetMimeTypeHandlerData> widgets = test.second;
2364                final boolean isShortcut = (widgets == null);
2365                final String mimeType = desc.getMimeType(index);
2366                if (isShortcut) {
2367                    final Intent intent = data.getItemAt(index).getIntent();
2368                    Object info = model.infoFromShortcutIntent(mContext, intent, data.getIcon());
2369                    onDropExternal(new int[] { x, y }, info, layout, false);
2370                } else {
2371                    if (widgets.size() == 1) {
2372                        // If there is only one item, then go ahead and add and configure
2373                        // that widget
2374                        final AppWidgetProviderInfo widgetInfo = widgets.get(0).widgetInfo;
2375                        final PendingAddWidgetInfo createInfo =
2376                                new PendingAddWidgetInfo(widgetInfo, mimeType, data);
2377                        mLauncher.addAppWidgetFromDrop(createInfo,
2378                            LauncherSettings.Favorites.CONTAINER_DESKTOP, mCurrentPage, null, pos);
2379                    } else {
2380                        // Show the widget picker dialog if there is more than one widget
2381                        // that can handle this data type
2382                        final InstallWidgetReceiver.WidgetListAdapter adapter =
2383                            new InstallWidgetReceiver.WidgetListAdapter(mLauncher, mimeType,
2384                                    data, widgets, layout, mCurrentPage, pos);
2385                        final AlertDialog.Builder builder =
2386                            new AlertDialog.Builder(mContext);
2387                        builder.setAdapter(adapter, adapter);
2388                        builder.setCancelable(true);
2389                        builder.setTitle(mContext.getString(
2390                                R.string.external_drop_widget_pick_title));
2391                        builder.setIcon(R.drawable.ic_no_applications);
2392                        builder.show();
2393                    }
2394                }
2395            }
2396            return true;
2397        }
2398        case DragEvent.ACTION_DRAG_ENDED:
2399            // Hide the page outlines after the drop
2400            layout.setIsDragOccuring(false);
2401            layout.onDragExit();
2402            hideOutlines();
2403            return true;
2404        }
2405        return super.onDragEvent(event);
2406    }
2407
2408    /*
2409    *
2410    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2411    * coordinate space. The argument xy is modified with the return result.
2412    *
2413    */
2414   void mapPointFromSelfToChild(View v, float[] xy) {
2415       mapPointFromSelfToChild(v, xy, null);
2416   }
2417
2418   /*
2419    *
2420    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2421    * coordinate space. The argument xy is modified with the return result.
2422    *
2423    * if cachedInverseMatrix is not null, this method will just use that matrix instead of
2424    * computing it itself; we use this to avoid redundant matrix inversions in
2425    * findMatchingPageForDragOver
2426    *
2427    */
2428   void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) {
2429       if (cachedInverseMatrix == null) {
2430           v.getMatrix().invert(mTempInverseMatrix);
2431           cachedInverseMatrix = mTempInverseMatrix;
2432       }
2433       xy[0] = xy[0] + mScrollX - v.getLeft();
2434       xy[1] = xy[1] + mScrollY - v.getTop();
2435       cachedInverseMatrix.mapPoints(xy);
2436   }
2437
2438   /*
2439    * Maps a point from the Workspace's coordinate system to another sibling view's. (Workspace
2440    * covers the full screen)
2441    */
2442   void mapPointFromSelfToSibling(View v, float[] xy) {
2443       xy[0] = xy[0] - v.getLeft();
2444       xy[1] = xy[1] - v.getTop();
2445   }
2446
2447   /*
2448    *
2449    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
2450    * the parent View's coordinate space. The argument xy is modified with the return result.
2451    *
2452    */
2453   void mapPointFromChildToSelf(View v, float[] xy) {
2454       v.getMatrix().mapPoints(xy);
2455       xy[0] -= (mScrollX - v.getLeft());
2456       xy[1] -= (mScrollY - v.getTop());
2457   }
2458
2459   static private float squaredDistance(float[] point1, float[] point2) {
2460        float distanceX = point1[0] - point2[0];
2461        float distanceY = point2[1] - point2[1];
2462        return distanceX * distanceX + distanceY * distanceY;
2463   }
2464
2465    /*
2466     *
2467     * Returns true if the passed CellLayout cl overlaps with dragView
2468     *
2469     */
2470    boolean overlaps(CellLayout cl, DragView dragView,
2471            int dragViewX, int dragViewY, Matrix cachedInverseMatrix) {
2472        // Transform the coordinates of the item being dragged to the CellLayout's coordinates
2473        final float[] draggedItemTopLeft = mTempDragCoordinates;
2474        draggedItemTopLeft[0] = dragViewX;
2475        draggedItemTopLeft[1] = dragViewY;
2476        final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates;
2477        draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getDragRegionWidth();
2478        draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getDragRegionHeight();
2479
2480        // Transform the dragged item's top left coordinates
2481        // to the CellLayout's local coordinates
2482        mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix);
2483        float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]);
2484        float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]);
2485
2486        if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) {
2487            // Transform the dragged item's bottom right coordinates
2488            // to the CellLayout's local coordinates
2489            mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix);
2490            float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]);
2491            float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]);
2492
2493            if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) {
2494                float overlap = (overlapRegionRight - overlapRegionLeft) *
2495                         (overlapRegionBottom - overlapRegionTop);
2496                if (overlap > 0) {
2497                    return true;
2498                }
2499             }
2500        }
2501        return false;
2502    }
2503
2504    /*
2505     *
2506     * This method returns the CellLayout that is currently being dragged to. In order to drag
2507     * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
2508     * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
2509     *
2510     * Return null if no CellLayout is currently being dragged over
2511     *
2512     */
2513    private CellLayout findMatchingPageForDragOver(
2514            DragView dragView, float originX, float originY, boolean exact) {
2515        // We loop through all the screens (ie CellLayouts) and see which ones overlap
2516        // with the item being dragged and then choose the one that's closest to the touch point
2517        final int screenCount = getChildCount();
2518        CellLayout bestMatchingScreen = null;
2519        float smallestDistSoFar = Float.MAX_VALUE;
2520
2521        for (int i = 0; i < screenCount; i++) {
2522            CellLayout cl = (CellLayout) getChildAt(i);
2523
2524            final float[] touchXy = {originX, originY};
2525            // Transform the touch coordinates to the CellLayout's local coordinates
2526            // If the touch point is within the bounds of the cell layout, we can return immediately
2527            cl.getMatrix().invert(mTempInverseMatrix);
2528            mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix);
2529
2530            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
2531                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
2532                return cl;
2533            }
2534
2535            if (!exact && overlaps(cl, dragView, (int) originX, (int) originY, mTempInverseMatrix)) {
2536                // Get the center of the cell layout in screen coordinates
2537                final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
2538                cellLayoutCenter[0] = cl.getWidth()/2;
2539                cellLayoutCenter[1] = cl.getHeight()/2;
2540                mapPointFromChildToSelf(cl, cellLayoutCenter);
2541
2542                touchXy[0] = originX;
2543                touchXy[1] = originY;
2544
2545                // Calculate the distance between the center of the CellLayout
2546                // and the touch point
2547                float dist = squaredDistance(touchXy, cellLayoutCenter);
2548
2549                if (dist < smallestDistSoFar) {
2550                    smallestDistSoFar = dist;
2551                    bestMatchingScreen = cl;
2552                }
2553            }
2554        }
2555        return bestMatchingScreen;
2556    }
2557
2558    // This is used to compute the visual center of the dragView. This point is then
2559    // used to visualize drop locations and determine where to drop an item. The idea is that
2560    // the visual center represents the user's interpretation of where the item is, and hence
2561    // is the appropriate point to use when determining drop location.
2562    private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset,
2563            DragView dragView, float[] recycle) {
2564        float res[];
2565        if (recycle == null) {
2566            res = new float[2];
2567        } else {
2568            res = recycle;
2569        }
2570
2571        // First off, the drag view has been shifted in a way that is not represented in the
2572        // x and y values or the x/yOffsets. Here we account for that shift.
2573        x += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX);
2574        y += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
2575
2576        // These represent the visual top and left of drag view if a dragRect was provided.
2577        // If a dragRect was not provided, then they correspond to the actual view left and
2578        // top, as the dragRect is in that case taken to be the entire dragView.
2579        // R.dimen.dragViewOffsetY.
2580        int left = x - xOffset;
2581        int top = y - yOffset;
2582
2583        // In order to find the visual center, we shift by half the dragRect
2584        res[0] = left + dragView.getDragRegion().width() / 2;
2585        res[1] = top + dragView.getDragRegion().height() / 2;
2586
2587        return res;
2588    }
2589
2590    private boolean isDragWidget(DragObject d) {
2591        return (d.dragInfo instanceof LauncherAppWidgetInfo ||
2592                d.dragInfo instanceof PendingAddWidgetInfo);
2593    }
2594    private boolean isExternalDragWidget(DragObject d) {
2595        return d.dragSource != this && isDragWidget(d);
2596    }
2597
2598    public void onDragOver(DragObject d) {
2599        // Skip drag over events while we are dragging over side pages
2600        if (mInScrollArea) return;
2601        if (mIsSwitchingState) return;
2602
2603        Rect r = new Rect();
2604        CellLayout layout = null;
2605        ItemInfo item = (ItemInfo) d.dragInfo;
2606
2607        // Ensure that we have proper spans for the item that we are dropping
2608        if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found");
2609        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
2610            d.dragView, mDragViewVisualCenter);
2611
2612        // Identify whether we have dragged over a side page
2613        if (isSmall()) {
2614            if (mLauncher.getHotseat() != null && !isExternalDragWidget(d)) {
2615                mLauncher.getHotseat().getHitRect(r);
2616                if (r.contains(d.x, d.y)) {
2617                    layout = mLauncher.getHotseat().getLayout();
2618                }
2619            }
2620            if (layout == null) {
2621                layout = findMatchingPageForDragOver(d.dragView, d.x, d.y, true);
2622            }
2623            if (layout != mDragTargetLayout) {
2624                // Cancel all intermediate folder states
2625                cleanupFolderCreation(d);
2626
2627                if (mDragTargetLayout != null) {
2628                    mDragTargetLayout.setIsDragOverlapping(false);
2629                    mDragTargetLayout.onDragExit();
2630                }
2631                mDragTargetLayout = layout;
2632                if (mDragTargetLayout != null) {
2633                    mDragTargetLayout.setIsDragOverlapping(true);
2634                    mDragTargetLayout.onDragEnter();
2635                } else {
2636                    mLastDragOverView = null;
2637                }
2638
2639                boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED);
2640                if (isInSpringLoadedMode) {
2641                    if (mLauncher.isHotseatLayout(layout)) {
2642                        mSpringLoadedDragController.cancel();
2643                    } else {
2644                        mSpringLoadedDragController.setAlarm(mDragTargetLayout);
2645                    }
2646                }
2647            }
2648        } else {
2649            // Test to see if we are over the hotseat otherwise just use the current page
2650            if (mLauncher.getHotseat() != null && !isDragWidget(d)) {
2651                mLauncher.getHotseat().getHitRect(r);
2652                if (r.contains(d.x, d.y)) {
2653                    layout = mLauncher.getHotseat().getLayout();
2654                }
2655            }
2656            if (layout == null) {
2657                layout = getCurrentDropLayout();
2658            }
2659            if (layout != mDragTargetLayout) {
2660                if (mDragTargetLayout != null) {
2661                    mDragTargetLayout.setIsDragOverlapping(false);
2662                    mDragTargetLayout.onDragExit();
2663                }
2664                mDragTargetLayout = layout;
2665                mDragTargetLayout.setIsDragOverlapping(true);
2666                mDragTargetLayout.onDragEnter();
2667            }
2668        }
2669
2670        // Handle the drag over
2671        if (mDragTargetLayout != null) {
2672            final View child = (mDragInfo == null) ? null : mDragInfo.cell;
2673
2674            // We want the point to be mapped to the dragTarget.
2675            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
2676                mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter);
2677            } else {
2678                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
2679            }
2680            ItemInfo info = (ItemInfo) d.dragInfo;
2681
2682            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2683                    (int) mDragViewVisualCenter[1], 1, 1, mDragTargetLayout, mTargetCell);
2684            final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0],
2685                    mTargetCell[1]);
2686
2687            boolean userFolderPending = willCreateUserFolder(info, mDragTargetLayout,
2688                    mTargetCell, false);
2689            boolean isOverFolder = dragOverView instanceof FolderIcon;
2690            if (dragOverView != mLastDragOverView) {
2691                cancelFolderCreation();
2692                if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) {
2693                    ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo);
2694                }
2695            }
2696
2697            if (userFolderPending && dragOverView != mLastDragOverView) {
2698                mFolderCreationAlarm.setOnAlarmListener(new
2699                        FolderCreationAlarmListener(mDragTargetLayout, mTargetCell[0], mTargetCell[1]));
2700                mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT);
2701            }
2702
2703            if (dragOverView != mLastDragOverView && isOverFolder) {
2704                ((FolderIcon) dragOverView).onDragEnter(d.dragInfo);
2705                if (mDragTargetLayout != null) {
2706                    mDragTargetLayout.clearDragOutlines();
2707                }
2708            }
2709            mLastDragOverView = dragOverView;
2710
2711            if (!mCreateUserFolderOnDrop && !isOverFolder) {
2712                mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
2713                        (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
2714                        item.spanX, item.spanY);
2715            }
2716        }
2717    }
2718
2719    private void cleanupFolderCreation(DragObject d) {
2720        if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) {
2721            mDragFolderRingAnimator.animateToNaturalState();
2722        }
2723        if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) {
2724            if (d != null) {
2725                ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo);
2726            }
2727        }
2728        mFolderCreationAlarm.cancelAlarm();
2729    }
2730
2731    private void cancelFolderCreation() {
2732        if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) {
2733            mDragFolderRingAnimator.animateToNaturalState();
2734        }
2735        mCreateUserFolderOnDrop = false;
2736        mFolderCreationAlarm.cancelAlarm();
2737    }
2738
2739    class FolderCreationAlarmListener implements OnAlarmListener {
2740        CellLayout layout;
2741        int cellX;
2742        int cellY;
2743
2744        public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) {
2745            this.layout = layout;
2746            this.cellX = cellX;
2747            this.cellY = cellY;
2748        }
2749
2750        public void onAlarm(Alarm alarm) {
2751            if (mDragFolderRingAnimator == null) {
2752                mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null);
2753            }
2754            mDragFolderRingAnimator.setCell(cellX, cellY);
2755            mDragFolderRingAnimator.setCellLayout(layout);
2756            mDragFolderRingAnimator.animateToAcceptState();
2757            layout.showFolderAccept(mDragFolderRingAnimator);
2758            layout.clearDragOutlines();
2759            mCreateUserFolderOnDrop = true;
2760        }
2761    }
2762
2763    @Override
2764    public void getHitRect(Rect outRect) {
2765        // We want the workspace to have the whole area of the display (it will find the correct
2766        // cell layout to drop to in the existing drag/drop logic.
2767        outRect.set(0, 0, mDisplayWidth, mDisplayHeight);
2768    }
2769
2770    /**
2771     * Add the item specified by dragInfo to the given layout.
2772     * @return true if successful
2773     */
2774    public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) {
2775        if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) {
2776            onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false);
2777            return true;
2778        }
2779        mLauncher.showOutOfSpaceMessage();
2780        return false;
2781    }
2782
2783    private void onDropExternal(int[] touchXY, Object dragInfo,
2784            CellLayout cellLayout, boolean insertAtFirst) {
2785        onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null);
2786    }
2787
2788    /**
2789     * Drop an item that didn't originate on one of the workspace screens.
2790     * It may have come from Launcher (e.g. from all apps or customize), or it may have
2791     * come from another app altogether.
2792     *
2793     * NOTE: This can also be called when we are outside of a drag event, when we want
2794     * to add an item to one of the workspace screens.
2795     */
2796    private void onDropExternal(final int[] touchXY, final Object dragInfo,
2797            final CellLayout cellLayout, boolean insertAtFirst, DragObject d) {
2798        final Runnable exitSpringLoadedRunnable = new Runnable() {
2799            @Override
2800            public void run() {
2801                mLauncher.exitSpringLoadedDragModeDelayed(true, false);
2802            }
2803        };
2804
2805        ItemInfo info = (ItemInfo) dragInfo;
2806        int spanX = info.spanX;
2807        int spanY = info.spanY;
2808        if (mDragInfo != null) {
2809            spanX = mDragInfo.spanX;
2810            spanY = mDragInfo.spanY;
2811        }
2812
2813        final long container = mLauncher.isHotseatLayout(cellLayout) ?
2814                LauncherSettings.Favorites.CONTAINER_HOTSEAT :
2815                    LauncherSettings.Favorites.CONTAINER_DESKTOP;
2816        final int screen = indexOfChild(cellLayout);
2817        if (!mLauncher.isHotseatLayout(cellLayout) && screen != mCurrentPage
2818                && mState != State.SPRING_LOADED) {
2819            snapToPage(screen);
2820        }
2821
2822        if (info instanceof PendingAddItemInfo) {
2823            final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo;
2824
2825            boolean findNearestVacantCell = true;
2826            if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
2827                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
2828                        cellLayout, mTargetCell);
2829                if (willCreateUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, mTargetCell,
2830                        true) || willAddToExistingUserFolder((ItemInfo) d.dragInfo,
2831                                mDragTargetLayout, mTargetCell)) {
2832                    findNearestVacantCell = false;
2833                }
2834            }
2835            if (findNearestVacantCell) {
2836                    mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], spanX, spanY, null,
2837                        cellLayout, mTargetCell);
2838            }
2839
2840            Runnable onAnimationCompleteRunnable = new Runnable() {
2841                @Override
2842                public void run() {
2843                    // When dragging and dropping from customization tray, we deal with creating
2844                    // widgets/shortcuts/folders in a slightly different way
2845                    switch (pendingInfo.itemType) {
2846                    case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2847                        mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) pendingInfo,
2848                                container, screen, mTargetCell, null);
2849                        break;
2850                    case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2851                        mLauncher.processShortcutFromDrop(pendingInfo.componentName,
2852                                container, screen, mTargetCell, null);
2853                        break;
2854                    default:
2855                        throw new IllegalStateException("Unknown item type: " +
2856                                pendingInfo.itemType);
2857                    }
2858                    cellLayout.onDragExit();
2859                }
2860            };
2861
2862            // Now we animate the dragView, (ie. the widget or shortcut preview) into its final
2863            // location and size on the home screen.
2864            int loc[] = new int[2];
2865            cellLayout.cellToPoint(mTargetCell[0], mTargetCell[1], loc);
2866
2867            RectF r = new RectF();
2868            cellLayout.cellToRect(mTargetCell[0], mTargetCell[1], spanX, spanY, r);
2869            setFinalTransitionTransform(cellLayout);
2870            float cellLayoutScale =
2871                    mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(cellLayout, loc);
2872            resetTransitionTransform(cellLayout);
2873
2874            float dragViewScale =  r.width() / d.dragView.getMeasuredWidth();
2875            // The animation will scale the dragView about its center, so we need to center about
2876            // the final location.
2877            loc[0] -= (d.dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2;
2878            loc[1] -= (d.dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2;
2879
2880            mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, loc,
2881                    dragViewScale * cellLayoutScale, onAnimationCompleteRunnable);
2882        } else {
2883            // This is for other drag/drop cases, like dragging from All Apps
2884            View view = null;
2885
2886            switch (info.itemType) {
2887            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
2888            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2889                if (info.container == NO_ID && info instanceof ApplicationInfo) {
2890                    // Came from all apps -- make a copy
2891                    info = new ShortcutInfo((ApplicationInfo) info);
2892                }
2893                view = mLauncher.createShortcut(R.layout.application, cellLayout,
2894                        (ShortcutInfo) info);
2895                break;
2896            case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2897                view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout,
2898                        (FolderInfo) info, mIconCache);
2899                break;
2900            default:
2901                throw new IllegalStateException("Unknown item type: " + info.itemType);
2902            }
2903
2904            // First we find the cell nearest to point at which the item is
2905            // dropped, without any consideration to whether there is an item there.
2906            if (touchXY != null) {
2907                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
2908                        cellLayout, mTargetCell);
2909                d.postAnimationRunnable = exitSpringLoadedRunnable;
2910                if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, true,
2911                        d.dragView, d.postAnimationRunnable)) {
2912                    return;
2913                }
2914                if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, d, true)) {
2915                    return;
2916                }
2917            }
2918
2919            if (touchXY != null) {
2920                // when dragging and dropping, just find the closest free spot
2921                mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, null,
2922                        cellLayout, mTargetCell);
2923            } else {
2924                cellLayout.findCellForSpan(mTargetCell, 1, 1);
2925            }
2926            addInScreen(view, container, screen, mTargetCell[0], mTargetCell[1], info.spanX,
2927                    info.spanY, insertAtFirst);
2928            cellLayout.onDropChild(view);
2929            cellLayout.animateDrop();
2930            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
2931            cellLayout.getChildrenLayout().measureChild(view);
2932
2933            LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen,
2934                    lp.cellX, lp.cellY);
2935
2936            if (d.dragView != null) {
2937                // We wrap the animation call in the temporary set and reset of the current
2938                // cellLayout to its final transform -- this means we animate the drag view to
2939                // the correct final location.
2940                setFinalTransitionTransform(cellLayout);
2941                mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view,
2942                        exitSpringLoadedRunnable);
2943                resetTransitionTransform(cellLayout);
2944            }
2945        }
2946    }
2947
2948    public void setFinalTransitionTransform(CellLayout layout) {
2949        if (isSwitchingState()) {
2950            int index = indexOfChild(layout);
2951            mCurrentScaleX = layout.getScaleX();
2952            mCurrentScaleY = layout.getScaleY();
2953            mCurrentTranslationX = layout.getTranslationX();
2954            mCurrentTranslationY = layout.getTranslationY();
2955            mCurrentRotationY = layout.getRotationY();
2956            layout.setScaleX(mNewScaleXs[index]);
2957            layout.setScaleY(mNewScaleYs[index]);
2958            layout.setTranslationX(mNewTranslationXs[index]);
2959            layout.setTranslationY(mNewTranslationYs[index]);
2960            layout.setRotationY(mNewRotationYs[index]);
2961        }
2962    }
2963    public void resetTransitionTransform(CellLayout layout) {
2964        if (isSwitchingState()) {
2965            mCurrentScaleX = layout.getScaleX();
2966            mCurrentScaleY = layout.getScaleY();
2967            mCurrentTranslationX = layout.getTranslationX();
2968            mCurrentTranslationY = layout.getTranslationY();
2969            mCurrentRotationY = layout.getRotationY();
2970            layout.setScaleX(mCurrentScaleX);
2971            layout.setScaleY(mCurrentScaleY);
2972            layout.setTranslationX(mCurrentTranslationX);
2973            layout.setTranslationY(mCurrentTranslationY);
2974            layout.setRotationY(mCurrentRotationY);
2975        }
2976    }
2977
2978    /**
2979     * Return the current {@link CellLayout}, correctly picking the destination
2980     * screen while a scroll is in progress.
2981     */
2982    public CellLayout getCurrentDropLayout() {
2983        return (CellLayout) getChildAt(mNextPage == INVALID_PAGE ? mCurrentPage : mNextPage);
2984    }
2985
2986    /**
2987     * Return the current CellInfo describing our current drag; this method exists
2988     * so that Launcher can sync this object with the correct info when the activity is created/
2989     * destroyed
2990     *
2991     */
2992    public CellLayout.CellInfo getDragInfo() {
2993        return mDragInfo;
2994    }
2995
2996    /**
2997     * Calculate the nearest cell where the given object would be dropped.
2998     *
2999     * pixelX and pixelY should be in the coordinate system of layout
3000     */
3001    private int[] findNearestVacantArea(int pixelX, int pixelY,
3002            int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) {
3003        return layout.findNearestVacantArea(
3004                pixelX, pixelY, spanX, spanY, ignoreView, recycle);
3005    }
3006
3007    /**
3008     * Calculate the nearest cell where the given object would be dropped.
3009     *
3010     * pixelX and pixelY should be in the coordinate system of layout
3011     */
3012    private int[] findNearestArea(int pixelX, int pixelY,
3013            int spanX, int spanY, CellLayout layout, int[] recycle) {
3014        return layout.findNearestArea(
3015                pixelX, pixelY, spanX, spanY, recycle);
3016    }
3017
3018    void setup(DragController dragController) {
3019        mSpringLoadedDragController = new SpringLoadedDragController(mLauncher);
3020        mDragController = dragController;
3021
3022        // hardware layers on children are enabled on startup, but should be disabled until
3023        // needed
3024        updateChildrenLayersEnabled();
3025        setWallpaperDimension();
3026    }
3027
3028    /**
3029     * Called at the end of a drag which originated on the workspace.
3030     */
3031    public void onDropCompleted(View target, DragObject d, boolean success) {
3032        if (success) {
3033            if (target != this) {
3034                if (mDragInfo != null) {
3035                    getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
3036                    if (mDragInfo.cell instanceof DropTarget) {
3037                        mDragController.removeDropTarget((DropTarget) mDragInfo.cell);
3038                    }
3039                }
3040            }
3041        } else if (mDragInfo != null) {
3042            // NOTE: When 'success' is true, onDragExit is called by the DragController before
3043            // calling onDropCompleted(). We call it ourselves here, but maybe this should be
3044            // moved into DragController.cancelDrag().
3045            doDragExit(null);
3046            CellLayout cellLayout;
3047            if (mLauncher.isHotseatLayout(target)) {
3048                cellLayout = mLauncher.getHotseat().getLayout();
3049            } else {
3050                cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
3051            }
3052            cellLayout.onDropChild(mDragInfo.cell);
3053        }
3054        mDragOutline = null;
3055        mDragInfo = null;
3056    }
3057
3058    public boolean isDropEnabled() {
3059        return true;
3060    }
3061
3062    @Override
3063    protected void onRestoreInstanceState(Parcelable state) {
3064        super.onRestoreInstanceState(state);
3065        Launcher.setScreen(mCurrentPage);
3066    }
3067
3068    @Override
3069    public void scrollLeft() {
3070        if (!isSmall() && !mIsSwitchingState) {
3071            super.scrollLeft();
3072        }
3073        Folder openFolder = getOpenFolder();
3074        if (openFolder != null) {
3075            openFolder.completeDragExit();
3076        }
3077    }
3078
3079    @Override
3080    public void scrollRight() {
3081        if (!isSmall() && !mIsSwitchingState) {
3082            super.scrollRight();
3083        }
3084        Folder openFolder = getOpenFolder();
3085        if (openFolder != null) {
3086            openFolder.completeDragExit();
3087        }
3088    }
3089
3090    @Override
3091    public void onEnterScrollArea(int x, int y, int direction) {
3092        // Ignore the scroll area if we are dragging over the hot seat
3093        if (mLauncher.getHotseat() != null) {
3094            Rect r = new Rect();
3095            mLauncher.getHotseat().getHitRect(r);
3096            if (r.contains(x, y)) {
3097                return;
3098            }
3099        }
3100
3101        if (!isSmall() && !mIsSwitchingState) {
3102            mInScrollArea = true;
3103
3104            final int page = mCurrentPage + (direction == DragController.SCROLL_LEFT ? -1 : 1);
3105            final CellLayout layout = (CellLayout) getChildAt(page);
3106            cancelFolderCreation();
3107
3108            if (layout != null) {
3109                // Exit the current layout and mark the overlapping layout
3110                if (mDragTargetLayout != null) {
3111                    mDragTargetLayout.setIsDragOverlapping(false);
3112                    mDragTargetLayout.onDragExit();
3113                }
3114                mDragTargetLayout = layout;
3115                mDragTargetLayout.setIsDragOverlapping(true);
3116
3117                // Workspace is responsible for drawing the edge glow on adjacent pages,
3118                // so we need to redraw the workspace when this may have changed.
3119                invalidate();
3120            }
3121        }
3122    }
3123
3124    @Override
3125    public void onExitScrollArea() {
3126        if (mInScrollArea) {
3127            if (mDragTargetLayout != null) {
3128                // Unmark the overlapping layout and re-enter the current layout
3129                mDragTargetLayout.setIsDragOverlapping(false);
3130                mDragTargetLayout = getCurrentDropLayout();
3131                mDragTargetLayout.onDragEnter();
3132
3133                // Workspace is responsible for drawing the edge glow on adjacent pages,
3134                // so we need to redraw the workspace when this may have changed.
3135                invalidate();
3136            }
3137            mInScrollArea = false;
3138        }
3139    }
3140
3141    private void onResetScrollArea() {
3142        if (mDragTargetLayout != null) {
3143            // Unmark the overlapping layout
3144            mDragTargetLayout.setIsDragOverlapping(false);
3145
3146            // Workspace is responsible for drawing the edge glow on adjacent pages,
3147            // so we need to redraw the workspace when this may have changed.
3148            invalidate();
3149        }
3150        mInScrollArea = false;
3151    }
3152
3153    /**
3154     * Returns a specific CellLayout
3155     */
3156    CellLayout getParentCellLayoutForView(View v) {
3157        ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts();
3158        for (CellLayout layout : layouts) {
3159            if (layout.getChildrenLayout().indexOfChild(v) > -1) {
3160                return layout;
3161            }
3162        }
3163        return null;
3164    }
3165
3166    /**
3167     * Returns a list of all the CellLayouts in the workspace.
3168     */
3169    ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() {
3170        ArrayList<CellLayout> layouts = new ArrayList<CellLayout>();
3171        int screenCount = getChildCount();
3172        for (int screen = 0; screen < screenCount; screen++) {
3173            layouts.add(((CellLayout) getChildAt(screen)));
3174        }
3175        if (mLauncher.getHotseat() != null) {
3176            layouts.add(mLauncher.getHotseat().getLayout());
3177        }
3178        return layouts;
3179    }
3180
3181    /**
3182     * We should only use this to search for specific children.  Do not use this method to modify
3183     * CellLayoutChildren directly.
3184     */
3185    ArrayList<CellLayoutChildren> getWorkspaceAndHotseatCellLayoutChildren() {
3186        ArrayList<CellLayoutChildren> childrenLayouts = new ArrayList<CellLayoutChildren>();
3187        int screenCount = getChildCount();
3188        for (int screen = 0; screen < screenCount; screen++) {
3189            childrenLayouts.add(((CellLayout) getChildAt(screen)).getChildrenLayout());
3190        }
3191        if (mLauncher.getHotseat() != null) {
3192            childrenLayouts.add(mLauncher.getHotseat().getLayout().getChildrenLayout());
3193        }
3194        return childrenLayouts;
3195    }
3196
3197    public Folder getFolderForTag(Object tag) {
3198        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3199        for (CellLayoutChildren layout: childrenLayouts) {
3200            int count = layout.getChildCount();
3201            for (int i = 0; i < count; i++) {
3202                View child = layout.getChildAt(i);
3203                if (child instanceof Folder) {
3204                    Folder f = (Folder) child;
3205                    if (f.getInfo() == tag && f.getInfo().opened) {
3206                        return f;
3207                    }
3208                }
3209            }
3210        }
3211        return null;
3212    }
3213
3214    public View getViewForTag(Object tag) {
3215        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3216        for (CellLayoutChildren layout: childrenLayouts) {
3217            int count = layout.getChildCount();
3218            for (int i = 0; i < count; i++) {
3219                View child = layout.getChildAt(i);
3220                if (child.getTag() == tag) {
3221                    return child;
3222                }
3223            }
3224        }
3225        return null;
3226    }
3227
3228    void clearDropTargets() {
3229        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3230        for (CellLayoutChildren layout: childrenLayouts) {
3231            int childCount = layout.getChildCount();
3232            for (int j = 0; j < childCount; j++) {
3233                View v = layout.getChildAt(j);
3234                if (v instanceof DropTarget) {
3235                    mDragController.removeDropTarget((DropTarget) v);
3236                }
3237            }
3238        }
3239    }
3240
3241    void removeItems(final ArrayList<ApplicationInfo> apps) {
3242        final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext());
3243
3244        final HashSet<String> packageNames = new HashSet<String>();
3245        final int appCount = apps.size();
3246        for (int i = 0; i < appCount; i++) {
3247            packageNames.add(apps.get(i).componentName.getPackageName());
3248        }
3249
3250        ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
3251        for (final CellLayout layoutParent: cellLayouts) {
3252            final ViewGroup layout = layoutParent.getChildrenLayout();
3253
3254            // Avoid ANRs by treating each screen separately
3255            post(new Runnable() {
3256                public void run() {
3257                    final ArrayList<View> childrenToRemove = new ArrayList<View>();
3258                    childrenToRemove.clear();
3259
3260                    int childCount = layout.getChildCount();
3261                    for (int j = 0; j < childCount; j++) {
3262                        final View view = layout.getChildAt(j);
3263                        Object tag = view.getTag();
3264
3265                        if (tag instanceof ShortcutInfo) {
3266                            final ShortcutInfo info = (ShortcutInfo) tag;
3267                            final Intent intent = info.intent;
3268                            final ComponentName name = intent.getComponent();
3269
3270                            if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3271                                for (String packageName: packageNames) {
3272                                    if (packageName.equals(name.getPackageName())) {
3273                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3274                                        childrenToRemove.add(view);
3275                                    }
3276                                }
3277                            }
3278                        } else if (tag instanceof FolderInfo) {
3279                            final FolderInfo info = (FolderInfo) tag;
3280                            final ArrayList<ShortcutInfo> contents = info.contents;
3281                            final int contentsCount = contents.size();
3282                            final ArrayList<ShortcutInfo> appsToRemoveFromFolder =
3283                                    new ArrayList<ShortcutInfo>();
3284
3285                            for (int k = 0; k < contentsCount; k++) {
3286                                final ShortcutInfo appInfo = contents.get(k);
3287                                final Intent intent = appInfo.intent;
3288                                final ComponentName name = intent.getComponent();
3289
3290                                if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3291                                    for (String packageName: packageNames) {
3292                                        if (packageName.equals(name.getPackageName())) {
3293                                            appsToRemoveFromFolder.add(appInfo);
3294                                        }
3295                                    }
3296                                }
3297                            }
3298                            for (ShortcutInfo item: appsToRemoveFromFolder) {
3299                                info.remove(item);
3300                                LauncherModel.deleteItemFromDatabase(mLauncher, item);
3301                            }
3302                        } else if (tag instanceof LauncherAppWidgetInfo) {
3303                            final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag;
3304                            final AppWidgetProviderInfo provider =
3305                                    widgets.getAppWidgetInfo(info.appWidgetId);
3306                            if (provider != null) {
3307                                for (String packageName: packageNames) {
3308                                    if (packageName.equals(provider.provider.getPackageName())) {
3309                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3310                                        childrenToRemove.add(view);
3311                                    }
3312                                }
3313                            }
3314                        }
3315                    }
3316
3317                    childCount = childrenToRemove.size();
3318                    for (int j = 0; j < childCount; j++) {
3319                        View child = childrenToRemove.get(j);
3320                        // Note: We can not remove the view directly from CellLayoutChildren as this
3321                        // does not re-mark the spaces as unoccupied.
3322                        layoutParent.removeViewInLayout(child);
3323                        if (child instanceof DropTarget) {
3324                            mDragController.removeDropTarget((DropTarget)child);
3325                        }
3326                    }
3327
3328                    if (childCount > 0) {
3329                        layout.requestLayout();
3330                        layout.invalidate();
3331                    }
3332                }
3333            });
3334        }
3335    }
3336
3337    void updateShortcuts(ArrayList<ApplicationInfo> apps) {
3338        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3339        for (CellLayoutChildren layout: childrenLayouts) {
3340            int childCount = layout.getChildCount();
3341            for (int j = 0; j < childCount; j++) {
3342                final View view = layout.getChildAt(j);
3343                Object tag = view.getTag();
3344                if (tag instanceof ShortcutInfo) {
3345                    ShortcutInfo info = (ShortcutInfo)tag;
3346                    // We need to check for ACTION_MAIN otherwise getComponent() might
3347                    // return null for some shortcuts (for instance, for shortcuts to
3348                    // web pages.)
3349                    final Intent intent = info.intent;
3350                    final ComponentName name = intent.getComponent();
3351                    if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3352                            Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3353                        final int appCount = apps.size();
3354                        for (int k = 0; k < appCount; k++) {
3355                            ApplicationInfo app = apps.get(k);
3356                            if (app.componentName.equals(name)) {
3357                                info.setIcon(mIconCache.getIcon(info.intent));
3358                                ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null,
3359                                        new FastBitmapDrawable(info.getIcon(mIconCache)),
3360                                        null, null);
3361                                }
3362                        }
3363                    }
3364                }
3365            }
3366        }
3367    }
3368
3369    void moveToDefaultScreen(boolean animate) {
3370        if (!isSmall()) {
3371            if (animate) {
3372                snapToPage(mDefaultPage);
3373            } else {
3374                setCurrentPage(mDefaultPage);
3375            }
3376        }
3377        getChildAt(mDefaultPage).requestFocus();
3378    }
3379
3380    @Override
3381    public void syncPages() {
3382    }
3383
3384    @Override
3385    public void syncPageItems(int page, boolean immediate) {
3386    }
3387
3388    @Override
3389    protected String getCurrentPageDescription() {
3390        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
3391        return String.format(mContext.getString(R.string.workspace_scroll_format),
3392                page + 1, getChildCount());
3393    }
3394
3395    public void getLocationInDragLayer(int[] loc) {
3396        mLauncher.getDragLayer().getLocationInDragLayer(this, loc);
3397    }
3398
3399    void showDockDivider(boolean immediately) {
3400        final ViewGroup parent = (ViewGroup) getParent();
3401        final View qsbDivider = (ImageView) (parent.findViewById(R.id.qsb_divider));
3402        final View dockDivider = (ImageView) (parent.findViewById(R.id.dock_divider));
3403        if (qsbDivider != null && dockDivider != null) {
3404            qsbDivider.setVisibility(View.VISIBLE);
3405            dockDivider.setVisibility(View.VISIBLE);
3406            if (mDividerAnimator != null) {
3407                mDividerAnimator.cancel();
3408                mDividerAnimator = null;
3409            }
3410            if (immediately) {
3411                qsbDivider.setAlpha(1f);
3412                dockDivider.setAlpha(1f);
3413            } else {
3414                mDividerAnimator = new AnimatorSet();
3415                mDividerAnimator.playTogether(ObjectAnimator.ofFloat(qsbDivider, "alpha", 1f),
3416                        ObjectAnimator.ofFloat(dockDivider, "alpha", 1f));
3417                mDividerAnimator.setDuration(sScrollIndicatorFadeInDuration);
3418                mDividerAnimator.start();
3419            }
3420        }
3421    }
3422
3423    void hideDockDivider(boolean immediately) {
3424        final ViewGroup parent = (ViewGroup) getParent();
3425        final View qsbDivider = (ImageView) (parent.findViewById(R.id.qsb_divider));
3426        final View dockDivider = (ImageView) (parent.findViewById(R.id.dock_divider));
3427        if (qsbDivider != null && dockDivider != null) {
3428            if (mDividerAnimator != null) {
3429                mDividerAnimator.cancel();
3430                mDividerAnimator = null;
3431            }
3432            if (immediately) {
3433                qsbDivider.setVisibility(View.GONE);
3434                dockDivider.setVisibility(View.GONE);
3435                qsbDivider.setAlpha(0f);
3436                dockDivider.setAlpha(0f);
3437            } else {
3438                mDividerAnimator = new AnimatorSet();
3439                mDividerAnimator.playTogether(ObjectAnimator.ofFloat(qsbDivider, "alpha", 0f),
3440                        ObjectAnimator.ofFloat(dockDivider, "alpha", 0f));
3441                mDividerAnimator.addListener(new AnimatorListenerAdapter() {
3442                    private boolean cancelled = false;
3443                    @Override
3444                    public void onAnimationCancel(android.animation.Animator animation) {
3445                        cancelled = true;
3446                    }
3447                    @Override
3448                    public void onAnimationEnd(android.animation.Animator animation) {
3449                        if (!cancelled) {
3450                            qsbDivider.setVisibility(View.GONE);
3451                            dockDivider.setVisibility(View.GONE);
3452                        }
3453                    }
3454                });
3455                mDividerAnimator.setDuration(sScrollIndicatorFadeOutDuration);
3456                mDividerAnimator.start();
3457            }
3458        }
3459    }
3460}
3461