Workspace.java revision 700eef7bc66687ba626e507d93dcb93f829a5fba
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 = 2f;
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 IconKeyEventListener());
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 = Math.max((int) (minDim * WALLPAPER_SCREENS_SPAN), maxDim);
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        // Clear the pressed state if necessary
1886        if (child instanceof BubbleTextView) {
1887            BubbleTextView icon = (BubbleTextView) child;
1888            icon.clearPressedOrFocusedBackground();
1889        }
1890
1891        mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(),
1892                DragController.DRAG_ACTION_MOVE, dragRect);
1893        b.recycle();
1894    }
1895
1896    void addApplicationShortcut(ShortcutInfo info, CellLayout target, long container, int screen,
1897            int cellX, int cellY, boolean insertAtFirst, int intersectX, int intersectY) {
1898        View view = mLauncher.createShortcut(R.layout.application, target, (ShortcutInfo) info);
1899
1900        final int[] cellXY = new int[2];
1901        target.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY);
1902        addInScreen(view, container, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst);
1903        LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen, cellXY[0],
1904                cellXY[1]);
1905    }
1906
1907    public boolean transitionStateShouldAllowDrop() {
1908        return (!isSwitchingState() || mTransitionProgress > 0.5f);
1909    }
1910
1911    /**
1912     * {@inheritDoc}
1913     */
1914    public boolean acceptDrop(DragObject d) {
1915        // If it's an external drop (e.g. from All Apps), check if it should be accepted
1916        if (d.dragSource != this) {
1917            // Don't accept the drop if we're not over a screen at time of drop
1918            if (mDragTargetLayout == null) {
1919                return false;
1920            }
1921            if (!transitionStateShouldAllowDrop()) return false;
1922
1923            mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
1924                    d.dragView, mDragViewVisualCenter);
1925
1926            // We want the point to be mapped to the dragTarget.
1927            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
1928                mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter);
1929            } else {
1930                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
1931            }
1932
1933            int spanX = 1;
1934            int spanY = 1;
1935            View ignoreView = null;
1936            if (mDragInfo != null) {
1937                final CellLayout.CellInfo dragCellInfo = mDragInfo;
1938                spanX = dragCellInfo.spanX;
1939                spanY = dragCellInfo.spanY;
1940                ignoreView = dragCellInfo.cell;
1941            } else {
1942                final ItemInfo dragInfo = (ItemInfo) d.dragInfo;
1943                spanX = dragInfo.spanX;
1944                spanY = dragInfo.spanY;
1945            }
1946
1947            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
1948                    (int) mDragViewVisualCenter[1], spanX, spanY, mDragTargetLayout, mTargetCell);
1949            if (willCreateUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, mTargetCell, true)) {
1950                return true;
1951            }
1952            if (willAddToExistingUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout,
1953                    mTargetCell)) {
1954                return true;
1955            }
1956
1957
1958            // Don't accept the drop if there's no room for the item
1959            if (!mDragTargetLayout.findCellForSpanIgnoring(null, spanX, spanY, ignoreView)) {
1960                mLauncher.showOutOfSpaceMessage();
1961                return false;
1962            }
1963        }
1964        return true;
1965    }
1966
1967    boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell,
1968            boolean considerTimeout) {
1969        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
1970
1971        boolean hasntMoved = false;
1972        if (mDragInfo != null) {
1973            CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell);
1974            hasntMoved = (mDragInfo.cellX == targetCell[0] &&
1975                    mDragInfo.cellY == targetCell[1]) && (cellParent == target);
1976        }
1977
1978        if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) {
1979            return false;
1980        }
1981
1982        boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo);
1983        boolean willBecomeShortcut =
1984                (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
1985                info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT);
1986
1987        return (aboveShortcut && willBecomeShortcut);
1988    }
1989
1990    boolean willAddToExistingUserFolder(Object dragInfo, CellLayout target, int[] targetCell) {
1991        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
1992        if (dropOverView instanceof FolderIcon) {
1993            FolderIcon fi = (FolderIcon) dropOverView;
1994            if (fi.acceptDrop(dragInfo)) {
1995                return true;
1996            }
1997        }
1998        return false;
1999    }
2000
2001    boolean createUserFolderIfNecessary(View newView, long container, CellLayout target,
2002            int[] targetCell, boolean external, DragView dragView, Runnable postAnimationRunnable) {
2003        View v = target.getChildAt(targetCell[0], targetCell[1]);
2004        boolean hasntMoved = false;
2005        if (mDragInfo != null) {
2006            CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell);
2007            hasntMoved = (mDragInfo.cellX == targetCell[0] &&
2008                    mDragInfo.cellY == targetCell[1]) && (cellParent == target);
2009        }
2010
2011        if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false;
2012        mCreateUserFolderOnDrop = false;
2013        final int screen = (targetCell == null) ? mDragInfo.screen : indexOfChild(target);
2014
2015        boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo);
2016        boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo);
2017
2018        if (aboveShortcut && willBecomeShortcut) {
2019            ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag();
2020            ShortcutInfo destInfo = (ShortcutInfo) v.getTag();
2021            // if the drag started here, we need to remove it from the workspace
2022            if (!external) {
2023                getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2024            }
2025
2026            Rect folderLocation = new Rect();
2027            float scale = mLauncher.getDragLayer().getDescendantRectRelativeToSelf(v, folderLocation);
2028            target.removeView(v);
2029
2030            FolderIcon fi =
2031                mLauncher.addFolder(target, container, screen, targetCell[0], targetCell[1]);
2032            destInfo.cellX = -1;
2033            destInfo.cellY = -1;
2034            sourceInfo.cellX = -1;
2035            sourceInfo.cellY = -1;
2036
2037            // If the dragView is null, we can't animate
2038            boolean animate = dragView != null;
2039            if (animate) {
2040                fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale,
2041                        postAnimationRunnable);
2042            } else {
2043                fi.addItem(destInfo);
2044                fi.addItem(sourceInfo);
2045            }
2046            return true;
2047        }
2048        return false;
2049    }
2050
2051    boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell,
2052            DragObject d, boolean external) {
2053        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2054        if (dropOverView instanceof FolderIcon) {
2055            FolderIcon fi = (FolderIcon) dropOverView;
2056            if (fi.acceptDrop(d.dragInfo)) {
2057                fi.onDrop(d);
2058
2059                // if the drag started here, we need to remove it from the workspace
2060                if (!external) {
2061                    getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2062                }
2063                return true;
2064            }
2065        }
2066        return false;
2067    }
2068
2069    public void onDrop(DragObject d) {
2070        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView,
2071                mDragViewVisualCenter);
2072
2073        // We want the point to be mapped to the dragTarget.
2074        if (mDragTargetLayout != null) {
2075            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
2076                mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter);
2077            } else {
2078                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
2079            }
2080        }
2081
2082        CellLayout dropTargetLayout = mDragTargetLayout;
2083
2084        int snapScreen = -1;
2085        if (d.dragSource != this) {
2086            final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0],
2087                    (int) mDragViewVisualCenter[1] };
2088            onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d);
2089        } else if (mDragInfo != null) {
2090            final View cell = mDragInfo.cell;
2091
2092            if (dropTargetLayout != null) {
2093                // Move internally
2094                boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout);
2095                boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout);
2096                long container = hasMovedIntoHotseat ?
2097                        LauncherSettings.Favorites.CONTAINER_HOTSEAT :
2098                        LauncherSettings.Favorites.CONTAINER_DESKTOP;
2099                int screen = (mTargetCell[0] < 0) ?
2100                        mDragInfo.screen : indexOfChild(dropTargetLayout);
2101                int spanX = mDragInfo != null ? mDragInfo.spanX : 1;
2102                int spanY = mDragInfo != null ? mDragInfo.spanY : 1;
2103                // First we find the cell nearest to point at which the item is
2104                // dropped, without any consideration to whether there is an item there.
2105                mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int)
2106                        mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell);
2107                // If the item being dropped is a shortcut and the nearest drop
2108                // cell also contains a shortcut, then create a folder with the two shortcuts.
2109                if (!mInScrollArea && createUserFolderIfNecessary(cell, container,
2110                        dropTargetLayout, mTargetCell, false, d.dragView, null)) {
2111                    return;
2112                }
2113
2114                if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell, d, false)) {
2115                    return;
2116                }
2117
2118                // Aside from the special case where we're dropping a shortcut onto a shortcut,
2119                // we need to find the nearest cell location that is vacant
2120                mTargetCell = findNearestVacantArea((int) mDragViewVisualCenter[0],
2121                        (int) mDragViewVisualCenter[1], mDragInfo.spanX, mDragInfo.spanY, cell,
2122                        dropTargetLayout, mTargetCell);
2123
2124                if (mCurrentPage != screen && !hasMovedIntoHotseat) {
2125                    snapScreen = screen;
2126                    snapToPage(screen);
2127                }
2128
2129                if (mTargetCell[0] >= 0 && mTargetCell[1] >= 0) {
2130                    if (hasMovedLayouts) {
2131                        // Reparent the view
2132                        getParentCellLayoutForView(cell).removeView(cell);
2133                        addInScreen(cell, container, screen, mTargetCell[0], mTargetCell[1],
2134                                mDragInfo.spanX, mDragInfo.spanY);
2135                    }
2136
2137                    // update the item's position after drop
2138                    final ItemInfo info = (ItemInfo) cell.getTag();
2139                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
2140                    dropTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1]);
2141                    lp.cellX = mTargetCell[0];
2142                    lp.cellY = mTargetCell[1];
2143                    cell.setId(LauncherModel.getCellLayoutChildId(container, mDragInfo.screen,
2144                            mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY));
2145
2146                    if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
2147                            cell instanceof LauncherAppWidgetHostView) {
2148                        final CellLayout cellLayout = dropTargetLayout;
2149                        // We post this call so that the widget has a chance to be placed
2150                        // in its final location
2151
2152                        final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell;
2153                        AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo();
2154                        if (pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) {
2155                            final Runnable resizeRunnable = new Runnable() {
2156                                public void run() {
2157                                    DragLayer dragLayer = mLauncher.getDragLayer();
2158                                    dragLayer.addResizeFrame(info, hostView, cellLayout);
2159                                }
2160                            };
2161                            post(new Runnable() {
2162                                public void run() {
2163                                    if (!isPageMoving()) {
2164                                        resizeRunnable.run();
2165                                    } else {
2166                                        mDelayedResizeRunnable = resizeRunnable;
2167                                    }
2168                                }
2169                            });
2170                        }
2171                    }
2172
2173                    LauncherModel.moveItemInDatabase(mLauncher, info, container, screen, lp.cellX,
2174                            lp.cellY);
2175                }
2176            }
2177
2178            final CellLayout parent = (CellLayout) cell.getParent().getParent();
2179
2180            // Prepare it to be animated into its new position
2181            // This must be called after the view has been re-parented
2182            final Runnable disableHardwareLayersRunnable = new Runnable() {
2183                @Override
2184                public void run() {
2185                    mAnimatingViewIntoPlace = false;
2186                    updateChildrenLayersEnabled();
2187                }
2188            };
2189            mAnimatingViewIntoPlace = true;
2190            if (d.dragView.hasDrawn()) {
2191                int duration = snapScreen < 0 ? -1 : ADJACENT_SCREEN_DROP_DURATION;
2192                setFinalScrollForPageChange(snapScreen);
2193                mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration,
2194                        disableHardwareLayersRunnable);
2195                resetFinalScrollForPageChange(snapScreen);
2196            } else {
2197                cell.setVisibility(VISIBLE);
2198            }
2199            parent.onDropChild(cell);
2200        }
2201    }
2202
2203    public void setFinalScrollForPageChange(int screen) {
2204        if (screen >= 0) {
2205            mSavedScrollX = getScrollX();
2206            CellLayout cl = (CellLayout) getChildAt(screen);
2207            mSavedTranslationX = cl.getTranslationX();
2208            mSavedRotationY = cl.getRotationY();
2209            final int newX = getChildOffset(screen) - getRelativeChildOffset(screen);
2210            setScrollX(newX);
2211            cl.setTranslationX(0f);
2212            cl.setRotationY(0f);
2213        }
2214    }
2215
2216    public void resetFinalScrollForPageChange(int screen) {
2217        if (screen >= 0) {
2218            CellLayout cl = (CellLayout) getChildAt(screen);
2219            setScrollX(mSavedScrollX);
2220            cl.setTranslationX(mSavedTranslationX);
2221            cl.setRotationY(mSavedRotationY);
2222        }
2223    }
2224
2225    public void getViewLocationRelativeToSelf(View v, int[] location) {
2226        getLocationInWindow(location);
2227        int x = location[0];
2228        int y = location[1];
2229
2230        v.getLocationInWindow(location);
2231        int vX = location[0];
2232        int vY = location[1];
2233
2234        location[0] = vX - x;
2235        location[1] = vY - y;
2236    }
2237
2238    public void onDragEnter(DragObject d) {
2239        if (mDragTargetLayout != null) {
2240            mDragTargetLayout.setIsDragOverlapping(false);
2241            mDragTargetLayout.onDragExit();
2242        }
2243        mDragTargetLayout = getCurrentDropLayout();
2244        mDragTargetLayout.setIsDragOverlapping(true);
2245        mDragTargetLayout.onDragEnter();
2246
2247        // Because we don't have space in the Phone UI (the CellLayouts run to the edge) we
2248        // don't need to show the outlines
2249        if (LauncherApplication.isScreenLarge()) {
2250            showOutlines();
2251        }
2252    }
2253
2254    private void doDragExit(DragObject d) {
2255        // Clean up folders
2256        cleanupFolderCreation(d);
2257
2258        // Reset the scroll area and previous drag target
2259        onResetScrollArea();
2260
2261        if (mDragTargetLayout != null) {
2262            mDragTargetLayout.setIsDragOverlapping(false);
2263            mDragTargetLayout.onDragExit();
2264        }
2265        mLastDragOverView = null;
2266
2267        if (!mIsPageMoving) {
2268            hideOutlines();
2269        }
2270    }
2271
2272    public void onDragExit(DragObject d) {
2273        doDragExit(d);
2274    }
2275
2276    public DropTarget getDropTargetDelegate(DragObject d) {
2277        return null;
2278    }
2279
2280    /**
2281     * Tests to see if the drop will be accepted by Launcher, and if so, includes additional data
2282     * in the returned structure related to the widgets that match the drop (or a null list if it is
2283     * a shortcut drop).  If the drop is not accepted then a null structure is returned.
2284     */
2285    private Pair<Integer, List<WidgetMimeTypeHandlerData>> validateDrag(DragEvent event) {
2286        final LauncherModel model = mLauncher.getModel();
2287        final ClipDescription desc = event.getClipDescription();
2288        final int mimeTypeCount = desc.getMimeTypeCount();
2289        for (int i = 0; i < mimeTypeCount; ++i) {
2290            final String mimeType = desc.getMimeType(i);
2291            if (mimeType.equals(InstallShortcutReceiver.SHORTCUT_MIMETYPE)) {
2292                return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, null);
2293            } else {
2294                final List<WidgetMimeTypeHandlerData> widgets =
2295                    model.resolveWidgetsForMimeType(mContext, mimeType);
2296                if (widgets.size() > 0) {
2297                    return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, widgets);
2298                }
2299            }
2300        }
2301        return null;
2302    }
2303
2304    /**
2305     * Global drag and drop handler
2306     */
2307    @Override
2308    public boolean onDragEvent(DragEvent event) {
2309        final ClipDescription desc = event.getClipDescription();
2310        final CellLayout layout = (CellLayout) getChildAt(mCurrentPage);
2311        final int[] pos = new int[2];
2312        layout.getLocationOnScreen(pos);
2313        // We need to offset the drag coordinates to layout coordinate space
2314        final int x = (int) event.getX() - pos[0];
2315        final int y = (int) event.getY() - pos[1];
2316
2317        switch (event.getAction()) {
2318        case DragEvent.ACTION_DRAG_STARTED: {
2319            // Validate this drag
2320            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
2321            if (test != null) {
2322                boolean isShortcut = (test.second == null);
2323                if (isShortcut) {
2324                    // Check if we have enough space on this screen to add a new shortcut
2325                    if (!layout.findCellForSpan(pos, 1, 1)) {
2326                        mLauncher.showOutOfSpaceMessage();
2327                        return false;
2328                    }
2329                }
2330            } else {
2331                // Show error message if we couldn't accept any of the items
2332                Toast.makeText(mContext, mContext.getString(R.string.external_drop_widget_error),
2333                        Toast.LENGTH_SHORT).show();
2334                return false;
2335            }
2336
2337            // Create the drag outline
2338            // We need to add extra padding to the bitmap to make room for the glow effect
2339            final Canvas canvas = new Canvas();
2340            final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
2341            mDragOutline = createExternalDragOutline(canvas, bitmapPadding);
2342
2343            // Show the current page outlines to indicate that we can accept this drop
2344            showOutlines();
2345            layout.setIsDragOccuring(true);
2346            layout.onDragEnter();
2347            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
2348
2349            return true;
2350        }
2351        case DragEvent.ACTION_DRAG_LOCATION:
2352            // Visualize the drop location
2353            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
2354            return true;
2355        case DragEvent.ACTION_DROP: {
2356            // Try and add any shortcuts
2357            final LauncherModel model = mLauncher.getModel();
2358            final ClipData data = event.getClipData();
2359
2360            // We assume that the mime types are ordered in descending importance of
2361            // representation. So we enumerate the list of mime types and alert the
2362            // user if any widgets can handle the drop.  Only the most preferred
2363            // representation will be handled.
2364            pos[0] = x;
2365            pos[1] = y;
2366            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
2367            if (test != null) {
2368                final int index = test.first;
2369                final List<WidgetMimeTypeHandlerData> widgets = test.second;
2370                final boolean isShortcut = (widgets == null);
2371                final String mimeType = desc.getMimeType(index);
2372                if (isShortcut) {
2373                    final Intent intent = data.getItemAt(index).getIntent();
2374                    Object info = model.infoFromShortcutIntent(mContext, intent, data.getIcon());
2375                    onDropExternal(new int[] { x, y }, info, layout, false);
2376                } else {
2377                    if (widgets.size() == 1) {
2378                        // If there is only one item, then go ahead and add and configure
2379                        // that widget
2380                        final AppWidgetProviderInfo widgetInfo = widgets.get(0).widgetInfo;
2381                        final PendingAddWidgetInfo createInfo =
2382                                new PendingAddWidgetInfo(widgetInfo, mimeType, data);
2383                        mLauncher.addAppWidgetFromDrop(createInfo,
2384                            LauncherSettings.Favorites.CONTAINER_DESKTOP, mCurrentPage, null, pos);
2385                    } else {
2386                        // Show the widget picker dialog if there is more than one widget
2387                        // that can handle this data type
2388                        final InstallWidgetReceiver.WidgetListAdapter adapter =
2389                            new InstallWidgetReceiver.WidgetListAdapter(mLauncher, mimeType,
2390                                    data, widgets, layout, mCurrentPage, pos);
2391                        final AlertDialog.Builder builder =
2392                            new AlertDialog.Builder(mContext);
2393                        builder.setAdapter(adapter, adapter);
2394                        builder.setCancelable(true);
2395                        builder.setTitle(mContext.getString(
2396                                R.string.external_drop_widget_pick_title));
2397                        builder.setIcon(R.drawable.ic_no_applications);
2398                        builder.show();
2399                    }
2400                }
2401            }
2402            return true;
2403        }
2404        case DragEvent.ACTION_DRAG_ENDED:
2405            // Hide the page outlines after the drop
2406            layout.setIsDragOccuring(false);
2407            layout.onDragExit();
2408            hideOutlines();
2409            return true;
2410        }
2411        return super.onDragEvent(event);
2412    }
2413
2414    /*
2415    *
2416    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2417    * coordinate space. The argument xy is modified with the return result.
2418    *
2419    */
2420   void mapPointFromSelfToChild(View v, float[] xy) {
2421       mapPointFromSelfToChild(v, xy, null);
2422   }
2423
2424   /*
2425    *
2426    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2427    * coordinate space. The argument xy is modified with the return result.
2428    *
2429    * if cachedInverseMatrix is not null, this method will just use that matrix instead of
2430    * computing it itself; we use this to avoid redundant matrix inversions in
2431    * findMatchingPageForDragOver
2432    *
2433    */
2434   void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) {
2435       if (cachedInverseMatrix == null) {
2436           v.getMatrix().invert(mTempInverseMatrix);
2437           cachedInverseMatrix = mTempInverseMatrix;
2438       }
2439       xy[0] = xy[0] + mScrollX - v.getLeft();
2440       xy[1] = xy[1] + mScrollY - v.getTop();
2441       cachedInverseMatrix.mapPoints(xy);
2442   }
2443
2444   /*
2445    * Maps a point from the Workspace's coordinate system to another sibling view's. (Workspace
2446    * covers the full screen)
2447    */
2448   void mapPointFromSelfToSibling(View v, float[] xy) {
2449       xy[0] = xy[0] - v.getLeft();
2450       xy[1] = xy[1] - v.getTop();
2451   }
2452
2453   /*
2454    *
2455    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
2456    * the parent View's coordinate space. The argument xy is modified with the return result.
2457    *
2458    */
2459   void mapPointFromChildToSelf(View v, float[] xy) {
2460       v.getMatrix().mapPoints(xy);
2461       xy[0] -= (mScrollX - v.getLeft());
2462       xy[1] -= (mScrollY - v.getTop());
2463   }
2464
2465   static private float squaredDistance(float[] point1, float[] point2) {
2466        float distanceX = point1[0] - point2[0];
2467        float distanceY = point2[1] - point2[1];
2468        return distanceX * distanceX + distanceY * distanceY;
2469   }
2470
2471    /*
2472     *
2473     * Returns true if the passed CellLayout cl overlaps with dragView
2474     *
2475     */
2476    boolean overlaps(CellLayout cl, DragView dragView,
2477            int dragViewX, int dragViewY, Matrix cachedInverseMatrix) {
2478        // Transform the coordinates of the item being dragged to the CellLayout's coordinates
2479        final float[] draggedItemTopLeft = mTempDragCoordinates;
2480        draggedItemTopLeft[0] = dragViewX;
2481        draggedItemTopLeft[1] = dragViewY;
2482        final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates;
2483        draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getDragRegionWidth();
2484        draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getDragRegionHeight();
2485
2486        // Transform the dragged item's top left coordinates
2487        // to the CellLayout's local coordinates
2488        mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix);
2489        float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]);
2490        float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]);
2491
2492        if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) {
2493            // Transform the dragged item's bottom right coordinates
2494            // to the CellLayout's local coordinates
2495            mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix);
2496            float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]);
2497            float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]);
2498
2499            if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) {
2500                float overlap = (overlapRegionRight - overlapRegionLeft) *
2501                         (overlapRegionBottom - overlapRegionTop);
2502                if (overlap > 0) {
2503                    return true;
2504                }
2505             }
2506        }
2507        return false;
2508    }
2509
2510    /*
2511     *
2512     * This method returns the CellLayout that is currently being dragged to. In order to drag
2513     * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
2514     * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
2515     *
2516     * Return null if no CellLayout is currently being dragged over
2517     *
2518     */
2519    private CellLayout findMatchingPageForDragOver(
2520            DragView dragView, float originX, float originY, boolean exact) {
2521        // We loop through all the screens (ie CellLayouts) and see which ones overlap
2522        // with the item being dragged and then choose the one that's closest to the touch point
2523        final int screenCount = getChildCount();
2524        CellLayout bestMatchingScreen = null;
2525        float smallestDistSoFar = Float.MAX_VALUE;
2526
2527        for (int i = 0; i < screenCount; i++) {
2528            CellLayout cl = (CellLayout) getChildAt(i);
2529
2530            final float[] touchXy = {originX, originY};
2531            // Transform the touch coordinates to the CellLayout's local coordinates
2532            // If the touch point is within the bounds of the cell layout, we can return immediately
2533            cl.getMatrix().invert(mTempInverseMatrix);
2534            mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix);
2535
2536            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
2537                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
2538                return cl;
2539            }
2540
2541            if (!exact && overlaps(cl, dragView, (int) originX, (int) originY, mTempInverseMatrix)) {
2542                // Get the center of the cell layout in screen coordinates
2543                final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
2544                cellLayoutCenter[0] = cl.getWidth()/2;
2545                cellLayoutCenter[1] = cl.getHeight()/2;
2546                mapPointFromChildToSelf(cl, cellLayoutCenter);
2547
2548                touchXy[0] = originX;
2549                touchXy[1] = originY;
2550
2551                // Calculate the distance between the center of the CellLayout
2552                // and the touch point
2553                float dist = squaredDistance(touchXy, cellLayoutCenter);
2554
2555                if (dist < smallestDistSoFar) {
2556                    smallestDistSoFar = dist;
2557                    bestMatchingScreen = cl;
2558                }
2559            }
2560        }
2561        return bestMatchingScreen;
2562    }
2563
2564    // This is used to compute the visual center of the dragView. This point is then
2565    // used to visualize drop locations and determine where to drop an item. The idea is that
2566    // the visual center represents the user's interpretation of where the item is, and hence
2567    // is the appropriate point to use when determining drop location.
2568    private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset,
2569            DragView dragView, float[] recycle) {
2570        float res[];
2571        if (recycle == null) {
2572            res = new float[2];
2573        } else {
2574            res = recycle;
2575        }
2576
2577        // First off, the drag view has been shifted in a way that is not represented in the
2578        // x and y values or the x/yOffsets. Here we account for that shift.
2579        x += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX);
2580        y += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
2581
2582        // These represent the visual top and left of drag view if a dragRect was provided.
2583        // If a dragRect was not provided, then they correspond to the actual view left and
2584        // top, as the dragRect is in that case taken to be the entire dragView.
2585        // R.dimen.dragViewOffsetY.
2586        int left = x - xOffset;
2587        int top = y - yOffset;
2588
2589        // In order to find the visual center, we shift by half the dragRect
2590        res[0] = left + dragView.getDragRegion().width() / 2;
2591        res[1] = top + dragView.getDragRegion().height() / 2;
2592
2593        return res;
2594    }
2595
2596    private boolean isDragWidget(DragObject d) {
2597        return (d.dragInfo instanceof LauncherAppWidgetInfo ||
2598                d.dragInfo instanceof PendingAddWidgetInfo);
2599    }
2600    private boolean isExternalDragWidget(DragObject d) {
2601        return d.dragSource != this && isDragWidget(d);
2602    }
2603
2604    public void onDragOver(DragObject d) {
2605        // Skip drag over events while we are dragging over side pages
2606        if (mInScrollArea) return;
2607        if (mIsSwitchingState) return;
2608
2609        Rect r = new Rect();
2610        CellLayout layout = null;
2611        ItemInfo item = (ItemInfo) d.dragInfo;
2612
2613        // Ensure that we have proper spans for the item that we are dropping
2614        if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found");
2615        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
2616            d.dragView, mDragViewVisualCenter);
2617
2618        // Identify whether we have dragged over a side page
2619        if (isSmall()) {
2620            if (mLauncher.getHotseat() != null && !isExternalDragWidget(d)) {
2621                mLauncher.getHotseat().getHitRect(r);
2622                if (r.contains(d.x, d.y)) {
2623                    layout = mLauncher.getHotseat().getLayout();
2624                }
2625            }
2626            if (layout == null) {
2627                layout = findMatchingPageForDragOver(d.dragView, d.x, d.y, true);
2628            }
2629            if (layout != mDragTargetLayout) {
2630                // Cancel all intermediate folder states
2631                cleanupFolderCreation(d);
2632
2633                if (mDragTargetLayout != null) {
2634                    mDragTargetLayout.setIsDragOverlapping(false);
2635                    mDragTargetLayout.onDragExit();
2636                }
2637                mDragTargetLayout = layout;
2638                if (mDragTargetLayout != null) {
2639                    mDragTargetLayout.setIsDragOverlapping(true);
2640                    mDragTargetLayout.onDragEnter();
2641                } else {
2642                    mLastDragOverView = null;
2643                }
2644
2645                boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED);
2646                if (isInSpringLoadedMode) {
2647                    if (mLauncher.isHotseatLayout(layout)) {
2648                        mSpringLoadedDragController.cancel();
2649                    } else {
2650                        mSpringLoadedDragController.setAlarm(mDragTargetLayout);
2651                    }
2652                }
2653            }
2654        } else {
2655            // Test to see if we are over the hotseat otherwise just use the current page
2656            if (mLauncher.getHotseat() != null && !isDragWidget(d)) {
2657                mLauncher.getHotseat().getHitRect(r);
2658                if (r.contains(d.x, d.y)) {
2659                    layout = mLauncher.getHotseat().getLayout();
2660                }
2661            }
2662            if (layout == null) {
2663                layout = getCurrentDropLayout();
2664            }
2665            if (layout != mDragTargetLayout) {
2666                if (mDragTargetLayout != null) {
2667                    mDragTargetLayout.setIsDragOverlapping(false);
2668                    mDragTargetLayout.onDragExit();
2669                }
2670                mDragTargetLayout = layout;
2671                mDragTargetLayout.setIsDragOverlapping(true);
2672                mDragTargetLayout.onDragEnter();
2673            }
2674        }
2675
2676        // Handle the drag over
2677        if (mDragTargetLayout != null) {
2678            final View child = (mDragInfo == null) ? null : mDragInfo.cell;
2679
2680            // We want the point to be mapped to the dragTarget.
2681            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
2682                mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter);
2683            } else {
2684                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
2685            }
2686            ItemInfo info = (ItemInfo) d.dragInfo;
2687
2688            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2689                    (int) mDragViewVisualCenter[1], 1, 1, mDragTargetLayout, mTargetCell);
2690            final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0],
2691                    mTargetCell[1]);
2692
2693            boolean userFolderPending = willCreateUserFolder(info, mDragTargetLayout,
2694                    mTargetCell, false);
2695            boolean isOverFolder = dragOverView instanceof FolderIcon;
2696            if (dragOverView != mLastDragOverView) {
2697                cancelFolderCreation();
2698                if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) {
2699                    ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo);
2700                }
2701            }
2702
2703            if (userFolderPending && dragOverView != mLastDragOverView) {
2704                mFolderCreationAlarm.setOnAlarmListener(new
2705                        FolderCreationAlarmListener(mDragTargetLayout, mTargetCell[0], mTargetCell[1]));
2706                mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT);
2707            }
2708
2709            if (dragOverView != mLastDragOverView && isOverFolder) {
2710                ((FolderIcon) dragOverView).onDragEnter(d.dragInfo);
2711                if (mDragTargetLayout != null) {
2712                    mDragTargetLayout.clearDragOutlines();
2713                }
2714            }
2715            mLastDragOverView = dragOverView;
2716
2717            if (!mCreateUserFolderOnDrop && !isOverFolder) {
2718                mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
2719                        (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
2720                        item.spanX, item.spanY);
2721            }
2722        }
2723    }
2724
2725    private void cleanupFolderCreation(DragObject d) {
2726        if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) {
2727            mDragFolderRingAnimator.animateToNaturalState();
2728        }
2729        if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) {
2730            if (d != null) {
2731                ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo);
2732            }
2733        }
2734        mFolderCreationAlarm.cancelAlarm();
2735    }
2736
2737    private void cancelFolderCreation() {
2738        if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) {
2739            mDragFolderRingAnimator.animateToNaturalState();
2740        }
2741        mCreateUserFolderOnDrop = false;
2742        mFolderCreationAlarm.cancelAlarm();
2743    }
2744
2745    class FolderCreationAlarmListener implements OnAlarmListener {
2746        CellLayout layout;
2747        int cellX;
2748        int cellY;
2749
2750        public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) {
2751            this.layout = layout;
2752            this.cellX = cellX;
2753            this.cellY = cellY;
2754        }
2755
2756        public void onAlarm(Alarm alarm) {
2757            if (mDragFolderRingAnimator == null) {
2758                mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null);
2759            }
2760            mDragFolderRingAnimator.setCell(cellX, cellY);
2761            mDragFolderRingAnimator.setCellLayout(layout);
2762            mDragFolderRingAnimator.animateToAcceptState();
2763            layout.showFolderAccept(mDragFolderRingAnimator);
2764            layout.clearDragOutlines();
2765            mCreateUserFolderOnDrop = true;
2766        }
2767    }
2768
2769    @Override
2770    public void getHitRect(Rect outRect) {
2771        // We want the workspace to have the whole area of the display (it will find the correct
2772        // cell layout to drop to in the existing drag/drop logic.
2773        outRect.set(0, 0, mDisplayWidth, mDisplayHeight);
2774    }
2775
2776    /**
2777     * Add the item specified by dragInfo to the given layout.
2778     * @return true if successful
2779     */
2780    public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) {
2781        if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) {
2782            onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false);
2783            return true;
2784        }
2785        mLauncher.showOutOfSpaceMessage();
2786        return false;
2787    }
2788
2789    private void onDropExternal(int[] touchXY, Object dragInfo,
2790            CellLayout cellLayout, boolean insertAtFirst) {
2791        onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null);
2792    }
2793
2794    /**
2795     * Drop an item that didn't originate on one of the workspace screens.
2796     * It may have come from Launcher (e.g. from all apps or customize), or it may have
2797     * come from another app altogether.
2798     *
2799     * NOTE: This can also be called when we are outside of a drag event, when we want
2800     * to add an item to one of the workspace screens.
2801     */
2802    private void onDropExternal(final int[] touchXY, final Object dragInfo,
2803            final CellLayout cellLayout, boolean insertAtFirst, DragObject d) {
2804        final Runnable exitSpringLoadedRunnable = new Runnable() {
2805            @Override
2806            public void run() {
2807                mLauncher.exitSpringLoadedDragModeDelayed(true, false);
2808            }
2809        };
2810
2811        ItemInfo info = (ItemInfo) dragInfo;
2812        int spanX = info.spanX;
2813        int spanY = info.spanY;
2814        if (mDragInfo != null) {
2815            spanX = mDragInfo.spanX;
2816            spanY = mDragInfo.spanY;
2817        }
2818
2819        final long container = mLauncher.isHotseatLayout(cellLayout) ?
2820                LauncherSettings.Favorites.CONTAINER_HOTSEAT :
2821                    LauncherSettings.Favorites.CONTAINER_DESKTOP;
2822        final int screen = indexOfChild(cellLayout);
2823        if (!mLauncher.isHotseatLayout(cellLayout) && screen != mCurrentPage
2824                && mState != State.SPRING_LOADED) {
2825            snapToPage(screen);
2826        }
2827
2828        if (info instanceof PendingAddItemInfo) {
2829            final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo;
2830
2831            boolean findNearestVacantCell = true;
2832            if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
2833                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
2834                        cellLayout, mTargetCell);
2835                if (willCreateUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, mTargetCell,
2836                        true) || willAddToExistingUserFolder((ItemInfo) d.dragInfo,
2837                                mDragTargetLayout, mTargetCell)) {
2838                    findNearestVacantCell = false;
2839                }
2840            }
2841            if (findNearestVacantCell) {
2842                    mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], spanX, spanY, null,
2843                        cellLayout, mTargetCell);
2844            }
2845
2846            Runnable onAnimationCompleteRunnable = new Runnable() {
2847                @Override
2848                public void run() {
2849                    // When dragging and dropping from customization tray, we deal with creating
2850                    // widgets/shortcuts/folders in a slightly different way
2851                    switch (pendingInfo.itemType) {
2852                    case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2853                        mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) pendingInfo,
2854                                container, screen, mTargetCell, null);
2855                        break;
2856                    case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2857                        mLauncher.processShortcutFromDrop(pendingInfo.componentName,
2858                                container, screen, mTargetCell, null);
2859                        break;
2860                    default:
2861                        throw new IllegalStateException("Unknown item type: " +
2862                                pendingInfo.itemType);
2863                    }
2864                    cellLayout.onDragExit();
2865                }
2866            };
2867
2868            // Now we animate the dragView, (ie. the widget or shortcut preview) into its final
2869            // location and size on the home screen.
2870            int loc[] = new int[2];
2871            cellLayout.cellToPoint(mTargetCell[0], mTargetCell[1], loc);
2872
2873            RectF r = new RectF();
2874            cellLayout.cellToRect(mTargetCell[0], mTargetCell[1], spanX, spanY, r);
2875            setFinalTransitionTransform(cellLayout);
2876            float cellLayoutScale =
2877                    mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(cellLayout, loc);
2878            resetTransitionTransform(cellLayout);
2879
2880            float dragViewScale =  r.width() / d.dragView.getMeasuredWidth();
2881            // The animation will scale the dragView about its center, so we need to center about
2882            // the final location.
2883            loc[0] -= (d.dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2;
2884            loc[1] -= (d.dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2;
2885
2886            mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, loc,
2887                    dragViewScale * cellLayoutScale, onAnimationCompleteRunnable);
2888        } else {
2889            // This is for other drag/drop cases, like dragging from All Apps
2890            View view = null;
2891
2892            switch (info.itemType) {
2893            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
2894            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2895                if (info.container == NO_ID && info instanceof ApplicationInfo) {
2896                    // Came from all apps -- make a copy
2897                    info = new ShortcutInfo((ApplicationInfo) info);
2898                }
2899                view = mLauncher.createShortcut(R.layout.application, cellLayout,
2900                        (ShortcutInfo) info);
2901                break;
2902            case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2903                view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout,
2904                        (FolderInfo) info, mIconCache);
2905                break;
2906            default:
2907                throw new IllegalStateException("Unknown item type: " + info.itemType);
2908            }
2909
2910            // First we find the cell nearest to point at which the item is
2911            // dropped, without any consideration to whether there is an item there.
2912            if (touchXY != null) {
2913                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
2914                        cellLayout, mTargetCell);
2915                d.postAnimationRunnable = exitSpringLoadedRunnable;
2916                if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, true,
2917                        d.dragView, d.postAnimationRunnable)) {
2918                    return;
2919                }
2920                if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, d, true)) {
2921                    return;
2922                }
2923            }
2924
2925            if (touchXY != null) {
2926                // when dragging and dropping, just find the closest free spot
2927                mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, null,
2928                        cellLayout, mTargetCell);
2929            } else {
2930                cellLayout.findCellForSpan(mTargetCell, 1, 1);
2931            }
2932            addInScreen(view, container, screen, mTargetCell[0], mTargetCell[1], info.spanX,
2933                    info.spanY, insertAtFirst);
2934            cellLayout.onDropChild(view);
2935            cellLayout.animateDrop();
2936            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
2937            cellLayout.getChildrenLayout().measureChild(view);
2938
2939            LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen,
2940                    lp.cellX, lp.cellY);
2941
2942            if (d.dragView != null) {
2943                // We wrap the animation call in the temporary set and reset of the current
2944                // cellLayout to its final transform -- this means we animate the drag view to
2945                // the correct final location.
2946                setFinalTransitionTransform(cellLayout);
2947                mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view,
2948                        exitSpringLoadedRunnable);
2949                resetTransitionTransform(cellLayout);
2950            }
2951        }
2952    }
2953
2954    public void setFinalTransitionTransform(CellLayout layout) {
2955        if (isSwitchingState()) {
2956            int index = indexOfChild(layout);
2957            mCurrentScaleX = layout.getScaleX();
2958            mCurrentScaleY = layout.getScaleY();
2959            mCurrentTranslationX = layout.getTranslationX();
2960            mCurrentTranslationY = layout.getTranslationY();
2961            mCurrentRotationY = layout.getRotationY();
2962            layout.setScaleX(mNewScaleXs[index]);
2963            layout.setScaleY(mNewScaleYs[index]);
2964            layout.setTranslationX(mNewTranslationXs[index]);
2965            layout.setTranslationY(mNewTranslationYs[index]);
2966            layout.setRotationY(mNewRotationYs[index]);
2967        }
2968    }
2969    public void resetTransitionTransform(CellLayout layout) {
2970        if (isSwitchingState()) {
2971            mCurrentScaleX = layout.getScaleX();
2972            mCurrentScaleY = layout.getScaleY();
2973            mCurrentTranslationX = layout.getTranslationX();
2974            mCurrentTranslationY = layout.getTranslationY();
2975            mCurrentRotationY = layout.getRotationY();
2976            layout.setScaleX(mCurrentScaleX);
2977            layout.setScaleY(mCurrentScaleY);
2978            layout.setTranslationX(mCurrentTranslationX);
2979            layout.setTranslationY(mCurrentTranslationY);
2980            layout.setRotationY(mCurrentRotationY);
2981        }
2982    }
2983
2984    /**
2985     * Return the current {@link CellLayout}, correctly picking the destination
2986     * screen while a scroll is in progress.
2987     */
2988    public CellLayout getCurrentDropLayout() {
2989        return (CellLayout) getChildAt(mNextPage == INVALID_PAGE ? mCurrentPage : mNextPage);
2990    }
2991
2992    /**
2993     * Return the current CellInfo describing our current drag; this method exists
2994     * so that Launcher can sync this object with the correct info when the activity is created/
2995     * destroyed
2996     *
2997     */
2998    public CellLayout.CellInfo getDragInfo() {
2999        return mDragInfo;
3000    }
3001
3002    /**
3003     * Calculate the nearest cell where the given object would be dropped.
3004     *
3005     * pixelX and pixelY should be in the coordinate system of layout
3006     */
3007    private int[] findNearestVacantArea(int pixelX, int pixelY,
3008            int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) {
3009        return layout.findNearestVacantArea(
3010                pixelX, pixelY, spanX, spanY, ignoreView, recycle);
3011    }
3012
3013    /**
3014     * Calculate the nearest cell where the given object would be dropped.
3015     *
3016     * pixelX and pixelY should be in the coordinate system of layout
3017     */
3018    private int[] findNearestArea(int pixelX, int pixelY,
3019            int spanX, int spanY, CellLayout layout, int[] recycle) {
3020        return layout.findNearestArea(
3021                pixelX, pixelY, spanX, spanY, recycle);
3022    }
3023
3024    void setup(DragController dragController) {
3025        mSpringLoadedDragController = new SpringLoadedDragController(mLauncher);
3026        mDragController = dragController;
3027
3028        // hardware layers on children are enabled on startup, but should be disabled until
3029        // needed
3030        updateChildrenLayersEnabled();
3031        setWallpaperDimension();
3032    }
3033
3034    /**
3035     * Called at the end of a drag which originated on the workspace.
3036     */
3037    public void onDropCompleted(View target, DragObject d, boolean success) {
3038        if (success) {
3039            if (target != this) {
3040                if (mDragInfo != null) {
3041                    getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
3042                    if (mDragInfo.cell instanceof DropTarget) {
3043                        mDragController.removeDropTarget((DropTarget) mDragInfo.cell);
3044                    }
3045                }
3046            }
3047        } else if (mDragInfo != null) {
3048            // NOTE: When 'success' is true, onDragExit is called by the DragController before
3049            // calling onDropCompleted(). We call it ourselves here, but maybe this should be
3050            // moved into DragController.cancelDrag().
3051            doDragExit(null);
3052            CellLayout cellLayout;
3053            if (mLauncher.isHotseatLayout(target)) {
3054                cellLayout = mLauncher.getHotseat().getLayout();
3055            } else {
3056                cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
3057            }
3058            cellLayout.onDropChild(mDragInfo.cell);
3059        }
3060        if (d.cancelled &&  mDragInfo.cell != null) {
3061                mDragInfo.cell.setVisibility(VISIBLE);
3062        }
3063        mDragOutline = null;
3064        mDragInfo = null;
3065    }
3066
3067    public boolean isDropEnabled() {
3068        return true;
3069    }
3070
3071    @Override
3072    protected void onRestoreInstanceState(Parcelable state) {
3073        super.onRestoreInstanceState(state);
3074        Launcher.setScreen(mCurrentPage);
3075    }
3076
3077    @Override
3078    public void scrollLeft() {
3079        if (!isSmall() && !mIsSwitchingState) {
3080            super.scrollLeft();
3081        }
3082        Folder openFolder = getOpenFolder();
3083        if (openFolder != null) {
3084            openFolder.completeDragExit();
3085        }
3086    }
3087
3088    @Override
3089    public void scrollRight() {
3090        if (!isSmall() && !mIsSwitchingState) {
3091            super.scrollRight();
3092        }
3093        Folder openFolder = getOpenFolder();
3094        if (openFolder != null) {
3095            openFolder.completeDragExit();
3096        }
3097    }
3098
3099    @Override
3100    public boolean onEnterScrollArea(int x, int y, int direction) {
3101        // Ignore the scroll area if we are dragging over the hot seat
3102        if (mLauncher.getHotseat() != null) {
3103            Rect r = new Rect();
3104            mLauncher.getHotseat().getHitRect(r);
3105            if (r.contains(x, y)) {
3106                return false;
3107            }
3108        }
3109
3110        boolean result = false;
3111        if (!isSmall() && !mIsSwitchingState) {
3112            mInScrollArea = true;
3113
3114            final int page = mCurrentPage + (direction == DragController.SCROLL_LEFT ? -1 : 1);
3115            final CellLayout layout = (CellLayout) getChildAt(page);
3116            cancelFolderCreation();
3117
3118            if (layout != null) {
3119                // Exit the current layout and mark the overlapping layout
3120                if (mDragTargetLayout != null) {
3121                    mDragTargetLayout.setIsDragOverlapping(false);
3122                    mDragTargetLayout.onDragExit();
3123                }
3124                mDragTargetLayout = layout;
3125                mDragTargetLayout.setIsDragOverlapping(true);
3126
3127                // Workspace is responsible for drawing the edge glow on adjacent pages,
3128                // so we need to redraw the workspace when this may have changed.
3129                invalidate();
3130                result = true;
3131            }
3132        }
3133        return result;
3134    }
3135
3136    @Override
3137    public boolean onExitScrollArea() {
3138        boolean result = false;
3139        if (mInScrollArea) {
3140            if (mDragTargetLayout != null) {
3141                // Unmark the overlapping layout and re-enter the current layout
3142                mDragTargetLayout.setIsDragOverlapping(false);
3143                mDragTargetLayout = getCurrentDropLayout();
3144                mDragTargetLayout.onDragEnter();
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                result = true;
3150            }
3151            mInScrollArea = false;
3152        }
3153        return result;
3154    }
3155
3156    private void onResetScrollArea() {
3157        if (mDragTargetLayout != null) {
3158            // Unmark the overlapping layout
3159            mDragTargetLayout.setIsDragOverlapping(false);
3160
3161            // Workspace is responsible for drawing the edge glow on adjacent pages,
3162            // so we need to redraw the workspace when this may have changed.
3163            invalidate();
3164        }
3165        mInScrollArea = false;
3166    }
3167
3168    /**
3169     * Returns a specific CellLayout
3170     */
3171    CellLayout getParentCellLayoutForView(View v) {
3172        ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts();
3173        for (CellLayout layout : layouts) {
3174            if (layout.getChildrenLayout().indexOfChild(v) > -1) {
3175                return layout;
3176            }
3177        }
3178        return null;
3179    }
3180
3181    /**
3182     * Returns a list of all the CellLayouts in the workspace.
3183     */
3184    ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() {
3185        ArrayList<CellLayout> layouts = new ArrayList<CellLayout>();
3186        int screenCount = getChildCount();
3187        for (int screen = 0; screen < screenCount; screen++) {
3188            layouts.add(((CellLayout) getChildAt(screen)));
3189        }
3190        if (mLauncher.getHotseat() != null) {
3191            layouts.add(mLauncher.getHotseat().getLayout());
3192        }
3193        return layouts;
3194    }
3195
3196    /**
3197     * We should only use this to search for specific children.  Do not use this method to modify
3198     * CellLayoutChildren directly.
3199     */
3200    ArrayList<CellLayoutChildren> getWorkspaceAndHotseatCellLayoutChildren() {
3201        ArrayList<CellLayoutChildren> childrenLayouts = new ArrayList<CellLayoutChildren>();
3202        int screenCount = getChildCount();
3203        for (int screen = 0; screen < screenCount; screen++) {
3204            childrenLayouts.add(((CellLayout) getChildAt(screen)).getChildrenLayout());
3205        }
3206        if (mLauncher.getHotseat() != null) {
3207            childrenLayouts.add(mLauncher.getHotseat().getLayout().getChildrenLayout());
3208        }
3209        return childrenLayouts;
3210    }
3211
3212    public Folder getFolderForTag(Object tag) {
3213        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3214        for (CellLayoutChildren layout: childrenLayouts) {
3215            int count = layout.getChildCount();
3216            for (int i = 0; i < count; i++) {
3217                View child = layout.getChildAt(i);
3218                if (child instanceof Folder) {
3219                    Folder f = (Folder) child;
3220                    if (f.getInfo() == tag && f.getInfo().opened) {
3221                        return f;
3222                    }
3223                }
3224            }
3225        }
3226        return null;
3227    }
3228
3229    public View getViewForTag(Object tag) {
3230        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3231        for (CellLayoutChildren layout: childrenLayouts) {
3232            int count = layout.getChildCount();
3233            for (int i = 0; i < count; i++) {
3234                View child = layout.getChildAt(i);
3235                if (child.getTag() == tag) {
3236                    return child;
3237                }
3238            }
3239        }
3240        return null;
3241    }
3242
3243    void clearDropTargets() {
3244        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3245        for (CellLayoutChildren layout: childrenLayouts) {
3246            int childCount = layout.getChildCount();
3247            for (int j = 0; j < childCount; j++) {
3248                View v = layout.getChildAt(j);
3249                if (v instanceof DropTarget) {
3250                    mDragController.removeDropTarget((DropTarget) v);
3251                }
3252            }
3253        }
3254    }
3255
3256    void removeItems(final ArrayList<ApplicationInfo> apps) {
3257        final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext());
3258
3259        final HashSet<String> packageNames = new HashSet<String>();
3260        final int appCount = apps.size();
3261        for (int i = 0; i < appCount; i++) {
3262            packageNames.add(apps.get(i).componentName.getPackageName());
3263        }
3264
3265        ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
3266        for (final CellLayout layoutParent: cellLayouts) {
3267            final ViewGroup layout = layoutParent.getChildrenLayout();
3268
3269            // Avoid ANRs by treating each screen separately
3270            post(new Runnable() {
3271                public void run() {
3272                    final ArrayList<View> childrenToRemove = new ArrayList<View>();
3273                    childrenToRemove.clear();
3274
3275                    int childCount = layout.getChildCount();
3276                    for (int j = 0; j < childCount; j++) {
3277                        final View view = layout.getChildAt(j);
3278                        Object tag = view.getTag();
3279
3280                        if (tag instanceof ShortcutInfo) {
3281                            final ShortcutInfo info = (ShortcutInfo) tag;
3282                            final Intent intent = info.intent;
3283                            final ComponentName name = intent.getComponent();
3284
3285                            if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3286                                for (String packageName: packageNames) {
3287                                    if (packageName.equals(name.getPackageName())) {
3288                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3289                                        childrenToRemove.add(view);
3290                                    }
3291                                }
3292                            }
3293                        } else if (tag instanceof FolderInfo) {
3294                            final FolderInfo info = (FolderInfo) tag;
3295                            final ArrayList<ShortcutInfo> contents = info.contents;
3296                            final int contentsCount = contents.size();
3297                            final ArrayList<ShortcutInfo> appsToRemoveFromFolder =
3298                                    new ArrayList<ShortcutInfo>();
3299
3300                            for (int k = 0; k < contentsCount; k++) {
3301                                final ShortcutInfo appInfo = contents.get(k);
3302                                final Intent intent = appInfo.intent;
3303                                final ComponentName name = intent.getComponent();
3304
3305                                if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3306                                    for (String packageName: packageNames) {
3307                                        if (packageName.equals(name.getPackageName())) {
3308                                            appsToRemoveFromFolder.add(appInfo);
3309                                        }
3310                                    }
3311                                }
3312                            }
3313                            for (ShortcutInfo item: appsToRemoveFromFolder) {
3314                                info.remove(item);
3315                                LauncherModel.deleteItemFromDatabase(mLauncher, item);
3316                            }
3317                        } else if (tag instanceof LauncherAppWidgetInfo) {
3318                            final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag;
3319                            final AppWidgetProviderInfo provider =
3320                                    widgets.getAppWidgetInfo(info.appWidgetId);
3321                            if (provider != null) {
3322                                for (String packageName: packageNames) {
3323                                    if (packageName.equals(provider.provider.getPackageName())) {
3324                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3325                                        childrenToRemove.add(view);
3326                                    }
3327                                }
3328                            }
3329                        }
3330                    }
3331
3332                    childCount = childrenToRemove.size();
3333                    for (int j = 0; j < childCount; j++) {
3334                        View child = childrenToRemove.get(j);
3335                        // Note: We can not remove the view directly from CellLayoutChildren as this
3336                        // does not re-mark the spaces as unoccupied.
3337                        layoutParent.removeViewInLayout(child);
3338                        if (child instanceof DropTarget) {
3339                            mDragController.removeDropTarget((DropTarget)child);
3340                        }
3341                    }
3342
3343                    if (childCount > 0) {
3344                        layout.requestLayout();
3345                        layout.invalidate();
3346                    }
3347                }
3348            });
3349        }
3350    }
3351
3352    void updateShortcuts(ArrayList<ApplicationInfo> apps) {
3353        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3354        for (CellLayoutChildren layout: childrenLayouts) {
3355            int childCount = layout.getChildCount();
3356            for (int j = 0; j < childCount; j++) {
3357                final View view = layout.getChildAt(j);
3358                Object tag = view.getTag();
3359                if (tag instanceof ShortcutInfo) {
3360                    ShortcutInfo info = (ShortcutInfo)tag;
3361                    // We need to check for ACTION_MAIN otherwise getComponent() might
3362                    // return null for some shortcuts (for instance, for shortcuts to
3363                    // web pages.)
3364                    final Intent intent = info.intent;
3365                    final ComponentName name = intent.getComponent();
3366                    if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3367                            Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3368                        final int appCount = apps.size();
3369                        for (int k = 0; k < appCount; k++) {
3370                            ApplicationInfo app = apps.get(k);
3371                            if (app.componentName.equals(name)) {
3372                                info.setIcon(mIconCache.getIcon(info.intent));
3373                                ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null,
3374                                        new FastBitmapDrawable(info.getIcon(mIconCache)),
3375                                        null, null);
3376                                }
3377                        }
3378                    }
3379                }
3380            }
3381        }
3382    }
3383
3384    void moveToDefaultScreen(boolean animate) {
3385        if (!isSmall()) {
3386            if (animate) {
3387                snapToPage(mDefaultPage);
3388            } else {
3389                setCurrentPage(mDefaultPage);
3390            }
3391        }
3392        getChildAt(mDefaultPage).requestFocus();
3393    }
3394
3395    @Override
3396    public void syncPages() {
3397    }
3398
3399    @Override
3400    public void syncPageItems(int page, boolean immediate) {
3401    }
3402
3403    @Override
3404    protected String getCurrentPageDescription() {
3405        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
3406        return String.format(mContext.getString(R.string.workspace_scroll_format),
3407                page + 1, getChildCount());
3408    }
3409
3410    public void getLocationInDragLayer(int[] loc) {
3411        mLauncher.getDragLayer().getLocationInDragLayer(this, loc);
3412    }
3413
3414    void showDockDivider(boolean immediately) {
3415        final ViewGroup parent = (ViewGroup) getParent();
3416        final View qsbDivider = (ImageView) (parent.findViewById(R.id.qsb_divider));
3417        final View dockDivider = (ImageView) (parent.findViewById(R.id.dock_divider));
3418        if (qsbDivider != null && dockDivider != null) {
3419            qsbDivider.setVisibility(View.VISIBLE);
3420            dockDivider.setVisibility(View.VISIBLE);
3421            if (mDividerAnimator != null) {
3422                mDividerAnimator.cancel();
3423                mDividerAnimator = null;
3424            }
3425            if (immediately) {
3426                qsbDivider.setAlpha(1f);
3427                dockDivider.setAlpha(1f);
3428            } else {
3429                mDividerAnimator = new AnimatorSet();
3430                mDividerAnimator.playTogether(ObjectAnimator.ofFloat(qsbDivider, "alpha", 1f),
3431                        ObjectAnimator.ofFloat(dockDivider, "alpha", 1f));
3432                mDividerAnimator.setDuration(sScrollIndicatorFadeInDuration);
3433                mDividerAnimator.start();
3434            }
3435        }
3436    }
3437
3438    void hideDockDivider(boolean immediately) {
3439        final ViewGroup parent = (ViewGroup) getParent();
3440        final View qsbDivider = (ImageView) (parent.findViewById(R.id.qsb_divider));
3441        final View dockDivider = (ImageView) (parent.findViewById(R.id.dock_divider));
3442        if (qsbDivider != null && dockDivider != null) {
3443            if (mDividerAnimator != null) {
3444                mDividerAnimator.cancel();
3445                mDividerAnimator = null;
3446            }
3447            if (immediately) {
3448                qsbDivider.setVisibility(View.GONE);
3449                dockDivider.setVisibility(View.GONE);
3450                qsbDivider.setAlpha(0f);
3451                dockDivider.setAlpha(0f);
3452            } else {
3453                mDividerAnimator = new AnimatorSet();
3454                mDividerAnimator.playTogether(ObjectAnimator.ofFloat(qsbDivider, "alpha", 0f),
3455                        ObjectAnimator.ofFloat(dockDivider, "alpha", 0f));
3456                mDividerAnimator.addListener(new AnimatorListenerAdapter() {
3457                    private boolean cancelled = false;
3458                    @Override
3459                    public void onAnimationCancel(android.animation.Animator animation) {
3460                        cancelled = true;
3461                    }
3462                    @Override
3463                    public void onAnimationEnd(android.animation.Animator animation) {
3464                        if (!cancelled) {
3465                            qsbDivider.setVisibility(View.GONE);
3466                            dockDivider.setVisibility(View.GONE);
3467                        }
3468                    }
3469                });
3470                mDividerAnimator.setDuration(sScrollIndicatorFadeOutDuration);
3471                mDividerAnimator.start();
3472            }
3473        }
3474    }
3475}
3476